CJHauser commited on
Commit
af65aab
路
verified 路
1 Parent(s): 3bed81a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +226 -67
app.py CHANGED
@@ -1,18 +1,49 @@
1
- import os, sys, json, time, threading, subprocess, glob, html, logging, collections
2
- import datetime, shutil, platform, traceback
3
  from http.server import BaseHTTPRequestHandler, HTTPServer
4
  from huggingface_hub import HfApi, hf_hub_download
5
 
6
  DATA = "/data"
7
  BUCKET = os.environ.get("BUCKET", "")
8
  MAX_PARAMS_B = 1.5
9
- MAX_GB = 3.0
 
10
  TIMEOUT = 900
11
  HEARTBEAT_S = 30
12
  SUMMARY_EVERY = 50
13
  N_QUESTIONS = 25
 
 
14
  api = HfApi()
15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  STATUS = {"current": "starting", "queue": 0, "model_started": 0.0, "stage": "init"}
17
  SESSION = {"ok": 0, "failed": 0, "skipped": 0, "started": time.time()}
18
  CACHE = {"t": 0, "rows": [], "counts": {}}
@@ -30,8 +61,7 @@ class BufHandler(logging.Handler):
30
  def setup_log():
31
  log.setLevel(logging.DEBUG)
32
  fmt = logging.Formatter("%(asctime)s %(levelname)s %(message)s", "%H:%M:%S")
33
- sh = logging.StreamHandler(sys.stdout)
34
- handlers = [sh, BufHandler()]
35
  try:
36
  os.makedirs(f"{DATA}/logs", exist_ok=True)
37
  day = datetime.date.today().isoformat()
@@ -62,15 +92,37 @@ def disk_free_gb(path):
62
 
63
 
64
  def startup_report():
65
- log.info("=== startup ===")
66
  log.info("python %s on %s, cpus=%s", platform.python_version(), platform.platform(), os.cpu_count())
 
 
 
 
 
 
 
 
 
 
67
  try:
68
  import llama_cpp
69
  log.info("llama_cpp version %s", llama_cpp.__version__)
 
 
 
 
70
  except Exception as e:
71
  log.error("llama_cpp import failed: %s", e)
72
- log.info("config: MAX_PARAMS_B=%s MAX_GB=%s TIMEOUT=%ss N_QUESTIONS=%s BUCKET=%s",
73
- MAX_PARAMS_B, MAX_GB, TIMEOUT, N_QUESTIONS, BUCKET or "(unset)")
 
 
 
 
 
 
 
 
74
  log.info("HF_TOKEN set: %s, HF_HOME=%s", bool(os.environ.get("HF_TOKEN")), os.environ.get("HF_HOME"))
75
  log.info("mem available: %.1f GB, disk free (cwd): %.1f GB, disk free (%s): %.1f GB",
76
  mem_avail_gb(), disk_free_gb("."), DATA, disk_free_gb(DATA))
@@ -81,20 +133,23 @@ def startup_report():
81
  log.info("%s is writable", DATA)
82
  except Exception as e:
83
  log.error("%s is NOT writable (%s): results will not persist!", DATA, e)
84
- log.info("existing result files: %d", len(glob.glob(f"{DATA}/results/*.json")))
 
85
 
86
 
87
  # ---------- worker (separate process) ----------
 
88
  def worker(path):
89
  def say(msg):
90
  print(msg, flush=True)
91
 
92
  t_start = time.time()
93
- say(f"worker start: {os.path.basename(path)} ({os.path.getsize(path) / 1e9:.2f} GB)")
94
 
95
  t = time.time()
96
  from llama_cpp import Llama
97
- from datasets import load_dataset
 
98
  say(f"imports done in {time.time() - t:.1f}s")
99
 
100
  t = time.time()
@@ -102,26 +157,78 @@ def worker(path):
102
  say(f"dataset loaded in {time.time() - t:.1f}s ({len(ds)} questions)")
103
 
104
  t = time.time()
105
- verbose = os.environ.get("LLAMA_VERBOSE") == "1"
106
- llm = Llama(model_path=path, n_ctx=512, n_threads=2, verbose=verbose)
 
 
 
 
 
 
 
 
107
  say(f"model loaded in {time.time() - t:.1f}s")
108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  correct, toks, t0 = 0, 0, time.time()
110
  for i, ex in enumerate(ds):
111
  qt = time.time()
