Alovestocode commited on
Commit
231dc34
·
verified ·
1 Parent(s): fb0ad83

Push all files including app.py, requirements.txt, and other config files

Browse files
Files changed (5) hide show
  1. app.py +820 -206
  2. apt.txt +2 -0
  3. requirements.txt +12 -9
  4. style.css +150 -0
  5. test_api.py +72 -21
app.py CHANGED
@@ -1,258 +1,872 @@
1
  import os
2
  import time
3
  import gc
4
- import torch
 
 
 
 
5
  import gradio as gr
6
- from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
 
 
 
7
  import spaces # Import spaces early to enable ZeroGPU support
 
8
 
9
- # Configuration
10
- MAX_NEW_TOKENS = int(os.environ.get("MAX_NEW_TOKENS", "600"))
11
- DEFAULT_TEMPERATURE = float(os.environ.get("DEFAULT_TEMPERATURE", "0.2"))
12
- DEFAULT_TOP_P = float(os.environ.get("DEFAULT_TOP_P", "0.9"))
13
- HF_TOKEN = os.environ.get("HF_TOKEN")
14
 
15
- MODEL_ID = "Alovestocode/router-gemma3-merged"
16
 
17
- # Global model cache
18
- _MODEL = None
19
- _TOKENIZER = None
20
- ACTIVE_STRATEGY = None
21
 
22
- # Detect ZeroGPU environment
23
- IS_ZEROGPU = os.environ.get("SPACE_RUNTIME_STATELESS", "0") == "1"
24
- if os.environ.get("SPACES_ZERO_GPU") is not None:
25
- IS_ZEROGPU = True
26
-
27
- def load_model():
28
- """Load the model on CPU. GPU movement happens inside @spaces.GPU decorated function."""
29
- global _MODEL, _TOKENIZER, ACTIVE_STRATEGY
30
-
31
- if _MODEL is None:
32
- print(f"Loading model {MODEL_ID}...")
33
- _TOKENIZER = AutoTokenizer.from_pretrained(MODEL_ID, use_fast=False, token=HF_TOKEN)
34
-
35
- if IS_ZEROGPU:
36
- # ZeroGPU: load on CPU with device_map=None
37
- try:
38
- kwargs = {
39
- "device_map": None, # Stay on CPU for ZeroGPU
40
- "quantization_config": BitsAndBytesConfig(load_in_8bit=True),
41
- "trust_remote_code": True,
42
- "low_cpu_mem_usage": True,
43
- "token": HF_TOKEN,
44
- }
45
- _MODEL = AutoModelForCausalLM.from_pretrained(MODEL_ID, **kwargs)
46
- ACTIVE_STRATEGY = "8bit"
47
- except Exception:
48
- # Fallback to bf16 on CPU
49
- kwargs = {
50
- "device_map": None,
51
- "torch_dtype": torch.bfloat16,
52
- "trust_remote_code": True,
53
- "low_cpu_mem_usage": True,
54
- "token": HF_TOKEN,
55
- }
56
- _MODEL = AutoModelForCausalLM.from_pretrained(MODEL_ID, **kwargs)
57
- ACTIVE_STRATEGY = "bf16"
58
- else:
59
- # Local environment: use GPU if available
60
- if torch.cuda.is_available():
61
- try:
62
- kwargs = {
63
- "device_map": "auto",
64
- "quantization_config": BitsAndBytesConfig(load_in_8bit=True),
65
- "trust_remote_code": True,
66
- "low_cpu_mem_usage": True,
67
- "token": HF_TOKEN,
68
- }
69
- _MODEL = AutoModelForCausalLM.from_pretrained(MODEL_ID, **kwargs)
70
- ACTIVE_STRATEGY = "8bit"
71
- except Exception:
72
- kwargs = {
73
- "device_map": "auto",
74
- "torch_dtype": torch.bfloat16,
75
- "trust_remote_code": True,
76
- "low_cpu_mem_usage": True,
77
- "token": HF_TOKEN,
78
- }
79
- _MODEL = AutoModelForCausalLM.from_pretrained(MODEL_ID, **kwargs)
80
- ACTIVE_STRATEGY = "bf16"
81
- else:
82
- kwargs = {
83
- "device_map": "cpu",
84
- "torch_dtype": torch.float32,
85
- "trust_remote_code": True,
86
- "low_cpu_mem_usage": True,
87
- "token": HF_TOKEN,
88
- }
89
- _MODEL = AutoModelForCausalLM.from_pretrained(MODEL_ID, **kwargs)
90
- ACTIVE_STRATEGY = "cpu"
91
-
92
- _MODEL = _MODEL.eval()
93
- print(f"Loaded {MODEL_ID} with strategy='{ACTIVE_STRATEGY}' (ZeroGPU={IS_ZEROGPU})")
94
 
95
- return _MODEL, _TOKENIZER
 
 
 
 
 
 
 
 
 
 
96
 
97
- def get_duration(prompt, max_new_tokens, temperature, top_p):
98
- """Estimate generation duration for ZeroGPU scheduling."""
99
- # Base time + token generation time
100
- base_duration = 20
101
- token_duration = max_new_tokens * 0.005 # ~200 tokens/second
102
- return base_duration + token_duration
103
 
104
- @spaces.GPU(duration=get_duration)
105
- def generate_response(prompt, max_new_tokens=MAX_NEW_TOKENS, temperature=DEFAULT_TEMPERATURE, top_p=DEFAULT_TOP_P):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  """
107
- Generate response using the router model.
108
- In ZeroGPU mode: model is loaded on CPU, moved to GPU here, then back to CPU after.
109
  """
110
- if not prompt.strip():
111
- return "ERROR: Prompt must not be empty."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
- global _MODEL
114
- model, tokenizer = load_model()
115
 
116
- # In ZeroGPU: move model to GPU inside this @spaces.GPU function
117
- current_device = torch.device("cpu")
118
- if IS_ZEROGPU and torch.cuda.is_available():
119
- current_device = torch.device("cuda")
120
- model = model.to(current_device)
121
- elif torch.cuda.is_available() and not IS_ZEROGPU:
122
- current_device = torch.device("cuda")
123
 
124
- inputs = tokenizer(prompt, return_tensors="pt").to(current_device)
125
- eos = tokenizer.eos_token_id
 
 
 
 
 
 
 
 
 
 
 
126
 
127
- try:
128
- with torch.inference_mode():
129
- output_ids = model.generate(
130
- **inputs,
131
- max_new_tokens=max_new_tokens,
132
- temperature=temperature,
133
- top_p=top_p,
134
- do_sample=True,
135
- eos_token_id=eos,
136
- pad_token_id=eos,
 
137
  )
138
-
139
- text = tokenizer.decode(output_ids[0], skip_special_tokens=True)
140
- result = text[len(prompt):].strip() or text.strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
  finally:
142
- # In ZeroGPU: move model back to CPU to free GPU memory
143
- if IS_ZEROGPU and torch.cuda.is_available():
144
- _MODEL = model.to(torch.device("cpu"))
145
- torch.cuda.empty_cache()
146
-
147
- return result
148
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
  # Gradio UI
 
150
  with gr.Blocks(
151
- title="Router Model API - ZeroGPU",
152
  theme=gr.themes.Soft(
153
  primary_hue="indigo",
154
  secondary_hue="purple",
155
  neutral_hue="slate",
156
  radius_size="lg",
 
157
  ),
158
  css="""
159
- .main-header {
160
- text-align: center;
161
- padding: 20px;
162
- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
163
- color: white;
164
- border-radius: 10px;
165
- margin-bottom: 20px;
166
- }
167
- .info-box {
168
- background: #f0f0f0;
169
- padding: 15px;
170
- border-radius: 8px;
171
- margin-bottom: 20px;
172
- }
173
  """
174
  ) as demo:
175
  # Header
176
  gr.Markdown("""
177
- <div class="main-header">
178
- <h1>🚀 Router Model API - ZeroGPU</h1>
179
- <p>Intelligent routing agent for coordinating specialized AI agents</p>
180
- </div>
181
  """)
182
 
183
  with gr.Row():
184
- # Left Panel - Input
185
- with gr.Column(scale=1):
186
- gr.Markdown("### 📝 Input")
187
- prompt_input = gr.Textbox(
188
- label="Router Prompt",
189
- lines=10,
190
- placeholder="Enter your router prompt here...\n\nExample:\nYou are the Router Agent coordinating Math, Code, and General-Search specialists.\nUser query: Solve the integral of x^2 from 0 to 1",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
191
  )
192
 
193
- with gr.Accordion("⚙️ Generation Parameters", open=True):
194
- max_tokens_input = gr.Slider(
195
- minimum=64,
196
- maximum=2048,
197
- value=MAX_NEW_TOKENS,
198
- step=16,
199
- label="Max New Tokens",
200
- info="Maximum number of tokens to generate"
201
  )
202
- temp_input = gr.Slider(
203
- minimum=0.0,
204
- maximum=2.0,
205
- value=DEFAULT_TEMPERATURE,
206
- step=0.05,
207
  label="Temperature",
208
- info="Controls randomness: lower = more deterministic"
209
  )
210
- top_p_input = gr.Slider(
211
- minimum=0.0,
212
- maximum=1.0,
213
- value=DEFAULT_TOP_P,
214
- step=0.05,
215
- label="Top-p (Nucleus Sampling)",
216
- info="Probability mass to consider for sampling"
 
 
 
 
 
 
 
 
217
  )
218
 
219
- generate_btn = gr.Button("🚀 Generate", variant="primary")
220
- clear_btn = gr.Button("🗑️ Clear", variant="secondary")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
 
222
- # Right Panel - Output
223
- with gr.Column(scale=1):
224
- gr.Markdown("### 📤 Output")
225
- output = gr.Textbox(
226
- label="Generated Response",
227
- lines=25,
228
- placeholder="Generated response will appear here...",
229
  show_copy_button=True,
 
 
230
  )
231
 
232
- with gr.Accordion("📚 Model Information", open=False):
233
- gr.Markdown(f"""
234
- **Model:** `{MODEL_ID}`
235
- **Strategy:** `{ACTIVE_STRATEGY or 'pending'}`
236
- **ZeroGPU:** `{IS_ZEROGPU}`
237
- **Max Tokens:** `{MAX_NEW_TOKENS}`
238
- **Default Temperature:** `{DEFAULT_TEMPERATURE}`
239
- **Default Top-p:** `{DEFAULT_TOP_P}`
240
- """)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
241
 
