C19, before and after: merging the two cut checks keeps every check and every result, and saves about 40 lines

NVIDIA-NeMo/RL #4507, review comment C19. "Before" links pin the PR head 7f7a7a5; "after" is a tested copy, not in the PR.

Before
Two functions check each restored call. The second one calls the first, then rebuilds the same lookups, and the trained rows are re-indexed 7 times across the file.
Proposed
Build the row index once, and do every per-cut check in one function, _check_cuts.
Status
Proposed, not in the PR. Written and tested on a copy: 27 of 27 unit tests pass before and after, and 300 random cases with deliberate breakage give the same pass/fail and the same error message. It saves 40 lines in the test script, 33 counting the unit-test edits. The review comment first said ~100; that was wrong.

Five pages on this PR. Page 1 explains what the test proves. This one: what C19 changes in the code, and how we know it still checks the same things.

After phase 2, the test checks every restored call: it finished exactly once, it wrote at least one new token, its row ends where the logged token count says, and the row's closing reply starts with the restored prefix. Today _assert_prefix_boundary does that. Then _rows_diverged_before_cut calls it, builds its own row lookups again, looks up each restored hash a second time, and decides which rows to set aside. C19 puts both into one loop over the cuts. The checks themselves are most of the code, so merging removes only the repeated setup.

Every check, before and after

same check, moved built several times → built once repeated work, removed check dropped (cannot fail) What is checked or built Before (head lines) After (in the tested copy) Row index: no row twice, no split group 7×: L215, L216, L431 … L507 2×, both in compare (L509-510) Row lookup for the cut checks 2×: L304-308, L430-436 1× (L362-365) Each cut's completion line, exactly once L309-327, list scan per cut log read once (L354-357), check L371-376 Each cut's restore line, exactly once 2×: L337-347, L444-449 log read once (L358-361), check L386-391 At least one new token (tail > 0) L330-331 L379-380 prefix + tail = logged total L332-336 L381-386 The cut has a trained row L348-351 L393-396 Row ends with the logged token count L352-359 L397-405 Reply starts with the restored prefix L360-364 L406-410 Skip rows that match the reference L450-455 L412-417 Set-aside row: matches before the reply L456-462 L418-424 Not every cut is set aside L464-468 L426-430 No dump file mixes two training steps L122-125 dropped: one step per file

"After" line numbers are in the tested copy, which is not in the PR; the code itself is below. The dropped check made sure no dump file mixes two training steps. JsonDebugWriter names each file after its step and writes that step on every row, so a file cannot hold two.

The change in the code

Two moves. First, compare builds the row index once, after it keeps only the reference's steps, and hands it to every check. load_training_records cannot return it, because the cleanup check still needs each step's records.

@@ _gym_prefix_recovery_parity.py · compare()
         if record["train_step"] <= args.steps
     ]
+    baseline = _rows_by_identity(baseline_records)
+    recovery = _rows_by_identity(recovery_records)
     selection = read_json(args.selection)
     …
-    reward_signal = _assert_reward_signal(baseline_records)
+    reward_signal = _assert_reward_signal(baseline)
     …
