Update app.py
Browse files13 unmodified lines1415161718192021222324218 unmodified lines2432442452462472482492501 unmodified line2522532542552562572582592602612622632642652662674 unmodified lines2722732742752762772782792806 unmodified lines287288289290291292293294295296297298299115 unmodified lines41541641741841942076 unmodified lines49749849950050150250350480 unmodified lines58558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561664 unmodified lines68168268368468568668768868969069169213 unmodified lines7067077087097107117127137147157167177187197 unmodified lines72772872973073173213 unmodified linesIDLE_HEARTBEAT_S = 1800SUMMARY_EVERY = 50N_QUESTIONS = int(os.environ.get("N_QUESTIONS", "100"))MAX_REPOS = int(os.environ.get("MAX_REPOS", "6000")) # 0 = every gguf repo on the HubLOG_FLUSH_S = int(os.environ.get("LOG_FLUSH_S", "60"))RUN_ID = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")BENCH = 4 # scoring version: 3 = next-token letter logits, logits_all=TrueDONE_FILE = "state/done-v4.txt"api = HfApi()218 unmodified linesexcept Exception as e:say(f"warm-up failed (ignored): {e}")label_ids = {}correct, deg, toks, t0 = 0, 0, 0, time.time()for i, ex in enumerate(ds):qt = time.time()labels = ex["choices"]["label"]1 unmodified lineprompt = f"Question: {ex['question']}\n{opts}\nAnswer:"for lab in labels:if lab not in label_ids:label_ids[lab] = llm.tokenize(f"Answer: {lab}".encode(), add_bos=False)[-1]if len(label_ids) == len(labels) and i == 0:say("label tokens: " + ", ".join(f"{l}->{label_ids[l]}({llm.detokenize([label_ids[l]]).decode('utf-8', errors='replace')!r})"for l in labels if l in label_ids))ptoks = llm.tokenize(prompt.encode())[-500:]llm.reset()llm.eval(ptoks)logits = llm.scores[llm.n_tokens - 1]vals = [float(logits[label_ids[l]]) for l in labels]m = max(vals)exps = [math.exp(v - m) for v in vals]probs = [e / sum(exps) for e in exps]4 unmodified linestoks += len(ptoks)degenerate = (max(vals) - min(vals)) < 1e-6deg += degeneratetop_tok = llm.detokenize([int(np.argmax(logits))]).decode("utf-8", errors="replace")say(f"Q{i + 1}/{len(ds)} expected={ex['answerKey']} pred={pred} conf={probs[best]:.2f} "f"{'OK' if ok else 'x'} top={top_tok!r} logits={[round(v, 1) for v in vals]} "f"prompt_tok={len(ptoks)} {time.time() - qt:.1f}s running={correct}/{i + 1}")if i == 4 and deg == 5:say("DEGENERATE_LOGITS first 5 questions had identical label logits; scores would be meaningless")6 unmodified linessys.exit(4)elapsed = time.time() - t0say(f"benchmark done in {elapsed:.1f}s ({toks / elapsed:.1f} prompt tok/s), worker total {time.time() - t_start:.1f}s, "f"degenerate questions: {deg}/{len(ds)}")if deg > len(ds) // 2:say("DEGENERATE_LOGITS majority of questions had identical label logits")sys.exit(6)say("RESULT " + json.dumps({"score": correct / len(ds), "n_questions": len(ds),"tok_per_s": round(toks / elapsed, 1), "n_params": n_params}))LOADER_HINT = re.compile(r"error|unknown|fail|unsupported|arch|invalid|mismatch|missing|not found", re.I)115 unmodified linesknown = params_b > 0arch = gguf.get("architecture")task = getattr(info, "pipeline_tag", None)all_gguf = [s for s in info.siblings if s.rfilename.endswith(".gguf")]log.debug("%s: metadata in %.1fs, arch=%s task=%s params=%.3fB gguf_files=%d",mid, time.time() - t, arch, task, params_b, len(all_gguf))76 unmodified linesdt = time.time() - t0if s == "ok":SESSION["ok"] += 1log.info("%s: OK score=%.2f (%d q) prompt-tok/s=%s params=%sB (%.0fs total)",mid, result["score"], result["n_questions"], result["tok_per_s"], result.get("params_b", "?"), dt)elif s == "failed":SESSION["failed"] += 1log.error("%s: FAILED after %.0fs: %s", mid, dt, result.get("error", "").replace("\n", " | ")[:400])80 unmodified linesstart_loop()# ---------- status page (reads full history from the mount) ----------def refresh():if time.time() - CACHE["t"] < 60:returnrows, counts = [], {"ok": 0, "failed": 0, "skipped": 0, "old": 0}for f in glob.glob(f"{DATA}/results/*.json"):try:r = json.load(open(f))except Exception:continueif r.get("bench") != BENCH:counts["old"] += 1continues = r.get("status", "")if s == "ok":counts["ok"] += 1rows.append(r)elif s == "failed":counts["failed"] += 1else:counts["skipped"] += 1rows.sort(key=lambda r: (-r["score"], -r["tok_per_s"]))CACHE.update(t=time.time(), rows=rows[:200], counts=counts)PAGE_STYLE = "font-family:sans-serif;max-width:900px;margin:2em auto;padding:0 12px"class H(BaseHTTPRequestHandler):64 unmodified lines<button name="confirm" value="no" formnovalidate style="padding:6px 14px">No, keep my results</button></form>""")refresh()c = CACHE["counts"]body = "".join(f"<tr><td>{html.escape(r['model'])}</td><td>{r.get('params_b', '?')}B</td>"f"<td>{r['score']:.2f}</td><td>{r.get('n_questions', '?')}</td><td>{r['tok_per_s']}</td>"f"<td>{html.escape(r.get('file', ''))}</td></tr>" for r in CACHE["rows"])link = f'<a href="https://huggingface.co/buckets/{BUCKET}">bucket</a>' if BUCKET else "bucket"el = time.time() - STATUS["model_started"] if STATUS["model_started"] else 013 unmodified linesself.send_html(f"""{top}<h2>Tiny model leaderboard</h2><p>Now: <b>{html.escape(STATUS['current'])}</b> ({STATUS['stage']}, {el:.0f}s)<br>all-time (bench v{BENCH}): ok {c.get('ok', 0)} · failed {c.get('failed', 0)} · skipped {c.get('skipped', 0)}· old-format results ignored {c.get('old', 0)} · queue {STATUS['queue']}<br>this session: ok {SESSION['ok']} · failed {SESSION['failed']} · skipped {SESSION['skipped']}</p><p>Score = ARC-Easy, {N_QUESTIONS} questions, zero-shot, answer picked by next-token letter logits (chance = 0.25).Raw results: {link} (top 200 shown, refreshed every 60s) ·<a href="/logs">recent logs</a> (<a href="/logs?n=1000">1000 lines</a>)</p><table border=1 cellpadding=4><tr><th>model</th><th>params</th><th>score</th><th>n</th><th>prompt tok/s</th><th>file</th></tr>{body}</table>""", extra_head=head)def log_message(self, *a):pass7 unmodified linesstartup_report()os.makedirs(f"{DATA}/results", exist_ok=True)threading.Thread(target=heartbeat, daemon=True).start()start_loop()log.info("status page listening on :7860")ThreadingHTTPServer(("0.0.0.0", 7860), H).serve_forever()13 unmodified lines1415161718192021222324252627218 unmodified lines2462472482492502512522532542552562572582592602612622632642652662672682692702712722732741 unmodified line2762772782792802812822832842852862872882892902912922932942952962972982994 unmodified lines3043053063073083093103116 unmodified lines318319320321322323324325326327328329330331332333334335115 unmodified lines45145245345445545645776 unmodified lines53453553653753853954054154254380 unmodified lines62462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566664 unmodified lines73173273373473573673773873974074174274374474574674774874913 unmodified lines7637647657667677687697707717727737747757767777787797807 unmodified lines78878979079179279379413 unmodified linesIDLE_HEARTBEAT_S = 1800SUMMARY_EVERY = 50N_QUESTIONS = int(os.environ.get("N_QUESTIONS", "100"))MAX_REPOS = int(os.environ.get("MAX_REPOS", "7000")) # 0 = every gguf repo on the HubLOG_FLUSH_S = int(os.environ.get("LOG_FLUSH_S", "60"))CACHE_EVERY_S = 120RUN_ID = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")BENCH = 5 # scoring version: 4 = letter logits (variants merged), space-token handling, format checkSHOW_BENCH = (3, 4) # result versions shown in the tableUNRELIABLE_MASS = 0.02 # mean share of probability on answer letters below this = unreliable scoreDONE_FILE = f"state/done-v{BENCH}.txt"api = HfApi()218 unmodified linesexcept Exception as e:say(f"warm-up failed (ignored): {e}")def lse(a):a = np.asarray(a, dtype=np.float64)m = a.max()return float(m + np.log(np.exp(a - m).sum()))def tok_str(i):return llm.detokenize([int(i)]).decode("utf-8", errors="replace")def letter_ids(lab):"""All single-token forms of an answer label ('A', ' A', ...). Their probabilities are summed."""ids = set()for s in (f"Answer: {lab}", lab, f" {lab}"):try:toks = llm.tokenize(s.encode(), add_bos=False)if toks:ids.add(int(toks[-1]))except Exception:passreturn sorted(ids)label_ids = {}correct, deg, toks, t0 = 0, 0, 0, time.time()masses = []for i, ex in enumerate(ds):qt = time.time()labels = ex["choices"]["label"]1 unmodified lineprompt = f"Question: {ex['question']}\n{opts}\nAnswer:"for lab in labels:if lab not in label_ids:label_ids[lab] = letter_ids(lab)if i == 0:say("label tokens: " + "; ".join(f"{l}=" + "|".join(repr(tok_str(t)) for t in label_ids[l]) for l in labels))ptoks = llm.tokenize(prompt.encode())[-500:]llm.reset()llm.eval(ptoks)row = np.asarray(llm.scores[llm.n_tokens - 1], dtype=np.float64)top_id = int(np.argmax(row))top_tok = tok_str(top_id)note = ""if top_tok.strip() == "":# the model wants a space/newline token before the answer: feed it, then read the next rowllm.eval([top_id])row = np.asarray(llm.scores[llm.n_tokens - 1], dtype=np.float64)note = " +ws"vals = [lse(row[label_ids[l]]) for l in labels]mass = math.exp(lse(row[[t for l in labels for t in label_ids[l]]]) - lse(row))masses.append(mass)m = max(vals)exps = [math.exp(v - m) for v in vals]probs = [e / sum(exps) for e in exps]4 unmodified linestoks += len(ptoks)degenerate = (max(vals) - min(vals)) < 1e-6deg += degeneratesay(f"Q{i + 1}/{len(ds)} expected={ex['answerKey']} pred={pred} conf={probs[best]:.2f} mass={mass:.2f} "f"{'OK' if ok else 'x'} top={top_tok!r}{note} logits={[round(v, 1) for v in vals]} "f"prompt_tok={len(ptoks)} {time.time() - qt:.1f}s running={correct}/{i + 1}")if i == 4 and deg == 5:say("DEGENERATE_LOGITS first 5 questions had identical label logits; scores would be meaningless")6 unmodified linessys.exit(4)elapsed = time.time() - t0mean_mass = sum(masses) / len(masses)unreliable = mean_mass < UNRELIABLE_MASSsay(f"benchmark done in {elapsed:.1f}s ({toks / elapsed:.1f} prompt tok/s), worker total {time.time() - t_start:.1f}s, "f"degenerate questions: {deg}/{len(ds)}, mean answer-letter mass: {mean_mass:.3f}")if unreliable:say(f"LOW_FORMAT_MASS mean mass {mean_mass:.4f} < {UNRELIABLE_MASS}: the model does not answer with a letter, score is unreliable")if deg > len(ds) // 2:say("DEGENERATE_LOGITS majority of questions had identical label logits")sys.exit(6)say("RESULT " + json.dumps({"score": correct / len(ds), "n_questions": len(ds),"tok_per_s": round(toks / elapsed, 1), "n_params": n_params,"format_mass": round(mean_mass, 4), "unreliable": unreliable}))LOADER_HINT = re.compile(r"error|unknown|fail|unsupported|arch|invalid|mismatch|missing|not found", re.I)115 unmodified linesknown = params_b > 0arch = gguf.get("architecture")task = getattr(info, "pipeline_tag", None)result["task"] = taskall_gguf = [s for s in info.siblings if s.rfilename.endswith(".gguf")]log.debug("%s: metadata in %.1fs, arch=%s task=%s params=%.3fB gguf_files=%d",mid, time.time() - t, arch, task, params_b, len(all_gguf))76 unmodified linesdt = time.time() - t0if s == "ok":SESSION["ok"] += 1log.info("%s: OK score=%.2f (%d q) fmt=%.2f%s prompt-tok/s=%s params=%sB (%.0fs total)",mid, result["score"], result["n_questions"], result.get("format_mass", 0)," UNRELIABLE" if result.get("unreliable") else "", result["tok_per_s"],result.get("params_b", "?"), dt)elif s == "failed":SESSION["failed"] += 1log.error("%s: FAILED after %.0fs: %s", mid, dt, result.get("error", "").replace("\n", " | ")[:400])80 unmodified linesstart_loop()# ---------- results table (built in the background so the page never waits on the mount) ----------def refresh():t0 = time.time()rows, counts = [], {"ok": 0, "failed": 0, "skipped": 0, "old": 0, "unreliable": 0}for f in glob.glob(f"{DATA}/results/*.json"):try:r = json.load(open(f))except Exception:continueif r.get("bench") not in SHOW_BENCH:counts["old"] += 1continues = r.get("status", "")if s == "ok":counts["ok"] += 1if r.get("unreliable"):counts["unreliable"] += 1rows.append(r)elif s == "failed":counts["failed"] += 1else:counts["skipped"] += 1rows.sort(key=lambda r: (bool(r.get("unreliable")), -r["score"], -r["tok_per_s"]))CACHE.update(t=time.time(), rows=rows[:300], counts=counts)log.debug("table refreshed in %.1fs (%d ok rows)", time.time() - t0, counts["ok"])def cache_loop():while True:try:refresh()except Exception:log.exception("table refresh failed")time.sleep(CACHE_EVERY_S)PAGE_STYLE = "font-family:sans-serif;max-width:1100px;margin:2em auto;padding:0 12px"class H(BaseHTTPRequestHandler):64 unmodified lines<button name="confirm" value="no" formnovalidate style="padding:6px 14px">No, keep my results</button></form>""")c = CACHE["counts"]rows_html = []for r in CACHE["rows"]:style = " style='color:#999'" if r.get("unreliable") else ""rows_html.append(f"<tr{style}><td>{html.escape(r['model'])}</td><td>{r.get('params_b', '?')}B</td>"f"<td>{r['score']:.2f}{'?' if r.get('unreliable') else ''}</td><td>{r.get('n_questions', '?')}</td>"f"<td>{r.get('format_mass', '')}</td><td>{r['tok_per_s']}</td>"f"<td>{html.escape(str(r.get('task') or ''))}</td><td>{html.escape(r.get('file', ''))}</td>"f"<td>v{r.get('bench', '?')}</td></tr>")body = "".join(rows_html)if CACHE["t"] == 0:body = "<tr><td colspan=9>Building the results table in the background, refresh in a minute…</td></tr>"link = f'<a href="https://huggingface.co/buckets/{BUCKET}">bucket</a>' if BUCKET else "bucket"el = time.time() - STATUS["model_started"] if STATUS["model_started"] else 013 unmodified linesself.send_html(f"""{top}<h2>Tiny model leaderboard</h2><p>Now: <b>{html.escape(STATUS['current'])}</b> ({STATUS['stage']}, {el:.0f}s)<br>in table (v{'/v'.join(str(v) for v in SHOW_BENCH)}): ok {c.get('ok', 0)} (unreliable {c.get('unreliable', 0)})· failed {c.get('failed', 0)} · skipped {c.get('skipped', 0)}· ignored old formats {c.get('old', 0)} · queue {STATUS['queue']}<br>this session: ok {SESSION['ok']} · failed {SESSION['failed']} · skipped {SESSION['skipped']}</p><p>Score = ARC-Easy, {N_QUESTIONS} questions, zero-shot, answer picked by next-token letter logits (chance = 0.25;one score is only good to about ±10 points at this size). <b>fmt</b> = share of probability the model puts on the answerletters; grey rows with “?” are below {UNRELIABLE_MASS} (the model doesn't answer with a letter, so the score is unreliable).Rows marked v3 use the previous scoring and are replaced as the v{BENCH} run reaches them.Raw results: {link} (top 300 shown, table rebuilt every {CACHE_EVERY_S}s) ·<a href="/logs">recent logs</a> (<a href="/logs?n=1000">1000 lines</a>)</p><table border=1 cellpadding=4><tr><th>model</th><th>params</th><th>score</th><th>n</th><th>fmt</th><th>prompt tok/s</th><th>task</th><th>file</th><th>v</th></tr>{body}</table>""", extra_head=head)def log_message(self, *a):pass7 unmodified linesstartup_report()os.makedirs(f"{DATA}/results", exist_ok=True)threading.Thread(target=heartbeat, daemon=True).start()threading.Thread(target=cache_loop, daemon=True).start()start_loop()log.info("status page listening on :7860")ThreadingHTTPServer(("0.0.0.0", 7860), H).serve_forever()
app.py+98-36