242
- # Event handlers
243
- generate_btn.click(
244
- fn=generate_response,
245
- inputs=[prompt_input, max_tokens_input, temp_input, top_p_input],
246
- outputs=output,
247
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
248
 
249
- clear_btn.click(
250
- fn=lambda: ("", ""),
251
- inputs=None,
252
- outputs=[prompt_input, output],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
253
  )
254
 
255
- # Launch the app
256
- if __name__ == "__main__":
257
- print("Warm start skipped for ZeroGPU. Model will load on first request.")
258
- demo.queue(max_size=8).launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import time
3
  import gc
4
+ import sys
5
+ import threading
6
+ from itertools import islice
7
+ from datetime import datetime
8
+ import re # for parsing <think> blocks
9
  import gradio as gr
10
+ import torch
11
+ from transformers import pipeline, TextIteratorStreamer, StoppingCriteria
12
+ from transformers import AutoTokenizer
13
+ from ddgs import DDGS
14
  import spaces # Import spaces early to enable ZeroGPU support
15
+ from torch.utils._pytree import tree_map
16
 
17
+ # Global event to signal cancellation from the UI thread to the generation thread
18
+ cancel_event = threading.Event()
 
 
 
19
 
20
+ access_token=os.environ['HF_TOKEN']
21
 
22
+ # Optional: Disable GPU visibility if you wish to force CPU usage
23
+ # os.environ["CUDA_VISIBLE_DEVICES"] = ""
 
 
24
 
25
+ # ------------------------------
26
+ # Torch-Compatible Model Definitions with Adjusted Descriptions
27
+ # ------------------------------
28
+ MODELS = {
29
+ # "Qwen/Qwen3-Next-80B-A3B-Instruct-FP8": {
30
+ # "repo_id": "Qwen/Qwen3-Next-80B-A3B-Instruct-FP8",
31
+ # "description": "Sparse Mixture-of-Experts (MoE) causal language model with 80B total parameters and approximately 3B activated per inference step. Features include native 32,768-token context (extendable to 131,072 via YaRN), 16 query heads and 2 KV heads, head dimension of 256, and FP8 quantization for efficiency. Optimized for fast, stable instruction-following dialogue without 'thinking' traces, making it ideal for general chat and low-latency applications [[2]][[3]][[5]][[8]].",
32
+ # "params_b": 80.0
33
+ # },
34
+ # "Qwen/Qwen3-Next-80B-A3B-Thinking-FP8": {
35
+ # "repo_id": "Qwen/Qwen3-Next-80B-A3B-Thinking-FP8",
36
+ # "description": "Sparse Mixture-of-Experts (MoE) causal language model with 80B total parameters and approximately 3B activated per inference step. Features include native 32,768-token context (extendable to 131,072 via YaRN), 16 query heads and 2 KV heads, head dimension of 256, and FP8 quantization. Specialized for complex reasoning, math, and coding tasks, this model outputs structured 'thinking' traces by default and is designed to be used with a reasoning parser [[10]][[11]][[14]][[18]].",
37
+ # "params_b": 80.0
38
+ # },
39
+ "Qwen3-32B-FP8": {
40
+ "repo_id": "Qwen/Qwen3-32B-FP8",
41
+ "description": "Dense causal language model with 32.8B total parameters (31.2B non-embedding), 64 layers, 64 query heads & 8 KV heads, native 32,768-token context (extendable to 131,072 via YaRN). Features seamless switching between thinking mode (for complex reasoning, math, coding) and non-thinking mode (for efficient dialogue), strong multilingual support (100+ languages), and leading open-source agent capabilities.",
42
+ "params_b": 32.8
43
+ },
44
+ # ~30.5B total parameters (MoE: 3.3B activated)
45
+ # "Qwen3-30B-A3B-Instruct-2507": {
46
+ # "repo_id": "Qwen/Qwen3-30B-A3B-Instruct-2507",
47
+ # "description": "non-thinking-mode MoE model based on Qwen3-30B-A3B-Instruct-2507. Features 30.5B total parameters (3.3B activated), 128 experts (8 activated), 48 layers, and native 262,144-token context. Excels in instruction following, logical reasoning, multilingualism, coding, and long-context understanding. Supports only non-thinking mode (no <think> blocks). Quantized using AWQ (W4A16) with lm_head and gating layers preserved in higher precision.",
48
+ # "params_b": 30.5
49
+ # },
50
+ # "Qwen3-30B-A3B-Thinking-2507": {
51
+ # "repo_id": "Qwen/Qwen3-30B-A3B-Thinking-2507",
52
+ # "description": "thinking-mode MoE model based on Qwen3-30B-A3B-Thinking-2507. Contains 30.5B total parameters (3.3B activated), 128 experts (8 activated), 48 layers, and 262,144-token native context. Optimized for deep reasoning in mathematics, science, coding, and agent tasks. Outputs include automatic reasoning delimiters (<think>...</think>). Quantized with AWQ (W4A16), preserving lm_head and expert gating layers.",
53
+ # "params_b": 30.5
54
+ # },
55
+ "gpt-oss-20b-BF16": {
56
+ "repo_id": "unsloth/gpt-oss-20b-BF16",
57
+ "description": "A 20B-parameter open-source GPT-style language model quantized to INT4 using AutoRound, with FP8 key-value cache for efficient inference. Optimized for performance and memory efficiency on Intel hardware while maintaining strong language generation capabilities.",
58
+ "params_b": 20.0
59
+ },
60
+ "Qwen3-4B-Instruct-2507": {
61
+ "repo_id": "Qwen/Qwen3-4B-Instruct-2507",
62
+ "description": "Updated non-thinking instruct variant of Qwen3-4B with 4.0B parameters, featuring significant improvements in instruction following, logical reasoning, multilingualism, and 256K long-context understanding. Strong performance across knowledge, coding, alignment, and agent benchmarks.",
63
+ "params_b": 4.0
64
+ },
65
+ "Apriel-1.5-15b-Thinker": {
66
+ "repo_id": "ServiceNow-AI/Apriel-1.5-15b-Thinker",
67
+ "description": "Multimodal reasoning model with 15B parameters, trained via extensive mid-training on text and image data, and fine-tuned only on text (no image SFT). Achieves competitive performance on reasoning benchmarks like Artificial Analysis (score: 52), Tau2 Bench Telecom (68), and IFBench (62). Supports both text and image understanding, fits on a single GPU, and includes structured reasoning output with tool and function calling capabilities.",
68
+ "params_b": 15.0
69
+ },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
+ # 14.8B total parameters
72
+ "Qwen3-14B": {
73
+ "repo_id": "Qwen/Qwen3-14B",
74
+ "description": "Dense causal language model with 14.8 B total parameters (13.2 B non-embedding), 40 layers, 40 query heads & 8 KV heads, 32 768-token context (131 072 via YaRN), enhanced human preference alignment & advanced agent integration.",
75
+ "params_b": 14.8
76
+ },
77
+ "Qwen/Qwen3-14B-FP8": {
78
+ "repo_id": "Qwen/Qwen3-14B-FP8",
79
+ "description": "FP8-quantized version of Qwen3-14B for efficient inference.",
80
+ "params_b": 14.8
81
+ },
82
 
83
+ # ~15B (commented out in original, but larger than 14B)
84
+ # "Apriel-1.5-15b-Thinker": { ... },
 
 
 
 
85
 
86
+ # 5B
87
+ # "Apriel-5B-Instruct": {
88
+ # "repo_id": "ServiceNow-AI/Apriel-5B-Instruct",
89
+ # "description": "A 5B-parameter instruction-tuned model from ServiceNow’s Apriel series, optimized for enterprise tasks and general-purpose instruction following."
90
+ # },
91
+
92
+ # 4.3B
93
+ "Phi-4-mini-Reasoning": {
94
+ "repo_id": "microsoft/Phi-4-mini-reasoning",
95
+ "description": "Phi-4-mini-Reasoning (4.3B parameters)",
96
+ "params_b": 4.3
97
+ },
98
+ "Phi-4-mini-Instruct": {
99
+ "repo_id": "microsoft/Phi-4-mini-instruct",
100
+ "description": "Phi-4-mini-Instruct (4.3B parameters)",
101
+ "params_b": 4.3
102
+ },
103
+
104
+ # 4.0B
105
+ "Qwen3-4B": {
106
+ "repo_id": "Qwen/Qwen3-4B",
107
+ "description": "Dense causal language model with 4.0 B total parameters (3.6 B non-embedding), 36 layers, 32 query heads & 8 KV heads, native 32 768-token context (extendable to 131 072 via YaRN), balanced mid-range capacity & long-context reasoning.",
108
+ "params_b": 4.0
109
+ },
110
+
111
+ "Gemma-3-4B-IT": {
112
+ "repo_id": "unsloth/gemma-3-4b-it",
113
+ "description": "Gemma-3-4B-IT",
114
+ "params_b": 4.0
115
+ },
116
+ "MiniCPM3-4B": {
117
+ "repo_id": "openbmb/MiniCPM3-4B",
118
+ "description": "MiniCPM3-4B",
119
+ "params_b": 4.0
120
+ },
121
+ "Gemma-3n-E4B": {
122
+ "repo_id": "google/gemma-3n-E4B",
123
+ "description": "Gemma 3n base model with effective 4 B parameters (≈3 GB VRAM)",
124
+ "params_b": 4.0
125
+ },
126
+ "SmallThinker-4BA0.6B-Instruct": {
127
+ "repo_id": "PowerInfer/SmallThinker-4BA0.6B-Instruct",
128
+ "description": "SmallThinker 4 B backbone with 0.6 B activated parameters, instruction‑tuned",
129
+ "params_b": 4.0
130
+ },
131
+
132
+ # ~3B
133
+ # "AI21-Jamba-Reasoning-3B": {
134
+ # "repo_id": "ai21labs/AI21-Jamba-Reasoning-3B",
135
+ # "description": "A compact 3B hybrid Transformer–Mamba reasoning model with 256K context length, strong intelligence benchmark scores (61% MMLU-Pro, 52% IFBench), and efficient inference suitable for edge and datacenter use. Outperforms Gemma-3 4B and Llama-3.2 3B despite smaller size."
136
+ # },
137
+ "Qwen2.5-Taiwan-3B-Reason-GRPO": {
138
+ "repo_id": "benchang1110/Qwen2.5-Taiwan-3B-Reason-GRPO",
139
+ "description": "Qwen2.5-Taiwan model with 3 B parameters, Reason-GRPO fine-tuned",
140
+ "params_b": 3.0
141
+ },
142
+ "Llama-3.2-Taiwan-3B-Instruct": {
143
+ "repo_id": "lianghsun/Llama-3.2-Taiwan-3B-Instruct",
144
+ "description": "Llama-3.2-Taiwan-3B-Instruct",
145
+ "params_b": 3.0
146
+ },
147
+ "Qwen2.5-3B-Instruct": {
148
+ "repo_id": "Qwen/Qwen2.5-3B-Instruct",
149
+ "description": "Qwen2.5-3B-Instruct",
150
+ "params_b": 3.0
151
+ },
152
+ "Qwen2.5-Omni-3B": {
153
+ "repo_id": "Qwen/Qwen2.5-Omni-3B",
154
+ "description": "Qwen2.5-Omni-3B",
155
+ "params_b": 3.0
156
+ },
157
+ "Granite-4.0-Micro": {
158
+ "repo_id": "ibm-granite/granite-4.0-micro",
159
+ "description": "A 3B-parameter long-context instruct model from IBM, finetuned for enhanced instruction following and tool-calling. Supports 12 languages including English, Chinese, Arabic, and Japanese. Built on a dense Transformer with GQA, RoPE, SwiGLU, and 128K context length. Trained using SFT, RL alignment, and model merging techniques for enterprise applications.",
160
+ "params_b": 3.0
161
+ },
162
+
163
+ # 2.6B
164
+ "LFM2-2.6B": {
165
+ "repo_id": "LiquidAI/LFM2-2.6B",
166
+ "description": "The 2.6B parameter model in the LFM2 series, it outperforms models in the 3B+ class and features a hybrid architecture for faster inference.",
167
+ "params_b": 2.6
168
+ },
169
+
170
+ # 1.7B
171
+ "Qwen3-1.7B": {
172
+ "repo_id": "Qwen/Qwen3-1.7B",
173
+ "description": "Dense causal language model with 1.7 B total parameters (1.4 B non-embedding), 28 layers, 16 query heads & 8 KV heads, 32 768-token context, stronger reasoning vs. 0.6 B variant, dual-mode inference, instruction following across 100+ languages.",
174
+ "params_b": 1.7
175
+ },
176
+
177
+ # ~2B (effective)
178
+ "Gemma-3n-E2B": {
179
+ "repo_id": "google/gemma-3n-E2B",
180
+ "description": "Gemma 3n base model with effective 2 B parameters (≈2 GB VRAM)",
181
+ "params_b": 2.0
182
+ },
183
+
184
+ # 1.5B
185
+ "Nemotron-Research-Reasoning-Qwen-1.5B": {
186
+ "repo_id": "nvidia/Nemotron-Research-Reasoning-Qwen-1.5B",
187
+ "description": "Nemotron-Research-Reasoning-Qwen-1.5B",
188
+ "params_b": 1.5
189
+ },
190
+ "Falcon-H1-1.5B-Instruct": {
191
+ "repo_id": "tiiuae/Falcon-H1-1.5B-Instruct",
192
+ "description": "Falcon‑H1 model with 1.5 B parameters, instruction‑tuned",
193
+ "params_b": 1.5
194
+ },
195
+ "Qwen2.5-Taiwan-1.5B-Instruct": {
196
+ "repo_id": "benchang1110/Qwen2.5-Taiwan-1.5B-Instruct",
197
+ "description": "Qwen2.5-Taiwan-1.5B-Instruct",
198
+ "params_b": 1.5
199
+ },
200
+
201
+ # 1.2B
202
+ "LFM2-1.2B": {
203
+ "repo_id": "LiquidAI/LFM2-1.2B",
204
+ "description": "A 1.2B parameter hybrid language model from Liquid AI, designed for efficient on-device and edge AI deployment, outperforming larger models like Llama-2-7b-hf in specific tasks.",
205
+ "params_b": 1.2
206
+ },
207
+
208
+ # 1.1B
209
+ "Taiwan-ELM-1_1B-Instruct": {
210
+ "repo_id": "liswei/Taiwan-ELM-1_1B-Instruct",
211
+ "description": "Taiwan-ELM-1_1B-Instruct",
212
+ "params_b": 1.1
213
+ },
214
+
215
+ # 1B
216
+ "Llama-3.2-Taiwan-1B": {
217
+ "repo_id": "lianghsun/Llama-3.2-Taiwan-1B",
218
+ "description": "Llama-3.2-Taiwan base model with 1 B parameters",
219
+ "params_b": 1.0
220
+ },
221
+
222
+ # 700M
223
+ "LFM2-700M": {
224
+ "repo_id": "LiquidAI/LFM2-700M",
225
+ "description": "A 700M parameter model from the LFM2 family, designed for high efficiency on edge devices with a hybrid architecture of multiplicative gates and short convolutions.",
226
+ "params_b": 0.7
227
+ },
228
+
229
+ # 600M
230
+ "Qwen3-0.6B": {
231
+ "repo_id": "Qwen/Qwen3-0.6B",
232
+ "description": "Dense causal language model with 0.6 B total parameters (0.44 B non-embedding), 28 transformer layers, 16 query heads & 8 KV heads, native 32 768-token context window, dual-mode generation, full multilingual & agentic capabilities.",
233
+ "params_b": 0.6
234
+ },
235
+ "Qwen3-0.6B-Taiwan": {
236
+ "repo_id": "ShengweiPeng/Qwen3-0.6B-Taiwan",
237
+ "description": "Qwen3-Taiwan model with 0.6 B parameters",
238
+ "params_b": 0.6
239
+ },
240
+
241
+ # 500M
242
+ "Qwen2.5-0.5B-Taiwan-Instruct": {
243
+ "repo_id": "ShengweiPeng/Qwen2.5-0.5B-Taiwan-Instruct",
244
+ "description": "Qwen2.5-Taiwan model with 0.5 B parameters, instruction-tuned",
245
+ "params_b": 0.5
246
+ },
247
+
248
+ # 360M
249
+ "SmolLM2-360M-Instruct": {
250
+ "repo_id": "HuggingFaceTB/SmolLM2-360M-Instruct",
251
+ "description": "Original SmolLM2‑360M Instruct",
252
+ "params_b": 0.36
253
+ },
254
+ "SmolLM2-360M-Instruct-TaiwanChat": {
255
+ "repo_id": "Luigi/SmolLM2-360M-Instruct-TaiwanChat",
256
+ "description": "SmolLM2‑360M Instruct fine-tuned on TaiwanChat",
257
+ "params_b": 0.36
258
+ },
259
+
260
+ # 350M
261
+ "LFM2-350M": {
262
+ "repo_id": "LiquidAI/LFM2-350M",
263
+ "description": "A compact 350M parameter hybrid model optimized for edge and on-device applications, offering significantly faster training and inference speeds compared to models like Qwen3.",
264
+ "params_b": 0.35
265
+ },
266
+
267
+ # 270M
268
+ "parser_model_ner_gemma_v0.1": {
269
+ "repo_id": "myfi/parser_model_ner_gemma_v0.1",
270
+ "description": "A lightweight named‑entity‑like (NER) parser fine‑tuned from Google’s **Gemma‑3‑270M** model. The base Gemma‑3‑270M is a 270 M‑parameter, hyper‑efficient LLM designed for on‑device inference, supporting >140 languages, a 128 k‑token context window, and instruction‑following capabilities [2][7]. This variant is further trained on standard NER corpora (e.g., CoNLL‑2003, OntoNotes) to extract PERSON, ORG, LOC, and MISC entities with high precision while keeping the memory footprint low (≈240 MB VRAM in BF16 quantized form) [1]. It is released under the Apache‑2.0 license and can be used for fast, cost‑effective entity extraction in low‑resource environments.",
271
+ "params_b": 0.27
272
+ },
273
+ "Gemma-3-Taiwan-270M-it": {
274
+ "repo_id": "lianghsun/Gemma-3-Taiwan-270M-it",
275
+ "description": "google/gemma-3-270m-it fintuned on Taiwan Chinese dataset",
276
+ "params_b": 0.27
277
+ },
278
+ "gemma-3-270m-it": {
279
+ "repo_id": "google/gemma-3-270m-it",
280
+ "description": "Gemma‑3‑270M‑IT is a compact, 270‑million‑parameter language model fine‑tuned for Italian, offering fast and efficient on‑device text generation and comprehension in the Italian language.",
281
+ "params_b": 0.27
282
+ },
283
+ "Taiwan-ELM-270M-Instruct": {
284
+ "repo_id": "liswei/Taiwan-ELM-270M-Instruct",
285
+ "description": "Taiwan-ELM-270M-Instruct",
286
+ "params_b": 0.27
287
+ },
288
+
289
+ # 135M
290
+ "SmolLM2-135M-multilingual-base": {
291
+ "repo_id": "agentlans/SmolLM2-135M-multilingual-base",
292
+ "description": "SmolLM2-135M-multilingual-base",
293
+ "params_b": 0.135
294
+ },
295
+ "SmolLM-135M-Taiwan-Instruct-v1.0": {
296
+ "repo_id": "benchang1110/SmolLM-135M-Taiwan-Instruct-v1.0",
297
+ "description": "135-million-parameter F32 safetensors instruction-finetuned variant of SmolLM-135M-Taiwan, trained on the 416 k-example ChatTaiwan dataset for Traditional Chinese conversational and instruction-following tasks",
298
+ "params_b": 0.135
299
+ },
300
+ "SmolLM2_135M_Grpo_Gsm8k": {
301
+ "repo_id": "prithivMLmods/SmolLM2_135M_Grpo_Gsm8k",
302
+ "description": "SmolLM2_135M_Grpo_Gsm8k",
303
+ "params_b": 0.135
304
+ },
305
+ "SmolLM2-135M-Instruct": {
306
+ "repo_id": "HuggingFaceTB/SmolLM2-135M-Instruct",
307
+ "description": "Original SmolLM2‑135M Instruct",
308
+ "params_b": 0.135
309
+ },
310
+ "SmolLM2-135M-Instruct-TaiwanChat": {
311
+ "repo_id": "Luigi/SmolLM2-135M-Instruct-TaiwanChat",
312
+ "description": "SmolLM2‑135M Instruct fine-tuned on TaiwanChat",
313
+ "params_b": 0.135
314
+ },
315
+ }
316
+
317
+ # Global cache for pipelines to avoid re-loading.
318
+ PIPELINES = {}
319
+
320
+ def load_pipeline(model_name):
321
+ """
322
+ Load and cache a transformers pipeline for text generation.
323
+ Tries bfloat16, falls back to float16 or float32 if unsupported.
324
+ """
325
+ global PIPELINES
326
+ if model_name in PIPELINES:
327
+ return PIPELINES[model_name]
328
+ repo = MODELS[model_name]["repo_id"]
329
+ tokenizer = AutoTokenizer.from_pretrained(repo,
330
+ token=access_token)
331
+ for dtype in (torch.bfloat16, torch.float16, torch.float32):
332
+ try:
333
+ pipe = pipeline(
334
+ task="text-generation",
335
+ model=repo,
336
+ tokenizer=tokenizer,
337
+ trust_remote_code=True,
338
+ dtype=dtype, # Use `dtype` instead of deprecated `torch_dtype`
339
+ device_map="auto",
340
+ use_cache=True, # Enable past-key-value caching
341
+ token=access_token)
342
+ PIPELINES[model_name] = pipe
343
+ return pipe
344
+ except Exception:
345
+ continue
346
+ # Final fallback
347
+ pipe = pipeline(
348
+ task="text-generation",
349
+ model=repo,
350
+ tokenizer=tokenizer,
351
+ trust_remote_code=True,
352
+ device_map="auto",
353
+ use_cache=True
354
+ )
355
+ PIPELINES[model_name] = pipe
356
+ return pipe
357
+
358
+
359
+ def retrieve_context(query, max_results=6, max_chars=50):
360
  """
361
+ Retrieve search snippets from DuckDuckGo (runs in background).
362
+ Returns a list of result strings.
363
  """
364
+ try:
365
+ with DDGS() as ddgs:
366
+ return [f"{i+1}. {r.get('title','No Title')} - {r.get('body','')[:max_chars]}"
367
+ for i, r in enumerate(islice(ddgs.text(query, region="wt-wt", safesearch="off", timelimit="y"), max_results))]
368
+ except Exception:
369
+ return []
370
+
371
+ def format_conversation(history, system_prompt, tokenizer):
372
+ if hasattr(tokenizer, "chat_template") and tokenizer.chat_template:
373
+ messages = [{"role": "system", "content": system_prompt.strip()}] + history
374
+ return tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True, enable_thinking=True)
375
+ else:
376
+ # Fallback for base LMs without chat template
377
+ prompt = system_prompt.strip() + "\n"
378
+ for msg in history:
379
+ if msg['role'] == 'user':
380
+ prompt += "User: " + msg['content'].strip() + "\n"
381
+ elif msg['role'] == 'assistant':
382
+ prompt += "Assistant: " + msg['content'].strip() + "\n"
383
+ if not prompt.strip().endswith("Assistant:"):
384
+ prompt += "Assistant: "
385
+ return prompt
386
+
387
+ def get_duration(user_msg, chat_history, system_prompt, enable_search, max_results, max_chars, model_name, max_tokens, temperature, top_k, top_p, repeat_penalty, search_timeout):
388
+ # Get model size from the MODELS dict (more reliable than string parsing)
389
+ model_size = MODELS[model_name].get("params_b", 4.0) # Default to 4B if not found
390
 