112
- opts = "\n".join(f"{l}. {t}" for l, t in zip(ex["choices"]["label"], ex["choices"]["text"]))
113
- out = llm(f"Question: {ex['question']}\n{opts}\nAnswer:", max_tokens=2, temperature=0)
114
- pt, ct = out["usage"]["prompt_tokens"], out["usage"]["completion_tokens"]
115
- toks += pt + ct
116
- pred = out["choices"][0]["text"]
117
- ok = pred.strip().upper().startswith(ex["answerKey"])
 
 
 
 
 
 
 
 
 
 
 
118
  correct += ok
119
- say(f"Q{i + 1}/{len(ds)} expected={ex['answerKey']} got={pred!r} {'OK' if ok else 'x'} "
120
- f"prompt_tok={pt} out_tok={ct} {time.time() - qt:.1f}s running={correct}/{i + 1}")
 
 
 
 
 
 
 
121
 
122
  elapsed = time.time() - t0
123
- say(f"benchmark done in {elapsed:.1f}s, worker total {time.time() - t_start:.1f}s")
124
- say("RESULT " + json.dumps({"arc_easy_25": correct / len(ds), "tok_per_s": round(toks / elapsed, 1)}))
 
 
 
 
125
 
126
 
127
  def run_worker(path):
@@ -137,26 +244,43 @@ def run_worker(path):
137
 
138
  timer = threading.Timer(TIMEOUT, kill)
139
  timer.start()
140
- result, tail = None, collections.deque(maxlen=15)
 
141
  try:
142
  for line in proc.stdout:
143
  line = line.rstrip()
144
  if not line:
145
  continue
 
 
146
  if line.startswith("RESULT "):
147
  result = json.loads(line[7:])
148
  continue
 
 
 
 
 
149
  tail.append(line)
 
 
 
 
 
 
 
150
  log.info(" [worker] %s", line[:400])
151
  proc.wait()
152
  finally:
153
  timer.cancel()
154
- return proc.returncode, result, list(tail), timed_out["v"]
 
 
155
 
156
 
157
  # ---------- storage (mounted bucket) ----------
158
  def load_done():
159
- p = f"{DATA}/state/done.txt"
160
  return set(open(p).read().split()) if os.path.exists(p) else set()
161
 
162
 
@@ -167,6 +291,16 @@ def push(text, remote):
167
  f.write(text)
168
 
169
 
 
 
 
 
 
 
 
 
 
 
170
  # ---------- heartbeat ----------
171
  def heartbeat():
172
  while True:
@@ -182,11 +316,11 @@ def heartbeat():
182
  # ---------- main loop ----------
183
  def loop():
184
  done = load_done()
185
- log.info("resuming: %d models already done", len(done))
186
  STATUS["stage"] = "listing"
187
  t = time.time()
188
  try:
189
- ids = sorted(m.id for m in api.list_models(filter="gguf", limit=5000))
190
  except Exception:
191
  log.exception("list_models failed")
192
  STATUS["current"] = "error: list_models failed"
@@ -197,48 +331,66 @@ def loop():
197
 
198
  for n, mid in enumerate(todo, 1):
199
  STATUS.update(current=mid, model_started=time.time(), stage="metadata")
200
- result, path, t0 = {"model": mid, "ts": time.time()}, None, time.time()
201
  log.info("[%d/%d] %s: start", n, len(todo), mid)
202
  try:
203
  t = time.time()
204
  info = api.model_info(mid, files_metadata=True)
205
  gguf = getattr(info, "gguf", None) or {}
206
  params_b = (gguf.get("total") or 0) / 1e9
 
 
 
207
  all_gguf = [s for s in info.siblings if s.rfilename.endswith(".gguf")]
208
- files = [s for s in all_gguf if s.size and s.size / 1e9 <= MAX_GB]
209
- log.debug("%s: metadata in %.1fs, gguf_meta_keys=%s params=%.3fB gguf_files=%d usable=%d",
210
- mid, time.time() - t, sorted(gguf.keys())[:8], params_b, len(all_gguf), len(files))
211
-
212
- if not params_b:
213
- result["status"] = "skipped_no_param_metadata"
214
- log.info("%s: skip, no param count in gguf metadata", mid)
215
- elif params_b > MAX_PARAMS_B:
216
  result.update(status="skipped_too_big", params_b=round(params_b, 2))
217
  log.info("%s: skip, %.2fB params > %.1fB limit", mid, params_b, MAX_PARAMS_B)
218
- elif not files:
219
- result["status"] = "skipped_no_usable_file"
220
- sizes = [f"{s.rfilename}={((s.size or 0) / 1e9):.2f}GB" for s in all_gguf[:5]]
221
- log.info("%s: skip, no gguf <= %.1f GB (found %d: %s)", mid, MAX_GB, len(all_gguf), sizes)
222
  else:
223
- f = min(files, key=lambda s: s.size)
224
- log.info("%s: %.2fB params, %d candidate files, picked %s (%.2f GB)",
225
- mid, params_b, len(files), f.rfilename, f.size / 1e9)
226
- STATUS["stage"] = "download"
227
- t = time.time()
228
- path = hf_hub_download(mid, f.rfilename)
229
- log.info("%s: downloaded in %.1fs (%.1f MB/s), mem_avail=%.1fGB disk_free=%.1fGB",
230
- mid, time.time() - t, f.size / 1e6 / max(time.time() - t, 0.01),
231
- mem_avail_gb(), disk_free_gb("."))
232
- result.update(file=f.rfilename, params_b=round(params_b, 2))
233
-
234
- STATUS["stage"] = "benchmark"
235
- rc, res, tail, timed_out = run_worker(path)
236
- if timed_out:
237
- result.update(status="failed", error=f"timeout after {TIMEOUT}s")
238
- elif rc == 0 and res:
239
- result.update(res, status="ok")
240
  else:
241
- result.update(status="failed", error=f"exit code {rc}: " + " | ".join(tail)[-500:])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
242
  except Exception as e:
243
  log.exception("%s: exception during processing", mid)
244
  result.update(status="failed", error=f"{type(e).__name__}: {e}"[:500])
@@ -254,18 +406,21 @@ def loop():
254
  dt = time.time() - t0
255
  if s == "ok":
256
  SESSION["ok"] += 1
257
- log.info("%s: OK score=%.2f tok/s=%s (%.0fs total)", mid, result["arc_easy_25"], result["tok_per_s"], dt)
 
258
  elif s == "failed":
259
  SESSION["failed"] += 1
260
  log.error("%s: FAILED after %.0fs: %s", mid, dt, result.get("error", "").replace("\n", " | ")[:400])
261
  else:
262
  SESSION["skipped"] += 1
 
 
263
 
264
  STATUS["stage"] = "saving"
265
  try:
266
  push(json.dumps(result), f"results/{mid.replace('/', '__')}.json")
267
  done.add(mid)
268
- push("\n".join(sorted(done)), "state/done.txt")
269
  log.debug("%s: saved result (%d done total)", mid, len(done))
270
  except Exception:
271
  log.exception("%s: write failed", mid)
@@ -283,12 +438,15 @@ def loop():
283
  def refresh():
284
  if time.time() - CACHE["t"] < 60:
285
  return
286
- rows, counts = [], {"ok": 0, "failed": 0, "skipped": 0}
287
  for f in glob.glob(f"{DATA}/results/*.json"):
288
  try:
289
  r = json.load(open(f))
290
  except Exception:
291
  continue
 
 
 
292
  s = r.get("status", "")
293
  if s == "ok":
294
  counts["ok"] += 1
@@ -319,7 +477,7 @@ class H(BaseHTTPRequestHandler):
319
  refresh()
320
  c = CACHE["counts"]
321
  body = "".join(
322
- f"<tr><td>{html.escape(r['model'])}</td><td>{r['params_b']}B</td>"
323
  f"<td>{r['arc_easy_25']:.2f}</td><td>{r['tok_per_s']}</td>"
324
  f"<td>{html.escape(r.get('file', ''))}</td></tr>" for r in CACHE["rows"])
325
  link = f'<a href="https://huggingface.co/buckets/{BUCKET}">bucket</a>' if BUCKET else "bucket"
@@ -327,13 +485,14 @@ class H(BaseHTTPRequestHandler):
327
  page = f"""<html><body style="font-family:sans-serif;max-width:900px;margin:2em auto">
328
  <h2>Tiny model leaderboard</h2>
329
  <p>Now: <b>{html.escape(STATUS['current'])}</b> ({STATUS['stage']}, {el:.0f}s)<br>
330
- all-time: ok {c.get('ok', 0)} 路 failed {c.get('failed', 0)} 路 skipped {c.get('skipped', 0)}
331
- 路 queue {STATUS['queue']}<br>
332
  this session: ok {SESSION['ok']} 路 failed {SESSION['failed']} 路 skipped {SESSION['skipped']}</p>
333
- <p>Raw results: {link} (top 200 shown, refreshed every 60s) 路
 
334
  <a href="/logs">recent logs</a> (<a href="/logs?n=1000">1000 lines</a>)</p>
335
  <table border=1 cellpadding=4><tr><th>model</th><th>params</th><th>ARC-E ({N_QUESTIONS})</th>
336
- <th>tok/s</th><th>file</th></tr>{body}</table></body></html>"""
337
  self.send_response(200)
338
  self.send_header("Content-Type", "text/html")
339
  self.end_headers()
 
1
+ import os, sys, re, json, math, time, threading, subprocess, glob, html, logging, collections
2
+ import datetime, shutil, platform
3
  from http.server import BaseHTTPRequestHandler, HTTPServer
4
  from huggingface_hub import HfApi, hf_hub_download
5
 
6
  DATA = "/data"
7
  BUCKET = os.environ.get("BUCKET", "")
8
  MAX_PARAMS_B = 1.5
9
+ MAX_GB = 3.0 # file size cap when the repo reports a param count
10
+ UNKNOWN_MAX_GB = 1.6 # tighter cap when params are unknown (verified after load)
11
  TIMEOUT = 900
12
  HEARTBEAT_S = 30
13
  SUMMARY_EVERY = 50
14
  N_QUESTIONS = 25
15
+ BENCH = 2 # scoring version: 2 = next-token letter logits
16
+ DONE_FILE = "state/done-v2.txt"
17
  api = HfApi()
18
 
19
+
20
+ def cpu_quota():
21
+ """CPUs this container may actually use (cgroup quota), or None if unknown."""
22
+ try:
23
+ q, p = open("/sys/fs/cgroup/cpu.max").read().split()
24
+ if q != "max":
25
+ return max(1, round(int(q) / int(p)))
26
+ except Exception:
27
+ pass
28
+ try:
29
+ q = int(open("/sys/fs/cgroup/cpu/cpu.cfs_quota_us").read())
30
+ p = int(open("/sys/fs/cgroup/cpu/cpu.cfs_period_us").read())
31
+ if q > 0:
32
+ return max(1, round(q / p))
33
+ except Exception:
34
+ pass
35
+ return None
36
+
37
+
38
+ THREADS = int(os.environ.get("THREADS", "0") or 0) or cpu_quota() or 2
39
+
40
+ # files that are never a standalone language model
41
+ BAD_NAME = re.compile(r"mmproj|lora|adapter|imatrix|draft", re.I)
42
+ SHARD = re.compile(r"-\d{5}-of-\d{5}", re.I)
43
+ NON_TEXT_TASKS = {"text-to-image", "image-to-image", "image-to-3d", "text-to-3d", "text-to-video",
44
+ "image-to-video", "unconditional-image-generation", "text-to-speech",
45
+ "automatic-speech-recognition"}
46
+
47
  STATUS = {"current": "starting", "queue": 0, "model_started": 0.0, "stage": "init"}
48
  SESSION = {"ok": 0, "failed": 0, "skipped": 0, "started": time.time()}
49
  CACHE = {"t": 0, "rows": [], "counts": {}}
 
61
  def setup_log():
62
  log.setLevel(logging.DEBUG)
63
  fmt = logging.Formatter("%(asctime)s %(levelname)s %(message)s", "%H:%M:%S")
64
+ handlers = [logging.StreamHandler(sys.stdout), BufHandler()]
 
65
  try:
66
  os.makedirs(f"{DATA}/logs", exist_ok=True)
67
  day = datetime.date.today().isoformat()
 
92
 
93
 
94
  def startup_report():
95
+ log.info("=== startup (bench v%d) ===", BENCH)
96
  log.info("python %s on %s, cpus=%s", platform.python_version(), platform.platform(), os.cpu_count())
97
+ try:
98
+ log.info("affinity cpus=%d, cgroup quota=%s, using THREADS=%d",
99
+ len(os.sched_getaffinity(0)), cpu_quota(), THREADS)
100
+ except Exception:
101
+ log.info("cgroup quota=%s, using THREADS=%d", cpu_quota(), THREADS)
102
+ for p in ("/sys/fs/cgroup/cpu.max", "/sys/fs/cgroup/memory.max"):
103
+ try:
104
+ log.info("%s = %s", p, open(p).read().strip())
105
+ except Exception:
106
+ pass
107
  try:
108
  import llama_cpp
