File size: 9,906 Bytes
7437abd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
"""Reproduce the pretraining token stream, and prove it is the stream the model saw.

The published corpus is plain `{"text": …}` JSONL, which is the right shape for a *corpus* and the wrong
shape for a *claim*. This script turns one into the other: it encodes every row with the tokenizer in this
folder, in file order, and compares the result against the counts and the sha256 recorded in `stats.json`.
A consumer who wants "the ids the model was trained on" runs this and gets either a match or a concrete
disagreement — never a plausible-looking array.

    python tokenizer/tokenize.py --verify                      # every deterministic file in stats.json
    python tokenizer/tokenize.py --file data/pretrain/train.jsonl --verify
    python tokenizer/tokenize.py --file data/pretrain/train.jsonl --out ids.npy
    python tokenizer/tokenize.py --file data/pretrain/train.jsonl --out ids.npy --padded 512

The recipe verified here is the pretraining one, and only that one, because it is a pure function of
(tokenizer, text): `PretrainDataset.__getitem__` encodes with `add_special_tokens=False, max_length=510,
truncation=True`, then wraps the ids in BOS and EOS. The SFT loader is deliberately *not* a pure function —
it injects a system prompt for 20% of rows and strips empty think tags at load time — so this script refuses
to pretend otherwise; `RECIPE.md` says what that loader does and what the fixed part is.

Needs `tokenizers` and `numpy` only. `transformers` is not imported: the whole point is that the ids do not
depend on a library version rediscovering them.
"""
from __future__ import annotations

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

# P1 in SCHEMA.md: tokens(text) <= seq_len - 2, with seq_len 512. The loader would truncate silently; this
# refuses instead, because a silent truncation is exactly the difference between two token streams.
MAX_TOKENS = 510
HEAD = 16          # ids quoted from the start of the stream, so a hash mismatch can be localised
TAIL = 16


def load_stats(path: Path) -> dict:
    doc = json.loads(path.read_text(encoding="utf-8"))
    if doc.get("schema") != 1:
        raise SystemExit(f"{path}: unknown stats schema {doc.get('schema')!r}; refusing to guess")
    return doc


def special_ids(tokenizer_json: Path) -> dict:
    """`<|im_start|>` -> id, from the tokenizer's own added-token table."""
    doc = json.loads(tokenizer_json.read_text(encoding="utf-8"))
    return {t["content"]: t["id"] for t in doc.get("added_tokens") or []}


def load_tokenizer(tokenizer_json: Path):
    try:
        from tokenizers import Tokenizer
    except ImportError:
        raise SystemExit("needs `tokenizers` (pip install tokenizers numpy)")
    return Tokenizer.from_file(str(tokenizer_json))


def encode_row(tk, text: str, bos: int, eos: int, source: str, line_no: int):
    ids = tk.encode(text, add_special_tokens=False).ids
    if len(ids) > MAX_TOKENS:
        raise SystemExit(
            f"{source}:{line_no}: {len(ids)} tokens > {MAX_TOKENS}. The trainer would truncate this row "
            "silently, so the ids would not be the ids in stats.json. This is a P1 violation in the "
            "artifact, not a problem with the tokenizer."
        )
    return [bos, *ids, eos]


