R-Kentaren commited on
Commit
9a0f889
·
verified ·
1 Parent(s): 31c47f7

Rename app.py to config.py

Browse files
Files changed (2) hide show
  1. app.py +0 -872
  2. config.py +137 -0
app.py DELETED
@@ -1,872 +0,0 @@
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()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
config.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ------------------------------
2
+ # Torch-Compatible Model Definitions with Adjusted Descriptions
3
+ # ------------------------------
4
+ MODELS = {
5
+
6
+ # 1.5B
7
+ "Nemotron-Research-Reasoning-Qwen-1.5B": {
8
+ "repo_id": "nvidia/Nemotron-Research-Reasoning-Qwen-1.5B",
9
+ "description": "Nemotron-Research-Reasoning-Qwen-1.5B",
10
+ "params_b": 1.5
11
+ },
12
+ "Falcon-H1-1.5B-Instruct": {
13
+ "repo_id": "tiiuae/Falcon-H1-1.5B-Instruct",
14
+ "description": "Falcon‑H1 model with 1.5 B parameters, instruction‑tuned",
15
+ "params_b": 1.5
16
+ },
17
+ "Qwen2.5-Taiwan-1.5B-Instruct": {
18
+ "repo_id": "benchang1110/Qwen2.5-Taiwan-1.5B-Instruct",
19
+ "description": "Qwen2.5-Taiwan-1.5B-Instruct",
20
+ "params_b": 1.5
21
+ },
22
+
23
+ # 1.2B
24
+ "LFM2-1.2B": {
25
+ "repo_id": "LiquidAI/LFM2-1.2B",
26
+ "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.",
27
+ "params_b": 1.2
28
+ },
29
+
30
+ # 1.1B
31
+ "Taiwan-ELM-1_1B-Instruct": {
32
+ "repo_id": "liswei/Taiwan-ELM-1_1B-Instruct",
33
+ "description": "Taiwan-ELM-1_1B-Instruct",
34
+ "params_b": 1.1
35
+ },
36
+
37
+ # 1B
38
+ "Llama-3.2-Taiwan-1B": {
39
+ "repo_id": "lianghsun/Llama-3.2-Taiwan-1B",
40
+ "description": "Llama-3.2-Taiwan base model with 1 B parameters",
41
+ "params_b": 1.0
42
+ },
43
+
44
+ # 700M
45
+ "LFM2-700M": {
46
+ "repo_id": "LiquidAI/LFM2-700M",
47
+ "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.",
48
+ "params_b": 0.7
49
+ },
50
+
51
+ # 600M
52
+ "Qwen3-0.6B": {
53
+ "repo_id": "Qwen/Qwen3-0.6B",
54
+ "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.",
55
+ "params_b": 0.6
56
+ },
57
+ "Qwen3-0.6B-Taiwan": {
58
+ "repo_id": "ShengweiPeng/Qwen3-0.6B-Taiwan",
59
+ "description": "Qwen3-Taiwan model with 0.6 B parameters",
60
+ "params_b": 0.6
61
+ },
62
+
63
+ # 500M
64
+ "Qwen2.5-0.5B-Taiwan-Instruct": {
65
+ "repo_id": "ShengweiPeng/Qwen2.5-0.5B-Taiwan-Instruct",
66
+ "description": "Qwen2.5-Taiwan model with 0.5 B parameters, instruction-tuned",
67
+ "params_b": 0.5
68
+ },
69
+
70
+ # 360M
71
+ "SmolLM2-360M-Instruct": {
72
+ "repo_id": "HuggingFaceTB/SmolLM2-360M-Instruct",
73
+ "description": "Original SmolLM2‑360M Instruct",
74
+ "params_b": 0.36
75
+ },
76
+ "SmolLM2-360M-Instruct-TaiwanChat": {
77
+ "repo_id": "Luigi/SmolLM2-360M-Instruct-TaiwanChat",
78
+ "description": "SmolLM2‑360M Instruct fine-tuned on TaiwanChat",
79
+ "params_b": 0.36
80
+ },
81
+
82
+ # 350M
83
+ "LFM2-350M": {
84
+ "repo_id": "LiquidAI/LFM2-350M",
85
+ "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.",
86
+ "params_b": 0.35
87
+ },
88
+
89
+ # 270M
90
+ "parser_model_ner_gemma_v0.1": {
91
+ "repo_id": "myfi/parser_model_ner_gemma_v0.1",
92
+ "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.",
93
+ "params_b": 0.27
94
+ },
95
+ "Gemma-3-Taiwan-270M-it": {
96
+ "repo_id": "lianghsun/Gemma-3-Taiwan-270M-it",
97
+ "description": "google/gemma-3-270m-it fintuned on Taiwan Chinese dataset",
98
+ "params_b": 0.27
99
+ },
100
+ "gemma-3-270m-it": {
101
+ "repo_id": "google/gemma-3-270m-it",
102
+ "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.",
103
+ "params_b": 0.27
104
+ },
105
+ "Taiwan-ELM-270M-Instruct": {
106
+ "repo_id": "liswei/Taiwan-ELM-270M-Instruct",
107
+ "description": "Taiwan-ELM-270M-Instruct",
108
+ "params_b": 0.27
109
+ },
110
+
111
+ # 135M
112
+ "SmolLM2-135M-multilingual-base": {
113
+ "repo_id": "agentlans/SmolLM2-135M-multilingual-base",
114
+ "description": "SmolLM2-135M-multilingual-base",
115
+ "params_b": 0.135
116
+ },
117
+ "SmolLM-135M-Taiwan-Instruct-v1.0": {
118
+ "repo_id": "benchang1110/SmolLM-135M-Taiwan-Instruct-v1.0",
119
+ "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",
120
+ "params_b": 0.135
121
+ },
122
+ "SmolLM2_135M_Grpo_Gsm8k": {
123
+ "repo_id": "prithivMLmods/SmolLM2_135M_Grpo_Gsm8k",
124
+ "description": "SmolLM2_135M_Grpo_Gsm8k",
125
+ "params_b": 0.135
126
+ },
127
+ "SmolLM2-135M-Instruct": {
128
+ "repo_id": "HuggingFaceTB/SmolLM2-135M-Instruct",
129
+ "description": "Original SmolLM2‑135M Instruct",
130
+ "params_b": 0.135
131
+ },
132
+ "SmolLM2-135M-Instruct-TaiwanChat": {
133
+ "repo_id": "Luigi/SmolLM2-135M-Instruct-TaiwanChat",
134
+ "description": "SmolLM2‑135M Instruct fine-tuned on TaiwanChat",
135
+ "params_b": 0.135
136
+ },
137
+ }