-    diverged = _rows_diverged_before_cut(
-        selection, recovery_log, baseline_records, recovery_records
-    )
+    _, diverged = _check_cuts(selection, recovery_log, baseline, recovery)
     …
     _compare_training_rows(
-        baseline_records,
-        recovery_records,
+        baseline,
+        recovery,

Second, the two cut functions (82 + 58 lines) become one 108-line _check_cuts. It reads the log once into two lookups, completion lines and restore lines, each keyed by call and prefix length. Then it runs today's checks for each cut, in today's order, with today's error messages. Like today, it counts duplicate log lines only for calls that were cut. (The sketch in the first version of C19 counted them for every call, which would have quietly made the test stricter.)

Show the full tested _check_cuts
def _check_cuts(
    selection: Mapping[str, Any],
    recovery_log: str,
    baseline: Mapping[tuple[int, int, int], Mapping[str, Any]],
    recovery: Mapping[tuple[int, int, int], Mapping[str, Any]],
) -> tuple[dict[tuple[str, int], int], frozenset[tuple[int, int, int]]]:
    """Check each restored call's trained row, and find rows phase 1 diverged.

    Each restored call must complete once and train on its restored prefix. A
    restored call closes its row, so the ``total_generation_tokens`` it logs on
    completion end the row: counting back finds where the call starts. That
    holds even when the trainer masked positions inside the call (top-k/top-p
    ``-inf`` logprobs drop out of ``token_mask``), which a search for the last
    unmasked segment would mistake for the call's start. A dropped or
    duplicated token moves that start, so the restored prefix no longer sits
    there.

    vLLM sampling is not batch-invariant, so phase 1 can take the other side of
    a near-tie before the cut. Recovery must then continue phase 1's tokens, and
    the reference no longer predicts that row. A row is set aside only when the
    reference's call opens differently at the same position. Everything before
    the closing call must still match, and at least one restored row must match
    the reference outright, so a capture that recorded the wrong tokens for
    every cut cannot pass.

    Returns:
        Each cut's ``(group_id, generation_index)`` mapped to the index in its
        trained row where the restored call's generated tokens begin, and the
        identities of the rows set aside.
    """
    completed: dict[tuple[str, int], list[dict[str, str]]] = {}
    for match in _COMPLETED_PREFIX_LINE.finditer(recovery_log):
        key = (match["source_model_call_id"], int(match["prefix_tokens"]))
        completed.setdefault(key, []).append(match.groupdict())
    hashes: dict[tuple[str, int], list[str]] = {}
    for line in restored_prefixes(recovery_log):
        key = (line["source_model_call_id"], line["prefix_tokens"])
        hashes.setdefault(key, []).append(line["prefix_ids_sha256"])
    by_call = {
        (row["group_id"], int(row["generation_index"])): identity
        for identity, row in recovery.items()
    }
    starts: dict[tuple[str, int], int] = {}
    diverged: set[tuple[int, int, int]] = set()
    for cut in selection["cuts"]:
        source = cut["model_call_id"]
        prefix_tokens = int(cut["prefix_token_count"])
        matches = completed.get((source, prefix_tokens), [])
        if len(matches) != 1:
            raise AssertionError(
                "restored prefix did not complete exactly once: "
                f"source={source!r}, matches={matches!r}"
            )
        tail_tokens = int(matches[0]["tail_tokens"])
        total_tokens = int(matches[0]["total_tokens"])
        if tail_tokens <= 0:
            raise AssertionError("restored generation produced no suffix tokens")
        if prefix_tokens + tail_tokens != total_tokens:
            raise AssertionError(
                "restored generation token accounting has a gap or overlap: "
                f"prefix={prefix_tokens}, tail={tail_tokens}, total={total_tokens}"
            )
        cut_hashes = hashes.get((source, prefix_tokens), [])
        if len(cut_hashes) != 1:
            raise AssertionError(
                f"restored prefix {source!r} was logged {len(cut_hashes)} times, "
                "expected once"
            )
        restored_hash = cut_hashes[0]
        key = (cut["group_id"], int(cut["generation_index"]))
        identity = by_call.get(key)
        if identity is None:
            raise AssertionError(f"restored call {source!r} has no trained row")
        right = recovery[identity]
        start = len(right["token_ids"]) - total_tokens
        # The token before a call's generated tokens is its own prompt, never
        # trained; landing on a trained token means the row's length is off.
        if start < 1 or right["token_loss_mask"][start - 1]:
            raise AssertionError(
                f"trained row for {source!r} does not end with its "
                f"{total_tokens} generated tokens: row has {len(right['token_ids'])}"
            )
        if _closing_prefix_sha256(right, start, prefix_tokens) != restored_hash:
            raise AssertionError(
                f"row for {source!r} does not start its closing call with its "
                f"{prefix_tokens} restored prefix tokens"
            )
        starts[key] = start
        left = baseline.get(identity)
        if (
            left is None
            or _closing_prefix_sha256(left, start, prefix_tokens) == restored_hash
        ):
            continue
        if (
            left["token_ids"][:start] != right["token_ids"][:start]
            or left["token_loss_mask"][:start] != right["token_loss_mask"][:start]
        ):
            raise AssertionError(
                f"row {identity!r} differs before its restored closing call"
            )
        diverged.add(identity)
    if diverged and len(diverged) == len(selection["cuts"]):
        raise AssertionError(
            "every restored prefix differed from the reference, so no restored "
            "row checks the regenerated tail"
        )
    return starts, frozenset(diverged)

How we know it still checks the same things

CheckResult
The PR's 27 unit tests27/27 pass before and after. Only call sites changed (they now pass the index or call _check_cuts); no assertion and no expected message was weakened.
300 random cases, each run as-is and with each kind of breakage: a dropped token, a duplicated token, a wrong prefix hash, a missing or repeated completion line, a repeated restore line, every cut set aside, a change before the cut on a set-aside rowBefore and after give the same pass/fail and the same error message in every case, both for the cut checks alone and for the full compare run on dumped files.
ruff (repo config)Clean.

What does change. With several faults at once, a different one can be reported first, because there is now one loop instead of two. An empty dump file now raises IndexError instead of an AssertionError, but the trainer never writes one. Found along the way, in both versions: a few duplicated-token cases (1–4 in 300) pass, when the duplicated token sits where the count-back cannot see the shift. That is in today's code, not caused by C19.

So what. C19 is a correct, modest cleanup: one place to read the per-cut checks, the row index built once, and 33 fewer lines for the PR. It is not the ~100-line cut the first version of the comment claimed.

C19 — parity.py:138