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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
if __name__ == "__main__":
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import os
|
| 3 |
+
import gc
|
| 4 |
+
import re
|
| 5 |
+
import time
|
| 6 |
+
import json
|
| 7 |
+
import tempfile
|
| 8 |
+
import threading
|
| 9 |
+
import traceback
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from collections import deque
|
| 12 |
+
|
| 13 |
import gradio as gr
|
| 14 |
+
import spaces
|
| 15 |
+
import torch
|
| 16 |
|
| 17 |
+
from PIL import Image, ImageOps
|
| 18 |
+
from transformers import (
|
| 19 |
+
AutoProcessor,
|
| 20 |
+
AutoModelForImageTextToText,
|
| 21 |
+
BitsAndBytesConfig,
|
| 22 |
+
TextIteratorStreamer,
|
| 23 |
+
StoppingCriteria,
|
| 24 |
+
StoppingCriteriaList,
|
| 25 |
+
)
|
| 26 |
|
| 27 |
+
# ============================================================
|
| 28 |
+
# 1. GLOBAL CONFIGURATION
|
| 29 |
+
# ============================================================
|
| 30 |
+
|
| 31 |
+
APP_TITLE = "Qwen3.5 Advanced Chat"
|
| 32 |
+
DEFAULT_MODEL = "Qwen/Qwen3.5-9B"
|
| 33 |
+
|
| 34 |
+
MODEL_ID = os.getenv("MODEL_ID", DEFAULT_MODEL)
|
| 35 |
+
MODEL_REVISION = os.getenv("MODEL_REVISION", "main")
|
| 36 |
+
MODEL_DTYPE = os.getenv("MODEL_DTYPE", "bf16").lower()
|
| 37 |
+
QUANTIZE = os.getenv("QUANTIZE", "none").lower()
|
| 38 |
+
DEVICE_MAP = os.getenv("DEVICE_MAP", "auto")
|
| 39 |
+
ATTENTION_IMPLEMENTATION = os.getenv("ATTENTION_IMPLEMENTATION", "sdpa")
|
| 40 |
+
TRUST_REMOTE_CODE = os.getenv("TRUST_REMOTE_CODE", "false").lower() == "true"
|
| 41 |
+
|
| 42 |
+
# Set GPU_RESERVATION_SECONDS to a value supported by your
|
| 43 |
+
# ZeroGPU deployment. The value is a reservation, not a guarantee
|
| 44 |
+
# of that much inference time or an estimate of queue wait.
|
| 45 |
+
GPU_RESERVATION_SECONDS = int(
|
| 46 |
+
os.getenv("GPU_RESERVATION_SECONDS", "120")
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
MAX_CONTEXT_TOKENS = int(os.getenv("MAX_CONTEXT_TOKENS", "16384"))
|
| 50 |
+
MAX_NEW_TOKENS = int(os.getenv("MAX_NEW_TOKENS", "1024"))
|
| 51 |
+
MAX_UPLOAD_MB = int(os.getenv("MAX_UPLOAD_MB", "20"))
|
| 52 |
+
MAX_TEXT_FILE_CHARS = int(os.getenv("MAX_TEXT_FILE_CHARS", "30000"))
|
| 53 |
+
|
| 54 |
+
DEFAULT_SYSTEM_PROMPT = (
|
| 55 |
+
"You are a helpful, accurate, and direct assistant. "
|
| 56 |
+
"Respond in the language used by the user."
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
TEXT_EXTENSIONS = {
|
| 60 |
+
".txt", ".md", ".markdown", ".rst", ".log", ".csv", ".tsv",
|
| 61 |
+
".json", ".jsonl", ".yaml", ".yml", ".toml", ".ini", ".cfg",
|
| 62 |
+
".conf", ".xml", ".html", ".htm", ".css", ".js", ".jsx",
|
| 63 |
+
".ts", ".tsx", ".py", ".c", ".h", ".cpp", ".java", ".go",
|
| 64 |
+
".rs", ".rb", ".php", ".sh", ".sql", ".r", ".lua", ".diff",
|
| 65 |
+
".patch", ".tex", ".srt", ".vtt",
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
IMAGE_EXTENSIONS = {
|
| 69 |
+
".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tif", ".tiff",
|
| 70 |
+
".gif", ".ico", ".heic", ".heif", ".avif",
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
MODEL_LOCK = threading.RLock()
|
| 74 |
+
MODEL = None
|
| 75 |
+
PROCESSOR = None
|
| 76 |
+
TOKENIZER = None
|
| 77 |
+
ACTIVE_MODEL_CONFIG = {}
|
| 78 |
+
MODEL_LOAD_ERROR = None
|
| 79 |
+
|
| 80 |
+
METRICS = deque(maxlen=100)
|
| 81 |
+
STOP_EVENTS = {}
|
| 82 |
+
STOP_LOCK = threading.Lock()
|
| 83 |
+
|
| 84 |
+
# ============================================================
|
| 85 |
+
# 2. MODEL LOADING
|
| 86 |
+
# ============================================================
|
| 87 |
+
|
| 88 |
+
def resolve_dtype(name):
|
| 89 |
+
options = {
|
| 90 |
+
"bf16": torch.bfloat16,
|
| 91 |
+
"bfloat16": torch.bfloat16,
|
| 92 |
+
"fp16": torch.float16,
|
| 93 |
+
"float16": torch.float16,
|
| 94 |
+
"fp32": torch.float32,
|
| 95 |
+
"float32": torch.float32,
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
if name not in options:
|
| 99 |
+
raise ValueError(f"Unsupported dtype: {name}")
|
| 100 |
+
|
| 101 |
+
if name in ("bf16", "bfloat16") and torch.cuda.is_available():
|
| 102 |
+
if not torch.cuda.is_bf16_supported():
|
| 103 |
+
print("[MODEL] Warning: BF16 is not supported by this GPU.")
|
| 104 |
+
|
| 105 |
+
return options[name]
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def load_model(
|
| 109 |
+
model_id,
|
| 110 |
+
revision="main",
|
| 111 |
+
dtype_name="bf16",
|
| 112 |
+
quantization="none",
|
| 113 |
+
device_map="auto",
|
| 114 |
+
attention="sdpa",
|
| 115 |
+
trust_remote_code=False,
|
| 116 |
+
):
|
| 117 |
+
global MODEL, PROCESSOR, TOKENIZER
|
| 118 |
+
global ACTIVE_MODEL_CONFIG, MODEL_LOAD_ERROR
|
| 119 |
+
|
| 120 |
+
dtype = resolve_dtype(dtype_name)
|
| 121 |
+
quantization = quantization.lower()
|
| 122 |
+
|
| 123 |
+
if quantization not in ("none", "4bit", "8bit"):
|
| 124 |
+
raise ValueError("Quantization must be none, 4bit, or 8bit.")
|
| 125 |
+
|
| 126 |
+
kwargs = {
|
| 127 |
+
"revision": revision,
|
| 128 |
+
"torch_dtype": dtype,
|
| 129 |
+
"device_map": device_map,
|
| 130 |
+
"trust_remote_code": trust_remote_code,
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
if attention != "auto":
|
| 134 |
+
kwargs["attn_implementation"] = attention
|
| 135 |
+
|
| 136 |
+
if quantization == "4bit":
|
| 137 |
+
kwargs["quantization_config"] = BitsAndBytesConfig(
|
| 138 |
+
load_in_4bit=True,
|
| 139 |
+
bnb_4bit_quant_type="nf4",
|
| 140 |
+
bnb_4bit_compute_dtype=dtype,
|
| 141 |
+
bnb_4bit_use_double_quant=True,
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
elif quantization == "8bit":
|
| 145 |
+
kwargs["quantization_config"] = BitsAndBytesConfig(
|
| 146 |
+
load_in_8bit=True,
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
print(f"[MODEL] Loading {model_id} ({dtype_name}, {quantization})")
|
| 150 |
+
|
| 151 |
+
processor = AutoProcessor.from_pretrained(
|
| 152 |
+
model_id,
|
| 153 |
+
revision=revision,
|
| 154 |
+
trust_remote_code=trust_remote_code,
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
# Qwen3.5 is a multimodal model. Use the image-text model class.
|
| 158 |
+
model = AutoModelForImageTextToText.from_pretrained(
|
| 159 |
+
model_id,
|
| 160 |
+
**kwargs,
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
model.eval()
|
| 164 |
+
|
| 165 |
+
tokenizer = getattr(processor, "tokenizer", None)
|
| 166 |
+
|
| 167 |
+
if tokenizer is None:
|
| 168 |
+
tokenizer = processor
|
| 169 |
+
|
| 170 |
+
with MODEL_LOCK:
|
| 171 |
+
old_model = MODEL
|
| 172 |
+
|
| 173 |
+
MODEL = model
|
| 174 |
+
PROCESSOR = processor
|
| 175 |
+
TOKENIZER = tokenizer
|
| 176 |
+
|
| 177 |
+
ACTIVE_MODEL_CONFIG = {
|
| 178 |
+
"model_id": model_id,
|
| 179 |
+
"revision": revision,
|
| 180 |
+
"dtype": dtype_name,
|
| 181 |
+
"quantization": quantization,
|
| 182 |
+
"device_map": device_map,
|
| 183 |
+
"attention": attention,
|
| 184 |
+
"trust_remote_code": trust_remote_code,
|
| 185 |
+
"loaded_at": time.time(),
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
MODEL_LOAD_ERROR = None
|
| 189 |
+
|
| 190 |
+
if old_model is not None:
|
| 191 |
+
del old_model
|
| 192 |
+
|
| 193 |
+
gc.collect()
|
| 194 |
+
|
| 195 |
+
if torch.cuda.is_available():
|
| 196 |
+
torch.cuda.empty_cache()
|
| 197 |
+
|
| 198 |
+
print("[MODEL] Model loaded successfully.")
|
| 199 |
+
return True
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def ensure_model_loaded():
|
| 203 |
+
global MODEL_LOAD_ERROR
|
| 204 |
+
|
| 205 |
+
if MODEL is not None:
|
| 206 |
+
return
|
| 207 |
+
|
| 208 |
+
try:
|
| 209 |
+
load_model(
|
| 210 |
+
MODEL_ID,
|
| 211 |
+
MODEL_REVISION,
|
| 212 |
+
MODEL_DTYPE,
|
| 213 |
+
QUANTIZE,
|
| 214 |
+
DEVICE_MAP,
|
| 215 |
+
ATTENTION_IMPLEMENTATION,
|
| 216 |
+
TRUST_REMOTE_CODE,
|
| 217 |
+
)
|
| 218 |
+
except Exception as exc:
|
| 219 |
+
MODEL_LOAD_ERROR = str(exc)
|
| 220 |
+
raise RuntimeError(
|
| 221 |
+
f"Model loading failed: {exc}. "
|
| 222 |
+
"Check the Transformers version, GPU memory, and model ID."
|
| 223 |
+
) from exc
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
# ============================================================
|
| 227 |
+
# 3. FILE AND IMAGE PROCESSING
|
| 228 |
+
# ============================================================
|
| 229 |
+
|
| 230 |
+
def get_path(item):
|
| 231 |
+
if isinstance(item, str):
|
| 232 |
+
return item
|
| 233 |
+
|
| 234 |
+
if isinstance(item, dict):
|
| 235 |
+
return item.get("path") or item.get("url")
|
| 236 |
+
|
| 237 |
+
return None
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def read_text_file(path):
|
| 241 |
+
name = Path(path).name
|
| 242 |
+
|
| 243 |
+
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
| 244 |
+
text = f.read(MAX_TEXT_FILE_CHARS + 1)
|
| 245 |
+
|
| 246 |
+
if len(text) > MAX_TEXT_FILE_CHARS:
|
| 247 |
+
text = text[:MAX_TEXT_FILE_CHARS] + "\n[File truncated]"
|
| 248 |
+
|
| 249 |
+
return f"--- File: {name} ---\n{text}\n--- End file ---"
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def prepare_image(path):
|
| 253 |
+
if not path or not os.path.isfile(path):
|
| 254 |
+
raise gr.Error("The uploaded image could not be found.")
|
| 255 |
+
|
| 256 |
+
size_mb = os.path.getsize(path) / (1024 * 1024)
|
| 257 |
+
|
| 258 |
+
if size_mb > MAX_UPLOAD_MB:
|
| 259 |
+
raise gr.Error(f"Image exceeds the {MAX_UPLOAD_MB} MB upload limit.")
|
| 260 |
+
|
| 261 |
+
try:
|
| 262 |
+
with Image.open(path) as image:
|
| 263 |
+
image = ImageOps.exif_transpose(image)
|
| 264 |
+
image.load()
|
| 265 |
+
return image.convert("RGB").copy()
|
| 266 |
+
except Exception as exc:
|
| 267 |
+
raise gr.Error(f"Unable to open image: {Path(path).name}") from exc
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def file_to_part(path):
|
| 271 |
+
if not path:
|
| 272 |
+
return None
|
| 273 |
+
|
| 274 |
+
suffix = Path(path).suffix.lower()
|
| 275 |
+
|
| 276 |
+
if suffix in IMAGE_EXTENSIONS:
|
| 277 |
+
return {
|
| 278 |
+
"type": "image",
|
| 279 |
+
"image": prepare_image(path),
|
| 280 |
+
}
|
| 281 |
+
|
| 282 |
+
if suffix in TEXT_EXTENSIONS:
|
| 283 |
+
return {
|
| 284 |
+
"type": "text",
|
| 285 |
+
"text": read_text_file(path),
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
# Try unknown file types as images; fail with a readable error.
|
| 289 |
+
try:
|
| 290 |
+
return {
|
| 291 |
+
"type": "image",
|
| 292 |
+
"image": prepare_image(path),
|
| 293 |
+
}
|
| 294 |
+
except gr.Error:
|
| 295 |
+
raise gr.Error(
|
| 296 |
+
f"Unsupported attachment: {Path(path).name}. "
|
| 297 |
+
"Upload an image or a supported text file."
|
| 298 |
+
)
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def normalize_content(content):
|
| 302 |
+
"""Convert Gradio message content into Qwen-compatible chat parts."""
|
| 303 |
+
if isinstance(content, str):
|
| 304 |
+
return [{"type": "text", "text": content}] if content else []
|
| 305 |
+
|
| 306 |
+
if isinstance(content, dict):
|
| 307 |
+
if content.get("type") == "text":
|
| 308 |
+
return [{
|
| 309 |
+
"type": "text",
|
| 310 |
+
"text": content.get("text", ""),
|
| 311 |
+
}]
|
| 312 |
+
|
| 313 |
+
if content.get("type") == "image":
|
| 314 |
+
path = content.get("path") or content.get("url")
|
| 315 |
+
return [file_to_part(path)] if path else []
|
| 316 |
+
|
| 317 |
+
path = get_path(content)
|
| 318 |
+
part = file_to_part(path)
|
| 319 |
+
return [part] if part else []
|
| 320 |
+
|
| 321 |
+
if not isinstance(content, (list, tuple)):
|
| 322 |
+
return []
|
| 323 |
+
|
| 324 |
+
parts = []
|
| 325 |
+
|
| 326 |
+
for item in content:
|
| 327 |
+
if isinstance(item, str):
|
| 328 |
+
if item.strip():
|
| 329 |
+
parts.append({"type": "text", "text": item})
|
| 330 |
+
|
| 331 |
+
elif isinstance(item, dict):
|
| 332 |
+
if item.get("type") == "text":
|
| 333 |
+
parts.append({
|
| 334 |
+
"type": "text",
|
| 335 |
+
"text": item.get("text", ""),
|
| 336 |
+
})
|
| 337 |
+
|
| 338 |
+
elif item.get("type") == "image":
|
| 339 |
+
path = get_path(item)
|
| 340 |
+
|
| 341 |
+
if path:
|
| 342 |
+
parts.append(file_to_part(path))
|
| 343 |
+
elif item.get("image") is not None:
|
| 344 |
+
parts.append(item)
|
| 345 |
+
|
| 346 |
+
else:
|
| 347 |
+
path = get_path(item)
|
| 348 |
+
part = file_to_part(path)
|
| 349 |
+
|
| 350 |
+
if part:
|
| 351 |
+
parts.append(part)
|
| 352 |
+
|
| 353 |
+
elif isinstance(item, (list, tuple)) and item:
|
| 354 |
+
part = file_to_part(get_path(item[0]) or item[0])
|
| 355 |
+
|
| 356 |
+
if part:
|
| 357 |
+
parts.append(part)
|
| 358 |
+
|
| 359 |
+
return parts
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
def build_messages(message, history, system_prompt, history_limit):
|
| 363 |
+
messages = []
|
| 364 |
+
|
| 365 |
+
if system_prompt.strip():
|
| 366 |
+
messages.append({
|
| 367 |
+
"role": "system",
|
| 368 |
+
"content": system_prompt.strip(),
|
| 369 |
+
})
|
| 370 |
+
|
| 371 |
+
# Keep only the most recent conversation turns.
|
| 372 |
+
history = (history or [])[-int(history_limit):]
|
| 373 |
+
|
| 374 |
+
for turn in history:
|
| 375 |
+
if not isinstance(turn, dict):
|
| 376 |
+
continue
|
| 377 |
+
|
| 378 |
+
role = turn.get("role")
|
| 379 |
+
|
| 380 |
+
if role not in ("user", "assistant"):
|
| 381 |
+
continue
|
| 382 |
+
|
| 383 |
+
# Drop internal reasoning/notice bubbles from context.
|
| 384 |
+
if (turn.get("metadata") or {}).get("title"):
|
| 385 |
+
continue
|
| 386 |
+
|
| 387 |
+
content = normalize_content(turn.get("content"))
|
| 388 |
+
|
| 389 |
+
if content:
|
| 390 |
+
messages.append({
|
| 391 |
+
"role": role,
|
| 392 |
+
"content": content,
|
| 393 |
+
})
|
| 394 |
+
|
| 395 |
+
current_parts = []
|
| 396 |
+
|
| 397 |
+
for item in message.get("files") or []:
|
| 398 |
+
path = get_path(item) or item
|
| 399 |
+
|
| 400 |
+
part = file_to_part(path)
|
| 401 |
+
|
| 402 |
+
if part:
|
| 403 |
+
current_parts.append(part)
|
| 404 |
+
|
| 405 |
+
text = message.get("text") or ""
|
| 406 |
+
|
| 407 |
+
if text.strip():
|
| 408 |
+
current_parts.append({
|
| 409 |
+
"type": "text",
|
| 410 |
+
"text": text,
|
| 411 |
+
})
|
| 412 |
+
|
| 413 |
+
if not current_parts:
|
| 414 |
+
raise gr.Error("Enter a message or attach a file.")
|
| 415 |
+
|
| 416 |
+
messages.append({
|
| 417 |
+
"role": "user",
|
| 418 |
+
"content": current_parts,
|
| 419 |
+
})
|
| 420 |
+
|
| 421 |
+
return messages
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
# ============================================================
|
| 425 |
+
# 4. GENERATION HELPERS
|
| 426 |
+
# ============================================================
|
| 427 |
+
|
| 428 |
+
def model_device(model):
|
| 429 |
+
try:
|
| 430 |
+
return model.device
|
| 431 |
+
except Exception:
|
| 432 |
+
return next(model.parameters()).device
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
def get_stop_sequences(value):
|
| 436 |
+
if not value.strip():
|
| 437 |
+
return []
|
| 438 |
+
|
| 439 |
+
try:
|
| 440 |
+
parsed = json.loads(value)
|
| 441 |
+
|
| 442 |
+
if isinstance(parsed, list):
|
| 443 |
+
return [str(x) for x in parsed if str(x)]
|
| 444 |
+
except json.JSONDecodeError:
|
| 445 |
+
pass
|
| 446 |
+
|
| 447 |
+
return [line.strip() for line in value.splitlines() if line.strip()]
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
class StopOnEvent(StoppingCriteria):
|
| 451 |
+
def __init__(self, event):
|
| 452 |
+
self.event = event
|
| 453 |
+
|
| 454 |
+
def __call__(self, input_ids, scores, **kwargs):
|
| 455 |
+
return self.event.is_set()
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
def seed_everything(seed):
|
| 459 |
+
seed = int(seed)
|
| 460 |
+
|
| 461 |
+
if seed < 0:
|
| 462 |
+
return
|
| 463 |
+
|
| 464 |
+
torch.manual_seed(seed)
|
| 465 |
+
|
| 466 |
+
if torch.cuda.is_available():
|
| 467 |
+
torch.cuda.manual_seed_all(seed)
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
def get_supported_generation_kwargs(model, requested):
|
| 471 |
+
"""
|
| 472 |
+
Avoid passing unsupported generation parameters to older Transformers
|
| 473 |
+
releases. Unsupported settings are reported in the UI.
|
| 474 |
+
"""
|
| 475 |
+
config = model.generation_config
|
| 476 |
+
supported = {}
|
| 477 |
+
ignored = []
|
| 478 |
+
|
| 479 |
+
for key, value in requested.items():
|
| 480 |
+
if hasattr(config, key):
|
| 481 |
+
supported[key] = value
|
| 482 |
+
else:
|
| 483 |
+
ignored.append(key)
|
| 484 |
+
|
| 485 |
+
return supported, ignored
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
def make_generation_kwargs(
|
| 489 |
+
model,
|
| 490 |
temperature,
|
| 491 |
top_p,
|
| 492 |
+
top_k,
|
| 493 |
+
min_p,
|
| 494 |
+
typical_p,
|
| 495 |
+
repetition_penalty,
|
| 496 |
+
no_repeat_ngram_size,
|
| 497 |
+
max_new_tokens,
|
| 498 |
+
min_new_tokens,
|
| 499 |
+
num_beams,
|
| 500 |
+
length_penalty,
|
| 501 |
+
early_stopping,
|
| 502 |
+
do_sample,
|
| 503 |
+
use_cache,
|
| 504 |
+
seed,
|
| 505 |
+
max_time,
|
| 506 |
+
epsilon_cutoff,
|
| 507 |
+
eta_cutoff,
|
| 508 |
):
|
| 509 |
+
requested = {
|
| 510 |
+
"max_new_tokens": int(max_new_tokens),
|
| 511 |
+
"min_new_tokens": int(min_new_tokens),
|
| 512 |
+
"do_sample": bool(do_sample),
|
| 513 |
+
"num_beams": int(num_beams),
|
| 514 |
+
"length_penalty": float(length_penalty),
|
| 515 |
+
"early_stopping": bool(early_stopping),
|
| 516 |
+
"repetition_penalty": float(repetition_penalty),
|
| 517 |
+
"no_repeat_ngram_size": int(no_repeat_ngram_size),
|
| 518 |
+
"use_cache": bool(use_cache),
|
| 519 |
+
"max_time": float(max_time),
|
| 520 |
+
"epsilon_cutoff": float(epsilon_cutoff),
|
| 521 |
+
"eta_cutoff": float(eta_cutoff),
|
| 522 |
+
"typical_p": float(typical_p),
|
| 523 |
+
}
|
| 524 |
+
|
| 525 |
+
if do_sample:
|
| 526 |
+
requested.update({
|
| 527 |
+
"temperature": float(temperature),
|
| 528 |
+
"top_p": float(top_p),
|
| 529 |
+
"top_k": int(top_k),
|
| 530 |
+
"min_p": float(min_p),
|
| 531 |
+
})
|
| 532 |
+
|
| 533 |
+
supported, ignored = get_supported_generation_kwargs(
|
| 534 |
+
model,
|
| 535 |
+
requested,
|
| 536 |
+
)
|
| 537 |
+
|
| 538 |
+
# Sampling and beam-search parameters should not be mixed accidentally.
|
| 539 |
+
if not do_sample:
|
| 540 |
+
for key in ("temperature", "top_p", "top_k", "min_p", "typical_p"):
|
| 541 |
+
supported.pop(key, None)
|
| 542 |
+
|
| 543 |
+
if int(num_beams) == 1:
|
| 544 |
+
supported["early_stopping"] = False
|
| 545 |
+
|
| 546 |
+
seed_everything(seed)
|
| 547 |
+
|
| 548 |
+
return supported, ignored
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
# ============================================================
|
| 552 |
+
# 5. GPU RESERVATION
|
| 553 |
+
# ============================================================
|
| 554 |
+
|
| 555 |
+
def reservation_duration(*args, **kwargs):
|
| 556 |
"""
|
| 557 |
+
ZeroGPU charges/allocates a GPU reservation; it does not control queue
|
| 558 |
+
wait. Configure this value for the limits of your Space.
|
| 559 |
"""
|
| 560 |
+
return GPU_RESERVATION_SECONDS
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
# ============================================================
|
| 564 |
+
# 6. MODEL GENERATION
|
| 565 |
+
# ============================================================
|
| 566 |
|
| 567 |
+
@spaces.GPU(
|
| 568 |
+
duration=reservation_duration,
|
| 569 |
+
size=os.getenv("ZEROGPU_SIZE", "large"),
|
| 570 |
+
)
|
| 571 |
+
def generate(
|
| 572 |
+
messages,
|
| 573 |
+
temperature,
|
| 574 |
+
top_p,
|
| 575 |
+
top_k,
|
| 576 |
+
min_p,
|
| 577 |
+
typical_p,
|
| 578 |
+
repetition_penalty,
|
| 579 |
+
no_repeat_ngram_size,
|
| 580 |
+
max_new_tokens,
|
| 581 |
+
min_new_tokens,
|
| 582 |
+
num_beams,
|
| 583 |
+
length_penalty,
|
| 584 |
+
early_stopping,
|
| 585 |
+
do_sample,
|
| 586 |
+
use_cache,
|
| 587 |
+
seed,
|
| 588 |
+
max_time,
|
| 589 |
+
epsilon_cutoff,
|
| 590 |
+
eta_cutoff,
|
| 591 |
+
enable_thinking,
|
| 592 |
+
stop_sequences_text,
|
| 593 |
+
request_id,
|
| 594 |
+
):
|
| 595 |
+
ensure_model_loaded()
|
| 596 |
|
| 597 |
+
with MODEL_LOCK:
|
| 598 |
+
model = MODEL
|
| 599 |
+
processor = PROCESSOR
|
| 600 |
+
tokenizer = TOKENIZER
|
| 601 |
|
| 602 |
+
start_time = time.perf_counter()
|
| 603 |
|
| 604 |
+
template_kwargs = {
|
| 605 |
+
"enable_thinking": bool(enable_thinking),
|
| 606 |
+
"preserve_thinking": False,
|
| 607 |
+
}
|
| 608 |
|
| 609 |
+
# Keep the latest Transformers/model template compatible.
|
| 610 |
+
try:
|
| 611 |
+
inputs = processor.apply_chat_template(
|
| 612 |
+
messages,
|
| 613 |
+
add_generation_prompt=True,
|
| 614 |
+
tokenize=True,
|
| 615 |
+
return_dict=True,
|
| 616 |
+
return_tensors="pt",
|
| 617 |
+
**template_kwargs,
|
| 618 |
+
)
|
| 619 |
+
except TypeError:
|
| 620 |
+
# Older templates may not accept these kwargs.
|
| 621 |
+
inputs = processor.apply_chat_template(
|
| 622 |
+
messages,
|
| 623 |
+
add_generation_prompt=True,
|
| 624 |
+
tokenize=True,
|
| 625 |
+
return_dict=True,
|
| 626 |
+
return_tensors="pt",
|
| 627 |
+
)
|
| 628 |
+
|
| 629 |
+
inputs = inputs.to(model_device(model))
|
| 630 |
+
|
| 631 |
+
generation_kwargs, ignored = make_generation_kwargs(
|
| 632 |
+
model=model,
|
| 633 |
temperature=temperature,
|
| 634 |
top_p=top_p,
|
| 635 |
+
top_k=top_k,
|
| 636 |
+
min_p=min_p,
|
| 637 |
+
typical_p=typical_p,
|
| 638 |
+
repetition_penalty=repetition_penalty,
|
| 639 |
+
no_repeat_ngram_size=no_repeat_ngram_size,
|
| 640 |
+
max_new_tokens=max_new_tokens,
|
| 641 |
+
min_new_tokens=min_new_tokens,
|
| 642 |
+
num_beams=num_beams,
|
| 643 |
+
length_penalty=length_penalty,
|
| 644 |
+
early_stopping=early_stopping,
|
| 645 |
+
do_sample=do_sample,
|
| 646 |
+
use_cache=use_cache,
|
| 647 |
+
seed=seed,
|
| 648 |
+
max_time=max_time,
|
| 649 |
+
epsilon_cutoff=epsilon_cutoff,
|
| 650 |
+
eta_cutoff=eta_cutoff,
|
| 651 |
+
)
|
| 652 |
+
|
| 653 |
+
if ignored:
|
| 654 |
+
print(f"[GENERATION] Unsupported parameters skipped: {ignored}")
|
| 655 |
+
|
| 656 |
+
streamer = TextIteratorStreamer(
|
| 657 |
+
tokenizer,
|
| 658 |
+
skip_prompt=True,
|
| 659 |
+
skip_special_tokens=True,
|
| 660 |
+
timeout=2.0,
|
| 661 |
+
)
|
| 662 |
+
|
| 663 |
+
stop_event = threading.Event()
|
| 664 |
+
|
| 665 |
+
with STOP_LOCK:
|
| 666 |
+
STOP_EVENTS[request_id] = stop_event
|
| 667 |
+
|
| 668 |
+
stopping = StoppingCriteriaList([StopOnEvent(stop_event)])
|
| 669 |
+
|
| 670 |
+
kwargs = {
|
| 671 |
+
**inputs,
|
| 672 |
+
**generation_kwargs,
|
| 673 |
+
"streamer": streamer,
|
| 674 |
+
"stopping_criteria": stopping,
|
| 675 |
+
}
|
| 676 |
+
|
| 677 |
+
stop_sequences = get_stop_sequences(stop_sequences_text)
|
| 678 |
+
|
| 679 |
+
# stop_strings is supported by newer Transformers releases.
|
| 680 |
+
if stop_sequences:
|
| 681 |
+
kwargs["stop_strings"] = stop_sequences
|
| 682 |
+
kwargs["tokenizer"] = tokenizer
|
| 683 |
+
|
| 684 |
+
errors = []
|
| 685 |
+
|
| 686 |
+
def worker():
|
| 687 |
+
try:
|
| 688 |
+
with torch.inference_mode():
|
| 689 |
+
model.generate(**kwargs)
|
| 690 |
+
except Exception as exc:
|
| 691 |
+
errors.append(exc)
|
| 692 |
+
|
| 693 |
+
try:
|
| 694 |
+
streamer.end()
|
| 695 |
+
except Exception:
|
| 696 |
+
pass
|
| 697 |
+
|
| 698 |
+
thread = threading.Thread(target=worker, daemon=True)
|
| 699 |
+
thread.start()
|
| 700 |
+
|
| 701 |
+
reply = ""
|
| 702 |
+
first_token_time = None
|
| 703 |
+
|
| 704 |
+
try:
|
| 705 |
+
while True:
|
| 706 |
+
try:
|
| 707 |
+
chunk = next(streamer)
|
| 708 |
+
except StopIteration:
|
| 709 |
+
break
|
| 710 |
+
except Exception as exc:
|
| 711 |
+
# TextIteratorStreamer can time out while the worker is running.
|
| 712 |
+
if thread.is_alive():
|
| 713 |
+
if errors:
|
| 714 |
+
break
|
| 715 |
+
continue
|
| 716 |
+
break
|
| 717 |
+
|
| 718 |
+
if chunk:
|
| 719 |
+
if first_token_time is None:
|
| 720 |
+
first_token_time = time.perf_counter()
|
| 721 |
+
|
| 722 |
+
reply += chunk
|
| 723 |
+
|
| 724 |
+
yield {
|
| 725 |
+
"text": reply,
|
| 726 |
+
"request_id": request_id,
|
| 727 |
+
"error": None,
|
| 728 |
+
"metrics": None,
|
| 729 |
+
}
|
| 730 |
+
|
| 731 |
+
if not thread.is_alive() and not chunk:
|
| 732 |
+
break
|
| 733 |
+
|
| 734 |
+
thread.join(timeout=max(1.0, float(max_time) + 5.0))
|
| 735 |
+
|
| 736 |
+
if errors:
|
| 737 |
+
raise gr.Error(f"Generation failed: {errors[0]}")
|
| 738 |
+
|
| 739 |
+
elapsed = time.perf_counter() - start_time
|
| 740 |
+
|
| 741 |
+
try:
|
| 742 |
+
token_count = len(
|
| 743 |
+
tokenizer(reply, add_special_tokens=False).input_ids
|
| 744 |
+
)
|
| 745 |
+
except Exception:
|
| 746 |
+
token_count = 0
|
| 747 |
+
|
| 748 |
+
first_token_latency = (
|
| 749 |
+
first_token_time - start_time
|
| 750 |
+
if first_token_time is not None
|
| 751 |
+
else None
|
| 752 |
+
)
|
| 753 |
+
|
| 754 |
+
tokens_per_second = (
|
| 755 |
+
token_count / elapsed if elapsed > 0 else 0.0
|
| 756 |
+
)
|
| 757 |
+
|
| 758 |
+
metrics = {
|
| 759 |
+
"model": ACTIVE_MODEL_CONFIG.get("model_id", MODEL_ID),
|
| 760 |
+
"elapsed_seconds": round(elapsed, 2),
|
| 761 |
+
"first_token_seconds": (
|
| 762 |
+
round(first_token_latency, 2)
|
| 763 |
+
if first_token_latency is not None
|
| 764 |
+
else None
|
| 765 |
+
),
|
| 766 |
+
"generated_tokens": token_count,
|
| 767 |
+
"tokens_per_second": round(tokens_per_second, 2),
|
| 768 |
+
"reservation_seconds": GPU_RESERVATION_SECONDS,
|
| 769 |
+
"stopped": stop_event.is_set(),
|
| 770 |
+
"unsupported_parameters": ignored,
|
| 771 |
+
}
|
| 772 |
+
|
| 773 |
+
METRICS.append(metrics)
|
| 774 |
+
|
| 775 |
+
yield {
|
| 776 |
+
"text": reply,
|
| 777 |
+
"request_id": request_id,
|
| 778 |
+
"error": None,
|
| 779 |
+
"metrics": metrics,
|
| 780 |
+
}
|
| 781 |
+
|
| 782 |
+
finally:
|
| 783 |
+
with STOP_LOCK:
|
| 784 |
+
STOP_EVENTS.pop(request_id, None)
|
| 785 |
+
|
| 786 |
+
|
| 787 |
+
# ============================================================
|
| 788 |
+
# 7. CHAT HANDLER
|
| 789 |
+
# ============================================================
|
| 790 |
+
|
| 791 |
+
def respond(
|
| 792 |
+
message,
|
| 793 |
+
history,
|
| 794 |
+
system_prompt,
|
| 795 |
+
history_limit,
|
| 796 |
+
temperature,
|
| 797 |
+
top_p,
|
| 798 |
+
top_k,
|
| 799 |
+
min_p,
|
| 800 |
+
typical_p,
|
| 801 |
+
repetition_penalty,
|
| 802 |
+
no_repeat_ngram_size,
|
| 803 |
+
max_new_tokens,
|
| 804 |
+
min_new_tokens,
|
| 805 |
+
num_beams,
|
| 806 |
+
length_penalty,
|
| 807 |
+
early_stopping,
|
| 808 |
+
do_sample,
|
| 809 |
+
use_cache,
|
| 810 |
+
seed,
|
| 811 |
+
max_time,
|
| 812 |
+
epsilon_cutoff,
|
| 813 |
+
eta_cutoff,
|
| 814 |
+
enable_thinking,
|
| 815 |
+
stop_sequences_text,
|
| 816 |
+
):
|
| 817 |
+
request_id = f"{time.time_ns()}"
|
| 818 |
+
|
| 819 |
+
try:
|
| 820 |
+
messages = build_messages(
|
| 821 |
+
message,
|
| 822 |
+
history,
|
| 823 |
+
system_prompt,
|
| 824 |
+
history_limit,
|
| 825 |
+
)
|
| 826 |
+
|
| 827 |
+
# Keep the latest history within the configured token budget.
|
| 828 |
+
# This estimates text length; multimodal token usage may be higher.
|
| 829 |
+
while len(messages) > 2:
|
| 830 |
+
try:
|
| 831 |
+
rendered = PROCESSOR.apply_chat_template(
|
| 832 |
+
messages,
|
| 833 |
+
tokenize=True,
|
| 834 |
+
add_generation_prompt=True,
|
| 835 |
+
)
|
| 836 |
+
if len(rendered) <= MAX_CONTEXT_TOKENS:
|
| 837 |
+
break
|
| 838 |
+
except Exception:
|
| 839 |
+
break
|
| 840 |
+
|
| 841 |
+
# Remove the oldest user/assistant pair, preserving system prompt.
|
| 842 |
+
start = 1 if messages[0]["role"] == "system" else 0
|
| 843 |
+
|
| 844 |
+
if len(messages) - start <= 2:
|
| 845 |
+
break
|
| 846 |
+
|
| 847 |
+
del messages[start:start + 2]
|
| 848 |
+
|
| 849 |
+
current = ""
|
| 850 |
+
|
| 851 |
+
for item in generate(
|
| 852 |
+
messages,
|
| 853 |
+
temperature,
|
| 854 |
+
top_p,
|
| 855 |
+
top_k,
|
| 856 |
+
min_p,
|
| 857 |
+
typical_p,
|
| 858 |
+
repetition_penalty,
|
| 859 |
+
no_repeat_ngram_size,
|
| 860 |
+
max_new_tokens,
|
| 861 |
+
min_new_tokens,
|
| 862 |
+
num_beams,
|
| 863 |
+
length_penalty,
|
| 864 |
+
early_stopping,
|
| 865 |
+
do_sample,
|
| 866 |
+
use_cache,
|
| 867 |
+
seed,
|
| 868 |
+
max_time,
|
| 869 |
+
epsilon_cutoff,
|
| 870 |
+
eta_cutoff,
|
| 871 |
+
enable_thinking,
|
| 872 |
+
stop_sequences_text,
|
| 873 |
+
request_id,
|
| 874 |
+
):
|
| 875 |
+
current = item["text"]
|
| 876 |
+
|
| 877 |
+
yield (
|
| 878 |
+
current,
|
| 879 |
+
json.dumps(
|
| 880 |
+
item["metrics"] or {
|
| 881 |
+
"status": "Generating...",
|
| 882 |
+
"request_id": request_id,
|
| 883 |
+
},
|
| 884 |
+
indent=2,
|
| 885 |
+
ensure_ascii=False,
|
| 886 |
+
),
|
| 887 |
+
)
|
| 888 |
+
|
| 889 |
+
except Exception as exc:
|
| 890 |
+
yield (
|
| 891 |
+
f"**Error:** {exc}",
|
| 892 |
+
json.dumps({
|
| 893 |
+
"error": str(exc),
|
| 894 |
+
"traceback": traceback.format_exc()[-3000:],
|
| 895 |
+
}, indent=2, ensure_ascii=False),
|
| 896 |
+
)
|
| 897 |
+
|
| 898 |
+
|
| 899 |
+
def stop_generation():
|
| 900 |
+
with STOP_LOCK:
|
| 901 |
+
for event in STOP_EVENTS.values():
|
| 902 |
+
event.set()
|
| 903 |
+
|
| 904 |
+
return "Stop requested."
|
| 905 |
+
|
| 906 |
+
|
| 907 |
+
# ============================================================
|
| 908 |
+
# 8. MODEL SETTINGS / RELOAD
|
| 909 |
+
# ============================================================
|
| 910 |
+
|
| 911 |
+
def reload_model_ui(
|
| 912 |
+
model_id,
|
| 913 |
+
revision,
|
| 914 |
+
dtype,
|
| 915 |
+
quantization,
|
| 916 |
+
device_map,
|
| 917 |
+
attention,
|
| 918 |
+
trust_remote_code,
|
| 919 |
+
):
|
| 920 |
+
global MODEL, PROCESSOR, TOKENIZER
|
| 921 |
+
|
| 922 |
+
model_id = model_id.strip()
|
| 923 |
+
|
| 924 |
+
if not model_id:
|
| 925 |
+
raise gr.Error("Model ID cannot be empty.")
|
| 926 |
+
|
| 927 |
+
# Do not unload a model while a generation is still active.
|
| 928 |
+
with STOP_LOCK:
|
| 929 |
+
if STOP_EVENTS:
|
| 930 |
+
raise gr.Error(
|
| 931 |
+
"Wait for generation to finish before reloading the model."
|
| 932 |
+
)
|
| 933 |
+
|
| 934 |
+
with MODEL_LOCK:
|
| 935 |
+
old_model = MODEL
|
| 936 |
+
MODEL = None
|
| 937 |
+
PROCESSOR = None
|
| 938 |
+
TOKENIZER = None
|
| 939 |
|
| 940 |
+
del old_model
|
| 941 |
+
gc.collect()
|
| 942 |
|
| 943 |
+
if torch.cuda.is_available():
|
| 944 |
+
torch.cuda.empty_cache()
|
| 945 |
|
| 946 |
+
try:
|
| 947 |
+
load_model(
|
| 948 |
+
model_id,
|
| 949 |
+
revision,
|
| 950 |
+
dtype,
|
| 951 |
+
quantization,
|
| 952 |
+
device_map,
|
| 953 |
+
attention,
|
| 954 |
+
trust_remote_code,
|
| 955 |
+
)
|
| 956 |
+
except Exception as exc:
|
| 957 |
+
raise gr.Error(f"Model reload failed: {exc}") from exc
|
| 958 |
+
|
| 959 |
+
return (
|
| 960 |
+
f"Loaded: {model_id}",
|
| 961 |
+
json.dumps(ACTIVE_MODEL_CONFIG, indent=2, ensure_ascii=False),
|
| 962 |
+
)
|
| 963 |
+
|
| 964 |
+
|
| 965 |
+
def show_metrics():
|
| 966 |
+
return json.dumps(list(METRICS), indent=2, ensure_ascii=False)
|
| 967 |
+
|
| 968 |
+
|
| 969 |
+
def export_settings(*values):
|
| 970 |
+
settings = {
|
| 971 |
+
"system_prompt": values[0],
|
| 972 |
+
"history_limit": values[1],
|
| 973 |
+
"temperature": values[2],
|
| 974 |
+
"top_p": values[3],
|
| 975 |
+
"top_k": values[4],
|
| 976 |
+
"min_p": values[5],
|
| 977 |
+
"typical_p": values[6],
|
| 978 |
+
"repetition_penalty": values[7],
|
| 979 |
+
"no_repeat_ngram_size": values[8],
|
| 980 |
+
"max_new_tokens": values[9],
|
| 981 |
+
"min_new_tokens": values[10],
|
| 982 |
+
"num_beams": values[11],
|
| 983 |
+
"length_penalty": values[12],
|
| 984 |
+
"early_stopping": values[13],
|
| 985 |
+
"do_sample": values[14],
|
| 986 |
+
"use_cache": values[15],
|
| 987 |
+
"seed": values[16],
|
| 988 |
+
"max_time": values[17],
|
| 989 |
+
"epsilon_cutoff": values[18],
|
| 990 |
+
"eta_cutoff": values[19],
|
| 991 |
+
"enable_thinking": values[20],
|
| 992 |
+
"stop_sequences": values[21],
|
| 993 |
+
}
|
| 994 |
+
|
| 995 |
+
path = tempfile.mktemp(suffix=".json", prefix="qwen-settings-")
|
| 996 |
+
|
| 997 |
+
with open(path, "w", encoding="utf-8") as f:
|
| 998 |
+
json.dump(settings, f, indent=2, ensure_ascii=False)
|
| 999 |
+
|
| 1000 |
+
return path
|
| 1001 |
+
|
| 1002 |
+
|
| 1003 |
+
# ============================================================
|
| 1004 |
+
# 9. USER INTERFACE
|
| 1005 |
+
# ============================================================
|
| 1006 |
+
|
| 1007 |
+
with gr.Blocks(
|
| 1008 |
+
title=APP_TITLE,
|
| 1009 |
+
fill_height=True,
|
| 1010 |
+
theme=gr.themes.Soft(),
|
| 1011 |
+
) as demo:
|
| 1012 |
+
|
| 1013 |
+
gr.Markdown(
|
| 1014 |
+
"""
|
| 1015 |
+
# Qwen3.5 Advanced Chat
|
| 1016 |
+
|
| 1017 |
+
Advanced inference control panel for Qwen3.5-9B.
|
| 1018 |
+
|
| 1019 |
+
Configure sampling, reasoning, model loading, context,
|
| 1020 |
+
performance monitoring, and multimodal uploads.
|
| 1021 |
"""
|
| 1022 |
+
)
|
| 1023 |
+
|
| 1024 |
+
with gr.Row():
|
| 1025 |
+
with gr.Column(scale=3):
|
| 1026 |
+
user_message = gr.Textbox(
|
| 1027 |
+
label="Message",
|
| 1028 |
+
placeholder="Write your message here...",
|
| 1029 |
+
lines=4,
|
| 1030 |
+
)
|
| 1031 |
+
|
| 1032 |
+
upload_files = gr.File(
|
| 1033 |
+
label="Attachments (images and text files)",
|
| 1034 |
+
file_count="multiple",
|
| 1035 |
+
type="filepath",
|
| 1036 |
+
)
|
| 1037 |
+
|
| 1038 |
+
send_button = gr.Button("Generate", variant="primary")
|
| 1039 |
+
stop_button = gr.Button("Stop generation")
|
| 1040 |
+
|
| 1041 |
+
answer = gr.Markdown(label="Response")
|
| 1042 |
+
|
| 1043 |
+
with gr.Column(scale=2):
|
| 1044 |
+
gr.Markdown("### Performance")
|
| 1045 |
+
metrics_output = gr.Code(
|
| 1046 |
+
label="Last request metrics",
|
| 1047 |
+
language="json",
|
| 1048 |
+
value="{}",
|
| 1049 |
+
)
|
| 1050 |
+
|
| 1051 |
+
refresh_metrics = gr.Button("Refresh metrics")
|
| 1052 |
+
all_metrics = gr.Code(
|
| 1053 |
+
label="Recent requests",
|
| 1054 |
+
language="json",
|
| 1055 |
+
value="[]",
|
| 1056 |
+
)
|
| 1057 |
+
|
| 1058 |
+
# Keep full chat history as state.
|
| 1059 |
+
history_state = gr.State([])
|
| 1060 |
+
|
| 1061 |
+
with gr.Accordion("1. System prompt and context", open=False):
|
| 1062 |
+
system_prompt = gr.Textbox(
|
| 1063 |
+
label="System prompt",
|
| 1064 |
+
value=DEFAULT_SYSTEM_PROMPT,
|
| 1065 |
+
lines=5,
|
| 1066 |
+
)
|
| 1067 |
+
|
| 1068 |
+
history_limit = gr.Slider(
|
| 1069 |
+
minimum=0,
|
| 1070 |
+
maximum=40,
|
| 1071 |
+
value=12,
|
| 1072 |
+
step=1,
|
| 1073 |
+
label="Maximum prior messages",
|
| 1074 |
+
)
|
| 1075 |
+
|
| 1076 |
+
gr.Markdown(
|
| 1077 |
+
"The context token limit is configured with "
|
| 1078 |
+
"`MAX_CONTEXT_TOKENS`. Image tokens can consume additional context."
|
| 1079 |
+
)
|
| 1080 |
+
|
| 1081 |
+
with gr.Accordion("2. Sampling parameters", open=True):
|
| 1082 |
+
with gr.Row():
|
| 1083 |
+
temperature = gr.Slider(
|
| 1084 |
+
0, 2, value=0.7, step=0.05, label="Temperature"
|
| 1085 |
+
)
|
| 1086 |
+
top_p = gr.Slider(
|
| 1087 |
+
0, 1, value=0.8, step=0.01, label="Top-p"
|
| 1088 |
+
)
|
| 1089 |
+
top_k = gr.Slider(
|
| 1090 |
+
1, 100, value=20, step=1, label="Top-k"
|
| 1091 |
+
)
|
| 1092 |
+
|
| 1093 |
+
with gr.Row():
|
| 1094 |
+
min_p = gr.Slider(
|
| 1095 |
+
0, 1, value=0.0, step=0.01, label="Min-p"
|
| 1096 |
+
)
|
| 1097 |
+
typical_p = gr.Slider(
|
| 1098 |
+
0, 1, value=1.0, step=0.01, label="Typical-p"
|
| 1099 |
+
)
|
| 1100 |
+
|
| 1101 |
+
with gr.Row():
|
| 1102 |
+
repetition_penalty = gr.Slider(
|
| 1103 |
+
1, 2, value=1.0, step=0.05,
|
| 1104 |
+
label="Repetition penalty",
|
| 1105 |
+
)
|
| 1106 |
+
no_repeat_ngram_size = gr.Slider(
|
| 1107 |
+
0, 10, value=0, step=1,
|
| 1108 |
+
label="No-repeat n-gram size",
|
| 1109 |
+
)
|
| 1110 |
+
|
| 1111 |
+
with gr.Row():
|
| 1112 |
+
max_new_tokens = gr.Slider(
|
| 1113 |
+
16, 8192, value=1024, step=16,
|
| 1114 |
+
label="Max new tokens",
|
| 1115 |
+
)
|
| 1116 |
+
min_new_tokens = gr.Slider(
|
| 1117 |
+
0, 2048, value=0, step=8,
|
| 1118 |
+
label="Min new tokens",
|
| 1119 |
+
)
|
| 1120 |
+
|
| 1121 |
+
with gr.Row():
|
| 1122 |
+
do_sample = gr.Checkbox(
|
| 1123 |
+
value=True, label="Enable sampling"
|
| 1124 |
+
)
|
| 1125 |
+
use_cache = gr.Checkbox(
|
| 1126 |
+
value=True, label="Use KV cache"
|
| 1127 |
+
)
|
| 1128 |
+
|
| 1129 |
+
with gr.Row():
|
| 1130 |
+
num_beams = gr.Slider(
|
| 1131 |
+
1, 8, value=1, step=1, label="Beam count"
|
| 1132 |
+
)
|
| 1133 |
+
length_penalty = gr.Slider(
|
| 1134 |
+
0, 3, value=1.0, step=0.1,
|
| 1135 |
+
label="Length penalty",
|
| 1136 |
+
)
|
| 1137 |
+
early_stopping = gr.Checkbox(
|
| 1138 |
+
value=False, label="Early stopping"
|
| 1139 |
+
)
|
| 1140 |
+
|
| 1141 |
+
with gr.Row():
|
| 1142 |
+
epsilon_cutoff = gr.Slider(
|
| 1143 |
+
0, 0.01, value=0.0, step=0.0001,
|
| 1144 |
+
label="Epsilon cutoff",
|
| 1145 |
+
)
|
| 1146 |
+
eta_cutoff = gr.Slider(
|
| 1147 |
+
0, 0.1, value=0.0, step=0.001,
|
| 1148 |
+
label="Eta cutoff",
|
| 1149 |
+
)
|
| 1150 |
+
|
| 1151 |
+
seed = gr.Number(
|
| 1152 |
+
value=-1,
|
| 1153 |
+
precision=0,
|
| 1154 |
+
label="Random seed (-1 = no fixed seed)",
|
| 1155 |
+
)
|
| 1156 |
+
|
| 1157 |
+
max_time = gr.Slider(
|
| 1158 |
+
5, 180, value=90, step=5,
|
| 1159 |
+
label="Generation max time (seconds)",
|
| 1160 |
+
)
|
| 1161 |
+
|
| 1162 |
+
stop_sequences_text = gr.Textbox(
|
| 1163 |
+
label="Stop sequences (JSON array or one per line)",
|
| 1164 |
+
placeholder='["<|im_end|>", "STOP"]',
|
| 1165 |
+
lines=2,
|
| 1166 |
+
)
|
| 1167 |
+
|
| 1168 |
+
with gr.Accordion("3. Reasoning and chat template", open=False):
|
| 1169 |
+
enable_thinking = gr.Checkbox(
|
| 1170 |
+
value=False,
|
| 1171 |
+
label="Enable thinking",
|
| 1172 |
+
info=(
|
| 1173 |
+
"Qwen3.5 normally reasons by default. This option requests "
|
| 1174 |
+
"the template's enable_thinking setting when supported."
|
| 1175 |
+
),
|
| 1176 |
+
)
|
| 1177 |
+
|
| 1178 |
+
gr.Markdown(
|
| 1179 |
+
"""
|
| 1180 |
+
The chat template controls model-specific formatting. If the installed
|
| 1181 |
+
Transformers version does not support a template argument, the application
|
| 1182 |
+
falls back to the model's default template. The model may still reason
|
| 1183 |
+
internally even when thinking is not explicitly enabled.
|
| 1184 |
"""
|
| 1185 |
+
)
|
| 1186 |
+
|
| 1187 |
+
with gr.Accordion("4. Model loading and hardware", open=False):
|
| 1188 |
+
model_id_input = gr.Textbox(
|
| 1189 |
+
label="Hugging Face model ID",
|
| 1190 |
+
value=MODEL_ID,
|
| 1191 |
+
)
|
| 1192 |
+
|
| 1193 |
+
revision_input = gr.Textbox(
|
| 1194 |
+
label="Revision / branch",
|
| 1195 |
+
value=MODEL_REVISION,
|
| 1196 |
+
)
|
| 1197 |
+
|
| 1198 |
+
dtype_input = gr.Dropdown(
|
| 1199 |
+
choices=["bf16", "fp16", "fp32"],
|
| 1200 |
+
value=MODEL_DTYPE if MODEL_DTYPE in ["bf16", "fp16", "fp32"] else "bf16",
|
| 1201 |
+
label="Compute dtype",
|
| 1202 |
+
)
|
| 1203 |
+
|
| 1204 |
+
quantization_input = gr.Dropdown(
|
| 1205 |
+
choices=["none", "4bit", "8bit"],
|
| 1206 |
+
value=QUANTIZE if QUANTIZE in ["none", "4bit", "8bit"] else "none",
|
| 1207 |
+
label="Quantization",
|
| 1208 |
+
)
|
| 1209 |
+
|
| 1210 |
+
device_map_input = gr.Dropdown(
|
| 1211 |
+
choices=["auto", "cuda", "balanced", "cpu"],
|
| 1212 |
+
value=DEVICE_MAP if DEVICE_MAP in ["auto", "cuda", "balanced", "cpu"] else "auto",
|
| 1213 |
+
label="Device map",
|
| 1214 |
+
)
|
| 1215 |
+
|
| 1216 |
+
attention_input = gr.Dropdown(
|
| 1217 |
+
choices=["auto", "sdpa", "eager", "flash_attention_2"],
|
| 1218 |
+
value=ATTENTION_IMPLEMENTATION,
|
| 1219 |
+
label="Attention implementation",
|
| 1220 |
+
)
|
| 1221 |
|
| 1222 |
+
trust_remote_code_input = gr.Checkbox(
|
| 1223 |
+
value=TRUST_REMOTE_CODE,
|
| 1224 |
+
label="Trust remote code",
|
| 1225 |
+
)
|
| 1226 |
|
| 1227 |
+
reload_button = gr.Button(
|
| 1228 |
+
"Apply model settings and reload",
|
| 1229 |
+
variant="primary",
|
| 1230 |
+
)
|
| 1231 |
+
|
| 1232 |
+
model_status = gr.Textbox(
|
| 1233 |
+
label="Model status",
|
| 1234 |
+
value=f"Configured model: {MODEL_ID}",
|
| 1235 |
+
interactive=False,
|
| 1236 |
+
)
|
| 1237 |
+
|
| 1238 |
+
active_model_config = gr.Code(
|
| 1239 |
+
label="Active model configuration",
|
| 1240 |
+
language="json",
|
| 1241 |
+
value=json.dumps(ACTIVE_MODEL_CONFIG, indent=2),
|
| 1242 |
+
)
|
| 1243 |
+
|
| 1244 |
+
gr.Markdown(
|
| 1245 |
+
"""
|
| 1246 |
+
**Warning:** Reloading can take time and may fail if the GPU lacks memory.
|
| 1247 |
+
4-bit and 8-bit quantization require compatible bitsandbytes kernels.
|
| 1248 |
+
Device map and attention choices depend on the host hardware and installed
|
| 1249 |
+
libraries. ZeroGPU may restrict supported device placement and model loading.
|
| 1250 |
+
"""
|
| 1251 |
+
)
|
| 1252 |
+
|
| 1253 |
+
with gr.Accordion("5. Runtime and ZeroGPU", open=False):
|
| 1254 |
+
gr.Markdown(
|
| 1255 |
+
f"""
|
| 1256 |
+
- Configured GPU reservation: **{GPU_RESERVATION_SECONDS} seconds**
|
| 1257 |
+
- Maximum context estimate: **{MAX_CONTEXT_TOKENS} tokens**
|
| 1258 |
+
- Maximum attachment size: **{MAX_UPLOAD_MB} MB**
|
| 1259 |
+
|
| 1260 |
+
These runtime limits are configured with environment variables. A Gradio
|
| 1261 |
+
slider cannot override the hosting platform's actual GPU time limit.
|
| 1262 |
+
|
| 1263 |
+
Relevant environment variables:
|
| 1264 |
+
|
| 1265 |
+
- `GPU_RESERVATION_SECONDS`
|
| 1266 |
+
- `ZEROGPU_SIZE`
|
| 1267 |
+
- `MAX_CONTEXT_TOKENS`
|
| 1268 |
+
- `MAX_NEW_TOKENS`
|
| 1269 |
+
- `MODEL_ID`
|
| 1270 |
+
- `MODEL_REVISION`
|
| 1271 |
+
- `MODEL_DTYPE`
|
| 1272 |
+
- `QUANTIZE`
|
| 1273 |
+
- `DEVICE_MAP`
|
| 1274 |
+
- `ATTENTION_IMPLEMENTATION`
|
| 1275 |
+
"""
|
| 1276 |
+
)
|
| 1277 |
+
|
| 1278 |
+
with gr.Accordion("6. Import / export settings", open=False):
|
| 1279 |
+
export_button = gr.Button("Export generation settings")
|
| 1280 |
+
settings_file = gr.File(label="Settings JSON")
|
| 1281 |
+
|
| 1282 |
+
generation_inputs = [
|
| 1283 |
+
system_prompt,
|
| 1284 |
+
history_limit,
|
| 1285 |
+
temperature,
|
| 1286 |
+
top_p,
|
| 1287 |
+
top_k,
|
| 1288 |
+
min_p,
|
| 1289 |
+
typical_p,
|
| 1290 |
+
repetition_penalty,
|
| 1291 |
+
no_repeat_ngram_size,
|
| 1292 |
+
max_new_tokens,
|
| 1293 |
+
min_new_tokens,
|
| 1294 |
+
num_beams,
|
| 1295 |
+
length_penalty,
|
| 1296 |
+
early_stopping,
|
| 1297 |
+
do_sample,
|
| 1298 |
+
use_cache,
|
| 1299 |
+
seed,
|
| 1300 |
+
max_time,
|
| 1301 |
+
epsilon_cutoff,
|
| 1302 |
+
eta_cutoff,
|
| 1303 |
+
enable_thinking,
|
| 1304 |
+
stop_sequences_text,
|
| 1305 |
+
]
|
| 1306 |
+
|
| 1307 |
+
def run_chat(text, files, history, *settings):
|
| 1308 |
+
message = {
|
| 1309 |
+
"text": text or "",
|
| 1310 |
+
"files": files or [],
|
| 1311 |
+
}
|
| 1312 |
+
|
| 1313 |
+
for current_answer, current_metrics in respond(
|
| 1314 |
+
message,
|
| 1315 |
+
history,
|
| 1316 |
+
*settings,
|
| 1317 |
+
):
|
| 1318 |
+
yield current_answer, current_metrics
|
| 1319 |
+
|
| 1320 |
+
send_button.click(
|
| 1321 |
+
fn=run_chat,
|
| 1322 |
+
inputs=[
|
| 1323 |
+
user_message,
|
| 1324 |
+
upload_files,
|
| 1325 |
+
history_state,
|
| 1326 |
+
*generation_inputs,
|
| 1327 |
+
],
|
| 1328 |
+
outputs=[answer, metrics_output],
|
| 1329 |
+
)
|
| 1330 |
+
|
| 1331 |
+
user_message.submit(
|
| 1332 |
+
fn=run_chat,
|
| 1333 |
+
inputs=[
|
| 1334 |
+
user_message,
|
| 1335 |
+
upload_files,
|
| 1336 |
+
history_state,
|
| 1337 |
+
*generation_inputs,
|
| 1338 |
+
],
|
| 1339 |
+
outputs=[answer, metrics_output],
|
| 1340 |
+
)
|
| 1341 |
+
|
| 1342 |
+
stop_button.click(
|
| 1343 |
+
fn=stop_generation,
|
| 1344 |
+
inputs=[],
|
| 1345 |
+
outputs=[model_status],
|
| 1346 |
+
)
|
| 1347 |
+
|
| 1348 |
+
refresh_metrics.click(
|
| 1349 |
+
fn=show_metrics,
|
| 1350 |
+
inputs=[],
|
| 1351 |
+
outputs=[all_metrics],
|
| 1352 |
+
)
|
| 1353 |
+
|
| 1354 |
+
reload_button.click(
|
| 1355 |
+
fn=reload_model_ui,
|
| 1356 |
+
inputs=[
|
| 1357 |
+
model_id_input,
|
| 1358 |
+
revision_input,
|
| 1359 |
+
dtype_input,
|
| 1360 |
+
quantization_input,
|
| 1361 |
+
device_map_input,
|
| 1362 |
+
attention_input,
|
| 1363 |
+
trust_remote_code_input,
|
| 1364 |
+
],
|
| 1365 |
+
outputs=[model_status, active_model_config],
|
| 1366 |
+
)
|
| 1367 |
+
|
| 1368 |
+
export_button.click(
|
| 1369 |
+
fn=export_settings,
|
| 1370 |
+
inputs=generation_inputs,
|
| 1371 |
+
outputs=[settings_file],
|
| 1372 |
+
)
|
| 1373 |
+
|
| 1374 |
+
|
| 1375 |
+
# ============================================================
|
| 1376 |
+
# 10. STARTUP
|
| 1377 |
+
# ============================================================
|
| 1378 |
|
| 1379 |
if __name__ == "__main__":
|
| 1380 |
+
print("=" * 60)
|
| 1381 |
+
print(APP_TITLE)
|
| 1382 |
+
print("Model:", MODEL_ID)
|
| 1383 |
+
print("Device map:", DEVICE_MAP)
|
| 1384 |
+
print("Quantization:", QUANTIZE)
|
| 1385 |
+
print("Configured reservation:", GPU_RESERVATION_SECONDS)
|
| 1386 |
+
print("=" * 60)
|
| 1387 |
+
|
| 1388 |
+
# Load before serving so startup errors are visible in the logs.
|
| 1389 |
+
# If the hosting platform requires model loading inside its GPU
|
| 1390 |
+
# allocation, move this initialization into its supported lifecycle.
|
| 1391 |
+
try:
|
| 1392 |
+
ensure_model_loaded()
|
| 1393 |
+
except Exception:
|
| 1394 |
+
traceback.print_exc()
|
| 1395 |
+
|
| 1396 |
+
demo.queue(
|
| 1397 |
+
max_size=16,
|
| 1398 |
+
default_concurrency_limit=1,
|
| 1399 |
+
)
|
| 1400 |
+
|
| 1401 |
+
demo.launch(
|
| 1402 |
+
theme=gr.themes.Soft(),
|
| 1403 |
+
mcp_server=True,
|
| 1404 |
+
)
|