Update app.py
Browse files
app.py
CHANGED
|
@@ -19,7 +19,6 @@ try:
|
|
| 19 |
from spaces.config import Config as _ZeroGPUConfig
|
| 20 |
IS_ZEROGPU = bool(_ZeroGPUConfig.zero_gpu)
|
| 21 |
except ImportError:
|
| 22 |
-
# Local / non-ZeroGPU runtime — make @spaces.GPU harmless
|
| 23 |
class _DummySpaces:
|
| 24 |
@staticmethod
|
| 25 |
def GPU(fn):
|
|
@@ -35,9 +34,80 @@ DEFAULT_SYSTEM_PROMPT = (
|
|
| 35 |
STATIC_DIR = Path(__file__).parent / "static"
|
| 36 |
os.makedirs(STATIC_DIR, exist_ok=True)
|
| 37 |
|
| 38 |
-
# ──
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
MODEL_REGISTRY: Dict[str, Dict[str, Any]] = {
|
| 40 |
-
# Existing
|
| 41 |
"HuggingFaceTB/SmolLM2-360M-Instruct": {
|
| 42 |
"label": "SmolLM2 360M · ultra-fast",
|
| 43 |
"family": "causal-lm",
|
|
@@ -68,7 +138,6 @@ MODEL_REGISTRY: Dict[str, Dict[str, Any]] = {
|
|
| 68 |
"tasks": ["chat", "code", "summarize", "translate", "agent"],
|
| 69 |
"context": 128000,
|
| 70 |
},
|
| 71 |
-
# *new* T4-friendly additions
|
| 72 |
"microsoft/Phi-3-mini-4k-instruct": {
|
| 73 |
"label": "Phi-3 mini 4K · T4 sweet spot",
|
| 74 |
"family": "causal-lm",
|
|
@@ -168,6 +237,8 @@ def get_model(model_id: str) -> Dict[str, Any]:
|
|
| 168 |
if tokenizer.pad_token_id is None:
|
| 169 |
tokenizer.pad_token = tokenizer.eos_token
|
| 170 |
|
|
|
|
|
|
|
| 171 |
model = AutoModelForCausalLM.from_pretrained(
|
| 172 |
model_id,
|
| 173 |
torch_dtype=dtype,
|
|
@@ -211,11 +282,18 @@ def _build_prompt(model_id: str, messages: List[Dict[str, Any]],
|
|
| 211 |
if text:
|
| 212 |
flat_messages.append({"role": role, "content": text})
|
| 213 |
|
| 214 |
-
if
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
|
| 220 |
@spaces.GPU
|
| 221 |
def generate(model_id: str, messages: List[Dict[str, Any]],
|
|
|
|
| 19 |
from spaces.config import Config as _ZeroGPUConfig
|
| 20 |
IS_ZEROGPU = bool(_ZeroGPUConfig.zero_gpu)
|
| 21 |
except ImportError:
|
|
|
|
| 22 |
class _DummySpaces:
|
| 23 |
@staticmethod
|
| 24 |
def GPU(fn):
|
|
|
|
| 34 |
STATIC_DIR = Path(__file__).parent / "static"
|
| 35 |
os.makedirs(STATIC_DIR, exist_ok=True)
|
| 36 |
|
| 37 |
+
# ── Fallback chat templates for tokenizers missing .chat_template ───────
|
| 38 |
+
_FALLBACK_TEMPLATES = {
|
| 39 |
+
"chatml": (
|
| 40 |
+
"{% for message in messages %}"
|
| 41 |
+
"{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}"
|
| 42 |
+
"{% endfor %}"
|
| 43 |
+
"{% if add_generation_prompt %}"
|
| 44 |
+
"{{'<|im_start|>assistant\n'}}"
|
| 45 |
+
"{% endif %}"
|
| 46 |
+
),
|
| 47 |
+
"llama2": (
|
| 48 |
+
"{% if messages[0]['role'] == 'system' %}"
|
| 49 |
+
"{{'<<SYS>>\n' + messages[0]['content'] + '\n<</SYS>>\n\n'}}"
|
| 50 |
+
"{% set loop_messages = messages[1:] %}"
|
| 51 |
+
"{% else %}"
|
| 52 |
+
"{% set loop_messages = messages %}"
|
| 53 |
+
"{% endif %}"
|
| 54 |
+
"{% for message in loop_messages %}"
|
| 55 |
+
"{% if message['role'] == 'user' %}"
|
| 56 |
+
"{{'[INST] ' + message['content'] + ' [/INST]'}}"
|
| 57 |
+
"{% elif message['role'] == 'assistant' %}"
|
| 58 |
+
"{{message['content'] + '</s>'}}"
|
| 59 |
+
"{% endif %}"
|
| 60 |
+
"{% endfor %}"
|
| 61 |
+
),
|
| 62 |
+
"phi3": (
|
| 63 |
+
"{% for message in messages %}"
|
| 64 |
+
"{% if message['role'] == 'system' %}"
|
| 65 |
+
"{{'<|system|>\n' + message['content'] + '<|end|>\n'}}"
|
| 66 |
+
"{% elif message['role'] == 'user' %}"
|
| 67 |
+
"{{'<|user|>\n' + message['content'] + '<|end|>\n'}}"
|
| 68 |
+
"{% elif message['role'] == 'assistant' %}"
|
| 69 |
+
"{{'<|assistant|>\n' + message['content'] + '<|end|>\n'}}"
|
| 70 |
+
"{% endif %}"
|
| 71 |
+
"{% endfor %}"
|
| 72 |
+
"{% if add_generation_prompt %}"
|
| 73 |
+
"{{'<|assistant|>\n'}}"
|
| 74 |
+
"{% endif %}"
|
| 75 |
+
),
|
| 76 |
+
"qwen": (
|
| 77 |
+
"{% for message in messages %}"
|
| 78 |
+
"{% if message['role'] == 'system' %}"
|
| 79 |
+
"{{'<|im_start|>system\n' + message['content'] + '<|im_end|>\n'}}"
|
| 80 |
+
"{% elif message['role'] == 'user' %}"
|
| 81 |
+
"{{'<|im_start|>user\n' + message['content'] + '<|im_end|>\n'}}"
|
| 82 |
+
"{% elif message['role'] == 'assistant' %}"
|
| 83 |
+
"{{'<|im_start|>assistant\n' + message['content'] + '<|im_end|>\n'}}"
|
| 84 |
+
"{% endif %}"
|
| 85 |
+
"{% endfor %}"
|
| 86 |
+
"{% if add_generation_prompt %}"
|
| 87 |
+
"{{'<|im_start|>assistant\n'}}"
|
| 88 |
+
"{% endif %}"
|
| 89 |
+
),
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
def _pick_fallback_template(model_id: str) -> str:
|
| 93 |
+
mid = model_id.lower()
|
| 94 |
+
if "phi" in mid:
|
| 95 |
+
return _FALLBACK_TEMPLATES["phi3"]
|
| 96 |
+
if "qwen" in mid:
|
| 97 |
+
return _FALLBACK_TEMPLATES["qwen"]
|
| 98 |
+
if "tinyllama" in mid or "llama" in mid:
|
| 99 |
+
return _FALLBACK_TEMPLATES["llama2"]
|
| 100 |
+
return _FALLBACK_TEMPLATES["chatml"]
|
| 101 |
+
|
| 102 |
+
def _ensure_chat_template(tokenizer, model_id: str):
|
| 103 |
+
if getattr(tokenizer, "chat_template", None):
|
| 104 |
+
return
|
| 105 |
+
tpl = _pick_fallback_template(model_id)
|
| 106 |
+
tokenizer.chat_template = tpl
|
| 107 |
+
print(f"[chat_template] injected fallback template for {model_id}")
|
| 108 |
+
|
| 109 |
+
# ── Model Registry ──────────────────────────────────────────────────────
|
| 110 |
MODEL_REGISTRY: Dict[str, Dict[str, Any]] = {
|
|
|
|
| 111 |
"HuggingFaceTB/SmolLM2-360M-Instruct": {
|
| 112 |
"label": "SmolLM2 360M · ultra-fast",
|
| 113 |
"family": "causal-lm",
|
|
|
|
| 138 |
"tasks": ["chat", "code", "summarize", "translate", "agent"],
|
| 139 |
"context": 128000,
|
| 140 |
},
|
|
|
|
| 141 |
"microsoft/Phi-3-mini-4k-instruct": {
|
| 142 |
"label": "Phi-3 mini 4K · T4 sweet spot",
|
| 143 |
"family": "causal-lm",
|
|
|
|
| 237 |
if tokenizer.pad_token_id is None:
|
| 238 |
tokenizer.pad_token = tokenizer.eos_token
|
| 239 |
|
| 240 |
+
_ensure_chat_template(tokenizer, model_id)
|
| 241 |
+
|
| 242 |
model = AutoModelForCausalLM.from_pretrained(
|
| 243 |
model_id,
|
| 244 |
torch_dtype=dtype,
|
|
|
|
| 282 |
if text:
|
| 283 |
flat_messages.append({"role": role, "content": text})
|
| 284 |
|
| 285 |
+
if getattr(tokenizer, "chat_template", None):
|
| 286 |
+
try:
|
| 287 |
+
return tokenizer.apply_chat_template(
|
| 288 |
+
flat_messages, tokenize=False, add_generation_prompt=True
|
| 289 |
+
)
|
| 290 |
+
except Exception as e:
|
| 291 |
+
print(f"[chat_template] apply failed for {model_id}: {e}; using manual fallback")
|
| 292 |
+
|
| 293 |
+
# Manual fallback
|
| 294 |
+
lines = [f"{m['role']}: {m['content']}" for m in flat_messages]
|
| 295 |
+
lines.append("assistant:")
|
| 296 |
+
return "\n".join(lines) + "\n"
|
| 297 |
|
| 298 |
@spaces.GPU
|
| 299 |
def generate(model_id: str, messages: List[Dict[str, Any]],
|