File size: 7,434 Bytes
f36cc9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
"""Count reconsideration and verification markers in every trace of the marker arms, with token positions.

    uv run --no-project --with pandas --with pyarrow --with zstandard --with tokenizers python code/markers.py \
        --qwen-tokenizer path/to/Qwen3.5-9B/tokenizer.json \
        --r1-tokenizer path/to/DeepSeek-R1-Distill-Qwen-1.5B/tokenizer.json

The tokenizer files come from the public model repositories (Qwen/Qwen3.5-9B and
deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B); their SHA-256 digests are recorded in markers/marker_definitions.json.
Marker patterns, decoding and the stabilization rule are the frozen definitions of the registered replication
(markers/registration/). Writes markers/marker_counts.parquet and checks the paper's marker table.
"""

from __future__ import annotations

import argparse
import bisect
import hashlib
import json
import re
import sys
from pathlib import Path

import pandas as pd
from tokenizers import Tokenizer

sys.path.insert(0, str(Path(__file__).resolve().parent))
from common import ARMS, RECORDS, ROOT, iter_jsonl  # noqa: E402

RECONSIDER = re.compile(r"\b(Wait|wait|Hmm|Hold on|Alternatively|On second thought|reconsider|Let me re-?think|Let me re-?read)\b")
VERIFY = re.compile(
    r"(double[- ]check|Let me (?:verify|check|confirm|re-?(?:check|examine|verify|calculate|compute|evaluate|do))|\bre-?check|sanity check|\bverify\b)",
    re.I,
)
SETS = {  # experiment: (arms, tokenizer, readout set used for the stabilization point)
    "main256_32k": (["parent", "transplant_all32", "reverse_all32", "donor", "transplant_late16"], "qwen", "main256_first64"),
    "replication512_32k": (["parent", "transplant_all32"], "qwen", "readout256"),
    "shorterbetter_math128": (["parent", "transplant_all", "donor"], "r1", None),
}


class Decoder:
    def __init__(self, path: str):
        self.tok = Tokenizer.from_file(path)
        self.cache: dict[int, str] = {}

    def markers(self, ids):
        """Decode token by token without skipping special tokens; map each match to its token position."""
        pieces = []
        for i in ids:
            s = self.cache.get(i)
            if s is None:
                s = self.cache[i] = self.tok.decode([i], skip_special_tokens=False)
            pieces.append(s)
        cum, c = [], 0
        for p in pieces:
            c += len(p)
            cum.append(c)
        text = "".join(pieces)
        pos = lambda m: bisect.bisect_right(cum, m.start())  # noqa: E731
        return [pos(m) for m in RECONSIDER.finditer(text)], [pos(m) for m in VERIFY.finditer(text)]


def fixed_points(run: str, stem: str):
    """Stabilization point of each trace with forced readouts: the earliest 2,048-token grid point after which every
    readout's answer key equals the trace's final answer key; no matching terminal run gives the full length (None)."""
    sd = RECORDS / run / f"readout_subset_{stem}" / "scored"
    final = {r["id"]: r.get("answer_key") for r in iter_jsonl(sd / "traces.scored.jsonl")}
    reads: dict[str, list] = {}
    for r in iter_jsonl(sd / "readouts.scored.jsonl"):
        reads.setdefault(r["id"], []).append((int(r["t"]), r.get("answer_key")))
    fp = {}
    for i, rs in reads.items():
        rs.sort()
        k = len(rs)
        while k > 0 and final.get(i) is not None and rs[k - 1][1] == final[i]:
            k -= 1
        fp[i] = rs[k][0] if k < len(rs) else None
    for i in final:
        fp.setdefault(i, None)
    return fp


