Skip to content

Official Inference Code of EAGLE-4

feat(core): fp32 arbiter for greedy-parity divergences above the near-tie gap

Seyfal Sultanovf6149b060b21
diff --git a/tests/test_fp32_arbiter.py b/tests/test_fp32_arbiter.py
new file mode 100644
index 0000000..aeb95f3
--- /dev/null
+++ b/tests/test_fp32_arbiter.py
@@ -0,0 +1,275 @@
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""fp32 arbiter: the bf16-ulp rule and the parity classification, without a model (the scorer is injected)."""
+
+import copy
+import importlib.util
+import json
+import math
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+_TOOL = Path(__file__).resolve().parents[1] / "tools" / "fp32_arbiter.py"
+_spec = importlib.util.spec_from_file_location("fp32_arbiter", _TOOL)
+assert _spec is not None and _spec.loader is not None
+arbiter = importlib.util.module_from_spec(_spec)
+sys.modules["fp32_arbiter"] = arbiter # dataclasses with postponed annotations resolve through sys.modules
+_spec.loader.exec_module(arbiter)
+
+
+ "magnitude, ulp",
+ [
+ (16.0, 0.125),
+ (27.75, 0.125),
+ (31.999, 0.125),
+ (32.0, 0.25),
+ (1.0, 2**-7),
+ (0.3, 2**-9),
+ (100.0, 0.5),
+ (0.0, 2**-133),
+ ],
+)
+def test_bf16_ulp_is_the_spacing_at_that_magnitude(magnitude, ulp):
+ assert arbiter.bf16_ulp(magnitude) == ulp
+ if magnitude > 0:
+ assert arbiter.bf16_ulp(magnitude) == 2 ** (math.floor(math.log2(magnitude)) - 7)
+
+
+def scores(**logits):
+ table = {int(k): v for k, v in logits.items()}
+ top = sorted(([v, t] for t, v in table.items()), reverse=True)
+ return arbiter.Scores(table, top)
+
+
+def test_arbitrate_passes_within_two_ulps_and_fails_beyond():
+ # The RAG 87791f97 token-2 divergence: fp32 4087 = 27.7906, 310 = 27.5972: d 0.193 <= 2 * 0.125.
+ v = arbiter.arbitrate(4087, 310, scores(**{"4087": 27.790557861328125, "310": 27.597150802612305}))
+ assert v.passes and v.ulp == 0.125 and v.d == pytest.approx(0.1934, abs=1e-4)
+ assert (
+ v.reference_logit > v.candidate_logit
+ ) # fp32 prefers the native token: the pass is the rule, not an argmax match
+ assert arbiter.arbitrate(1, 2, scores(**{"1": 27.75, "2": 27.5})).passes # exactly 2 ulp
+ assert not arbiter.arbitrate(1, 2, scores(**{"1": 27.75, "2": 27.4})).passes # 2.8 ulp
+ assert arbiter.arbitrate(1, 2, scores(**{"1": 27.75, "2": 27.75})).passes # an exact tie
+ # The larger magnitude sets the ulp (0.25): 12 > 0.5 (the candidate is not the fp32 argmax here).
+ wide = arbiter.arbitrate(2, 1, scores(**{"1": 20.0, "2": 32.0}))
+ assert not wide.passes and wide.ulp == 0.25
+ assert not arbiter.arbitrate(1, 2, scores(**{"1": 27.75, "2": 27.5}), tolerance_ulps=1.0).passes
+
+
+def parity_docs():
+ prompts = {"a": [10, 11], "b": [20, 21], "c": [30], "d": [40], "e": [50]}
+ ref = {
+ "results": [
+ {"question_id": "a", "output_ids": [1, 2, 3], "top": [[[-0.1, 1], [-3.0, 9]]] * 3},
+ {
+ "question_id": "b",
+ "output_ids": [1, 2, 3],
+ "top": [[[-0.5, 1], [-0.6, 7]], [[-0.5, 2], [-0.6, 7]], [[-0.5, 3], [-0.6, 7]]],
+ },
+ {
+ "question_id": "c",
+ "output_ids": [1, 2, 3],
+ "top": [[[-0.5, 1], [-0.75, 7]]] * 3,
+ }, # gap 0.25 > 0.13: arbitrated
+ {"question_id": "d", "output_ids": [1, 2, 3], "top": [[[-0.5, 1], [-0.75, 7]]] * 3},
+ {"question_id": "e", "output_ids": [1, 2, 3], "top": [[[-0.5, 1], [-0.75, 7]]] * 3},
+ ]
+ }
+ cand = {
+ "results": [
+ {"question_id": "a", "output_ids": [1, 2, 3]}, # identical
+ {"question_id": "b", "output_ids": [1, 7, 3]}, # bf16 gap 0.1 <= 0.13: near tie, never scored
+ {"question_id": "c", "output_ids": [1, 2, 7]}, # fp32 d = 0.2 at |logit| ~27: 1.6 ulp, passes
+ {"question_id": "d", "output_ids": [7, 2, 3]}, # fp32 d = 0.5: 4 ulp, fails
+ {"question_id": "e", "output_ids": [1, 2]}, # prefix-equal, shorter: length
+ ]
+ }
+ return prompts, ref, cand
+
+
+def test_classify_parity_scores_only_the_divergences_above_the_tie_gap():
+ prompts, ref, cand = parity_docs()
+ calls = []
+
+ def score(prefix, tokens):
+ calls.append((list(prefix), list(tokens)))
+ return {("c", 3): scores(**{"3": 27.7, "7": 27.5}), ("d", 1): scores(**{"1": 27.75, "7": 27.25})}[
+ ("c", 3) if prefix == [30, 1, 2] else ("d", 1)
+ ]
+
+ result = arbiter.classify_parity(ref, cand, prompts, score)
+ by_id = {r["question_id"]: r for r in result["rows"]}
+ assert [r["status"] for r in result["rows"]] == ["identical", "near_tie", "fp32_pass", "fail", "length"]
+ assert result["counts"] == {
+ "identical": 1,
+ "near_tie": 1,
+ "fp32_pass": 1,
+ "fp32_argmax": 0,
+ "fail": 1,
+ "length": 1,
+ }
+ assert not result["passes"]
+ # The scored prefix is the prompt plus the reference tokens before the divergence, and only c and d are scored.
+ assert calls == [([30, 1, 2], [3, 7]), ([40], [1, 7])]
+ assert by_id["c"]["prefix_length"] == 3 and by_id["c"]["fp32"]["d"] == pytest.approx(0.2)
+ assert by_id["d"]["fp32"]["d"] == 0.5 and by_id["d"]["fp32_argmax"] == 1
+ assert "fp32" not in by_id["b"] and by_id["b"]["reference_gap"] == pytest.approx(0.1)
+ assert by_id["e"]["lengths"] == [3, 2]
+ for row in result["rows"]:
+ assert row["question_id"] in arbiter.format_row(row)
+
+
+def test_classify_parity_passes_when_every_scored_divergence_is_within_tolerance():
+ prompts, ref, cand = parity_docs()
+ cand["results"] = cand["results"][:3]
+ result = arbiter.classify_parity(ref, cand, prompts, lambda prefix, tokens: scores(**{"3": 27.7, "7": 27.5}))
+ assert result["passes"] and result["counts"]["fail"] == 0
+
+
+def test_candidate_token_outside_the_reference_top_k_is_still_arbitrated():
+ ref = {"results": [{"question_id": "x", "output_ids": [1, 2], "top": [[[-0.5, 1], [-0.6, 9]]] * 2}]}
+ cand = {"results": [{"question_id": "x", "output_ids": [1, 5]}]}
+ result = arbiter.classify_parity(ref, cand, {"x": [0]}, lambda prefix, tokens: scores(**{"2": 10.0, "5": 9.97}))
+ row = result["rows"][0]
+ assert row["reference_gap"] is None and row["status"] == "fp32_pass" and row["fp32"]["ulp"] == 2**-4
+
+
+# An fp32 re-forward where the candidate's token 3437 (21.0152) beats the reference's 5586 (20.6798) by d = 0.3354:
+# more than 2 bf16 ulp (0.25) at that size, so only the candidate-argmax rule passes it.
+FLIP = {"5586": 20.679800033569336, "3437": 21.015199661254883, "11": 18.5}
+
+
+def test_candidate_that_is_the_fp32_argmax_passes_above_the_ulp_limit():
+ v = arbiter.arbitrate(5586, 3437, scores(**FLIP))
+ assert v.d > v.tolerance_ulps * v.ulp == 0.25 # the pair-gap rule alone fails it
+ assert (v.status, v.passes, v.fp32_argmax) == ("fp32_argmax", True, 3437)
+
+
+def test_reference_that_is_the_fp32_argmax_still_fails_with_the_ids_swapped():
+ v = arbiter.arbitrate(3437, 5586, scores(**FLIP))
+ assert v.d > v.tolerance_ulps * v.ulp
+ assert (v.status, v.passes, v.fp32_argmax) == ("fail", False, 3437)
+
+
+def test_pair_gap_rule_decides_first_and_ties_at_the_top_count_as_argmax():
+ # Within 2 ulp the divergence is fp32_pass whichever token wins, so the two categories stay distinct.
+ assert arbiter.arbitrate(1, 2, scores(**{"1": 27.5, "2": 27.75})).status == "fp32_pass"
+ # Candidate 2 ties the top logit that topk reports under another token: it is still an fp32 argmax.
+ tied = arbiter.Scores({1: 27.0, 2: 28.0}, [[28.0, 9], [28.0, 2], [27.0, 1]])
+ assert arbiter.arbitrate(1, 2, tied).status == "fp32_argmax"
+ # A token above the candidate makes it fail even when the candidate beats the reference.
+ above = arbiter.Scores({1: 27.0, 2: 27.5}, [[28.0, 9], [27.5, 2], [27.0, 1]])
+ assert arbiter.arbitrate(1, 2, above).status == "fail"
+
+
+def flip_docs(reference_token, candidate_token):
+ """One prompt whose first divergence is at index 1, with a bf16 gap (0.375) above the near-tie gate."""
+ top = [[[-0.1, reference_token], [-0.475, candidate_token]]] * 2
+ ref = {"results": [{"question_id": "q", "output_ids": [7, reference_token], "top": top}]}
+ cand = {"results": [{"question_id": "q", "output_ids": [7, candidate_token]}]}
+ return ref, cand
+
+
+def test_classify_parity_uses_each_rows_own_candidate_token():
+ # Two runs of the same prompt diverge in opposite directions; the fp32 forward of the prefix is the same.
+ score = lambda prefix, tokens: scores(**FLIP) # noqa: E731
+ ours = arbiter.classify_parity(*flip_docs(5586, 3437), {"q": [0]}, score)
+ swapped = arbiter.classify_parity(*flip_docs(3437, 5586), {"q": [0]}, score)
+ assert ours["rows"][0]["status"] == "fp32_argmax" and ours["passes"]
+ assert ours["counts"]["fp32_argmax"] == 1 and ours["counts"]["fail"] == 0
+ assert swapped["rows"][0]["status"] == "fail" and not swapped["passes"]
+ assert ours["rows"][0]["fp32_argmax"] == swapped["rows"][0]["fp32_argmax"] == 3437
+ assert "fp32_argmax" in arbiter.format_row(ours["rows"][0])
+
+
+def saved_old_rule_report():
+ """A report written before the candidate-argmax rule: both flips saved as fail, with their fp32 evidence."""
+ rows = []
+ for ref_token, cand_token in ((5586, 3437), (3437, 5586)):
+ s = scores(**FLIP)
+ a, b = s.logits[ref_token], s.logits[cand_token]
+ old = {
+ "reference_token": ref_token,
+ "candidate_token": cand_token,
+ "reference_logit": a,
+ "candidate_logit": b,
+ "d": abs(a - b),
+ "ulp": 0.125,
+ "tolerance_ulps": 2.0,
+ "passes": False,
+ }
+ rows.append(
+ {
+ "question_id": f"q{ref_token}",
+ "index": 1,
+ "status": "fail",
+ "reference_token": ref_token,
+ "candidate_token": cand_token,
+ "reference_gap": 0.375,
+ "fp32": old,
+ "fp32_top": s.top,
+ "fp32_argmax": s.top[0][1],
+ }
+ )
+ rows.append(
+ {
+ "question_id": "n",
+ "index": 3,
+ "status": "near_tie",
+ "reference_token": 1,
+ "candidate_token": 2,
+ "reference_gap": 0.125,
+ }
+ )
+ counts = {"identical": 0, "near_tie": 1, "fp32_pass": 0, "fail": 2, "length": 0}
+ return {"tie_gap": 0.13, "tolerance_ulps": 2.0, "counts": counts, "passes": False, "rows": rows}
+
+
[email protected]("layout", ["verdicts", "candidates"])
+def test_rejudge_applies_the_current_rule_to_a_saved_report_without_changing_it(layout):
+ result = saved_old_rule_report()
+ report = {"verdicts": [result]} if layout == "verdicts" else {"candidates": {"live.json": result}}
+ original = copy.deepcopy(report)
+ again = arbiter.rejudge(report)
+ assert report == original # the saved evidence is never rewritten
+ redone = again["verdicts"][0] if layout == "verdicts" else again["candidates"]["live.json"]
+ assert [r["status"] for r in redone["rows"]] == ["fp32_argmax", "fail", "near_tie"]
+ assert redone["counts"] == {"identical": 0, "near_tie": 1, "fp32_pass": 0, "fp32_argmax": 1, "fail": 1, "length": 0}
+ assert not redone["passes"] and redone["tie_gap"] == 0.13
+ assert redone["rows"][0]["fp32"]["d"] == result["rows"][0]["fp32"]["d"] # same logits, new decision
+
+
+def test_rejudge_cli_writes_a_new_file_and_refuses_to_overwrite(tmp_path, capsys):
+ result = saved_old_rule_report()
+ result["rows"] = result["rows"][:1]
+ saved = tmp_path / "verdicts.json"
+ saved.write_text(json.dumps({"verdicts": [result]}))
+ before = saved.read_bytes()
+ out = tmp_path / "verdicts.rejudged.json"
+ assert arbiter.main(["rejudge", str(saved), "--out", str(out)]) == 0
+ assert saved.read_bytes() == before
+ written = json.loads(out.read_text())
+ assert written["rejudged_from"] == str(saved) and written["verdicts"][0]["counts"]["fp32_argmax"] == 1
+ assert "PASS" in capsys.readouterr().out
+ with pytest.raises(SystemExit):
+ arbiter.main(["rejudge", str(saved), "--out", str(saved)])
+ assert saved.read_bytes() == before
+
+
+def test_rule_and_rejudge_import_without_the_parity_http_client():
+ # Only from-parity needs greedy_parity, whose HTTP client imports requests; the public test env has no requests.
+ code = (
+ "import importlib.util, sys; sys.modules['requests'] = None; "
+ f"spec = importlib.util.spec_from_file_location('fp32_arbiter', {str(_TOOL)!r}); "
+ "m = importlib.util.module_from_spec(spec); sys.modules['fp32_arbiter'] = m; spec.loader.exec_module(m); "
+ "print(m.bf16_ulp(20.0))"
+ )
+ out = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True)
+ assert out.returncode == 0, out.stderr
+ assert out.stdout.strip() == "0.125"
diff --git a/tools/fp32_arbiter.py b/tools/fp32_arbiter.py
new file mode 100644
index 0000000..ed8c5f8
--- /dev/null
+++ b/tools/fp32_arbiter.py
@@ -0,0 +1,325 @@
+#!/usr/bin/env python3
+# Copyright 2026 Eagle AI Corp.
+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available
+
+"""fp32 arbiter for greedy-parity divergences above the near-tie gap.
+
+``greedy_parity.py compare`` calls a first divergence a near tie when the bf16 reference's logprob gap to the
+candidate's token is at most 0.13 (one bf16 ulp for logits in [16, 32)). Every divergence above that is decided
+here: the target is re-forwarded in float32 on the exact common prefix (same weights, the unmodified HF model,
+eager attention, no fused kernels), ``d = |logit_fp32(reference token) - logit_fp32(candidate token)|`` is taken,
+and with ``ulp = 2 ** (floor(log2(max(|a|, |b|))) - 7)`` (bf16 spacing at that magnitude) the divergence
+**passes** when ``d <= 2 ulp`` (``fp32_pass``) or when the candidate's own token is the fp32 argmax at that prefix
+(``fp32_argmax``: the bf16 reference is the one that is off), and **fails** otherwise. Exact bf16 ties fall under
+the same rule. Each divergence is reported as identical / near_tie / fp32_pass / fp32_argmax / fail with the fp32
+logits and token ids.
+
+ python tools/fp32_arbiter.py from-parity --model <model dir> --data question_multiturn.jsonl \\
+ --reference nospec.json --candidate live.json [static.json ...] --out arbiter.json
+ python tools/fp32_arbiter.py prefix --model <model dir> --prefix-ids ids.json --tokens 4087 310
+ python tools/fp32_arbiter.py rejudge arbiter.json --out arbiter.rejudged.json
+
+``rejudge`` re-decides a saved report under the current rule from the fp32 logits it recorded, without a model,
+and writes a new file next to the original evidence.
+
+The scorer (an fp32 forward at the last position of a prefix) is the only part that needs a GPU and the model;
+the rule and the parity classification are plain functions, tested on CPU.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import sys
+import time
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from typing import Callable, Dict, List, Mapping, Optional, Sequence
+
+TIE_GAP = 0.13
+TOLERANCE_ULPS = 2.0
+STATUSES = ("identical", "near_tie", "fp32_pass", "fp32_argmax", "fail", "length")
+
+# fp32 logits of the requested tokens at the position after ``prefix_ids``, plus the top-k (value, token) pairs.
+Scorer = Callable[[Sequence[int], Sequence[int]], "Scores"]
+
+
+@dataclass
+class Scores:
+ logits: Dict[int, float]
+ top: List[List[float]] # [[logit, token], ...] best first
+ seconds: float = 0.0
+
+
+@dataclass
+class Verdict:
+ reference_token: int
+ candidate_token: int
+ reference_logit: float
+ candidate_logit: float
+ d: float
+ ulp: float
+ tolerance_ulps: float
+ fp32_argmax: int
+ status: str # fp32_pass, fp32_argmax or fail
+ passes: bool
+
+
+def bf16_ulp(magnitude: float) -> float:
+ """bf16 spacing at ``magnitude``: 2 ** (floor(log2(magnitude)) - 7); 0.125 on [16, 32)."""
+ if magnitude <= 0.0:
+ return math.ldexp(1.0, -133) # smallest bf16 subnormal: a tie at 0 is still a tie
+ mantissa, exponent = math.frexp(magnitude) # magnitude = mantissa * 2 ** exponent, mantissa in [0.5, 1)
+ return math.ldexp(1.0, exponent - 8)
+
+
+def arbitrate(
+ reference_token: int, candidate_token: int, scores: Scores, tolerance_ulps: float = TOLERANCE_ULPS
+) -> Verdict:
+ """Within ``tolerance_ulps`` of each other passes; beyond it, the candidate passes only as the fp32 argmax."""
+ a, b = scores.logits[reference_token], scores.logits[candidate_token]
+ d = abs(a - b)
+ ulp = bf16_ulp(max(abs(a), abs(b)))
+ best_logit, best_token = scores.top[0]
+ if d <= tolerance_ulps * ulp:
+ status = "fp32_pass"
+ elif b >= best_logit: # a tie at the top still makes the candidate an fp32 argmax
+ status = "fp32_argmax"
+ else:
+ status = "fail"
+ return Verdict(
+ reference_token, candidate_token, a, b, d, ulp, tolerance_ulps, int(best_token), status, status != "fail"
+ )
+
+
+def first_divergence(reference: dict, candidate: dict) -> Optional[int]:
+ a, b = reference["output_ids"], candidate["output_ids"]
+ return next((i for i in range(min(len(a), len(b))) if a[i] != b[i]), None)
+
+
+def reference_gap(reference: dict, index: int, token: int) -> Optional[float]:
+ """The bf16 reference's logprob gap from its best to ``token`` at ``index`` (None when not in its saved top-k)."""
+ top = reference.get("top", [])
+ if index >= len(top):
+ return None
+ ranked = {tok: lp for lp, tok in top[index]}
+ return top[index][0][0] - ranked[token] if token in ranked else None
+
+
+def classify(
+ reference: dict,
+ candidate: dict,
+ prompt_ids: Sequence[int],
+ score: Scorer,
+ tie_gap: float = TIE_GAP,
+ tolerance_ulps: float = TOLERANCE_ULPS,
+) -> dict:
+ """One prompt's parity verdict (one of ``STATUSES``), with the fp32 evidence when scored."""
+ a, b = reference["output_ids"], candidate["output_ids"]
+ index = first_divergence(reference, candidate)
+ entry = {"question_id": candidate["question_id"], "index": index, "status": None}
+ if index is None:
+ entry["status"] = "identical" if len(a) == len(b) else "length"
+ entry["lengths"] = [len(a), len(b)]
+ return entry
+ ref_token, cand_token = a[index], b[index]
+ gap = reference_gap(reference, index, cand_token)
+ entry.update(reference_token=ref_token, candidate_token=cand_token, reference_gap=gap)
+ if gap is not None and gap <= tie_gap:
+ entry["status"] = "near_tie"
+ return entry
+ prefix = list(prompt_ids) + list(a[:index])
+ scores = score(prefix, [ref_token, cand_token])
+ verdict = arbitrate(ref_token, cand_token, scores, tolerance_ulps)
+ entry.update(
+ status=verdict.status,
+ prefix_length=len(prefix),
+ fp32=asdict(verdict),
+ fp32_top=scores.top,
+ fp32_argmax=verdict.fp32_argmax,
+ seconds=scores.seconds,
+ )
+ return entry
+
+
+def summarize(rows: List[dict]) -> dict:
+ """Counts per status; ``passes`` iff no row is ``fail`` or ``length``."""
+ counts = {s: sum(r["status"] == s for r in rows) for s in STATUSES}
+ return {"counts": counts, "passes": counts["fail"] == 0 and counts["length"] == 0, "rows": rows}
+
+
+def classify_parity(
+ reference_doc: dict,
+ candidate_doc: dict,
+ prompts: Mapping[str, Sequence[int]],
+ score: Scorer,
+ tie_gap: float = TIE_GAP,
+ tolerance_ulps: float = TOLERANCE_ULPS,
+) -> dict:
+ """Every prompt of a ``greedy_parity.py run`` pair; ``passes`` iff no prompt is ``fail`` or ``length``."""
+ reference = {r["question_id"]: r for r in reference_doc["results"]}
+ rows = [
+ classify(reference[c["question_id"]], c, prompts[c["question_id"]], score, tie_gap, tolerance_ulps)
+ for c in candidate_doc["results"]
+ ]
+ return {"tie_gap": tie_gap, "tolerance_ulps": tolerance_ulps, **summarize(rows)}
+
+
+def rejudge_row(row: dict) -> dict:
+ """``row`` decided again by ``arbitrate`` from the fp32 logits it saved (no re-scoring); unscored rows as they are."""
+ if "fp32" not in row:
+ return dict(row)
+ saved, ref_token, cand_token = row["fp32"], row["reference_token"], row["candidate_token"]
+ scores = Scores({ref_token: saved["reference_logit"], cand_token: saved["candidate_logit"]}, row["fp32_top"])
+ verdict = arbitrate(ref_token, cand_token, scores, saved["tolerance_ulps"])
+ return {**row, "status": verdict.status, "fp32": asdict(verdict), "fp32_argmax": verdict.fp32_argmax}
+
+
+def rejudge(report: dict) -> dict:
+ """A saved report (``from-parity``'s ``candidates`` or a list of ``verdicts``) under the current rule, as a copy."""
+ if "candidates" not in report and "verdicts" not in report:
+ raise ValueError("not an fp32 arbiter report: no 'candidates' or 'verdicts'")
+
+ def again(result: dict) -> dict:
+ return {**result, **summarize([rejudge_row(r) for r in result["rows"]])}
+
+ out = dict(report)
+ if "candidates" in report:
+ out["candidates"] = {name: again(result) for name, result in report["candidates"].items()}
+ if "verdicts" in report:
+ out["verdicts"] = [again(result) for result in report["verdicts"]]
+ return out
+
+
+def format_row(row: dict) -> str:
+ head = f"{row['question_id'][:8]} {row['status']:<11}"
+ if row["index"] is None:
+ return f"{head} lengths {row.get('lengths')}"
+ line = f"{head} at {row['index']}: ref {row['reference_token']} vs {row['candidate_token']}, ref bf16 gap {row['reference_gap']}"
+ if "fp32" in row:
+ v = row["fp32"]
+ line += (
+ f"; fp32 {v['reference_logit']:.4f} vs {v['candidate_logit']:.4f}, d {v['d']:.4f}, ulp {v['ulp']}"
+ f" ({v['d'] / v['ulp']:.2f} ulp, limit {v['tolerance_ulps']}), fp32 argmax {row['fp32_argmax']}"
+ )
+ return line
+
+
+def load_reference_model(model_path: str, device: str = "cuda"):
+ """The unmodified HF model in float32 with eager attention: the reference, not a serving path."""
+ import torch
+ import transformers
+
+ config = transformers.AutoConfig.from_pretrained(model_path, trust_remote_code=False)
+ cls = getattr(transformers, config.architectures[0], transformers.AutoModelForCausalLM)
+ started = time.monotonic()
+ # No device_map: it needs `accelerate`, which the serving venvs do not carry; the fp32 27B fits one B300.
+ model = cls.from_pretrained(model_path, dtype=torch.float32, attn_implementation="eager").to(device).eval()
+ dtypes = {str(p.dtype) for p in model.parameters()}
+ assert dtypes == {"torch.float32"}, dtypes
+ module = sys.modules[type(model).__module__]
+ fast = getattr(module, "is_fast_path_available", False)
+ assert not fast, "the reference must run the torch fallback kernels, not the fused fast path"
+ return model, time.monotonic() - started
+
+
+def hf_scorer(model, device: str = "cuda", topk: int = 10) -> Scorer:
+ import torch
+
+ def score(prefix_ids: Sequence[int], tokens: Sequence[int]) -> Scores:
+ ids = torch.tensor([list(prefix_ids)], dtype=torch.long, device=device)
+ started = time.monotonic()
+ with torch.inference_mode():
+ out = model(input_ids=ids, attention_mask=torch.ones_like(ids), use_cache=False, logits_to_keep=1)
+ logits = out.logits[0, -1].double()
+ values, indices = torch.topk(logits, topk)
+ return Scores(
+ {int(t): logits[t].item() for t in tokens},
+ [[v, int(i)] for v, i in zip(values.tolist(), indices.tolist())],
+ time.monotonic() - started,
+ )
+
+ return score
+
+
+def main(argv: Optional[Sequence[str]] = None) -> int:
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ sub = ap.add_subparsers(dest="command", required=True)
+ p = sub.add_parser("from-parity", help="arbitrate every first divergence of greedy_parity run outputs")
+ p.add_argument("--model", required=True)
+ p.add_argument("--data", required=True, help="question_multiturn.jsonl the parity runs used")
+ p.add_argument("--prompts", type=int, default=20, help="prompt count the parity runs used")
+ p.add_argument("--reference", required=True, help="no-spec parity json with --top-logprobs")
+ p.add_argument("--candidate", nargs="+", required=True)
+ p.add_argument("--tie-gap", type=float, default=TIE_GAP)
+ p.add_argument("--tolerance-ulps", type=float, default=TOLERANCE_ULPS)
+ p.add_argument("--out", required=True)
+ q = sub.add_parser("prefix", help="score two tokens after one explicit prefix")
+ q.add_argument("--model", required=True)
+ q.add_argument(
+ "--prefix-ids", required=True, help="json file with the full token id list (prompt + accepted tokens)"
+ )
+ q.add_argument("--tokens", type=int, nargs=2, required=True, metavar=("REFERENCE", "CANDIDATE"))
+ q.add_argument("--tolerance-ulps", type=float, default=TOLERANCE_ULPS)
+ q.add_argument("--out")
+ r = sub.add_parser("rejudge", help="re-decide a saved report from its fp32 logits (no model)")
+ r.add_argument("report")
+ r.add_argument("--out", required=True, help="a new file: the saved report stays the raw evidence")
+ args = ap.parse_args(argv)
+
+ if args.command == "rejudge":
+ if Path(args.out).resolve() == Path(args.report).resolve():
+ ap.error("--out must not overwrite the saved report")
+ report = rejudge(json.loads(Path(args.report).read_text()))
+ report["rejudged_from"] = args.report
+ results = list(report.get("candidates", {}).items())
+ results += [(v.get("candidate", str(i)), v) for i, v in enumerate(report.get("verdicts", []))]
+ for name, result in results:
+ print(f"== {name}")
+ for row in result["rows"]:
+ if row["status"] not in ("identical", "near_tie"):
+ print(format_row(row))
+ print(f"{'PASS' if result['passes'] else 'FAIL'} {json.dumps(result['counts'])}")
+ Path(args.out).write_text(json.dumps(report, indent=1))
+ return 0 if all(result["passes"] for _, result in results) else 1
+
+ model, load_seconds = load_reference_model(args.model)
+ score = hf_scorer(model)
+ if args.command == "prefix":
+ prefix = json.loads(Path(args.prefix_ids).read_text())
+ scores = score(prefix, args.tokens)
+ verdict = arbitrate(args.tokens[0], args.tokens[1], scores, args.tolerance_ulps)
+ report = {"model": args.model, "prefix_length": len(prefix), "fp32": asdict(verdict), "fp32_top": scores.top}
+ print(json.dumps(report["fp32"]))
+ if args.out:
+ Path(args.out).write_text(json.dumps(report, indent=1))
+ return 0 if verdict.passes else 1
+
+ from transformers import AutoTokenizer
+
+ # Imported here: greedy_parity is the HTTP client (it needs requests); the rule and rejudge do not.
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
+ from greedy_parity import encode_prompt, load_prompts
+
+ tokenizer = AutoTokenizer.from_pretrained(args.model)
+ prompts = {row["question_id"]: encode_prompt(tokenizer, row) for row in load_prompts(args.data, args.prompts)}
+ reference_doc = json.loads(Path(args.reference).read_text())
+ report = {"model": args.model, "load_seconds": load_seconds, "reference": args.reference, "candidates": {}}
+ passes = True
+ for path in args.candidate:
+ result = classify_parity(
+ reference_doc, json.loads(Path(path).read_text()), prompts, score, args.tie_gap, args.tolerance_ulps
+ )
+ report["candidates"][path] = result
+ print(f"== {path}")
+ for row in result["rows"]:
+ print(format_row(row))
+ print(f"{'PASS' if result['passes'] else 'FAIL'} {json.dumps(result['counts'])}", flush=True)
+ passes &= result["passes"]
+ Path(args.out).write_text(json.dumps(report, indent=1))
+ return 0 if passes else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/greedy_parity.py b/tools/greedy_parity.py
index ab2608f..28aeb6e 100644
--- a/tools/greedy_parity.py
+++ b/tools/greedy_parity.py
@@ -53,6 +53,18 @@ def load_prompts(path: str, count: int) -> List[dict]:
return picked
+def encode_prompt(tokenizer, row: dict) -> List[int]:
+ """The token ids ``run`` sends for a conversation's first turn (chat template applied client side)."""
+ messages = [
+ {"role": "system", "content": "You are a helpful assistant."},
+ {"role": "user", "content": row["turns"][0]},
+ ]
+ text = tokenizer.apply_chat_template(
+ messages, add_generation_prompt=True, tokenize=False, enable_thinking=True, reasoning_effort="xhigh"
+ )
+ return list(tokenizer.encode(text, add_special_tokens=False))
+
+
def run(args: argparse.Namespace) -> None:
from transformers import AutoTokenizer
@@ -61,16 +73,9 @@ def run(args: argparse.Namespace) -> None:
results = []
t0 = time.time()
for row in load_prompts(args.data, args.prompts):
- messages = [
- {"role": "system", "content": "You are a helpful assistant."},
- {"role": "user", "content": row["turns"][0]},
- ]
- text = tokenizer.apply_chat_template(
- messages, add_generation_prompt=True, tokenize=False, enable_thinking=True, reasoning_effort="xhigh"
- )
- input_ids = tokenizer.encode(text, add_special_tokens=False)
+ input_ids = encode_prompt(tokenizer, row)
payload = {
- "input_ids": list(input_ids),
+ "input_ids": input_ids,
"sampling_params": {"temperature": 0, "top_k": 1, "max_new_tokens": args.max_new_tokens},
}
if args.top_logprobs: