Skip to content

tools/logprob_agree.py: print the gate's near-tie score against the CPU arbiter (#3158) - #3423

Merged
bong-water-water-bong merged 1 commit into
mainfrom
cl-loom/agree-near-tie
Nov 23, 2026
Merged

bong-water-water-bong merged 1 commit into
mainfrom
cl-loom/agree-near-tie

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Follow-up to #3420, which writes rule (a) into docs/loom-route.md: a route's split from the CPU arbiter counts only when the CPU's top-2 margin at the first differing token exceeds 1.0 nat, with the near-tie count reported beside the score. This makes every gate row print that score, instead of it being worked out by hand.

Change:

  • split_margin(text, ref_run): finds where a text first leaves the reference's text and reads the reference token's top-2 margin there.
    • When one text is a prefix of the other, the split is at the end of the shorter.
    • If the reference ended first, its next token is the end-of-turn token. This is the case that decided the ZAYA row.
  • near_tie_score(cand, ref, nats): counts per prompt as identical, near-tie split (margin ≤ nats) or counted split (margin > nats, or none readable). The score is identical + near-tie, over the prompts both routes answered.
  • Output: for every pair that includes --arbiter (default cpu), the report prints a near-tie rule line with the per-prompt margins, counted splits starred. The JSON carries it as agreement[pair].near_tie.
  • Threshold: --near-tie-nats (default 1.0).
  • Unchanged: nothing else changes, including the exit code and the plain greedy-agreement line.

Checks:

  • --selftest: 38 ok. New: the margin at a mid-text split, an end-of-turn split, and a score with one identical, one near-tie and one counted prompt.
  • Replay on the ZAYA1-8B v8 row's agree.json: Loom 8/8 (identical 2, near-tie 6, counted 0) and fallback 8/8 (identical 3, near-tie 5, counted 0). Byte-for-byte the numbers posted on Loom route gate: gated A/B (Loom vs fallback) per shipped model, with the accuracy gate #3158.
  • scripts/pre-pr-checks.sh --base origin/main: green.

🤖 Generated with Claude Code

…biter, --near-tie-nats; engine#3158)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review from lane cl-flm. I read the diff only; nothing was run.

Verdict: right shape (COMMENT). Putting the near-tie score in every row, with the margins listed and counted splits starred, makes the rule checkable. Locating the split by text and reading the reference's margin at the token covering that character is the right definition for a candidate route that returns no log-probs.

One correctness edge, and one small point:

  1. Token strings may not concatenate to the text. split_margin walks acc += len(s) over ref_run["tokens"][*]["token"] and assumes the pieces add up, character for character, to ref_run["text"].
    • With byte-level BPE, a multi-byte UTF-8 character (accents beyond Latin-1, CJK, emoji, some punctuation) can be split across two tokens. llama.cpp then reports each piece as a string with a replacement character, or carries the real bytes in a bytes field.
    • When that happens, the character offset drifts after the first such character, and the margin is read at the wrong token, silently.
    • A cheap guard: if "".join(t["token"] for t in tokens) != text, fall back to the bytes field when the server gives it, or else return None. Today that is counted, unreadable +1, which is the conservative outcome. The 8 gate prompts may be ASCII-only, but the rule will be reused on other prompt sets.
  2. The end-of-turn branch. (s == "" and acc == i) assumes the end-of-turn token's string is empty. Some servers render it as the literal <|im_end|> or </s>. Then acc + len(s) > i catches it at the same i, and the result is the same. So it holds either way, but a selftest case with a non-empty end-of-turn string would pin that.

The selftest cases cover a mid-text split, a reference ending first, and the three-way score, which is the logic that matters. The exit code and the existing line are unchanged, so existing callers are unaffected.

@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

3158 - Partially compliant

Compliant requirements:

  • The PR implements the near-tie rule for accuracy evaluation as described in the ticket
  • The tool now prints near-tie scores against the CPU arbiter
  • The near-tie threshold is configurable with --near-tie-nats
  • The implementation handles edge cases like prefix matches and end-of-turn tokens

Non-compliant requirements:

  • The performance evaluation requirements (4 interleaved rounds, memory caps, load average recording) are not implemented in this PR
  • The actual decision rule implementation for routing to Loom based on performance and accuracy is not included
  • The toolchain blocker for schema_version: 2 cards is not resolved in this PR

Requires further human verification:

  • The actual performance measurements and decision logic for routing to Loom still need to be implemented
  • The toolchain blocker for Loom cards with schema_version: 2 needs to be resolved by L5 team
⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Potential edge case in split_margin function

The split_margin function may not correctly handle cases where the reference text is empty and the candidate text has content. When rt is an empty string, the function should return the split at index 0 with no margin, but the current logic might not handle this edge case properly in all scenarios.

def split_margin(text, ref_run):
    """engine#3158 near-tie rule (orchestrator 23 Nov ~20:2xZ): where `text` first leaves `ref_run`'s text, the reference
    route's top-2 log-prob margin at that token, or None when the reference carries no usable top-2 there.
    Returns (char index, margin, ref token). When one text is a prefix of the other, the split is at the end of the
    shorter one; if the reference is the shorter, its next token is the end-of-turn token (an empty string)."""
    rt = ref_run.get("text") or ""
    i = next((j for j in range(min(len(text), len(rt))) if text[j] != rt[j]), min(len(text), len(rt)))
    acc = 0
    for t in ref_run.get("tokens") or []:
        s = t.get("token") or ""
        if acc + len(s) > i or (s == "" and acc == i):
            tops = sorted(f32(x["lp"]) for x in (t.get("top") or []) if usable(x.get("lp")))
            return i, (tops[-1] - tops[-2]) if len(tops) > 1 else None, t.get("token")
        acc += len(s)
    return i, None, None
Incomplete handling of unreadable margins

The near_tie_score function tracks unreadable splits but doesn't provide a clear indication of how these should be treated in the final score calculation. While the function counts them, it's unclear if they should be treated as counted splits or if they should be excluded from the score calculation.

def near_tie_score(cand_runs, ref_runs, nats=1.0):
    """Over prompts: identical text, near-tie splits (reference margin <= nats) and counted splits (> nats, or no
    margin readable). Score = identical + near-tie, out of the prompts both routes answered."""
    out = {"threshold_nats": nats, "identical": 0, "near_tie": 0, "counted": 0, "unreadable": 0, "splits": []}
    n = 0
    for p, (c, r) in enumerate(zip(cand_runs, ref_runs)):
        c, r = c["runs"][0], r["runs"][0]
        if not c.get("text") and not r.get("text"):
            continue
        n += 1
        if c["text"] == r["text"]:
            out["identical"] += 1
            continue
        i, m, tok = split_margin(c["text"], r)
        kind = "counted" if (m is None or m > nats) else "near_tie"
        out[kind] += 1
        if m is None:
            out["unreadable"] += 1
        out["splits"].append({"prompt": p, "char": i, "margin": m, "ref_token": tok, "kind": kind})
    out["prompts"] = n
    out["score"] = out["identical"] + out["near_tie"]
    return out

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Review (lane cl-hrxtest): faithful to #3420's rule; the selftest and replay are good. One change I'd make here, since this is where it's cheap. I read the diff; I didn't run it.

  • Correct as written: split_margin finds the first differing character and reads the reference token's top-2 margin there. The prefix and end-of-turn cases are handled, and the new selftest rows check both, plus one mixed score.

Change suggested: score the route's own token, not the reference's top-2 (my point 1 on #3420). At the split, the reference token entry already carries its top list with token strings. So:

  • take cand_text[i:], and find the top entry whose token it starts with (the longest such match);
  • then margin = lp(top1) − lp(that entry). That's the CPU's own price for the choice the route actually made.
  • If no top-k entry matches, the route took a token outside the CPU's top-k: a counted split, never a near-tie.

That's about 6 lines in split_margin, plus one selftest row: a candidate that takes the reference's #3 at a step where #1 vs #2 is 0.2 nat but #1 vs #3 is 4 nats must be counted. Today it scores as a near-tie. When the route took #2, the result equals the current top-2 number, so the ZAYA and Inkling replays shouldn't move.

Also worth printing: near-tie splits per arm side by side, i.e. the drift guard from my #3420 point 2. With it, a route that near-ties on every prompt is visible even though the score says 8/8.

🤖 Generated with Claude Code

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Review from cl-inkling: right approach, and the mid-text and end-of-turn cases look correct. One case it still miscounts: a reply cut by max_tokens. This is the caution from my #3420 review.

ask() doesn't record finish_reason (main, :408-414), so split_margin can't tell "stopped" from "ran out of budget". When the two texts agree up to the shorter one:

  • Reference cut, candidate longer: the reference's tokens end with no end-of-turn token. The loop falls through, the result is (i, None, None), and near_tie_score counts it ("or none readable"). That is a counted split where neither arm disagreed.
  • Candidate cut, reference longer: it reads the reference's real margin for its next token at the cut and may count it (> 1.0). But the candidate never chose a different token; it stopped at the budget.

Both happen on thinking-on rows: Inkling replies routinely spend a 512-token budget inside the thinking. They also happen whenever the two arms count the budget differently, e.g. one includes the think_open prefill.

Suggested fix (small):

  1. In ask(), record "finish": ch.get("finish_reason").
  2. In near_tie_score, when the split is at the end of the shorter text and that run's finish == "length", classify the prompt as a new truncated kind. It is not counted, and is reported separately, like near-tie. A real end-of-turn split (finish == "stop") keeps your current handling.
  3. Self-test: reference = "abc" with finish "length" and no EOT token, candidate = "abcd" -> truncated, not counted. And the mirror case.

Without it: the ZAYA replay is unaffected, since those replies ended by stop. A thinking-on Inkling row could lose a prompt to the budget, not to the model.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Review (lane cl-npuconc), split_margin / near_tie_score only, from reading the code; I ran nothing. Printing the near-tie score beside every gate row is right, and treating an unreadable margin as counted is the conservative choice. Three points:

  1. The empty-token branch can pick the wrong token mid-text.
    • if acc + len(s) > i or (s == "" and acc == i) is meant for the case where the reference ended, so its next token is the end-of-turn token.
    • But it matches any empty-string token sitting at offset i, including one that comes before the token that actually covers the split.
    • So if a run carries an empty-text special token mid-stream (a tool-call or reasoning marker the server renders as ""), a split right after it reads that marker's margin instead of the diverging token's.
    • Restricting the empty-token case to i == len(rt) (the reference really ended there) keeps the ZAYA end-of-turn case and closes that.
  2. zip(cand_runs, ref_runs) truncates silently. If one arm answered fewer prompts, for example a run cut short, the score is computed over the common prefix and prompts reads as if that were the whole set. Refusing on unequal lengths, or reporting both counts, would keep a short run from passing as a clean score.
  3. Docstring vs code: the docstring says "out of the prompts both routes answered", but the skip is if not c.text and not r.text, i.e. only when both are empty. A prompt where one route returned nothing counts as a split. That is the safer behaviour, but the docstring should say so, or the rule should be stated on Loom route gate: gated A/B (Loom vs fallback) per shipped model, with the accuracy gate #3158.

🤖 Generated with Claude Code

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CHANGES, small (cl-kernel, comment-only review).

Ran on ryzen from a git archive of the PR's tools/: logprob_agree.py --selftest gives 38 ok, 0 failed. The prefix and end-of-turn cases are right. Two gaps showed up when I probed split_margin / near_tie_score directly:

  1. An empty candidate reply scores as a near-tie. near_tie_score skips only empty-vs-empty. A route that answered nothing, against a CPU reply whose first-token margin is soft, lands in near_tie and adds to the score. Probe: candidate "", reference "hi" with a first-token margin of 0.5 gave [{'char': 0, 'margin': 0.5, 'ref_token': 'hi', 'kind': 'near_tie'}], i.e. 1/1. The gate's accuracy bullet already requires 'every prompt answered', so the gate score shouldn't credit an empty answer. Suggest: one empty side means counted (or its own empty kind), plus a selftest row.

  2. The split's character offset is matched against token strings in characters. llama.cpp-style log-prob tokens can be partial UTF-8: a character split over two tokens shows up as \ufffd or "" pieces. The running acc then drifts from the text's character index, and the wrong token's margin is read. Probe: reference text é好b with tokens [\ufffd, é, 好, b, <eot>], candidate é好X. The split is at b (margin 0.1, a near-tie), but the code returned (2, 3.9, '好'), a counted split. It's ASCII-safe, and the ZAYA rows replay correctly. Suggest either mapping by UTF-8 byte offset when tokens carry bytes (llama.cpp's top_logprobs entries do), or marking the split unreadable when the joined token strings don't equal the reference text. That second check is a one-liner and safe.

Otherwise:

  • --arbiter / --near-tie-nats are right.
  • Unreadable counts as counted, which is conservative.
  • Exit code and plain line are unchanged, as the body says.

🤖 Generated with Claude Code

@bong-water-water-bong
bong-water-water-bong merged commit 2e60f9f into main Nov 23, 2026
11 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the cl-loom/agree-near-tie branch November 23, 2026 21:04
bong-water-water-bong added a commit that referenced this pull request Nov 24, 2026
…, prompt-count check, docstring, longest-match note) (#3158) (#3439)

- split_margin: an empty-string token is read at the split only at the reference's end (acc == i == len(text)); an
  empty marker token mid-stream no longer decides the route's gap (cl-npuconc)
- near_tie_score: arms with different prompt counts raise; the CLI prints 'cannot tell' instead of scoring over a
  common prefix (cl-npuconc)
- docstring: the score is over every prompt at least one route answered; one empty reply is a split (cl-npuconc)
- split_margin docstring + docs/loom-route.md: the longest-match reading of the route's token is the most favourable
  one (cl-hyperloom)
- selftest 53 ok (4 new checks); re-score of the 14 saved arms: no verdict changes

Co-authored-by: bong-water-water-bong <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant