Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -18,6 +18,7 @@ import unicodedata
|
|
| 18 |
from dataclasses import dataclass, field
|
| 19 |
from datetime import datetime
|
| 20 |
|
|
|
|
| 21 |
import torch
|
| 22 |
import torch.nn as nn
|
| 23 |
import torch.nn.functional as F
|
|
@@ -28,6 +29,22 @@ try:
|
|
| 28 |
except Exception: # older transformers
|
| 29 |
AutoModelForImageTextToText = None
|
| 30 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
# ββ Config ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 32 |
DEFAULT_MODEL_ID = os.environ.get("CARTOGEMMA_MODEL", "google/gemma-3-270m-it")
|
| 33 |
HF_TOKEN = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
|
|
@@ -196,8 +213,6 @@ class InteractiveProbe:
|
|
| 196 |
|
| 197 |
dtype = torch.bfloat16 if DEVICE == "cuda" else torch.float32
|
| 198 |
load_kw = dict(torch_dtype=dtype, **kw)
|
| 199 |
-
if DEVICE == "cuda":
|
| 200 |
-
load_kw["device_map"] = "auto"
|
| 201 |
# Try text CausalLM first; fall back to the multimodal head (gemma-3-4b,
|
| 202 |
# gemma-4, gemma3n are all image-text-to-text wrappers around a text LM).
|
| 203 |
self.model = None
|
|
@@ -213,8 +228,7 @@ class InteractiveProbe:
|
|
| 213 |
errs.append(f"{loader.__name__}: {type(e).__name__}: {e}")
|
| 214 |
if self.model is None:
|
| 215 |
raise RuntimeError("Could not load model with any auto-class:\n" + "\n".join(errs))
|
| 216 |
-
|
| 217 |
-
self.model = self.model.to(DEVICE)
|
| 218 |
self.model.eval()
|
| 219 |
|
| 220 |
# ββ Auto-discover the architecture (see resolver notes above) ββ
|
|
@@ -409,7 +423,7 @@ class InteractiveProbe:
|
|
| 409 |
cut = full_seq.shape[1]
|
| 410 |
else:
|
| 411 |
cut = min(trunk_len + 1 + tokens_to_keep, full_seq.shape[1])
|
| 412 |
-
self.history_ids = full_seq[:, :cut]
|
| 413 |
committed = self.tokenizer.decode(self.history_ids[0, trunk_len:], skip_special_tokens=True)
|
| 414 |
self.full_log.append({"type": "commit", "token": preview_obj["root_token"],
|
| 415 |
"full_text": committed, "kept_len": tokens_to_keep})
|
|
@@ -760,6 +774,39 @@ class Session:
|
|
| 760 |
self.loaded_system = None
|
| 761 |
self.loaded_user = None
|
| 762 |
self.last_selected = None # which branch index was last committed
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 763 |
|
| 764 |
def _reset_panes(self):
|
| 765 |
self.options = []
|
|
@@ -781,7 +828,16 @@ class Session:
|
|
| 781 |
)
|
| 782 |
if not changed:
|
| 783 |
return False
|
| 784 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 785 |
self.probe.set_seed()
|
| 786 |
self.probe.load_start(user_prompt or "", system_prompt or None)
|
| 787 |
self._reset_panes()
|
|
@@ -973,6 +1029,9 @@ def initial_load(model_id: str, system_prompt: str, user_prompt: str, s: Session
|
|
| 973 |
return panes_html(s) + (status_html(s),)
|
| 974 |
|
| 975 |
|
|
|
|
|
|
|
|
|
|
| 976 |
# ββ Gradio UI βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 977 |
CSS = """
|
| 978 |
/* ββ Global tightening ββ */
|
|
@@ -1102,17 +1161,11 @@ def build_ui():
|
|
| 1102 |
session = gr.State(Session())
|
| 1103 |
|
| 1104 |
# ββ Compact top bar: model | system | user | load ββ
|
| 1105 |
-
MODEL_PRESETS = [
|
| 1106 |
-
"google/gemma-3-270m-it",
|
| 1107 |
-
"google/gemma-3-1b-it",
|
| 1108 |
-
"google/gemma-3-1b-pt",
|
| 1109 |
-
"Qwen/Qwen3-0.6B",
|
| 1110 |
-
"meta-llama/Llama-3.2-1B-Instruct",
|
| 1111 |
-
]
|
| 1112 |
with gr.Row(elem_id="topbar"):
|
| 1113 |
model_id = gr.Dropdown(
|
| 1114 |
choices=MODEL_PRESETS, value=DEFAULT_MODEL_ID, label="Model",
|
| 1115 |
-
allow_custom_value=
|
| 1116 |
)
|
| 1117 |
system_prompt = gr.Textbox(label="System", value="",
|
| 1118 |
lines=1, max_lines=3, scale=4, container=True)
|
|
@@ -1176,29 +1229,42 @@ def build_ui():
|
|
| 1176 |
f"<div class='pane'><h3>Transcript</h3>{st}</div>",
|
| 1177 |
)
|
| 1178 |
|
|
|
|
| 1179 |
def on_load(mid, sp, up, s):
|
| 1180 |
-
|
| 1181 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1182 |
|
|
|
|
| 1183 |
def on_cmd(c, s, mid, sp):
|
| 1184 |
-
|
| 1185 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1186 |
|
| 1187 |
OUT_BASE = [summary_pane, ctx_pane, hm_pane, fut_pane, spark_pane, muted_html, status]
|
| 1188 |
load_btn.click(
|
| 1189 |
on_load,
|
| 1190 |
inputs=[model_id, system_prompt, user_prompt, session],
|
| 1191 |
outputs=OUT_BASE + [session],
|
|
|
|
| 1192 |
)
|
| 1193 |
run_btn.click(
|
| 1194 |
on_cmd,
|
| 1195 |
inputs=[cmd, session, model_id, system_prompt],
|
| 1196 |
outputs=OUT_BASE + [cmd, session],
|
|
|
|
| 1197 |
)
|
| 1198 |
cmd.submit(
|
| 1199 |
on_cmd,
|
| 1200 |
inputs=[cmd, session, model_id, system_prompt],
|
| 1201 |
outputs=OUT_BASE + [cmd, session],
|
|
|
|
| 1202 |
)
|
| 1203 |
return demo
|
| 1204 |
|
|
|
|
| 18 |
from dataclasses import dataclass, field
|
| 19 |
from datetime import datetime
|
| 20 |
|
| 21 |
+
import spaces # Must precede CUDA-touching imports on ZeroGPU
|
| 22 |
import torch
|
| 23 |
import torch.nn as nn
|
| 24 |
import torch.nn.functional as F
|
|
|
|
| 29 |
except Exception: # older transformers
|
| 30 |
AutoModelForImageTextToText = None
|
| 31 |
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
|
| 48 |
# ββ Config ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 49 |
DEFAULT_MODEL_ID = os.environ.get("CARTOGEMMA_MODEL", "google/gemma-3-270m-it")
|
| 50 |
HF_TOKEN = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
|
|
|
|
| 213 |
|
| 214 |
dtype = torch.bfloat16 if DEVICE == "cuda" else torch.float32
|
| 215 |
load_kw = dict(torch_dtype=dtype, **kw)
|
|
|
|
|
|
|
| 216 |
# Try text CausalLM first; fall back to the multimodal head (gemma-3-4b,
|
| 217 |
# gemma-4, gemma3n are all image-text-to-text wrappers around a text LM).
|
| 218 |
self.model = None
|
|
|
|
| 228 |
errs.append(f"{loader.__name__}: {type(e).__name__}: {e}")
|
| 229 |
if self.model is None:
|
| 230 |
raise RuntimeError("Could not load model with any auto-class:\n" + "\n".join(errs))
|
| 231 |
+
self.model = self.model.to(DEVICE)
|
|
|
|
| 232 |
self.model.eval()
|
| 233 |
|
| 234 |
# ββ Auto-discover the architecture (see resolver notes above) ββ
|
|
|
|
| 423 |
cut = full_seq.shape[1]
|
| 424 |
else:
|
| 425 |
cut = min(trunk_len + 1 + tokens_to_keep, full_seq.shape[1])
|
| 426 |
+
self.history_ids = full_seq[:, :cut].to(DEVICE)
|
| 427 |
committed = self.tokenizer.decode(self.history_ids[0, trunk_len:], skip_special_tokens=True)
|
| 428 |
self.full_log.append({"type": "commit", "token": preview_obj["root_token"],
|
| 429 |
"full_text": committed, "kept_len": tokens_to_keep})
|
|
|
|
| 774 |
self.loaded_system = None
|
| 775 |
self.loaded_user = None
|
| 776 |
self.last_selected = None # which branch index was last committed
|
| 777 |
+
self.history_cpu = None
|
| 778 |
+
self.muted_state = set()
|
| 779 |
+
self.full_log_state = []
|
| 780 |
+
|
| 781 |
+
def __getstate__(self):
|
| 782 |
+
d = self.__dict__.copy()
|
| 783 |
+
d["probe"] = None # never serialize model, CUDA tensors, or registered hooks
|
| 784 |
+
return d
|
| 785 |
+
|
| 786 |
+
def attach(self):
|
| 787 |
+
"""Restore per-user state on the GPU worker's singleton model."""
|
| 788 |
+
p = SHARED_PROBE
|
| 789 |
+
p.unmute_all() if p.muted_heads else None
|
| 790 |
+
p.snapshot = None
|
| 791 |
+
p.history_ids = self.history_cpu.to(DEVICE) if self.history_cpu is not None else None
|
| 792 |
+
p.full_log = list(self.full_log_state)
|
| 793 |
+
p.muted_heads = set(self.muted_state)
|
| 794 |
+
p._install_mute_hooks()
|
| 795 |
+
self.probe = p
|
| 796 |
+
|
| 797 |
+
def detach(self):
|
| 798 |
+
"""Ship only CPU data and plain objects back through ZeroGPU."""
|
| 799 |
+
p = self.probe
|
| 800 |
+
if p is not None:
|
| 801 |
+
self.history_cpu = p.history_ids.detach().cpu() if p.history_ids is not None else None
|
| 802 |
+
self.muted_state = set(p.muted_heads)
|
| 803 |
+
self.full_log_state = list(p.full_log)
|
| 804 |
+
p.snapshot = None
|
| 805 |
+
self.probe = None
|
| 806 |
+
for o in self.options:
|
| 807 |
+
if "full_ids" in o:
|
| 808 |
+
o["full_ids"] = o["full_ids"].detach().cpu()
|
| 809 |
+
|
| 810 |
|
| 811 |
def _reset_panes(self):
|
| 812 |
self.options = []
|
|
|
|
| 828 |
)
|
| 829 |
if not changed:
|
| 830 |
return False
|
| 831 |
+
if model_id != DEFAULT_MODEL_ID:
|
| 832 |
+
raise ValueError(f"ZeroGPU deployment is pinned to {DEFAULT_MODEL_ID}; change CARTOGEMMA_MODEL and restart to switch models")
|
| 833 |
+
self.probe = SHARED_PROBE
|
| 834 |
+
self.probe.unmute_all() if self.probe.muted_heads else None
|
| 835 |
+
self.probe.history_ids = None
|
| 836 |
+
self.probe.snapshot = None
|
| 837 |
+
self.probe.full_log = []
|
| 838 |
+
self.history_cpu = None
|
| 839 |
+
self.muted_state = set()
|
| 840 |
+
self.full_log_state = []
|
| 841 |
self.probe.set_seed()
|
| 842 |
self.probe.load_start(user_prompt or "", system_prompt or None)
|
| 843 |
self._reset_panes()
|
|
|
|
| 1029 |
return panes_html(s) + (status_html(s),)
|
| 1030 |
|
| 1031 |
|
| 1032 |
+
# Preload model on CUDA during Space startup; ZeroGPU packs its weights.
|
| 1033 |
+
SHARED_PROBE = InteractiveProbe(DEFAULT_MODEL_ID)
|
| 1034 |
+
|
| 1035 |
# ββ Gradio UI βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1036 |
CSS = """
|
| 1037 |
/* ββ Global tightening ββ */
|
|
|
|
| 1161 |
session = gr.State(Session())
|
| 1162 |
|
| 1163 |
# ββ Compact top bar: model | system | user | load ββ
|
| 1164 |
+
MODEL_PRESETS = [DEFAULT_MODEL_ID]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1165 |
with gr.Row(elem_id="topbar"):
|
| 1166 |
model_id = gr.Dropdown(
|
| 1167 |
choices=MODEL_PRESETS, value=DEFAULT_MODEL_ID, label="Model",
|
| 1168 |
+
allow_custom_value=False, filterable=False, scale=3, container=True,
|
| 1169 |
)
|
| 1170 |
system_prompt = gr.Textbox(label="System", value="",
|
| 1171 |
lines=1, max_lines=3, scale=4, container=True)
|
|
|
|
| 1229 |
f"<div class='pane'><h3>Transcript</h3>{st}</div>",
|
| 1230 |
)
|
| 1231 |
|
| 1232 |
+
@spaces.GPU(duration=120)
|
| 1233 |
def on_load(mid, sp, up, s):
|
| 1234 |
+
s.attach()
|
| 1235 |
+
try:
|
| 1236 |
+
summary, ctx, hm, fut, spk, mute, st = initial_load(mid, sp, up, s)
|
| 1237 |
+
return _wrap(summary, ctx, hm, fut, spk, mute, st) + (s,)
|
| 1238 |
+
finally:
|
| 1239 |
+
s.detach()
|
| 1240 |
|
| 1241 |
+
@spaces.GPU(duration=120)
|
| 1242 |
def on_cmd(c, s, mid, sp):
|
| 1243 |
+
s.attach()
|
| 1244 |
+
try:
|
| 1245 |
+
summary, ctx, hm, fut, spk, mute, st = handle_command(c, s, mid, sp)
|
| 1246 |
+
return _wrap(summary, ctx, hm, fut, spk, mute, st) + ("", s)
|
| 1247 |
+
finally:
|
| 1248 |
+
s.detach()
|
| 1249 |
|
| 1250 |
OUT_BASE = [summary_pane, ctx_pane, hm_pane, fut_pane, spark_pane, muted_html, status]
|
| 1251 |
load_btn.click(
|
| 1252 |
on_load,
|
| 1253 |
inputs=[model_id, system_prompt, user_prompt, session],
|
| 1254 |
outputs=OUT_BASE + [session],
|
| 1255 |
+
concurrency_id="cartogemma_gpu", concurrency_limit=1,
|
| 1256 |
)
|
| 1257 |
run_btn.click(
|
| 1258 |
on_cmd,
|
| 1259 |
inputs=[cmd, session, model_id, system_prompt],
|
| 1260 |
outputs=OUT_BASE + [cmd, session],
|
| 1261 |
+
concurrency_id="cartogemma_gpu", concurrency_limit=1,
|
| 1262 |
)
|
| 1263 |
cmd.submit(
|
| 1264 |
on_cmd,
|
| 1265 |
inputs=[cmd, session, model_id, system_prompt],
|
| 1266 |
outputs=OUT_BASE + [cmd, session],
|
| 1267 |
+
concurrency_id="cartogemma_gpu", concurrency_limit=1,
|
| 1268 |
)
|
| 1269 |
return demo
|
| 1270 |
|