def sha(path):
    return hashlib.sha256(Path(path).read_bytes()).hexdigest()


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--qwen-tokenizer", required=True)
    ap.add_argument("--r1-tokenizer", required=True)
    a = ap.parse_args()
    dec = {"qwen": Decoder(a.qwen_tokenizer), "r1": Decoder(a.r1_tokenizer)}
    rows = []
    for experiment, (arms, tk, readout_set) in SETS.items():
        for arm in arms:
            run, stem, _ = ARMS[experiment][arm]
            fp = fixed_points(run, stem) if readout_set else {}
            for r in iter_jsonl(RECORDS / run / f"{stem}.jsonl.zst"):
                ids = r.get("thinking_ids") or []
                rc, vf = dec[tk].markers(ids)
                L = len(ids)
                row = {"experiment": experiment, "arm": arm, "question_id": r["id"], "stratum": r["area"],
                       "thinking_tokens": L, "reconsideration": len(rc), "verification": len(vf),
                       "reconsideration_first2048": sum(p < 2048 for p in rc), "verification_first2048": sum(p < 2048 for p in vf),
                       "readout_set": None, "stabilization_point": None,
                       "reconsideration_after_stabilization": None, "verification_after_stabilization": None,
                       "reconsideration_positions": rc, "verification_positions": vf}
                if r["id"] in fp:
                    s = min(fp[r["id"]] if fp[r["id"]] is not None else L, L)
                    row.update(readout_set=readout_set, stabilization_point=s,
                               reconsideration_after_stabilization=sum(p >= s for p in rc),
                               verification_after_stabilization=sum(p >= s for p in vf))
                rows.append(row)
            print(experiment, arm, "done", flush=True)
    df = pd.DataFrame(rows)
    for col in ("stabilization_point", "reconsideration_after_stabilization", "verification_after_stabilization"):
        df[col] = df[col].astype("Int64")
    out = ROOT / "markers/marker_counts.parquet"
    df.to_parquet(out, index=False)
    print(out.relative_to(ROOT), len(df), "rows")
    check(df)
    print("tokenizer sha256: qwen", sha(a.qwen_tokenizer), "r1", sha(a.r1_tokenizer))


def check(df):
    """The paper's marker table (256-question panel), the registered replication and the ShorterBetter rates."""
    g = df[df.experiment == "main256_32k"].groupby("arm")
    rate = lambda d, k: 1000 * d[k].sum() / d.thinking_tokens.sum()  # noqa: E731
    # Per-trace means as printed; rates per 1,000 tokens at the three decimals of stats/audit/recheck_markers.json
    # (the paper prints them at two decimals after rounding these three-decimal values half away from zero).
    want = {"parent": (34.9, 2.298, 21.8, 7.5, 0.495), "transplant_all32": (19.4, 1.741, 9.3, 5.4, 0.482),
            "reverse_all32": (30.7, 2.189, 17.1, 7.1, 0.504), "donor": (16.8, 1.640, 7.9, 4.8, 0.470)}
    for arm, w in want.items():
        d = g.get_group(arm)
        got = (round(d.reconsideration.mean(), 1), round(rate(d, "reconsideration"), 3),
               round(d.reconsideration_after_stabilization.dropna().mean(), 1), round(d.verification.mean(), 1),
               round(rate(d, "verification"), 3))
        assert got == w, (arm, got, w)
    r = df[df.experiment == "replication512_32k"].groupby("arm")
    p, t = r.get_group("parent"), r.get_group("transplant_all32")
    assert round(p.reconsideration.mean(), 3) == 37.287 and round(t.reconsideration.mean(), 3) == 21.039
    assert round(rate(t, "reconsideration") / rate(p, "reconsideration"), 3) == 0.764
    assert round(rate(t, "verification") - rate(p, "verification"), 4) == 0.0060
    s = df[df.experiment == "shorterbetter_math128"].groupby("arm")
    assert [round(rate(s.get_group(a), "verification"), 3) for a in ("parent", "transplant_all", "donor")] == [0.375, 0.217, 0.170]
    print("marker checks passed")


if __name__ == "__main__":
    main()