391
+ # Only use AOT for models >= 2B parameters
392
+ use_aot = model_size >= 2
393
 
394
+ # Adjusted for H200 performance: faster inference, quicker compilation
395
+ base_duration = 20 if not use_aot else 40 # Reduced base times
396
+ token_duration = max_tokens * 0.005 # ~200 tokens/second average on H200
397
+ search_duration = 10 if enable_search else 0 # Reduced search time
398
+ aot_compilation_buffer = 20 if use_aot else 0 # Faster compilation on H200
 
 
399
 
400
+ return base_duration + token_duration + search_duration + aot_compilation_buffer
401
+
402
+ @spaces.GPU(duration=get_duration)
403
+ def chat_response(user_msg, chat_history, system_prompt,
404
+ enable_search, max_results, max_chars,
405
+ model_name, max_tokens, temperature,
406
+ top_k, top_p, repeat_penalty, search_timeout):
407
+ """
408
+ Generates streaming chat responses, optionally with background web search.
409
+ This version includes cancellation support.
410
+ """
411
+ # Clear the cancellation event at the start of a new generation
412
+ cancel_event.clear()
413
 
414
+ history = list(chat_history or [])
415
+ history.append({'role': 'user', 'content': user_msg})
416
+
417
+ # Launch web search if enabled
418
+ debug = ''
419
+ search_results = []
420
+ if enable_search:
421
+ debug = 'Search task started.'
422
+ thread_search = threading.Thread(
423
+ target=lambda: search_results.extend(
424
+ retrieve_context(user_msg, int(max_results), int(max_chars))
425
  )
426
+ )
427
+ thread_search.daemon = True
428
+ thread_search.start()
429
+ else:
430
+ debug = 'Web search disabled.'
431
+
432
+ try:
433
+ cur_date = datetime.now().strftime('%Y-%m-%d')
434
+ # merge any fetched search results into the system prompt
435
+ if search_results:
436
+
437
+ enriched = system_prompt.strip() + \
438
+ f'''\n# The following contents are the search results related to the user's message:
439
+ {search_results}
440
+ In the search results I provide to you, each result is formatted as [webpage X begin]...[webpage X end], where X represents the numerical index of each article. Please cite the context at the end of the relevant sentence when appropriate. Use the citation format [citation:X] in the corresponding part of your answer. If a sentence is derived from multiple contexts, list all relevant citation numbers, such as [citation:3][citation:5]. Be sure not to cluster all citations at the end; instead, include them in the corresponding parts of the answer.
441
+ When responding, please keep the following points in mind:
442
+ - Today is {cur_date}.
443
+ - Not all content in the search results is closely related to the user's question. You need to evaluate and filter the search results based on the question.
444
+ - For listing-type questions (e.g., listing all flight information), try to limit the answer to 10 key points and inform the user that they can refer to the search sources for complete information. Prioritize providing the most complete and relevant items in the list. Avoid mentioning content not provided in the search results unless necessary.
445
+ - For creative tasks (e.g., writing an essay), ensure that references are cited within the body of the text, such as [citation:3][citation:5], rather than only at the end of the text. You need to interpret and summarize the user's requirements, choose an appropriate format, fully utilize the search results, extract key information, and generate an answer that is insightful, creative, and professional. Extend the length of your response as much as possible, addressing each point in detail and from multiple perspectives, ensuring the content is rich and thorough.
446
+ - If the response is lengthy, structure it well and summarize it in paragraphs. If a point-by-point format is needed, try to limit it to 5 points and merge related content.
447
+ - For objective Q&A, if the answer is very brief, you may add one or two related sentences to enrich the content.
448
+ - Choose an appropriate and visually appealing format for your response based on the user's requirements and the content of the answer, ensuring strong readability.
449
+ - Your answer should synthesize information from multiple relevant webpages and avoid repeatedly citing the same webpage.
450
+ - Unless the user requests otherwise, your response should be in the same language as the user's question.
451
+ # The user's message is:
452
+ '''
453
+ else:
454
+ enriched = system_prompt
455
+
456
+ # wait up to 1s for snippets, then replace debug with them
457
+ if enable_search:
458
+ thread_search.join(timeout=float(search_timeout))
459
+ if search_results:
460
+ debug = "### Search results merged into prompt\n\n" + "\n".join(
461
+ f"- {r}" for r in search_results
462
+ )
463
+ else:
464
+ debug = "*No web search results found.*"
465
+
466
+ # merge fetched snippets into the system prompt
467
+ if search_results:
468
+ enriched = system_prompt.strip() + \
469
+ f'''\n# The following contents are the search results related to the user's message:
470
+ {search_results}
471
+ In the search results I provide to you, each result is formatted as [webpage X begin]...[webpage X end], where X represents the numerical index of each article. Please cite the context at the end of the relevant sentence when appropriate. Use the citation format [citation:X] in the corresponding part of your answer. If a sentence is derived from multiple contexts, list all relevant citation numbers, such as [citation:3][citation:5]. Be sure not to cluster all citations at the end; instead, include them in the corresponding parts of the answer.
472
+ When responding, please keep the following points in mind:
473
+ - Today is {cur_date}.
474
+ - Not all content in the search results is closely related to the user's question. You need to evaluate and filter the search results based on the question.
475
+ - For listing-type questions (e.g., listing all flight information), try to limit the answer to 10 key points and inform the user that they can refer to the search sources for complete information. Prioritize providing the most complete and relevant items in the list. Avoid mentioning content not provided in the search results unless necessary.
476
+ - For creative tasks (e.g., writing an essay), ensure that references are cited within the body of the text, such as [citation:3][citation:5], rather than only at the end of the text. You need to interpret and summarize the user's requirements, choose an appropriate format, fully utilize the search results, extract key information, and generate an answer that is insightful, creative, and professional. Extend the length of your response as much as possible, addressing each point in detail and from multiple perspectives, ensuring the content is rich and thorough.
477
+ - If the response is lengthy, structure it well and summarize it in paragraphs. If a point-by-point format is needed, try to limit it to 5 points and merge related content.
478
+ - For objective Q&A, if the answer is very brief, you may add one or two related sentences to enrich the content.
479
+ - Choose an appropriate and visually appealing format for your response based on the user's requirements and the content of the answer, ensuring strong readability.
480
+ - Your answer should synthesize information from multiple relevant webpages and avoid repeatedly citing the same webpage.
481
+ - Unless the user requests otherwise, your response should be in the same language as the user's question.
482
+ # The user's message is:
483
+ '''
484
+ else:
485
+ enriched = system_prompt
486
+
487
+ pipe = load_pipeline(model_name)
488
+
489
+ prompt = format_conversation(history, enriched, pipe.tokenizer)
490
+ prompt_debug = f"\n\n--- Prompt Preview ---\n```\n{prompt}\n```"
491
+ streamer = TextIteratorStreamer(pipe.tokenizer,
492
+ skip_prompt=True,
493
+ skip_special_tokens=True)
494
+ gen_thread = threading.Thread(
495
+ target=pipe,
496
+ args=(prompt,),
497
+ kwargs={
498
+ 'max_new_tokens': max_tokens,
499
+ 'temperature': temperature,
500
+ 'top_k': top_k,
501
+ 'top_p': top_p,
502
+ 'repetition_penalty': repeat_penalty,
503
+ 'streamer': streamer,
504
+ 'return_full_text': False,
505
+ }
506
+ )
507
+ gen_thread.start()
508
+
509
+ # Buffers for thought vs answer
510
+ thought_buf = ''
511
+ answer_buf = ''
512
+ in_thought = False
513
+ assistant_message_started = False
514
+
515
+ # First yield contains the user message
516
+ yield history, debug
517
+
518
+ # Stream tokens
519
+ for chunk in streamer:
520
+ # Check for cancellation signal
521
+ if cancel_event.is_set():
522
+ if assistant_message_started and history and history[-1]['role'] == 'assistant':
523
+ history[-1]['content'] += " [Generation Canceled]"
524
+ yield history, debug
525
+ break
526
+
527
+ text = chunk
528
+
529
+ # Detect start of thinking
530
+ if not in_thought and '<think>' in text:
531
+ in_thought = True
532
+ history.append({'role': 'assistant', 'content': '', 'metadata': {'title': '💭 Thought'}})
533
+ assistant_message_started = True
534
+ after = text.split('<think>', 1)[1]
535
+ thought_buf += after
536
+ if '</think>' in thought_buf:
537
+ before, after2 = thought_buf.split('</think>', 1)
538
+ history[-1]['content'] = before.strip()
539
+ in_thought = False
540
+ answer_buf = after2
541
+ history.append({'role': 'assistant', 'content': answer_buf})
542
+ else:
543
+ history[-1]['content'] = thought_buf
544
+ yield history, debug
545
+ continue
546
+
547
+ if in_thought:
548
+ thought_buf += text
549
+ if '</think>' in thought_buf:
550
+ before, after2 = thought_buf.split('</think>', 1)
551
+ history[-1]['content'] = before.strip()
552
+ in_thought = False
553
+ answer_buf = after2
554
+ history.append({'role': 'assistant', 'content': answer_buf})
555
+ else:
556
+ history[-1]['content'] = thought_buf
557
+ yield history, debug
558
+ continue
559
+
560
+ # Stream answer
561
+ if not assistant_message_started:
562
+ history.append({'role': 'assistant', 'content': ''})
563
+ assistant_message_started = True
564
+
565
+ answer_buf += text
566
+ history[-1]['content'] = answer_buf.strip()
567
+ yield history, debug
568
+
569
+ gen_thread.join()
570
+ yield history, debug + prompt_debug
571
+ except GeneratorExit:
572
+ # Handle cancellation gracefully
573
+ print("Chat response cancelled.")
574
+ # Don't yield anything - let the cancellation propagate
575
+ return
576
+ except Exception as e:
577
+ history.append({'role': 'assistant', 'content': f"Error: {e}"})
578
+ yield history, debug
579
  finally:
580
+ gc.collect()
 
 
 
 
 
581
 
582
+
583
+ def update_default_prompt(enable_search):
584
+ return f"You are a helpful assistant."
585
+
586
+ def update_duration_estimate(model_name, enable_search, max_results, max_chars, max_tokens, search_timeout):
587
+ """Calculate and format the estimated GPU duration for current settings."""
588
+ try:
589
+ dummy_msg, dummy_history, dummy_system_prompt = "", [], ""
590
+ duration = get_duration(dummy_msg, dummy_history, dummy_system_prompt,
591
+ enable_search, max_results, max_chars, model_name,
592
+ max_tokens, 0.7, 40, 0.9, 1.2, search_timeout)
593
+ model_size = MODELS[model_name].get("params_b", 4.0)
594
+ return (f"⏱️ **Estimated GPU Time: {duration:.1f} seconds**\n\n"
595
+ f"📊 **Model Size:** {model_size:.1f}B parameters\n"
596
+ f"🔍 **Web Search:** {'Enabled' if enable_search else 'Disabled'}")
597
+ except Exception as e:
598
+ return f"⚠️ Error calculating estimate: {e}"
599
+
600
+ # ------------------------------
601
  # Gradio UI
602
+ # ------------------------------
603
  with gr.Blocks(
604
+ title="LLM Inference with ZeroGPU",
605
  theme=gr.themes.Soft(
606
  primary_hue="indigo",
607
  secondary_hue="purple",
608
  neutral_hue="slate",
609
  radius_size="lg",
610
+ font=[gr.themes.GoogleFont("Inter"), "Arial", "sans-serif"]
611
  ),
612
  css="""
613
+ .duration-estimate { background: linear-gradient(135deg, #667eea15 0%, #764ba215 100%); border-left: 4px solid #667eea; padding: 12px; border-radius: 8px; margin: 16px 0; }
614
+ .chatbot { border-radius: 12px; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); }
615
+ button.primary { font-weight: 600; }
616
+ .gradio-accordion { margin-bottom: 12px; }
 
 
 
 
 
 
 
 
 
 
617
  """
618
  ) as demo:
619
  # Header
620
  gr.Markdown("""
621
+ # 🧠 ZeroGPU LLM Inference
622
+ ### Powered by Hugging Face ZeroGPU with Web Search Integration
 
 
623
  """)
624
 
625
  with gr.Row():
626
+ # Left Panel - Configuration
627
+ with gr.Column(scale=3):
628
+ # Core Settings (Always Visible)
629
+ with gr.Group():
630
+ gr.Markdown("### ⚙️ Core Settings")
631
+ model_dd = gr.Dropdown(
632
+ label="🤖 Model",
633
+ choices=list(MODELS.keys()),
634
+ value="Qwen3-1.7B",
635
+ info="Select the language model to use"
636
+ )
637
+ search_chk = gr.Checkbox(
638
+ label="🔍 Enable Web Search",
639
+ value=False,
640
+ info="Augment responses with real-time web data"
641
+ )
642
+ sys_prompt = gr.Textbox(
643
+ label="📝 System Prompt",
644
+ lines=3,
645
+ value=update_default_prompt(search_chk.value),
646
+ placeholder="Define the assistant's behavior and personality..."
647
+ )
648
+
649
+ # Duration Estimate
650
+ duration_display = gr.Markdown(
651
+ value=update_duration_estimate("Qwen3-1.7B", False, 4, 50, 1024, 5.0),
652
+ elem_classes="duration-estimate"
653
  )
654
 
655
+ # Advanced Settings (Collapsible)
656
+ with gr.Accordion("🎛️ Advanced Generation Parameters", open=False):
657
+ max_tok = gr.Slider(
658
+ 64, 16384, value=1024, step=32,
659
+ label="Max Tokens",
660
+ info="Maximum length of generated response"
 
 
661
  )
662
+ temp = gr.Slider(
663
+ 0.1, 2.0, value=0.7, step=0.1,
 
 
 
664
  label="Temperature",
665
+ info="Higher = more creative, Lower = more focused"
666
  )
667
+ with gr.Row():
668
+ k = gr.Slider(
669
+ 1, 100, value=40, step=1,
670
+ label="Top-K",
671
+ info="Number of top tokens to consider"
672
+ )
673
+ p = gr.Slider(
674
+ 0.1, 1.0, value=0.9, step=0.05,
675
+ label="Top-P",
676
+ info="Nucleus sampling threshold"
677
+ )
678
+ rp = gr.Slider(
679
+ 1.0, 2.0, value=1.2, step=0.1,
680
+ label="Repetition Penalty",
681
+ info="Penalize repeated tokens"
682
  )
683
 
684
+ # Web Search Settings (Collapsible)
685
+ with gr.Accordion("🌐 Web Search Settings", open=False, visible=False) as search_settings:
686
+ mr = gr.Number(
687
+ value=4, precision=0,
688
+ label="Max Results",
689
+ info="Number of search results to retrieve"
690
+ )
691
+ mc = gr.Number(
692
+ value=50, precision=0,
693
+ label="Max Chars/Result",
694
+ info="Character limit per search result"
695
+ )
696
+ st = gr.Slider(
697
+ minimum=0.0, maximum=30.0, step=0.5, value=5.0,
698
+ label="Search Timeout (s)",
699
+ info="Maximum time to wait for search results"
700
+ )
701
+
702
+ # Actions
703
+ with gr.Row():
704
+ clr = gr.Button("🗑️ Clear Chat", variant="secondary", scale=1)
705
 
706
+ # Right Panel - Chat Interface
707
+ with gr.Column(scale=7):
708
+ chat = gr.Chatbot(
709
+ type="messages",
710
+ height=600,
711
+ label="💬 Conversation",
 
712
  show_copy_button=True,
713
+ avatar_images=(None, "🤖"),
714
+ bubble_full_width=False
715
  )
716
 
717
+ # Input Area
718
+ with gr.Row():
719
+ txt = gr.Textbox(
720
+ placeholder="💭 Type your message here... (Press Enter to send)",
721
+ scale=9,
722
+ container=False,
723
+ show_label=False,
724
+ lines=1,
725
+ max_lines=5
726
+ )
727
+ with gr.Column(scale=1, min_width=120):
728
+ submit_btn = gr.Button("📤 Send", variant="primary", size="lg")
729
+ cancel_btn = gr.Button("⏹️ Stop", variant="stop", visible=False, size="lg")
730
+
731
+ # Example Prompts
732
+ gr.Examples(
733
+ examples=[
734
+ ["Explain quantum computing in simple terms"],
735
+ ["Write a Python function to calculate fibonacci numbers"],
736
+ ["What are the latest developments in AI? (Enable web search)"],
737
+ ["Tell me a creative story about a time traveler"],
738
+ ["Help me debug this code: def add(a,b): return a+b+1"]
739
+ ],
740
+ inputs=txt,
741
+ label="💡 Example Prompts"
742
+ )
743
+
744
+ # Debug/Status Info (Collapsible)
745
+ with gr.Accordion("🔍 Debug Info", open=False):
746
+ dbg = gr.Markdown()
747
 
748
+ # Footer
749
+ gr.Markdown("""
750
+ ---
751
+ 💡 **Tips:**
752
+ - Use **Advanced Parameters** to fine-tune creativity and response length
753
+ - Enable **Web Search** for real-time, up-to-date information
754
+ - Try different **models** for various tasks (reasoning, coding, general chat)
755
+ - Click the **Copy** button on responses to save them to your clipboard
756
+ """, elem_classes="footer")
757
+
758
+ # --- Event Listeners ---
759
+
760
+ # Group all inputs for cleaner event handling
761
+ chat_inputs = [txt, chat, sys_prompt, search_chk, mr, mc, model_dd, max_tok, temp, k, p, rp, st]
762
+ # Group all UI components that can be updated.
763
+ ui_components = [chat, dbg, txt, submit_btn, cancel_btn]
764
+
765
+ def submit_and_manage_ui(user_msg, chat_history, *args):
766
+ """
767
+ Orchestrator function that manages UI state and calls the backend chat function.
768
+ It uses a try...finally block to ensure the UI is always reset.
769
+ """
770
+ if not user_msg.strip():
771
+ # If the message is empty, do nothing.
772
+ # We yield an empty dict to avoid any state changes.
773
+ yield {}
774
+ return
775
+
776
+ # 1. Update UI to "generating" state.
777
+ # Crucially, we do NOT update the `chat` component here, as the backend
778
+ # will provide the correctly formatted history in the first response chunk.
779
+ yield {
780
+ txt: gr.update(value="", interactive=False),
781
+ submit_btn: gr.update(interactive=False),
782
+ cancel_btn: gr.update(visible=True),
783
+ }
784
+
785
+ cancelled = False
786
+ try:
787
+ # 2. Call the backend and stream updates
788
+ backend_args = [user_msg, chat_history] + list(args)
789
+ for response_chunk in chat_response(*backend_args):
790
+ yield {
791
+ chat: response_chunk[0],
792
+ dbg: response_chunk[1],
793
+ }
794
+ except GeneratorExit:
795
+ # Mark as cancelled and re-raise to prevent "generator ignored GeneratorExit"
796
+ cancelled = True
797
+ print("Generation cancelled by user.")
798
+ raise
799
+ except Exception as e:
800
+ print(f"An error occurred during generation: {e}")
801
+ # If an error happens, add it to the chat history to inform the user.
802
+ error_history = (chat_history or []) + [
803
+ {'role': 'user', 'content': user_msg},
804
+ {'role': 'assistant', 'content': f"**An error occurred:** {str(e)}"}
805
+ ]
806
+ yield {chat: error_history}
807
+ finally:
808
+ # Only reset UI if not cancelled (to avoid "generator ignored GeneratorExit")
809
+ if not cancelled:
810
+ print("Resetting UI state.")
811
+ yield {
812
+ txt: gr.update(interactive=True),
813
+ submit_btn: gr.update(interactive=True),
814
+ cancel_btn: gr.update(visible=False),
815
+ }
816
+
817
+ def set_cancel_flag():
818
+ """Called by the cancel button, sets the global event."""
819
+ cancel_event.set()
820
+ print("Cancellation signal sent.")
821
 
822
+ def reset_ui_after_cancel():
823
+ """Reset UI components after cancellation."""
824
+ cancel_event.clear() # Clear the flag for next generation
825
+ print("UI reset after cancellation.")
826
+ return {
827
+ txt: gr.update(interactive=True),
828
+ submit_btn: gr.update(interactive=True),
829
+ cancel_btn: gr.update(visible=False),
830
+ }
831
+
832
+ # Event for submitting text via Enter key or Submit button
833
+ submit_event = txt.submit(
834
+ fn=submit_and_manage_ui,
835
+ inputs=chat_inputs,
836
+ outputs=ui_components,
837
+ )
838
+ submit_btn.click(
839
+ fn=submit_and_manage_ui,
840
+ inputs=chat_inputs,
841
+ outputs=ui_components,
842
  )
843
 
844
+ # Event for the "Cancel" button.
845
+ # It sets the cancel flag, cancels the submit event, then resets the UI.
846
+ cancel_btn.click(
847
+ fn=set_cancel_flag,
848
+ cancels=[submit_event]
849
+ ).then(
850
+ fn=reset_ui_after_cancel,
851
+ outputs=ui_components
852
+ )
853
+
854
+ # Listeners for updating the duration estimate
855
+ duration_inputs = [model_dd, search_chk, mr, mc, max_tok, st]
856
+ for component in duration_inputs:
857
+ component.change(fn=update_duration_estimate, inputs=duration_inputs, outputs=duration_display)
858
+
859
+ # Toggle web search settings visibility
860
+ def toggle_search_settings(enabled):
861
+ return gr.update(visible=enabled)
862
+
863
+ search_chk.change(
864
+ fn=lambda enabled: (update_default_prompt(enabled), gr.update(visible=enabled)),
865
+ inputs=search_chk,
866
+ outputs=[sys_prompt, search_settings]
867
+ )
868
+
869
+ # Clear chat action
870
+ clr.click(fn=lambda: ([], "", ""), outputs=[chat, txt, dbg])
871
+
872
+ demo.launch()
apt.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ rustc
2
+ cargo
requirements.txt CHANGED
@@ -1,9 +1,12 @@
1
- bitsandbytes>=0.41.0
2
- fastapi>=0.110.0
3
- accelerate>=0.25.0
4
- spaces>=0.40.0
5
- torch>=2.1.0
6
- transformers>=4.40.0
7
- uvicorn>=0.22.0
8
- sentencepiece>=0.1.99
9
- gradio>=4.0.0
 
 
 
 
1
+ wheel
2
+ streamlit
3
+ ddgs
4
+ gradio>=5.0.0
5
+ torch>=2.8.0
6
+ transformers>=4.53.3
7
+ spaces
8
+ sentencepiece
9
+ accelerate
10
+ autoawq
11
+ timm
12
+ compressed-tensors
style.css ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Custom CSS for LLM Inference Interface */
2
+
3
+ /* Header styling */
4
+ .markdown h1 {
5
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
6
+ -webkit-background-clip: text;
7
+ -webkit-text-fill-color: transparent;
8
+ background-clip: text;
9
+ font-weight: 800;
10
+ margin-bottom: 0.5rem;
11
+ }
12
+
13
+ .markdown h3 {
14
+ color: #4a5568;
15
+ font-weight: 600;
16
+ margin-top: 0.25rem;
17
+ }
18
+
19
+ /* Duration estimate styling */
20
+ .duration-estimate {
21
+ background: linear-gradient(135deg, #667eea15 0%, #764ba215 100%);
22
+ border-left: 4px solid #667eea;
23
+ padding: 12px;
24
+ border-radius: 8px;
25
+ margin: 16px 0;
26
+ font-size: 0.9em;
27
+ }
28
+
29
+ /* Group styling for better visual separation */
30
+ .gradio-group {
31
+ border: 1px solid #e2e8f0;
32
+ border-radius: 12px;
33
+ padding: 16px;
34
+ background: #f8fafc;
35
+ margin-bottom: 16px;
36
+ }
37
+
38
+ /* Accordion styling */
39
+ .gradio-accordion {
40
+ border: 1px solid #e2e8f0;
41
+ border-radius: 8px;
42
+ margin-bottom: 12px;
43
+ }
44
+
45
+ .gradio-accordion .label-wrap {
46
+ background: #f1f5f9;
47
+ font-weight: 600;
48
+ }
49
+
50
+ /* Chat interface improvements */
51
+ .chatbot {
52
+ border-radius: 12px;
53
+ border: 1px solid #e2e8f0;
54
+ box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
55
+ }
56
+
57
+ /* Input area styling */
58
+ .textbox-container {
59
+ border-radius: 24px;
60
+ border: 2px solid #e2e8f0;
61
+ transition: border-color 0.2s;
62
+ }
63
+
64
+ .textbox-container:focus-within {
65
+ border-color: #667eea;
66
+ box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
67
+ }
68
+
69
+ /* Button improvements */
70
+ .gradio-button {
71
+ border-radius: 8px;
72
+ font-weight: 600;
73
+ transition: all 0.2s;
74
+ }
75
+
76
+ .gradio-button.primary {
77
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
78
+ border: none;
79
+ }
80
+
81
+ .gradio-button.primary:hover {
82
+ transform: translateY(-2px);
83
+ box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
84
+ }
85
+
86
+ .gradio-button.secondary {
87
+ border: 2px solid #e2e8f0;
88
+ background: white;
89
+ }
90
+
91
+ .gradio-button.secondary:hover {
92
+ border-color: #cbd5e0;
93
+ background: #f7fafc;
94
+ }
95
+
96
+ /* Slider styling */
97
+ .gradio-slider {
98
+ margin: 8px 0;
99
+ }
100
+
101
+ .gradio-slider input[type="range"] {
102
+ accent-color: #667eea;
103
+ }
104
+
105
+ /* Info text styling */
106
+ .info {
107
+ color: #718096;
108
+ font-size: 0.85em;
109
+ font-style: italic;
110
+ }
111
+
112
+ /* Footer styling */
113
+ .footer .markdown {
114
+ text-align: center;
115
+ color: #718096;
116
+ font-size: 0.9em;
117
+ padding: 16px;
118
+ background: #f8fafc;
119
+ border-radius: 8px;
120
+ }
121
+
122
+ /* Responsive adjustments */
123
+ @media (max-width: 768px) {
124
+ .gradio-row {
125
+ flex-direction: column;
126
+ }
127
+
128
+ .chatbot {
129
+ height: 400px !important;
130
+ }
131
+ }
132
+
133
+ /* Loading animation */
134
+ @keyframes pulse {
135
+ 0%, 100% {
136
+ opacity: 1;
137
+ }
138
+ 50% {
139
+ opacity: 0.5;
140
+ }
141
+ }
142
+
143
+ .generating {
144
+ animation: pulse 1.5s ease-in-out infinite;
145
+ }
146
+
147
+ /* Smooth transitions */
148
+ * {
149
+ transition: background-color 0.2s, border-color 0.2s;
150
+ }
test_api.py CHANGED
@@ -14,14 +14,25 @@ def test_healthcheck():
14
  try:
15
  response = requests.get(f"{BASE_URL}/health", timeout=10)
16
  print(f"Status: {response.status_code}")
 
 
 
 
17
  if response.status_code == 200:
18
- print(f"Response: {json.dumps(response.json(), indent=2)}")
19
- return True
 
 
 
 
 
20
  else:
21
- print(f"Error: {response.text}")
22
  return False
23
  except Exception as e:
24
  print(f"Exception: {e}")
 
 
25
  return False
26
 
27
  def test_generate():
@@ -38,33 +49,57 @@ def test_generate():
38
  f"{BASE_URL}/v1/generate",
39
  json=payload,
40
  headers={"Content-Type": "application/json"},
41
- timeout=60 # Longer timeout for model loading
42
  )
