magic-cap1b-data / generation /tokenizer.py
leejason2025's picture
Upload generation/tokenizer.py with huggingface_hub
0a663a9 verified
Raw History Blame Contribute Delete
9.44 kB
from __future__ import annotations
import re
# ---------------------------------------------------------------------------
# Vocabulary
# ---------------------------------------------------------------------------
# Base: 256 raw bytes. Token id is identical to the byte value, so
# encode/decode of arbitrary text is trivial and lossless.
BYTE_TOKENS = [f"<BYTE_{i}>" for i in range(256)]
N_BYTES = 256
# Reserved atomic tokens, ids 256+
DIGIT_TOKENS = [f"<DIGIT_{d}>" for d in range(10)]
OP_TOKENS = ["<ADD>", "<SUB>", "<MULTIPLY>"]
MARKER_TOKENS = ["<START>", "<STEP>", "<FINAL>", "<PIPE>", "<COLON>"]
STRUCTURAL_TOKENS = ["<BOUNDARY>", "<PAD>"]
RESERVED_TOKENS = DIGIT_TOKENS + OP_TOKENS + MARKER_TOKENS + STRUCTURAL_TOKENS
ALL_TOKENS = BYTE_TOKENS + RESERVED_TOKENS
TOKEN_TO_ID: dict[str, int] = {t: i for i, t in enumerate(ALL_TOKENS)}
ID_TO_TOKEN: dict[int, str] = {i: t for t, i in TOKEN_TO_ID.items()}
VOCAB_SIZE = len(ALL_TOKENS) # 276
DIGIT_BASE = TOKEN_TO_ID["<DIGIT_0>"] # 256
BOUNDARY_ID = TOKEN_TO_ID["<BOUNDARY>"]
PAD_ID = TOKEN_TO_ID["<PAD>"]
# Reserved-token id range, used by the invariant checks.
RESERVED_ID_MIN = N_BYTES
RESERVED_ID_MAX = VOCAB_SIZE - 1
# Canonical operation name -> reserved token. Aliases are normalised so the
# tokenizer does not care which spelling generator.py emits.
_OP_ALIASES = {
"ADD": "<ADD>",
"SUB": "<SUB>",
"SUBTRACT": "<SUB>",
"MUL": "<MULTIPLY>",
"MULT": "<MULTIPLY>",
"MULTIPLY": "<MULTIPLY>",
}
# Surface strings used when decoding reserved tokens back to text.
_RESERVED_SURFACE = {
"<ADD>": "ADD",
"<SUB>": "SUB",
"<MULTIPLY>": "MULTIPLY",
"<START>": "START",
"<STEP>": "STEP",
"<FINAL>": "FINAL",
"<PIPE>": "|",
"<COLON>": ":",
"<BOUNDARY>": "\n",
"<PAD>": "",
}
# ---------------------------------------------------------------------------
# Arithmetic-safety validation (B.4 exclusions)
# ---------------------------------------------------------------------------
_BANNED_PATTERNS = [
(re.compile(r"(?<=\d),(?=\d)"), "comma inside a number"),
(re.compile(r"(?<=\d)\.(?=\d)"), "decimal point inside a number"),
]
# A minus is UNARY (banned) only when nothing operand-like precedes it. After a
# variable, a digit, or a closing paren it is BINARY subtraction, which the code
# family legitimately emits as `x = x - 9`.
_MINUS_BEFORE_DIGIT = re.compile(r"-\s*\d")
_OPERAND_END = re.compile(r"[\w)\]]")
def assert_arithmetic_safe(text: str, where: str = "") -> None:
"""Raise if text violates a B.4 exclusion. Cheap, run on every record."""
for pattern, reason in _BANNED_PATTERNS:
if pattern.search(text):
raise ValueError(f"B.4 violation ({reason}) in {where or 'text'}: {text!r}")
for m in _MINUS_BEFORE_DIGIT.finditer(text):
prefix = text[:m.start()].rstrip()
if prefix and _OPERAND_END.match(prefix[-1]):
continue # binary subtraction
raise ValueError(
f"B.4 violation (unary negative sign before a number) in "
f"{where or 'text'}: {text!r}"
)
# ---------------------------------------------------------------------------
# Core encoders
# ---------------------------------------------------------------------------
def encode_number(n: int | str) -> list[int]:
"""
Canonical digit-by-digit serialization. `47` -> [<DIGIT_4>, <DIGIT_7>].
Reads the value it is given; performs no arithmetic.
"""
s = str(n)
if not s.isdigit():
raise ValueError(f"non-canonical number {n!r}: must be a nonnegative integer")
return [DIGIT_BASE + int(ch) for ch in s]
def encode_text(text: str) -> list[int]:
"""
General byte-level path with the digit override applied.
Every byte of the UTF-8 encoding becomes one token, except ASCII digits,
which become atomic <DIGIT_n> tokens. Byte ids 48-57 are therefore never
emitted, which is what `assert_digits_atomic` checks.
Emits no reserved marker or operator tokens. Handles arbitrary text,
including FineWeb-Edu background.
"""
out: list[int] = []
for b in text.encode("utf-8"):
if 48 <= b <= 57: # ASCII '0'-'9'
out.append(DIGIT_BASE + (b - 48))
else:
out.append(b)
return out
# ---------------------------------------------------------------------------
# Canonical specification path (B.2 format, atomic markers)
# START: 17 | STEP_1: ADD 6 | STEP_2: MULTIPLY 2 | FINAL: 46
# ---------------------------------------------------------------------------
_SEG_START = re.compile(r"^START\s*:\s*(\d+)$")
_SEG_STEP = re.compile(r"^STEP_(\d+)\s*:\s*([A-Za-z_]+)\s+(\d+)$")
_SEG_FINAL = re.compile(r"^FINAL\s*:\s*(\d*)$")
def parse_canonical(text: str) -> dict:
"""
Parse a canonical spec string into its stored parts. Pure string reading,
no arithmetic, so this respects the renderer-never-computes contract.
Returns {"start": str, "steps": [(index, OP, operand)], "final": str|None}
"""
start = None
steps: list[tuple[str, str, str]] = []
final = None
for raw in text.replace("\n", " ").split("|"):
seg = raw.strip()
if not seg:
continue
m = _SEG_START.match(seg)
if m:
start = m.group(1)
continue
m = _SEG_STEP.match(seg)
if m:
op = m.group(2).upper()
if op not in _OP_ALIASES:
raise ValueError(f"unknown operation {op!r} in canonical spec: {text!r}")
steps.append((m.group(1), op, m.group(3)))
continue
m = _SEG_FINAL.match(seg)
if m:
final = m.group(1) or None
continue
raise ValueError(f"unparseable canonical segment {seg!r} in: {text!r}")
if start is None:
raise ValueError(f"canonical spec has no START: {text!r}")
return {"start": start, "steps": steps, "final": final}
def encode_canonical(text: str) -> list[int]:
"""Encode a canonical spec string with atomic markers, operators, digits."""
return encode_canonical_parts(parse_canonical(text))
def encode_canonical_parts(parts: dict) -> list[int]:
ids: list[int] = [TOKEN_TO_ID["<START>"], TOKEN_TO_ID["<COLON>"]]
ids += encode_number(parts["start"])
for idx, op, operand in parts["steps"]:
ids.append(TOKEN_TO_ID["<PIPE>"])
ids.append(TOKEN_TO_ID["<STEP>"])
ids += encode_number(idx)
ids.append(TOKEN_TO_ID["<COLON>"])
ids.append(TOKEN_TO_ID[_OP_ALIASES[op]])
ids += encode_number(operand)
ids.append(TOKEN_TO_ID["<PIPE>"])
ids.append(TOKEN_TO_ID["<FINAL>"])
ids.append(TOKEN_TO_ID["<COLON>"])
if parts["final"] is not None:
ids += encode_number(parts["final"])
return ids
# ---------------------------------------------------------------------------
# Record routing
# ---------------------------------------------------------------------------
def encode_record(record: dict) -> list[int]:
"""
Encode one generator.py record.
Routing, and the reason for it: the `direct` family's surface text IS the
canonical specification, and B.4 wants atomic operator and marker tokens
there. Every other family has its own distinct surface text (verbal prose,
code trace, decomposed primitives) and goes through the byte-level path
on its OWN text.
Routing every family through the canonical encoder would collapse all
four families to near-identical token streams and destroy the family
contrast the whole experiment measures. `test_families_tokenize_differently`
is the regression guard for that.
"""
family = record["family"]
text = record["text"]
assert_arithmetic_safe(text, where=f"{family}/{record.get('program_id')}")
if family == "direct":
return encode_canonical(text)
return encode_text(text)
# ---------------------------------------------------------------------------
# Decoding and invariants
# ---------------------------------------------------------------------------
def decode(ids: list[int]) -> str:
"""Inverse of encode_text; reserved tokens decode to their surface form."""
out: list[str] = []
buf = bytearray()
def flush() -> None:
if buf:
out.append(buf.decode("utf-8", errors="replace"))
buf.clear()
for i in ids:
if i < N_BYTES:
buf.append(i)
continue
flush()
tok = ID_TO_TOKEN[i]
if tok.startswith("<DIGIT_"):
out.append(tok[len("<DIGIT_"):-1])
else:
out.append(_RESERVED_SURFACE[tok])
flush()
return "".join(out)
def assert_digits_atomic(ids: list[int]) -> None:
"""
Real check, not a tautology: a digit character may only ever appear as a
<DIGIT_n> token, so raw byte ids 48-57 must never occur in output.
"""
bad = [i for i in ids if 48 <= i <= 57]
if bad:
raise AssertionError(f"raw digit byte ids leaked into output: {sorted(set(bad))}")
def emits_reserved_markers(ids: list[int]) -> bool:
"""True if the sequence contains any operator or task-marker token.
Used by the contamination check: only synthetic data can produce these."""
marker_ids = {TOKEN_TO_ID[t] for t in OP_TOKENS + MARKER_TOKENS}
return any(i in marker_ids for i in ids)