109
  log.info("llama_cpp version %s", llama_cpp.__version__)
110
+ try:
111
+ log.info("llama.cpp system info: %s", llama_cpp.llama_print_system_info().decode().strip())
112
+ except Exception as e:
113
+ log.warning("could not read llama.cpp system info: %s", e)
114
  except Exception as e:
115
  log.error("llama_cpp import failed: %s", e)
116
+ try:
117
+ cpuinfo = open("/proc/cpuinfo").read()
118
+ model = re.search(r"model name\s*:\s*(.+)", cpuinfo)
119
+ flags = re.search(r"flags\s*:\s*(.+)", cpuinfo)
120
+ wanted = [f for f in ("avx", "avx2", "avx512f", "fma", "f16c") if flags and f" {f} " in f" {flags.group(1)} "]
121
+ log.info("cpu: %s | simd flags: %s", model.group(1) if model else "?", wanted)
122
+ except Exception:
123
+ pass
124
+ log.info("config: MAX_PARAMS_B=%s MAX_GB=%s UNKNOWN_MAX_GB=%s TIMEOUT=%ss N_QUESTIONS=%s BUCKET=%s",
125
+ MAX_PARAMS_B, MAX_GB, UNKNOWN_MAX_GB, TIMEOUT, N_QUESTIONS, BUCKET or "(unset)")
126
  log.info("HF_TOKEN set: %s, HF_HOME=%s", bool(os.environ.get("HF_TOKEN")), os.environ.get("HF_HOME"))
127
  log.info("mem available: %.1f GB, disk free (cwd): %.1f GB, disk free (%s): %.1f GB",
128
  mem_avail_gb(), disk_free_gb("."), DATA, disk_free_gb(DATA))
 
133
  log.info("%s is writable", DATA)
134
  except Exception as e:
135
  log.error("%s is NOT writable (%s): results will not persist!", DATA, e)
136
+ log.info("existing result files: %d, done in v%d list: %d",
137
+ len(glob.glob(f"{DATA}/results/*.json")), BENCH, len(load_done()))
138
 
139
 
140
  # ---------- worker (separate process) ----------
141
+ # exit codes: 0 ok, 3 model failed to load, 4 projected too slow, 5 actually too big
142
  def worker(path):
143
  def say(msg):
144
  print(msg, flush=True)
145
 
146
  t_start = time.time()
147
+ say(f"worker start: {os.path.basename(path)} ({os.path.getsize(path) / 1e9:.2f} GB) threads={THREADS}")
148
 
149
  t = time.time()
150
  from llama_cpp import Llama
151
+ from datasets import load_dataset, disable_progress_bars
152
+ disable_progress_bars()
153
  say(f"imports done in {time.time() - t:.1f}s")
154
 
155
  t = time.time()
 
157
  say(f"dataset loaded in {time.time() - t:.1f}s ({len(ds)} questions)")
158
 
159
  t = time.time()
160
+ try:
161
+ llm = Llama(model_path=path, n_ctx=512, n_threads=THREADS, n_threads_batch=THREADS, verbose=False)
162
+ except Exception as e:
163
+ say(f"LOAD_FAILED {type(e).__name__}: {e}")
164
+ say("LOAD_RETRY_VERBOSE (re-running loader with llama.cpp output to capture the reason)")
165
+ try:
166
+ Llama(model_path=path, n_ctx=512, n_threads=THREADS, n_threads_batch=THREADS, verbose=True)
167
+ except Exception:
168
+ pass
169
+ sys.exit(3)
170
  say(f"model loaded in {time.time() - t:.1f}s")
171
 
172
+ n_params = None
173
+ try:
174
+ n_params = int(llm._model.n_params())
175
+ except Exception as e:
176
+ say(f"could not read actual param count: {e}")
177
+ if n_params:
178
+ say(f"N_PARAMS {n_params} ({n_params / 1e9:.3f}B actual)")
179
+ if n_params / 1e9 > MAX_PARAMS_B * 1.1:
180
+ say(f"TOO_BIG {n_params / 1e9:.2f}B > {MAX_PARAMS_B}B limit")
181
+ sys.exit(5)
182
+
183
+ # warm-up: page the weights in so the first question isn't penalised
184
+ try:
185
+ t = time.time()
186
+ warm = llm.tokenize(("Question: what is the capital of France? " * 8).encode())[:64]
187
+ llm.reset()
188
+ llm.eval(warm)
189
+ say(f"warm-up ({len(warm)} tokens) in {time.time() - t:.1f}s")
190
+ except Exception as e:
191
+ say(f"warm-up failed (ignored): {e}")
192
+
193
+ label_ids = {}
194
  correct, toks, t0 = 0, 0, time.time()
195
  for i, ex in enumerate(ds):
196
  qt = time.time()
197
+ labels = ex["choices"]["label"]
198
+ opts = "\n".join(f"{l}. {t}" for l, t in zip(labels, ex["choices"]["text"]))
199
+ prompt = f"Question: {ex['question']}\n{opts}\nAnswer:"
200
+ for lab in labels:
201
+ if lab not in label_ids:
202
+ label_ids[lab] = llm.tokenize(f"Answer: {lab}".encode(), add_bos=False)[-1]
203
+ ptoks = llm.tokenize(prompt.encode())[-500:]
204
+ llm.reset()
205
+ llm.eval(ptoks)
206
+ logits = llm.scores[llm.n_tokens - 1]
207
+ vals = [float(logits[label_ids[l]]) for l in labels]
208
+ m = max(vals)
209
+ exps = [math.exp(v - m) for v in vals]
210
+ probs = [e / sum(exps) for e in exps]
211
+ best = max(range(len(labels)), key=lambda k: vals[k])
212
+ pred = labels[best]
213
+ ok = pred == ex["answerKey"]
214
  correct += ok
215
+ toks += len(ptoks)
216
+ say(f"Q{i + 1}/{len(ds)} expected={ex['answerKey']} pred={pred} conf={probs[best]:.2f} "
217
+ f"{'OK' if ok else 'x'} prompt_tok={len(ptoks)} {time.time() - qt:.1f}s running={correct}/{i + 1}")
218
+ if i == 2:
219
+ proj = (time.time() - t0) / 3 * len(ds)
220
+ say(f"projected benchmark time: {proj:.0f}s (limit {TIMEOUT}s)")
221
+ if proj > TIMEOUT * 0.9:
222
+ say(f"TOO_SLOW projected {proj:.0f}s")
223
+ sys.exit(4)
224
 
225
  elapsed = time.time() - t0
226
+ say(f"benchmark done in {elapsed:.1f}s ({toks / elapsed:.1f} prompt tok/s), worker total {time.time() - t_start:.1f}s")
227
+ say("RESULT " + json.dumps({"arc_easy_25": correct / len(ds), "tok_per_s": round(toks / elapsed, 1),
228
+ "n_params": n_params}))
229
+
230
+
231
+ LOADER_HINT = re.compile(r"error|unknown|fail|unsupported|arch|invalid|mismatch|missing|not found", re.I)
232
 
233
 
234
  def run_worker(path):
 
244
 
245
  timer = threading.Timer(TIMEOUT, kill)
246
  timer.start()
247
+ result, n_params = None, None
248
+ tail, verbose_mode, hints = collections.deque(maxlen=15), False, []
249
  try:
250
  for line in proc.stdout:
251
  line = line.rstrip()
252
  if not line:
253
  continue
254
+ if "unauthenticated requests" in line or line.startswith("Generating "):
255
+ continue
256
  if line.startswith("RESULT "):
257
  result = json.loads(line[7:])
258
  continue
259
+ if line.startswith("N_PARAMS "):
260
+ try:
261
+ n_params = int(line.split()[1])
262
+ except ValueError:
263
+ pass
264
  tail.append(line)
265
+ if line.startswith("LOAD_RETRY_VERBOSE"):
266
+ verbose_mode = True
267
+ if verbose_mode and not line.startswith(("LOAD_", "worker")):
268
+ # raw llama.cpp loader chatter: keep only the lines that explain the failure
269
+ if LOADER_HINT.search(line) and len(hints) < 8:
270
+ hints.append(line[:300])
271
+ continue
272
  log.info(" [worker] %s", line[:400])
273
  proc.wait()
274
  finally:
275
  timer.cancel()
276
+ for h in hints:
277
+ log.warning(" [llama.cpp] %s", h)
278
+ return proc.returncode, result, list(tail), timed_out["v"], hints, n_params
279
 
280
 
281
  # ---------- storage (mounted bucket) ----------
282
  def load_done():
283
+ p = f"{DATA}/{DONE_FILE}"
284
  return set(open(p).read().split()) if os.path.exists(p) else set()
285
 
286
 
 
291
  f.write(text)
292
 
293
 