43
  print(f"Status: {response.status_code}")
 
 
44
  if response.status_code == 200:
45
- result = response.json()
46
- print(f"Response keys: {list(result.keys())}")
47
- if "text" in result:
48
- print(f"Generated text (first 200 chars): {result['text'][:200]}...")
49
- else:
50
- print(f"Full response: {json.dumps(result, indent=2)}")
51
- return True
 
 
 
 
52
  else:
53
- print(f"Error: {response.text}")
54
  return False
55
  except Exception as e:
56
  print(f"Exception: {e}")
 
 
57
  return False
58
 
59
- def test_gradio_ui():
60
- """Test the Gradio UI endpoint."""
61
- print("\nTesting GET /gradio (UI redirect target)...")
62
  try:
63
- response = requests.get(f"{BASE_URL}/gradio", timeout=10)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  print(f"Status: {response.status_code}")
65
  if response.status_code == 200:
66
- print(f"Response length: {len(response.text)} chars")
67
- print(f"Response type: {response.headers.get('content-type', 'unknown')}")
68
  return True
69
  else:
70
  print(f"Error: {response.text[:200]}")
@@ -73,6 +108,21 @@ def test_gradio_ui():
73
  print(f"Exception: {e}")
74
  return False
75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  def main():
77
  """Run all API tests."""
78
  print("=" * 60)
@@ -81,15 +131,16 @@ def main():
81
  print(f"Base URL: {BASE_URL}\n")
82
 
83
  # Wait a moment for Space to be ready
84
- print("Waiting 5 seconds for Space to be ready...")
85
- time.sleep(5)
86
 
87
  results = []
88
 
89
  # Test endpoints
 
90
  results.append(("Health Check", test_healthcheck()))
91
  results.append(("Generate", test_generate()))
92
- results.append(("Gradio UI", test_gradio_ui()))
93
 
94
  # Summary
95
  print("\n" + "=" * 60)
 
14
  try:
15
  response = requests.get(f"{BASE_URL}/health", timeout=10)
16
  print(f"Status: {response.status_code}")
17
+ print(f"Headers: {dict(response.headers)}")
18
+ print(f"Content-Type: {response.headers.get('content-type', 'unknown')}")
19
+ print(f"Response length: {len(response.text)} bytes")
20
+
21
  if response.status_code == 200:
22
+ try:
23
+ data = response.json()
24
+ print(f"Response: {json.dumps(data, indent=2)}")
25
+ return True
26
+ except json.JSONDecodeError:
27
+ print(f"Not JSON. First 200 chars: {response.text[:200]}")
28
+ return False
29
  else:
30
+ print(f"Error: {response.text[:200]}")
31
  return False
32
  except Exception as e:
33
  print(f"Exception: {e}")
34
+ import traceback
35
+ traceback.print_exc()
36
  return False
37
 
38
  def test_generate():
 
49
  f"{BASE_URL}/v1/generate",
50
  json=payload,
51
  headers={"Content-Type": "application/json"},
52
+ timeout=120 # Longer timeout for model loading
53
  )
54
  print(f"Status: {response.status_code}")
55
+ print(f"Headers: {dict(response.headers)}")
56
+
57
  if response.status_code == 200:
58
+ try:
59
+ result = response.json()
60
+ print(f"Response keys: {list(result.keys())}")
61
+ if "text" in result:
62
+ print(f"Generated text (first 300 chars): {result['text'][:300]}...")
63
+ else:
64
+ print(f"Full response: {json.dumps(result, indent=2)}")
65
+ return True
66
+ except json.JSONDecodeError:
67
+ print(f"Not JSON. First 200 chars: {response.text[:200]}")
68
+ return False
69
  else:
70
+ print(f"Error: {response.text[:500]}")
71
  return False
72
  except Exception as e:
73
  print(f"Exception: {e}")
74
+ import traceback
75
+ traceback.print_exc()
76
  return False
77
 
78
+ def test_gradio_api():
79
+ """Test Gradio's built-in API endpoint."""
80
+ print("\nTesting Gradio API /api/predict...")
81
  try:
82
+ # Gradio creates /api/predict endpoints automatically
83
+ # We need to find the function index - usually 0 for the first function
84
+ payload = {
85
+ "data": [
86
+ "You are a router agent. User query: What is 2+2?",
87
+ 100,
88
+ 0.2,
89
+ 0.9
90
+ ],
91
+ "fn_index": 0
92
+ }
93
+ response = requests.post(
94
+ f"{BASE_URL}/api/predict",
95
+ json=payload,
96
+ headers={"Content-Type": "application/json"},
97
+ timeout=120
98
+ )
99
  print(f"Status: {response.status_code}")
100
  if response.status_code == 200:
101
+ result = response.json()
102
+ print(f"Gradio API Response: {json.dumps(result, indent=2)[:500]}...")
103
  return True
104
  else:
105
  print(f"Error: {response.text[:200]}")
 
108
  print(f"Exception: {e}")
109
  return False
110
 
111
+ def test_root():
112
+ """Test the root endpoint."""
113
+ print("\nTesting GET / (root)...")
114
+ try:
115
+ response = requests.get(f"{BASE_URL}/", timeout=10)
116
+ print(f"Status: {response.status_code}")
117
+ print(f"Content-Type: {response.headers.get('content-type', 'unknown')}")
118
+ print(f"Response length: {len(response.text)} chars")
119
+ if response.status_code == 200:
120
+ return True
121
+ return False
122
+ except Exception as e:
123
+ print(f"Exception: {e}")
124
+ return False
125
+
126
  def main():
127
  """Run all API tests."""
128
  print("=" * 60)
 
131
  print(f"Base URL: {BASE_URL}\n")
132
 
133
  # Wait a moment for Space to be ready
134
+ print("Waiting 3 seconds for Space to be ready...")
135
+ time.sleep(3)
136
 
137
  results = []
138
 
139
  # Test endpoints
140
+ results.append(("Root", test_root()))
141
  results.append(("Health Check", test_healthcheck()))
142
  results.append(("Generate", test_generate()))
143
+ results.append(("Gradio API", test_gradio_api()))
144
 
145
  # Summary
146
  print("\n" + "=" * 60)