Add AGILLM 4.3 Gradio GUI Space
Browse files- README.md +21 -6
- agillm41.py +0 -0
- app.py +547 -0
- requirements.txt +9 -0
README.md
CHANGED
|
@@ -1,13 +1,28 @@
|
|
| 1 |
---
|
| 2 |
title: AGILLM 4.3 ZeroGPU GUI
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
-
python_version:
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
title: AGILLM 4.3 ZeroGPU GUI
|
| 3 |
+
emoji: ⚡
|
| 4 |
+
colorFrom: indigo
|
| 5 |
+
colorTo: green
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 5.49.1
|
| 8 |
+
python_version: 3.10.13
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
| 11 |
+
startup_duration_timeout: 1h
|
| 12 |
+
models:
|
| 13 |
+
- OpenTransformer/AGILLM-4.3
|
| 14 |
+
tags:
|
| 15 |
+
- text-generation
|
| 16 |
+
- pytorch
|
| 17 |
+
- gradio
|
| 18 |
+
- zerogpu
|
| 19 |
+
- agillm
|
| 20 |
---
|
| 21 |
|
| 22 |
+
# AGILLM 4.3 ZeroGPU GUI
|
| 23 |
+
|
| 24 |
+
Gradio Space version of the AGILLM 4.3 local inference GUI for Hugging Face ZeroGPU.
|
| 25 |
+
|
| 26 |
+
This Space uses the same preferred `pretrain_delta_step00363424_20260703T1105Z.pt` checkpoint from `OpenTransformer/AGILLM-4.3`.
|
| 27 |
+
|
| 28 |
+
Inference runs inside a `spaces.GPU` call and supports Streaming vs Full result output. ZeroGPU is quota-limited, so shorter Max values are friendlier to the queue.
|
agillm41.py
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import re
|
| 4 |
+
import subprocess
|
| 5 |
+
import sys
|
| 6 |
+
import threading
|
| 7 |
+
import time
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
import gradio as gr
|
| 11 |
+
from huggingface_hub import hf_hub_download
|
| 12 |
+
|
| 13 |
+
try:
|
| 14 |
+
import spaces
|
| 15 |
+
except Exception:
|
| 16 |
+
class _SpacesFallback:
|
| 17 |
+
def GPU(self, *args, **kwargs):
|
| 18 |
+
if args and callable(args[0]) and len(args) == 1 and not kwargs:
|
| 19 |
+
return args[0]
|
| 20 |
+
|
| 21 |
+
def deco(fn):
|
| 22 |
+
return fn
|
| 23 |
+
|
| 24 |
+
return deco
|
| 25 |
+
|
| 26 |
+
spaces = _SpacesFallback()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
APP_DIR = Path(__file__).resolve().parent
|
| 30 |
+
RUNTIME = APP_DIR / "agillm41.py"
|
| 31 |
+
MODEL_REPO = "OpenTransformer/AGILLM-4.3"
|
| 32 |
+
CKPT_FILE = (
|
| 33 |
+
"checkpoints/recovery_fedC/artifacts/delta/"
|
| 34 |
+
"pretrain_delta_step00363424_20260703T1105Z__sha256_3e3f65ca7784/"
|
| 35 |
+
"pretrain_delta_step00363424_20260703T1105Z.pt"
|
| 36 |
+
)
|
| 37 |
+
TOKENIZER_FILE = (
|
| 38 |
+
"checkpoints/recovery_fedC/artifacts/full/"
|
| 39 |
+
"pretrain_step00002127_from00243186_20260701T0647Z__sha256_760874aadf59/"
|
| 40 |
+
"pretrain_step00002127_from00243186_20260701T0647Z.pt.tokenizer.json"
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
PROFILE = os.environ.get("AGILLM_SPACE_PROFILE", "cpu").strip().lower()
|
| 44 |
+
SPACE_REPO_NAME = os.environ.get("SPACE_REPO_NAME", "").strip().lower()
|
| 45 |
+
ACCELERATOR = os.environ.get("ACCELERATOR", "").strip().lower()
|
| 46 |
+
ZERO_GPU = (
|
| 47 |
+
PROFILE in {"zero", "zerogpu", "zero-gpu", "gpu"}
|
| 48 |
+
or "zerogpu" in SPACE_REPO_NAME
|
| 49 |
+
or ACCELERATOR.startswith("zero")
|
| 50 |
+
)
|
| 51 |
+
STAT_RE = re.compile(r"\[(?P<sec>[0-9.]+)s \| (?P<tok>[0-9]+) tokens \| (?P<tps>[0-9.]+) tok/s\]")
|
| 52 |
+
SERVER_LOCK = threading.RLock()
|
| 53 |
+
SERVER_PROC = None
|
| 54 |
+
SERVER_KEY = None
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _space_threads(default=2):
|
| 58 |
+
raw = os.environ.get("CPU_CORES") or os.cpu_count() or default
|
| 59 |
+
try:
|
| 60 |
+
return max(1, min(8, int(float(raw))))
|
| 61 |
+
except Exception:
|
| 62 |
+
return default
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _materialize_files():
|
| 66 |
+
local_dir = APP_DIR / "checkpoints"
|
| 67 |
+
local_dir.mkdir(parents=True, exist_ok=True)
|
| 68 |
+
ckpt = Path(hf_hub_download(MODEL_REPO, CKPT_FILE, repo_type="model", local_dir=local_dir))
|
| 69 |
+
tokenizer = Path(hf_hub_download(MODEL_REPO, TOKENIZER_FILE, repo_type="model", local_dir=local_dir))
|
| 70 |
+
return ckpt, tokenizer
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _runtime_env(tokenizer, threads):
|
| 74 |
+
env = os.environ.copy()
|
| 75 |
+
env["PYTHONUNBUFFERED"] = "1"
|
| 76 |
+
env["PYTHONUTF8"] = "1"
|
| 77 |
+
env["AGILLM43_TOKENIZER_JSON"] = str(tokenizer)
|
| 78 |
+
env["OMP_NUM_THREADS"] = str(max(1, int(threads)))
|
| 79 |
+
env["MKL_NUM_THREADS"] = str(max(1, int(threads)))
|
| 80 |
+
return env
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _mode_parts(mode_label):
|
| 84 |
+
if mode_label == "sat fixed":
|
| 85 |
+
return "sat", False
|
| 86 |
+
if mode_label == "sat var":
|
| 87 |
+
return "sat", True
|
| 88 |
+
return mode_label, None
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _payload(
|
| 92 |
+
prompt,
|
| 93 |
+
mode_label,
|
| 94 |
+
output_mode,
|
| 95 |
+
max_new,
|
| 96 |
+
min_new,
|
| 97 |
+
nat_passes,
|
| 98 |
+
temperature,
|
| 99 |
+
top_p,
|
| 100 |
+
top_k,
|
| 101 |
+
greedy,
|
| 102 |
+
ignore_eos,
|
| 103 |
+
repetition_penalty,
|
| 104 |
+
presence_penalty,
|
| 105 |
+
frequency_penalty,
|
| 106 |
+
penalty_last_n,
|
| 107 |
+
):
|
| 108 |
+
mode, sat_var = _mode_parts(mode_label)
|
| 109 |
+
data = {
|
| 110 |
+
"prompt": str(prompt or ""),
|
| 111 |
+
"mode": mode,
|
| 112 |
+
"max_new": int(max_new),
|
| 113 |
+
"min_new": int(min_new),
|
| 114 |
+
"nat_passes": int(nat_passes),
|
| 115 |
+
"temperature": float(temperature),
|
| 116 |
+
"top_p": float(top_p),
|
| 117 |
+
"top_k": int(top_k),
|
| 118 |
+
"greedy": bool(greedy),
|
| 119 |
+
"ignore_eos": bool(ignore_eos),
|
| 120 |
+
"repetition_penalty": float(repetition_penalty),
|
| 121 |
+
"presence_penalty": float(presence_penalty),
|
| 122 |
+
"frequency_penalty": float(frequency_penalty),
|
| 123 |
+
"penalty_last_n": int(penalty_last_n),
|
| 124 |
+
"stream": output_mode == "Streaming",
|
| 125 |
+
}
|
| 126 |
+
if sat_var is not None:
|
| 127 |
+
data["var"] = bool(sat_var)
|
| 128 |
+
return data
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def _command_from_payload(ckpt, data, device, threads):
|
| 132 |
+
cmd = [
|
| 133 |
+
sys.executable,
|
| 134 |
+
"-u",
|
| 135 |
+
str(RUNTIME),
|
| 136 |
+
"infer",
|
| 137 |
+
"--ckpt",
|
| 138 |
+
str(ckpt),
|
| 139 |
+
"--prompt",
|
| 140 |
+
data["prompt"],
|
| 141 |
+
"--mode",
|
| 142 |
+
data["mode"],
|
| 143 |
+
"--max_new",
|
| 144 |
+
str(data["max_new"]),
|
| 145 |
+
"--min_new",
|
| 146 |
+
str(data["min_new"]),
|
| 147 |
+
"--temperature",
|
| 148 |
+
str(data["temperature"]),
|
| 149 |
+
"--top_p",
|
| 150 |
+
str(data["top_p"]),
|
| 151 |
+
"--top_k",
|
| 152 |
+
str(data["top_k"]),
|
| 153 |
+
"--repetition_penalty",
|
| 154 |
+
str(data["repetition_penalty"]),
|
| 155 |
+
"--presence_penalty",
|
| 156 |
+
str(data["presence_penalty"]),
|
| 157 |
+
"--frequency_penalty",
|
| 158 |
+
str(data["frequency_penalty"]),
|
| 159 |
+
"--penalty_last_n",
|
| 160 |
+
str(data["penalty_last_n"]),
|
| 161 |
+
"--plain-output",
|
| 162 |
+
"--device",
|
| 163 |
+
device,
|
| 164 |
+
]
|
| 165 |
+
if device == "cpu":
|
| 166 |
+
cmd.extend(["--cpu_threads", str(max(1, int(threads))), "--infer_dtype", "fp32"])
|
| 167 |
+
else:
|
| 168 |
+
cmd.extend(["--infer_dtype", "fp16", "--attn_backend", "sdpa"])
|
| 169 |
+
if data.get("stream"):
|
| 170 |
+
cmd.append("--stream")
|
| 171 |
+
if data.get("greedy"):
|
| 172 |
+
cmd.append("--greedy")
|
| 173 |
+
if data.get("ignore_eos"):
|
| 174 |
+
cmd.append("--ignore_eos")
|
| 175 |
+
if data["mode"] == "nat":
|
| 176 |
+
cmd.extend(["--nat_passes", str(data["nat_passes"])])
|
| 177 |
+
if data["mode"] == "sat" and "var" in data:
|
| 178 |
+
cmd.append("--var" if data["var"] else "--no-var")
|
| 179 |
+
return cmd
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def _server_command(ckpt, threads):
|
| 183 |
+
return [
|
| 184 |
+
sys.executable,
|
| 185 |
+
"-u",
|
| 186 |
+
str(RUNTIME),
|
| 187 |
+
"infer",
|
| 188 |
+
"--server",
|
| 189 |
+
"--device",
|
| 190 |
+
"cpu",
|
| 191 |
+
"--cpu_threads",
|
| 192 |
+
str(max(1, int(threads))),
|
| 193 |
+
"--ckpt",
|
| 194 |
+
str(ckpt),
|
| 195 |
+
"--mode",
|
| 196 |
+
"nat",
|
| 197 |
+
"--max_new",
|
| 198 |
+
"64",
|
| 199 |
+
"--min_new",
|
| 200 |
+
"0",
|
| 201 |
+
"--temperature",
|
| 202 |
+
"0.25",
|
| 203 |
+
"--top_p",
|
| 204 |
+
"1.0",
|
| 205 |
+
"--greedy",
|
| 206 |
+
"--ignore_eos",
|
| 207 |
+
"--plain-output",
|
| 208 |
+
"--repetition_penalty",
|
| 209 |
+
"2.0",
|
| 210 |
+
"--presence_penalty",
|
| 211 |
+
"0.8",
|
| 212 |
+
"--frequency_penalty",
|
| 213 |
+
"1.2",
|
| 214 |
+
"--penalty_last_n",
|
| 215 |
+
"0",
|
| 216 |
+
"--infer_dtype",
|
| 217 |
+
"fp32",
|
| 218 |
+
]
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def _alive(proc):
|
| 222 |
+
return proc is not None and proc.poll() is None
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def _ensure_cpu_server(threads):
|
| 226 |
+
global SERVER_PROC, SERVER_KEY
|
| 227 |
+
ckpt, tokenizer = _materialize_files()
|
| 228 |
+
key = (str(ckpt), str(tokenizer), int(threads))
|
| 229 |
+
if _alive(SERVER_PROC) and SERVER_KEY == key:
|
| 230 |
+
return SERVER_PROC, ckpt
|
| 231 |
+
|
| 232 |
+
if _alive(SERVER_PROC):
|
| 233 |
+
try:
|
| 234 |
+
SERVER_PROC.stdin.write('{"cmd":"quit"}\n')
|
| 235 |
+
SERVER_PROC.stdin.flush()
|
| 236 |
+
except Exception:
|
| 237 |
+
pass
|
| 238 |
+
try:
|
| 239 |
+
SERVER_PROC.terminate()
|
| 240 |
+
except Exception:
|
| 241 |
+
pass
|
| 242 |
+
|
| 243 |
+
env = _runtime_env(tokenizer, threads)
|
| 244 |
+
proc = subprocess.Popen(
|
| 245 |
+
_server_command(ckpt, threads),
|
| 246 |
+
cwd=str(APP_DIR),
|
| 247 |
+
env=env,
|
| 248 |
+
text=True,
|
| 249 |
+
encoding="utf-8",
|
| 250 |
+
errors="replace",
|
| 251 |
+
stdin=subprocess.PIPE,
|
| 252 |
+
stdout=subprocess.PIPE,
|
| 253 |
+
stderr=subprocess.STDOUT,
|
| 254 |
+
bufsize=1,
|
| 255 |
+
)
|
| 256 |
+
boot = []
|
| 257 |
+
deadline = time.time() + 900
|
| 258 |
+
while time.time() < deadline:
|
| 259 |
+
line = proc.stdout.readline()
|
| 260 |
+
if line:
|
| 261 |
+
boot.append(line.rstrip("\n"))
|
| 262 |
+
if "[INFER_SERVER_READY]" in line:
|
| 263 |
+
SERVER_PROC = proc
|
| 264 |
+
SERVER_KEY = key
|
| 265 |
+
return proc, ckpt
|
| 266 |
+
if proc.poll() is not None:
|
| 267 |
+
tail = "\n".join(boot[-40:])
|
| 268 |
+
raise RuntimeError(f"runtime exited during warm load\n{tail}")
|
| 269 |
+
raise TimeoutError("warm load timed out before runtime was ready")
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def _strip_prompt(text, prompt):
|
| 273 |
+
text = (text or "").strip()
|
| 274 |
+
prompt = (prompt or "").strip()
|
| 275 |
+
if prompt and text.startswith(prompt):
|
| 276 |
+
return text[len(prompt):].lstrip()
|
| 277 |
+
return text
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def _stats_status(kind, started, stats, ckpt_name):
|
| 281 |
+
elapsed = max(0.001, time.time() - started)
|
| 282 |
+
if not stats:
|
| 283 |
+
return f"{kind} | button_to_done={elapsed:.2f}s | checkpoint={ckpt_name}"
|
| 284 |
+
tokens = int(stats.get("tokens") or 0)
|
| 285 |
+
button_tps = tokens / elapsed if tokens else 0.0
|
| 286 |
+
return (
|
| 287 |
+
f"{kind} | button_to_done={elapsed:.2f}s | "
|
| 288 |
+
f"button_to_done_tok_s={button_tps:.2f} | "
|
| 289 |
+
f"generation={stats.get('gen_s', '?')}s | "
|
| 290 |
+
f"generation_tok_s={stats.get('tok_s', '?')} | "
|
| 291 |
+
f"tokens={tokens} | checkpoint={ckpt_name}"
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def _read_result_lines(proc, prompt, streaming, started, ckpt_name):
|
| 296 |
+
slots = None
|
| 297 |
+
stats = None
|
| 298 |
+
final_lines = []
|
| 299 |
+
saw_start = False
|
| 300 |
+
while True:
|
| 301 |
+
line = proc.stdout.readline()
|
| 302 |
+
if not line:
|
| 303 |
+
if proc.poll() is not None:
|
| 304 |
+
raise RuntimeError("runtime exited mid-generation")
|
| 305 |
+
continue
|
| 306 |
+
s = line.rstrip("\n")
|
| 307 |
+
if "[INFER_SERVER_RESULT_START]" in s:
|
| 308 |
+
saw_start = True
|
| 309 |
+
continue
|
| 310 |
+
if "[INFER_SERVER_RESULT_END]" in s:
|
| 311 |
+
break
|
| 312 |
+
if "[INFER_SERVER_ERROR]" in s:
|
| 313 |
+
raise RuntimeError(s)
|
| 314 |
+
if not saw_start:
|
| 315 |
+
continue
|
| 316 |
+
if s.startswith("[STREAM_BEGIN] "):
|
| 317 |
+
try:
|
| 318 |
+
info = json.loads(s.split("] ", 1)[1])
|
| 319 |
+
slots = [""] * int(info.get("slots") or 0)
|
| 320 |
+
if streaming:
|
| 321 |
+
yield "".join("." for _ in slots), "streaming..."
|
| 322 |
+
except Exception:
|
| 323 |
+
pass
|
| 324 |
+
continue
|
| 325 |
+
if s.startswith("[STREAM_NAT] ") or s.startswith("[STREAM_AR] ") or s.startswith("[STREAM_SAT] "):
|
| 326 |
+
try:
|
| 327 |
+
event = json.loads(s.split("] ", 1)[1])
|
| 328 |
+
idx = event.get("pos", event.get("i"))
|
| 329 |
+
if slots is not None and idx is not None:
|
| 330 |
+
idx = int(idx)
|
| 331 |
+
if 0 <= idx < len(slots):
|
| 332 |
+
slots[idx] = str(event.get("text") or "")
|
| 333 |
+
if streaming and slots is not None:
|
| 334 |
+
yield "".join(piece if piece else "." for piece in slots), "streaming..."
|
| 335 |
+
except Exception:
|
| 336 |
+
pass
|
| 337 |
+
continue
|
| 338 |
+
match = STAT_RE.search(s)
|
| 339 |
+
if match:
|
| 340 |
+
stats = {
|
| 341 |
+
"gen_s": float(match.group("sec")),
|
| 342 |
+
"tokens": int(match.group("tok")),
|
| 343 |
+
"tok_s": float(match.group("tps")),
|
| 344 |
+
}
|
| 345 |
+
continue
|
| 346 |
+
if s.startswith("[infer]") or s.startswith("Generating") or s.startswith("["):
|
| 347 |
+
continue
|
| 348 |
+
final_lines.append(s)
|
| 349 |
+
if streaming and slots is None:
|
| 350 |
+
yield _strip_prompt(s, prompt), "streaming..."
|
| 351 |
+
|
| 352 |
+
final = _strip_prompt("\n".join(final_lines), prompt)
|
| 353 |
+
yield final, _stats_status("done", started, stats, ckpt_name)
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
def _read_one_shot(proc, prompt, streaming, started, ckpt_name):
|
| 357 |
+
slots = None
|
| 358 |
+
stats = None
|
| 359 |
+
final_lines = []
|
| 360 |
+
while True:
|
| 361 |
+
line = proc.stdout.readline()
|
| 362 |
+
if not line:
|
| 363 |
+
if proc.poll() is not None:
|
| 364 |
+
break
|
| 365 |
+
continue
|
| 366 |
+
s = line.rstrip("\n")
|
| 367 |
+
if s.startswith("[STREAM_BEGIN] "):
|
| 368 |
+
try:
|
| 369 |
+
info = json.loads(s.split("] ", 1)[1])
|
| 370 |
+
slots = [""] * int(info.get("slots") or 0)
|
| 371 |
+
if streaming:
|
| 372 |
+
yield "".join("." for _ in slots), "streaming..."
|
| 373 |
+
except Exception:
|
| 374 |
+
pass
|
| 375 |
+
continue
|
| 376 |
+
if s.startswith("[STREAM_NAT] ") or s.startswith("[STREAM_AR] ") or s.startswith("[STREAM_SAT] "):
|
| 377 |
+
try:
|
| 378 |
+
event = json.loads(s.split("] ", 1)[1])
|
| 379 |
+
idx = event.get("pos", event.get("i"))
|
| 380 |
+
if slots is not None and idx is not None:
|
| 381 |
+
idx = int(idx)
|
| 382 |
+
if 0 <= idx < len(slots):
|
| 383 |
+
slots[idx] = str(event.get("text") or "")
|
| 384 |
+
if streaming and slots is not None:
|
| 385 |
+
yield "".join(piece if piece else "." for piece in slots), "streaming..."
|
| 386 |
+
except Exception:
|
| 387 |
+
pass
|
| 388 |
+
continue
|
| 389 |
+
match = STAT_RE.search(s)
|
| 390 |
+
if match:
|
| 391 |
+
stats = {
|
| 392 |
+
"gen_s": float(match.group("sec")),
|
| 393 |
+
"tokens": int(match.group("tok")),
|
| 394 |
+
"tok_s": float(match.group("tps")),
|
| 395 |
+
}
|
| 396 |
+
continue
|
| 397 |
+
if s.startswith("[infer]") or s.startswith("Generating") or s.startswith("["):
|
| 398 |
+
continue
|
| 399 |
+
final_lines.append(s)
|
| 400 |
+
if streaming and slots is None:
|
| 401 |
+
yield _strip_prompt(s, prompt), "streaming..."
|
| 402 |
+
rc = proc.wait()
|
| 403 |
+
if rc != 0:
|
| 404 |
+
raise RuntimeError(f"runtime exited with rc={rc}")
|
| 405 |
+
final = _strip_prompt("\n".join(final_lines), prompt)
|
| 406 |
+
yield final, _stats_status("done", started, stats, ckpt_name)
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def _generate_cpu(data, threads):
|
| 410 |
+
streaming = bool(data.get("stream"))
|
| 411 |
+
started = time.time()
|
| 412 |
+
yield "", "loading warm CPU runtime..."
|
| 413 |
+
with SERVER_LOCK:
|
| 414 |
+
proc, ckpt = _ensure_cpu_server(threads)
|
| 415 |
+
proc.stdin.write(json.dumps(data) + "\n")
|
| 416 |
+
proc.stdin.flush()
|
| 417 |
+
yield from _read_result_lines(proc, data["prompt"], streaming, started, ckpt.name)
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
def _generate_once(data, device, threads):
|
| 421 |
+
streaming = bool(data.get("stream"))
|
| 422 |
+
started = time.time()
|
| 423 |
+
yield "", f"loading {device} runtime..."
|
| 424 |
+
ckpt, tokenizer = _materialize_files()
|
| 425 |
+
env = _runtime_env(tokenizer, threads)
|
| 426 |
+
proc = subprocess.Popen(
|
| 427 |
+
_command_from_payload(ckpt, data, device, threads),
|
| 428 |
+
cwd=str(APP_DIR),
|
| 429 |
+
env=env,
|
| 430 |
+
text=True,
|
| 431 |
+
encoding="utf-8",
|
| 432 |
+
errors="replace",
|
| 433 |
+
stdin=subprocess.DEVNULL,
|
| 434 |
+
stdout=subprocess.PIPE,
|
| 435 |
+
stderr=subprocess.STDOUT,
|
| 436 |
+
bufsize=1,
|
| 437 |
+
)
|
| 438 |
+
yield from _read_one_shot(proc, data["prompt"], streaming, started, ckpt.name)
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
def _collect_inputs(*args):
|
| 442 |
+
return _payload(*args[:-1]), int(args[-1])
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def generate_cpu(*args):
|
| 446 |
+
data, threads = _collect_inputs(*args)
|
| 447 |
+
yield from _generate_cpu(data, threads)
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
def _gpu_duration(*args):
|
| 451 |
+
try:
|
| 452 |
+
max_new = int(args[3])
|
| 453 |
+
except Exception:
|
| 454 |
+
max_new = 16
|
| 455 |
+
return max(60, min(240, 70 + max_new * 4))
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
@spaces.GPU(duration=_gpu_duration)
|
| 459 |
+
def generate_zerogpu(*args):
|
| 460 |
+
data, threads = _collect_inputs(*args)
|
| 461 |
+
yield from _generate_once(data, "cuda", threads)
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
def warm_load(threads):
|
| 465 |
+
if ZERO_GPU:
|
| 466 |
+
return "ZeroGPU warms inside each GPU call."
|
| 467 |
+
started = time.time()
|
| 468 |
+
with SERVER_LOCK:
|
| 469 |
+
_proc, ckpt = _ensure_cpu_server(int(threads))
|
| 470 |
+
return f"CPU runtime ready in {time.time() - started:.2f}s | checkpoint={ckpt.name}"
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def default_status():
|
| 474 |
+
hw = "ZeroGPU" if ZERO_GPU else "CPU"
|
| 475 |
+
accelerator = os.environ.get("ACCELERATOR", "none")
|
| 476 |
+
return f"{hw} Space | accelerator={accelerator} | profile={PROFILE}"
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
with gr.Blocks(title="AGILLM 4.3 Inference") as demo:
|
| 480 |
+
with gr.Row():
|
| 481 |
+
prompt = gr.Textbox(
|
| 482 |
+
value="The quick brown fox jumps over the lazy dog and then",
|
| 483 |
+
label="Prompt",
|
| 484 |
+
lines=2,
|
| 485 |
+
scale=5,
|
| 486 |
+
)
|
| 487 |
+
with gr.Row():
|
| 488 |
+
mode = gr.Dropdown(["nat", "sat fixed", "sat var", "ar"], value="nat", label="Mode")
|
| 489 |
+
output_mode = gr.Dropdown(["Streaming", "Full result"], value="Streaming", label="Output")
|
| 490 |
+
max_new = gr.Slider(1, 256, value=16 if ZERO_GPU else 8, step=1, label="Max")
|
| 491 |
+
min_new = gr.Slider(0, 256, value=0, step=1, label="Min")
|
| 492 |
+
nat_passes = gr.Slider(1, 128, value=1, step=1, label="NAT passes")
|
| 493 |
+
threads = gr.Slider(1, 8, value=_space_threads(), step=1, label="Threads")
|
| 494 |
+
with gr.Row():
|
| 495 |
+
temperature = gr.Number(value=0.25, label="Temp")
|
| 496 |
+
top_p = gr.Number(value=1.0, label="Top-p")
|
| 497 |
+
top_k = gr.Number(value=0, label="Top-k")
|
| 498 |
+
greedy = gr.Checkbox(value=True, label="Greedy")
|
| 499 |
+
ignore_eos = gr.Checkbox(value=True, label="Ignore EOS")
|
| 500 |
+
with gr.Row():
|
| 501 |
+
repetition_penalty = gr.Number(value=2.0, label="Repeat pen")
|
| 502 |
+
presence_penalty = gr.Number(value=0.8, label="Presence")
|
| 503 |
+
frequency_penalty = gr.Number(value=1.2, label="Frequency")
|
| 504 |
+
penalty_last_n = gr.Number(value=0, precision=0, label="Last N")
|
| 505 |
+
with gr.Row():
|
| 506 |
+
run = gr.Button("Run Inference", variant="primary")
|
| 507 |
+
warm = gr.Button("Warm Load")
|
| 508 |
+
output = gr.Textbox(label="Output", lines=14, show_copy_button=True)
|
| 509 |
+
status = gr.Textbox(value=default_status(), label="Status", lines=3)
|
| 510 |
+
|
| 511 |
+
inputs = [
|
| 512 |
+
prompt,
|
| 513 |
+
mode,
|
| 514 |
+
output_mode,
|
| 515 |
+
max_new,
|
| 516 |
+
min_new,
|
| 517 |
+
nat_passes,
|
| 518 |
+
temperature,
|
| 519 |
+
top_p,
|
| 520 |
+
top_k,
|
| 521 |
+
greedy,
|
| 522 |
+
ignore_eos,
|
| 523 |
+
repetition_penalty,
|
| 524 |
+
presence_penalty,
|
| 525 |
+
frequency_penalty,
|
| 526 |
+
penalty_last_n,
|
| 527 |
+
threads,
|
| 528 |
+
]
|
| 529 |
+
run.click(
|
| 530 |
+
fn=generate_zerogpu if ZERO_GPU else generate_cpu,
|
| 531 |
+
inputs=inputs,
|
| 532 |
+
outputs=[output, status],
|
| 533 |
+
show_progress="minimal",
|
| 534 |
+
concurrency_limit=1,
|
| 535 |
+
)
|
| 536 |
+
prompt.submit(
|
| 537 |
+
fn=generate_zerogpu if ZERO_GPU else generate_cpu,
|
| 538 |
+
inputs=inputs,
|
| 539 |
+
outputs=[output, status],
|
| 540 |
+
show_progress="minimal",
|
| 541 |
+
concurrency_limit=1,
|
| 542 |
+
)
|
| 543 |
+
warm.click(fn=warm_load, inputs=[threads], outputs=[status], show_progress="minimal", concurrency_limit=1)
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
if __name__ == "__main__":
|
| 547 |
+
demo.queue(max_size=8, default_concurrency_limit=1).launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch==2.8.0
|
| 2 |
+
gradio>=5.49.0
|
| 3 |
+
spaces
|
| 4 |
+
huggingface_hub>=1.21.0
|
| 5 |
+
transformers>=4.55.0
|
| 6 |
+
datasets>=4.0.0
|
| 7 |
+
tokenizers>=0.21.0
|
| 8 |
+
zstandard>=0.23.0
|
| 9 |
+
numpy>=1.26.0
|