def walk(tk, path: Path, bos: int, eos: int, limit: int | None = None):
    """One pass over a jsonl: the id stream's hash, its length, and the sizes a reader may want."""
    import numpy as np

    digest = hashlib.sha256()
    rows = n_ids = chars = longest = 0
    head: list[int] = []
    tail: list[int] = []
    lengths: list[int] = []
    with open(path, encoding="utf-8") as f:
        for line_no, line in enumerate(f, 1):
            if not line.strip():
                continue
            text = json.loads(line)["text"]
            ids = encode_row(tk, text, bos, eos, str(path), line_no)
            digest.update(np.asarray(ids, dtype="<u2").tobytes())
            rows += 1
            n_ids += len(ids)
            chars += len(text)
            lengths.append(len(ids) - 2)
            longest = max(longest, len(ids) - 2)
            if len(head) < HEAD:
                head.extend(ids[: HEAD - len(head)])
            tail = (tail + ids)[-TAIL:]
            if limit and rows >= limit:
                break
    lengths.sort()
    return {
        "rows": rows,
        "tokens": sum(lengths),
        "tokens_with_specials": n_ids,
        "chars": chars,
        "max_tokens_in_any_row": longest,
        "median_tokens_per_row": lengths[len(lengths) // 2] if lengths else 0,
        "ids_count": n_ids,
        "ids_sha256": digest.hexdigest(),
        "first_ids": head,
        "last_ids": tail,
    }


def write_ids(tk, path: Path, bos: int, eos: int, out: Path, padded: int | None, pad_id: int) -> None:
    import numpy as np

    if padded:
        rows = sum(1 for line in open(path, encoding="utf-8") if line.strip())
        matrix = np.full((rows, padded), pad_id, dtype="<u2")
        with open(path, encoding="utf-8") as f:
            i = 0
            for line_no, line in enumerate(f, 1):
                if not line.strip():
                    continue
                ids = encode_row(tk, json.loads(line)["text"], bos, eos, str(path), line_no)
                if len(ids) > padded:
                    raise SystemExit(f"{path}:{line_no}: {len(ids)} ids do not fit a {padded} window")
                matrix[i, : len(ids)] = ids
                i += 1
        np.save(out, matrix)
        print(f"wrote {out}  shape={matrix.shape} dtype={matrix.dtype}  pad={pad_id}  "
              f"(labels: same ids with {pad_id} -> -100)")
        return

    chunks, offsets = [], [0]
    with open(path, encoding="utf-8") as f:
        for line_no, line in enumerate(f, 1):
            if not line.strip():
                continue
            ids = encode_row(tk, json.loads(line)["text"], bos, eos, str(path), line_no)
            chunks.append(np.asarray(ids, dtype="<u2"))
            offsets.append(offsets[-1] + len(ids))
    flat = np.concatenate(chunks) if chunks else np.zeros(0, dtype="<u2")
    np.save(out, flat)
    off = Path(f"{out}.offsets.npy")
    np.save(off, np.asarray(offsets, dtype="<i8"))
    print(f"wrote {out}  ids={flat.size} dtype={flat.dtype}  and {off.name} ({len(offsets) - 1} rows)")


def main(argv=None) -> int:
    here = Path(__file__).resolve().parent
    ap = argparse.ArgumentParser(prog="tokenize", description=__doc__.splitlines()[0])
    ap.add_argument("--stats", default=str(here / "stats.json"), help="the bundle's stats.json")
    ap.add_argument("--data-root", default=".", help="root of the dataset repo (default: .)")
    ap.add_argument("--file", action="append", default=None,
                    help="a jsonl relative to --data-root (repeatable; default: every verified file)")
    ap.add_argument("--verify", action="store_true", help="compare against stats.json")
    ap.add_argument("--out", default=None, help="write the ids here (.npy)")
    ap.add_argument("--padded", type=int, default=None, metavar="SEQ",
                    help="write a (rows, SEQ) matrix instead of a ragged stream")
    ap.add_argument("--limit", type=int, default=None, help="stop after N rows (smoke test)")
    args = ap.parse_args(argv)

    stats = load_stats(Path(args.stats))
    tok_path = here / "tokenizer.json"
    if not tok_path.exists():
        raise SystemExit(f"{tok_path} is missing — run this from the tokenizer/ folder of the dataset repo")
    tk = load_tokenizer(tok_path)
    specials = special_ids(tok_path)
    try:
        bos = specials[stats["tokenizer"]["special_tokens"]["bos"]["token"]]
        eos = specials[stats["tokenizer"]["special_tokens"]["eos"]["token"]]
        pad = specials[stats["tokenizer"]["special_tokens"]["pad"]["token"]]
    except KeyError as exc:
        raise SystemExit(f"stats.json names a special token the tokenizer does not have: {exc}")

    root = Path(args.data_root)
    files = args.file or [p for p, d in stats["files"].items() if d.get("deterministic")]
    if not files:
        raise SystemExit("stats.json names no deterministic file to verify")

    failed = 0
    print(f"{'file':40} {'rows':>7} {'tokens':>12}  verdict")
    for rel in files:
        path = root / rel
        if not path.exists():
            print(f"{rel:40} {'':>7} {'':>12}  MISSING")
            failed += 1
            continue
        got = walk(tk, path, bos, eos, args.limit)
        want = stats["files"].get(rel, {})
        if args.out and len(files) == 1:
            write_ids(tk, path, bos, eos, Path(args.out), args.padded, pad)
        if not args.verify:
            print(f"{rel:40} {got['rows']:>7,} {got['tokens']:>12,}  (not compared)")
            continue
        problems = []
        if got["rows"] != want.get("rows"):
            problems.append(f"rows {got['rows']} != {want.get('rows')}")
        if got["ids_count"] != want.get("ids_count"):
            problems.append(f"ids {got['ids_count']} != {want.get('ids_count')}")
        if got["ids_sha256"] != want.get("ids_sha256"):
            problems.append(f"sha256 {got['ids_sha256'][:12]}… != {want.get('ids_sha256', '')[:12]}…")
        if problems:
            failed += 1
            print(f"{rel:40} {got['rows']:>7,} {got['tokens']:>12,}  MISMATCH — {'; '.join(problems)}")
        else:
            print(f"{rel:40} {got['rows']:>7,} {got['tokens']:>12,}  OK  {got['ids_sha256'][:16]}…")

    if failed:
        print(f"\n{failed} file(s) disagree with {args.stats}. Do not train on this token stream and call it "
              "a reproduction; the tokenizer version, the recipe, or the row order differs.")
        return 1
    if args.verify:
        print(f"\nall verified against {args.stats} — this is the ids the model was trained on.")
    return 0


if __name__ == "__main__":
    sys.exit(main())