294
+ # ---------- file selection ----------
295
+ def pick_file(siblings, max_gb):
296
+ cands = [s for s in siblings if s.rfilename.endswith(".gguf") and s.size and s.size / 1e9 <= max_gb
297
+ and not BAD_NAME.search(s.rfilename) and not SHARD.search(s.rfilename)]
298
+ if not cands:
299
+ return None, cands
300
+ q4 = [s for s in cands if "q4_k_m" in s.rfilename.lower()]
301
+ return min(q4 or cands, key=lambda s: s.size), cands
302
+
303
+
304
  # ---------- heartbeat ----------
305
  def heartbeat():
306
  while True:
 
316
  # ---------- main loop ----------
317
  def loop():
318
  done = load_done()
319
+ log.info("resuming: %d models already done under bench v%d", len(done), BENCH)
320
  STATUS["stage"] = "listing"
321
  t = time.time()
322
  try:
323
+ ids = sorted((m.id for m in api.list_models(filter="gguf", limit=5000)), key=str.lower)
324
  except Exception:
325
  log.exception("list_models failed")
326
  STATUS["current"] = "error: list_models failed"
 
331
 
332
  for n, mid in enumerate(todo, 1):
333
  STATUS.update(current=mid, model_started=time.time(), stage="metadata")
334
+ result, path, t0 = {"model": mid, "ts": time.time(), "bench": BENCH}, None, time.time()
335
  log.info("[%d/%d] %s: start", n, len(todo), mid)
336
  try:
337
  t = time.time()
338
  info = api.model_info(mid, files_metadata=True)
339
  gguf = getattr(info, "gguf", None) or {}
340
  params_b = (gguf.get("total") or 0) / 1e9
341
+ known = params_b > 0
342
+ arch = gguf.get("architecture")
343
+ task = getattr(info, "pipeline_tag", None)
344
  all_gguf = [s for s in info.siblings if s.rfilename.endswith(".gguf")]
345
+ log.debug("%s: metadata in %.1fs, arch=%s task=%s params=%.3fB gguf_files=%d",
346
+ mid, time.time() - t, arch, task, params_b, len(all_gguf))
347
+
348
+ if task in NON_TEXT_TASKS:
349
+ result["status"] = "skipped_not_text"
350
+ log.info("%s: skip, pipeline_tag=%s", mid, task)
351
+ elif known and params_b > MAX_PARAMS_B:
 
352
  result.update(status="skipped_too_big", params_b=round(params_b, 2))
353
  log.info("%s: skip, %.2fB params > %.1fB limit", mid, params_b, MAX_PARAMS_B)
 
 
 
 
354
  else:
355
+ cap = MAX_GB if known else UNKNOWN_MAX_GB
356
+ f, cands = pick_file(info.siblings, cap)
357
+ if not known:
358
+ log.info("%s: no param count in metadata, will verify after load (file cap %.1f GB)", mid, cap)
359
+ if f is None:
360
+ result["status"] = "skipped_no_usable_file"
361
+ names = [f"{s.rfilename}={((s.size or 0) / 1e9):.2f}GB" for s in all_gguf[:5]]
362
+ log.info("%s: skip, no usable model file <= %.1f GB (excluded mmproj/lora/draft/shards); found %d: %s",
363
+ mid, cap, len(all_gguf), names)
 
 
 
 
 
 
 
 
364
  else:
365
+ if known:
366
+ result["params_b"] = round(params_b, 2)
367
+ log.info("%s: params=%s arch=%s, %d candidate files, picked %s (%.2f GB)",
368
+ mid, f"{params_b:.2f}B" if known else "unknown", arch, len(cands), f.rfilename, f.size / 1e9)
369
+ STATUS["stage"] = "download"
370
+ t = time.time()
371
+ path = hf_hub_download(mid, f.rfilename)
372
+ dl = max(time.time() - t, 0.01)
373
+ log.info("%s: downloaded in %.1fs (%.1f MB/s), mem_avail=%.1fGB disk_free=%.1fGB",
374
+ mid, dl, f.size / 1e6 / dl, mem_avail_gb(), disk_free_gb("."))
375
+ result.update(file=f.rfilename, arch=arch)
376
+
377
+ STATUS["stage"] = "benchmark"
378
+ rc, res, tail, timed_out, hints, n_params = run_worker(path)
379
+ if n_params:
380
+ result["params_b"] = round(n_params / 1e9, 2)
381
+ if timed_out:
382
+ result.update(status="failed", error=f"timeout after {TIMEOUT}s")
383
+ elif rc == 0 and res:
384
+ res.pop("n_params", None)
385
+ result.update(res, status="ok")
386
+ elif rc == 3:
387
+ result.update(status="skipped_load_failed", error=" | ".join(hints or tail)[-500:])
388
+ elif rc == 4:
389
+ result.update(status="skipped_too_slow", error="projected benchmark time over limit")
390
+ elif rc == 5:
391
+ result.update(status="skipped_too_big", error="actual param count over limit after load")
392
+ else:
393
+ result.update(status="failed", error=f"exit code {rc}: " + " | ".join(tail)[-500:])
394
  except Exception as e:
395
  log.exception("%s: exception during processing", mid)
396
  result.update(status="failed", error=f"{type(e).__name__}: {e}"[:500])
 
406
  dt = time.time() - t0
407
  if s == "ok":
408
  SESSION["ok"] += 1
409
+ log.info("%s: OK score=%.2f prompt-tok/s=%s params=%sB (%.0fs total)",
410
+ mid, result["arc_easy_25"], result["tok_per_s"], result.get("params_b", "?"), dt)
411
  elif s == "failed":
412
  SESSION["failed"] += 1
413
  log.error("%s: FAILED after %.0fs: %s", mid, dt, result.get("error", "").replace("\n", " | ")[:400])
414
  else:
415
  SESSION["skipped"] += 1
416
+ if result.get("error"):
417
+ log.warning("%s: %s after %.0fs: %s", mid, s, dt, result["error"].replace("\n", " | ")[:300])
418
 
419
  STATUS["stage"] = "saving"
420
  try:
421
  push(json.dumps(result), f"results/{mid.replace('/', '__')}.json")
422
  done.add(mid)
423
+ push("\n".join(sorted(done)), DONE_FILE)
424
  log.debug("%s: saved result (%d done total)", mid, len(done))
425
  except Exception:
426
  log.exception("%s: write failed", mid)
 
438
  def refresh():
439
  if time.time() - CACHE["t"] < 60:
440
  return
441
+ rows, counts = [], {"ok": 0, "failed": 0, "skipped": 0, "old": 0}
442
  for f in glob.glob(f"{DATA}/results/*.json"):
443
  try:
444
  r = json.load(open(f))
445
  except Exception:
446
  continue
447
+ if r.get("bench") != BENCH:
448
+ counts["old"] += 1
449
+ continue
450
  s = r.get("status", "")
451
  if s == "ok":
452
  counts["ok"] += 1
 
477
  refresh()
478
  c = CACHE["counts"]
479
  body = "".join(
480
+ f"<tr><td>{html.escape(r['model'])}</td><td>{r.get('params_b', '?')}B</td>"
481
  f"<td>{r['arc_easy_25']:.2f}</td><td>{r['tok_per_s']}</td>"
482
  f"<td>{html.escape(r.get('file', ''))}</td></tr>" for r in CACHE["rows"])
483
  link = f'<a href="https://huggingface.co/buckets/{BUCKET}">bucket</a>' if BUCKET else "bucket"
 
485
  page = f"""<html><body style="font-family:sans-serif;max-width:900px;margin:2em auto">
486
  <h2>Tiny model leaderboard</h2>
487
  <p>Now: <b>{html.escape(STATUS['current'])}</b> ({STATUS['stage']}, {el:.0f}s)<br>
488
+ all-time (bench v{BENCH}): ok {c.get('ok', 0)} 路 failed {c.get('failed', 0)} 路 skipped {c.get('skipped', 0)}
489
+ 路 old-format results ignored {c.get('old', 0)} 路 queue {STATUS['queue']}<br>
490
  this session: ok {SESSION['ok']} 路 failed {SESSION['failed']} 路 skipped {SESSION['skipped']}</p>
491
+ <p>Score = ARC-Easy, {N_QUESTIONS} questions, zero-shot, answer picked by next-token letter logits.
492
+ Raw results: {link} (top 200 shown, refreshed every 60s) 路
493
  <a href="/logs">recent logs</a> (<a href="/logs?n=1000">1000 lines</a>)</p>
494
  <table border=1 cellpadding=4><tr><th>model</th><th>params</th><th>ARC-E ({N_QUESTIONS})</th>
495
+ <th>prompt tok/s</th><th>file</th></tr>{body}</table></body></html>"""
496
  self.send_response(200)
497
  self.send_header("Content-Type", "text/html")
498
  self.end_headers()