The neural notebook
← All chapters

IV-39 / Part IX · Tokenization

Byte-Pair Encoding: A Full Merge Trace

Learn byte-pair merges from a tiny corpus, count every candidate and tie, apply ranked rules to new text, and strictly decode the actual token expansions.

Review the ideas this chapter uses

Suppose a message repeats the same two bytes several times. We could give that pair a shared ID, then replace each occurrence with its shorter name. If the new names themselves repeat together, we could name that pair too. Byte-pair encoding (BPE) turns this idea into an explicit training procedure and an ordered list of rules that another text can reuse.

Learning objective: Perform deterministic byte-level BPE training and encoding step by step.

Compute it yourself

Byte-Pair Encoding: A Full Merge Trace

Type text to recompute the complete encoding and its actual reverse decoding. Spaces, combining marks, control characters and a leading BOM are data. The codec does not trim or normalize the text it receives; the text area converts carriage returns and CRLF to line feeds before an edit reaches the lab. This tiny lab accepts at most 24 UTF-8 bytes per text field and reports longer input explicitly.

corpusBytes4
byteCount6
actualMerges2
tokenCount2

Empty text is valid. When edited, the text area converts carriage returns and CRLF to line feeds before the lab reads the value. The codec preserves the text it receives; longer input is reported instead of cut off. UTF-16 storage units, Unicode scalars and UTF-8 bytes count different things. The escaped input below reveals spaces and line breaks; byte tables retain every byte.

Empty text is valid. When edited, the text area converts carriage returns and CRLF to line feeds before the lab reads the value. The codec preserves the text it receives; longer input is reported instead of cut off. UTF-16 storage units, Unicode scalars and UTF-8 bytes count different things. The escaped input below reveals spaces and line breaks; byte tables retain every byte.

Exact starting inputs for this saved calculation

corpusBytes 4. byteCount 6. actualMerges 2. tokenCount 2. Declare learned byte-pair encoding and both exact inputs. Validate every raw field before corpus then target Unicode semantics. Train on the corpus byte stream including spaces; encode the separate target using learned ranks. No normalization, word splitting, inferred EOS or pretrained vocabulary is used.

Declare learned byte-pair encoding and both exact inputs

byte IDs=0..255; learned ID=256+rank; EOS=512; each text field<=24 UTF-8 bytes

Validate every raw field before corpus then target Unicode semantics. Train on the corpus byte stream including spaces; encode the separate target using learned ranks. No normalization, word splitting, inferred EOS or pretrained vocabulary is used.

Saved inputs

requestedMerges
2
eos
0

Saved outputs

corpusUnits
4
corpusScalars
4
utf16Units
6
scalarCount
6
byteBound
24
mergeBase
256
mergeBound
4
EOS
512

Learn a byte vocabulary, then reuse its ranked rules

The training corpus is the text used to choose rules; the separate input text is what those rules encode. A token is a vocabulary item named by an integer ID. A byte is an integer0..255; UTF-8 stores one Unicode scalar in one to four bytes. A scalar is a code point, while a visible character can contain several scalars. This lab starts from bytes, so one visible character can already provide a pair to merge.

Exact corpus: "abab". Exact target: "ababab". JSON quotes show boundaries and escapes reveal line breaks or control characters. The streams preserve case, whitespace, combining marks and a leading BOM.

Corpus bytes: [97,98,97,98]. Target bytes: [97,98,97,98,97,98]. Initial training IDs: [97,98,97,98]. Initial target IDs: [97,98,97,98,97,98]. Initially each byte ID equals its byte value; later token IDs can cover several bytes.

Every corpus scalar encoding, payload and UTF-16 position (4 saved operations)

corpus_scalar_0: Encode scalar 0: U+0061

supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits

A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs.

corpus_scalar_1: Encode scalar 1: U+0062

supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits

A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs.

corpus_scalar_2: Encode scalar 2: U+0061

supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits

A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs.

corpus_scalar_3: Encode scalar 3: U+0062

supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits

A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs.

Every target scalar encoding, payload and UTF-16 position (6 saved operations)

source_scalar_0: Encode scalar 0: U+0061

supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits

A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs.

source_scalar_1: Encode scalar 1: U+0062

supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits

A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs.

source_scalar_2: Encode scalar 2: U+0061

supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits

A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs.

source_scalar_3: Encode scalar 3: U+0062

supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits

A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs.

source_scalar_4: Encode scalar 4: U+0061

supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits

A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs.

source_scalar_5: Encode scalar 5: U+0062

supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits

A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs.

UTF-16 offsets count storage units, not bytes or perceived characters. UTF-8 continuation bytes start with binary10 and contain six payload bits. The saved scalar encodings show each payload and actual byte; reverse decoding removes prefixes and combines six-bit payloads by multiplying the running integer by 64 and adding the next payload. A leading BOM and noncharacters are valid data; unpaired surrogates or malformed UTF-8 produce an unavailable result instead of replacement guesses.

Every real training round and final pair count

Requested merge budget completed. Requested budget: 2; actual learned rules: 2. Recount the current list from scratch each round. Count every adjacent occurrence, including overlaps. Select greatest final frequency; equal counts use the smaller numeric left ID, then smaller numeric right ID. Frequency1 is enough to merge.

Round 0: ID 256 for pair (97,98), frequency 2

Numeric sorted candidate indexLeft IDRight IDOverlapping frequency
097982
198971
Round 0: every overlapping count increment (3 saved operations)

train_count_0_0: Count round 0 pair at current-token position 0

frequency(left,right)=previous frequency+1; next counting position=position+1

Count every adjacent occurrence, including overlaps. The table starts empty each round. In aaaa, aa occurs at positions 0, 1 and 2 even though replacement will consume only two disjoint pairs.

train_count_0_1: Count round 0 pair at current-token position 1

frequency(left,right)=previous frequency+1; next counting position=position+1

Count every adjacent occurrence, including overlaps. The table starts empty each round. In aaaa, aa occurs at positions 0, 1 and 2 even though replacement will consume only two disjoint pairs.

train_count_0_2: Count round 0 pair at current-token position 2

frequency(left,right)=previous frequency+1; next counting position=position+1

Count every adjacent occurrence, including overlaps. The table starts empty each round. In aaaa, aa occurs at positions 0, 1 and 2 even though replacement will consume only two disjoint pairs.

Round 0: every final-frequency comparison and actual selection (3 saved operations)

train_compare_0_0: Compare round 0 candidate 0

take=first candidate or greater frequency or (equal frequency and numerically smaller (left,right))

Compare integer IDs, left first and then right, not string keys or encounter order. Candidate columns use numeric tuple order. The first comparison uses best IDs -1 and frequency 0 as an explicit empty-best sentinel.

train_compare_0_1: Compare round 0 candidate 1

take=first candidate or greater frequency or (equal frequency and numerically smaller (left,right))

Compare integer IDs, left first and then right, not string keys or encounter order. Candidate columns use numeric tuple order. The first comparison uses best IDs -1 and frequency 0 as an explicit empty-best sentinel.

train_select_0: Select round 0 winning pair

newID=256+rank; select greatest frequency, then smallest numeric pair

Frequency 1 is eligible. Requested merges are a budget; actual merges stop early only when no adjacent pair remains.

Round 0: concatenate both saved byte operands (1 saved operations)

train_rule_0: Build rule 0 byte expansion

new bytes=left bytes followed by right bytes

Both operands are bytes or earlier merge IDs. Their complete concatenation defines the new ID and cannot create a cycle. A piece may end inside a UTF-8 scalar, so its label uses ID and exact JSON bytes.

Training replacement: rank 0

Complete current-token list before: [97,98,97,98]. After: [256,256].

Position in this pass inputCurrent IDNext ID (−1 means absent)Matched (1/0)Emitted IDConsumed tokensNext positionEmitted prefix length
097981256221
297981256242

Round 1: ID 257 for pair (256,256), frequency 1

Numeric sorted candidate indexLeft IDRight IDOverlapping frequency
02562561
Round 1: every overlapping count increment (1 saved operations)

train_count_1_0: Count round 1 pair at current-token position 0

frequency(left,right)=previous frequency+1; next counting position=position+1

Count every adjacent occurrence, including overlaps. The table starts empty each round. In aaaa, aa occurs at positions 0, 1 and 2 even though replacement will consume only two disjoint pairs.

Round 1: every final-frequency comparison and actual selection (2 saved operations)

train_compare_1_0: Compare round 1 candidate 0

take=first candidate or greater frequency or (equal frequency and numerically smaller (left,right))

Compare integer IDs, left first and then right, not string keys or encounter order. Candidate columns use numeric tuple order. The first comparison uses best IDs -1 and frequency 0 as an explicit empty-best sentinel.

train_select_1: Select round 1 winning pair

newID=256+rank; select greatest frequency, then smallest numeric pair

Frequency 1 is eligible. Requested merges are a budget; actual merges stop early only when no adjacent pair remains.

Round 1: concatenate both saved byte operands (1 saved operations)

train_rule_1: Build rule 1 byte expansion

new bytes=left bytes followed by right bytes

Both operands are bytes or earlier merge IDs. Their complete concatenation defines the new ID and cannot create a cycle. A piece may end inside a UTF-8 scalar, so its label uses ID and exact JSON bytes.

Training replacement: rank 1

Complete current-token list before: [256,256]. After: [257].

Position in this pass inputCurrent IDNext ID (−1 means absent)Matched (1/0)Emitted IDConsumed tokensNext positionEmitted prefix length
02562561257221
Actual early stop, when a requested round has no pair (0 saved operations)

No operation is needed for this stage; no padding or fabricated decision is inserted.

Counting moves by one current token, so aaaa has three aa occurrences. Replacement moves by two after a match, so only positions0 and2 are consumed as disjoint pairs, giving[256,256]. Positions are zero-based indices in the list at the start of that pass, not byte offsets: an ID can already cover several original bytes. The nextID sentinel−1 means no next token; it is never emitted, padded or decoded. Comparison best IDs−1 similarly mean no prior candidate.

The complete learned rule table

RankNew IDLeft IDRight IDSaved piece labelActual concatenated bytes
02569798ID 256, bytes [97,98][97,98]
1257256256ID 257, bytes [97,98,97,98][97,98,97,98]

Rank is the order in which a rule was learned, starting at0. Its new ID is256+rank. Concatenating its left and right byte expansions defines its inverse. Operands are bytes or earlier rules, so the dependency chain cannot cycle. A byte piece can end inside a multibyte scalar; its honest label is its ID plus JSON bytes, not a guessed character. Only a complete concatenated byte stream is strictly decoded.

Possible vocabulary items: 259 =256 byte items +2 learned items +1 reserved EOS. This counts possible items, not highestID+1: EOS has name512 and leaves unused numeric gaps. Public token names are not automatically dense embedding row indices. A later language model must declare its map from these IDs to compact rows; this lab allocates no embedding table. Current target tokenCount=2 is a separate quantity, including EOS only when enabled.

Apply learned ranks to the separate target

Start from the target byte IDs. Apply rank0 everywhere with disjoint left-to-right replacements, then rank1, and so on. Even a rank with no matches performs the real saved copies. Target pair frequency and longest dictionary prefix do not choose the next piece.

Target rank application: rank 0

Complete current-token list before: [97,98,97,98,97,98]. After: [256,256,256].

Position in this pass inputCurrent IDNext ID (−1 means absent)Matched (1/0)Emitted IDConsumed tokensNext positionEmitted prefix length
097981256221
297981256242
497981256263

Target rank application: rank 1

Complete current-token list before: [256,256,256]. After: [257,256].

Position in this pass inputCurrent IDNext ID (−1 means absent)Matched (1/0)Emitted IDConsumed tokensNext positionEmitted prefix length
02562561257221
2256-10256132
Append target EOS only after all ranked passes (0 saved operations)

No operation is needed for this stage; no padding or fabricated decision is inserted.

Why one ascending pass per rank works here: a later rule emits a new higher ID, so it cannot manufacture an earlier rule’s lower-ID operand. Replacing two tokens with one also leaves a new token between untouched neighbors; it does not delete the entire gap and join them. Consequently a later pass cannot create a newly eligible earlier-rank pair. This argument uses this lab’s declared byte-stream rules.

Training corpus: real IDs, expansions and strict reconstruction

Actual reconstructed text: "abab". Actual expanded byte stream: [97,98,97,98].

Token indexActual IDSaved ID and JSON-byte labelExact byte expansion
0257ID 257, bytes [97,98,97,98][97,98,97,98]
Every actual corpus ID expansion (1 saved operations)

corpus_expand_0: corpus: expand ID at token 0

ID → validated byte expansion

Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used.

Every strict corpus byte-to-scalar reconstruction (4 saved operations)

corpus_decode_0: Decode UTF-8 scalar 0

accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar

Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved.

corpus_decode_1: Decode UTF-8 scalar 1

accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar

Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved.

corpus_decode_2: Decode UTF-8 scalar 2

accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar

Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved.

corpus_decode_3: Decode UTF-8 scalar 3

accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar

Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved.

Target text: real IDs, expansions and strict reconstruction

Actual reconstructed text: "ababab". Actual expanded byte stream: [97,98,97,98,97,98].

Token indexActual IDSaved ID and JSON-byte labelExact byte expansion
0257ID 257, bytes [97,98,97,98][97,98,97,98]
1256ID 256, bytes [97,98][97,98]
Every actual target ID expansion and explicit EOS removal (2 saved operations)

target_expand_0: target: expand ID at token 0

ID → validated byte expansion

Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used.

target_expand_1: target: expand ID at token 1

ID → validated byte expansion

Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used.

Every strict target byte-to-scalar reconstruction (6 saved operations)

target_decode_0: Decode UTF-8 scalar 0

accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar

Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved.

target_decode_1: Decode UTF-8 scalar 1

accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar

Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved.

target_decode_2: Decode UTF-8 scalar 2

accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar

Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved.

target_decode_3: Decode UTF-8 scalar 3

accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar

Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved.

target_decode_4: Decode UTF-8 scalar 4

accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar

Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved.

target_decode_5: Decode UTF-8 scalar 5

accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar

Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved.

Compare both real reconstructions and count final IDs (1 saved operations)

roundtrip: Compare both actual strict reconstructions with the original strings

corpusEqual=(corpusDecoded===corpus); equal=(targetDecoded===text)

Expand real corpus and target IDs separately, concatenate real bytes, strictly reconstruct Unicode scalars, and only then compare strings. Empty content reconstructs the empty string; optional target EOS emits no bytes.

Both inverse computations expand real IDs to bytes, strictly rebuild scalars, and only then compare with the starting strings. They never copy the input into the decoded field. Empty corpus is valid and learns no rules; empty target has[] content IDs, or[512] with EOS. EOS emits no bytes. U+0000 is different: it is a real scalar and byte0. Literal <eos> is ordinary text.

Two traps to try: bbaa gives three tied pairs, yet aa=(97,97), encountered last, wins numerically over ba/bb. For corpus bc bc ab with three merges, round2 picks(97,98) over(257,97)/(257,257) because97<257 numerically. Target abc still becomes[97,256]: rank0 already joined bc, so the later ab rule cannot apply. Longest-prefix lookup would give[258,99], a different method.

This authored toy uses at most24 bytes per field and four merges. It preserves exact text without normalization or word splitting and claims no production vocabulary quality, compression guarantee, learned prediction accuracy or measured speed. A tensor here is simply a saved one-dimensional array of exact integers with a named axis. The inspector retains complete source descriptors, per-rank lists, candidate columns and decoder evidence; empty arrays are omitted rather than padded.

Inspect all exact integers, text metadata and tensor storage

Every scalar output, including flattened operation outputs

Exact text evidence from the same record

These values are exact int32 integers, with no display rounding. Each one-dimensional tensor names what its axis counts. Empty arrays have no tensor; the empty stream is shown above instead of a made-up padding token.

CorpusCodePoints

Scalars=4 · int32 · precision 0 · Validated Unicode scalars in exact input order.

Zero-based storage indexExact integer
097
198
297
398

CorpusUTF16Offsets

Scalars=4 · int32 · precision 0 · Zero-based UTF-16 storage offset for each scalar.

Zero-based storage indexExact integer
00
11
22
33

CorpusUTF16Widths

Scalars=4 · int32 · precision 0 · UTF-16 storage units consumed by each scalar.

Zero-based storage indexExact integer
01
11
21
31

CorpusByteOffsets

Scalars=4 · int32 · precision 0 · Zero-based UTF-8 byte offset for each scalar.

Zero-based storage indexExact integer
00
11
22
33

CorpusByteWidths

Scalars=4 · int32 · precision 0 · Actual UTF-8 bytes emitted by each scalar.

Zero-based storage indexExact integer
01
11
21
31

CorpusBytes

Bytes=4 · int32 · precision 0 · Manual UTF-8 encoding in source order, preserving all data.

Zero-based storage indexExact integer
097
198
297
398

SourceCodePoints

Scalars=6 · int32 · precision 0 · Validated Unicode scalars in exact input order.

Zero-based storage indexExact integer
097
198
297
398
497
598

SourceUTF16Offsets

Scalars=6 · int32 · precision 0 · Zero-based UTF-16 storage offset for each scalar.

Zero-based storage indexExact integer
00
11
22
33
44
55

SourceUTF16Widths

Scalars=6 · int32 · precision 0 · UTF-16 storage units consumed by each scalar.

Zero-based storage indexExact integer
01
11
21
31
41
51

SourceByteOffsets

Scalars=6 · int32 · precision 0 · Zero-based UTF-8 byte offset for each scalar.

Zero-based storage indexExact integer
00
11
22
33
44
55

SourceByteWidths

Scalars=6 · int32 · precision 0 · Actual UTF-8 bytes emitted by each scalar.

Zero-based storage indexExact integer
01
11
21
31
41
51

SourceBytes

Bytes=6 · int32 · precision 0 · Manual UTF-8 encoding in source order, preserving all data.

Zero-based storage indexExact integer
097
198
297
398
497
598

TrainInitialIDs

Tokens=4 · int32 · precision 0 · Initial training byte IDs, one ID for each actual corpus byte.

Zero-based storage indexExact integer
097
198
297
398

TrainR0CandidateLeft

Candidates=2 · int32 · precision 0 · Numeric tuple order: left ID, then right ID; aligned candidate columns.

Zero-based storage indexExact integer
097
198

TrainR0CandidateRight

Candidates=2 · int32 · precision 0 · Right ID in the same sorted candidate order.

Zero-based storage indexExact integer
098
197

TrainR0CandidateFrequency

Candidates=2 · int32 · precision 0 · Actual adjacent-pair frequency, including overlapping occurrences.

Zero-based storage indexExact integer
02
11

TrainR0Before

Tokens=4 · int32 · precision 0 · Complete current token list before this nonoverlapping left-to-right pass.

Zero-based storage indexExact integer
097
198
297
398

TrainR0After

Tokens=2 · int32 · precision 0 · Complete actual output token list after this rank; no padding or truncation.

Zero-based storage indexExact integer
0256
1256

TrainR1CandidateLeft

Candidates=1 · int32 · precision 0 · Numeric tuple order: left ID, then right ID; aligned candidate columns.

Zero-based storage indexExact integer
0256

TrainR1CandidateRight

Candidates=1 · int32 · precision 0 · Right ID in the same sorted candidate order.

Zero-based storage indexExact integer
0256

TrainR1CandidateFrequency

Candidates=1 · int32 · precision 0 · Actual adjacent-pair frequency, including overlapping occurrences.

Zero-based storage indexExact integer
01

TrainR1Before

Tokens=2 · int32 · precision 0 · Complete current token list before this nonoverlapping left-to-right pass.

Zero-based storage indexExact integer
0256
1256

TrainR1After

Tokens=1 · int32 · precision 0 · Complete actual output token list after this rank; no padding or truncation.

Zero-based storage indexExact integer
0257

CorpusIDs

Tokens=1 · int32 · precision 0 · Final learned corpus token IDs; corpus training never contains EOS.

Zero-based storage indexExact integer
0257

RuleIDs

Rules=2 · int32 · precision 0 · Learned IDs in ascending rank, ID=256+rank.

Zero-based storage indexExact integer
0256
1257

RuleLeft

Rules=2 · int32 · precision 0 · Left operand ID for each learned rank.

Zero-based storage indexExact integer
097
1256

RuleRight

Rules=2 · int32 · precision 0 · Right operand ID for each learned rank.

Zero-based storage indexExact integer
098
1256

Rule256Bytes

Bytes=2 · int32 · precision 0 · Actual concatenated operand bytes; the piece alone need not be valid UTF-8.

Zero-based storage indexExact integer
097
198

Rule257Bytes

Bytes=4 · int32 · precision 0 · Actual concatenated operand bytes; the piece alone need not be valid UTF-8.

Zero-based storage indexExact integer
097
198
297
398

EncodeInitialIDs

Tokens=6 · int32 · precision 0 · Initial target byte IDs before any ranked application.

Zero-based storage indexExact integer
097
198
297
398
497
598

EncodeR0Before

Tokens=6 · int32 · precision 0 · Complete current token list before this nonoverlapping left-to-right pass.

Zero-based storage indexExact integer
097
198
297
398
497
598

EncodeR0After

Tokens=3 · int32 · precision 0 · Complete actual output token list after this rank; no padding or truncation.

Zero-based storage indexExact integer
0256
1256
2256

EncodeR1Before

Tokens=3 · int32 · precision 0 · Complete current token list before this nonoverlapping left-to-right pass.

Zero-based storage indexExact integer
0256
1256
2256

EncodeR1After

Tokens=2 · int32 · precision 0 · Complete actual output token list after this rank; no padding or truncation.

Zero-based storage indexExact integer
0257
1256

TargetIDs

Tokens=2 · int32 · precision 0 · Final target token IDs after all learned ranks, then optional unique EOS tail.

Zero-based storage indexExact integer
0257
1256

CorpusDecodedBytes

Bytes=4 · int32 · precision 0 · Actual final corpus ID expansions passed to strict UTF-8 decoding.

Zero-based storage indexExact integer
097
198
297
398

TargetDecodedBytes

Bytes=6 · int32 · precision 0 · Actual final target ID expansions passed to strict UTF-8 decoding.

Zero-based storage indexExact integer
097
198
297
398
497
598

Check your understanding

Use the inputs stated in each question. Live questions use the current calculation. Each option pairs a value or conclusion with its mechanism. Editing a raw input, resetting or selecting a trace step clears graded answers; local inspection selectors preserve them.

1. What does one learned BPE rule mean in this lab?
2. At reset (corpus abab, target ababab, two merges, EOS off), which target IDs and reconstruction are correct?
3. Current train_select_0 saves pair (97,98), frequency 2. Which value and mechanism describe the first learned rule?
4. Set corpus to aaaa and request one merge. How do the aa frequency and replacement result differ?
5. Train on bc bc ab for three merges, then encode abc with EOS off. Which numeric tie rule and target result are correct?

At reset, the authored corpus abab has four bytes[97,98,97,98]. The most frequent pair(97,98) occurs twice and becomes ID256 with bytes[97,98], so the training list becomes[256,256]. Recount that current list: its one pair(256,256) has frequency1 and becomes ID257 with bytes[97,98,97,98]. The corpus ends[257].

The separate target ababab has six bytes. Apply learned rank0 to get[256,256,256], then rank1 to get[257,256]. Reverse expansion joins four actual bytes and two actual bytes; strict UTF-8 reconstruction yields ababab. Enabling EOS adds target ID512 only after both passes, with an empty byte expansion. Corpus training never uses EOS.

Try corpus aaaa with one merge: overlapping aa counts3, but only two disjoint replacements occur. Try bbaa: all three pairs count1, yet last-encountered aa wins because its numeric tuple(97,97) is smaller than(98,97) and(98,98). Then try corpus bc bc ab, target abc, three merges: target[97,256] shows why ranked application differs from longest-prefix lookup.

Try an empty corpus, a one-byte corpus and requested merges0 separately. A zero budget skips training; a positive budget with fewer than two byte tokens stops early. One scalar need not mean one byte: corpus é and target é with four requested merges learn ID256=(195,169), leave both streams[256], and stop at one actual merge. Every field preserves case, spaces, line breaks, BOM and combining marks; each is bounded at24 UTF-8 bytes.

This is a small deterministic byte-stream tokenizer, not a trained language model or an accuracy/speed benchmark. Vocabulary items, token count, byte count and Unicode scalar count are distinct. The next Part uses token IDs as inputs and targets for a language-model objective; merging IDs alone does not learn predictions.

Reset uses training corpus abab, input text ababab, two requested merges and EOS off. The four summary values are corpusBytes=4, byteCount=6, actualMerges=2, tokenCount=2. The learned corpus ends as [257]; the separate target ends as [257,256]. In the target, ID 257 expands to four bytes and ID 256 to two, recovering all six target bytes. Try changing the corpus while keeping the target fixed: the shared naming rules change, even though the target’s characters do not.

Review IV-38 — Subwords and Vocabulary Trade-Offs for vocabularies and byte fallback, and IV-37 — From Unicode Text to Token IDs for Unicode scalars and strict UTF-8. Book II’s I.8 — Indexed quantities and summation supplies indexed-list notation; Book III’s III-39 — Reproducibility and Numerical Reliability motivates reproducible rules. IV-16 — Token IDs and Embedding Lookup Tables explains how these IDs later select embedding rows. Here we learn a tokenizer’s discrete rules, without training neural weights or measuring language quality.

What is being learned?

A corpus is the text used to learn the rules. This lab uses one literal byte stream, including spaces and line breaks. A target is the separate input text to encode afterward. Both first become UTF-8 bytes, integers from 0 through 255. A Unicode scalar is a permitted Unicode code-point number; UTF-8 represents each scalar with one to four bytes. A token is one item in the resulting sequence; its ID names a byte or learned byte sequence in the vocabulary.

An adjacent pair consists of two neighboring IDs in the current list. Its frequency is the number of adjacent positions containing that ordered pair. A merge replaces the pair with one new ID. A rule’s rank is its zero-based learning order: rank 0 is learned first. Its new ID is 256+rank, so at most four rules use IDs 256..259. An expansion gives the original bytes named by an ID. Base ID 97 expands to [97]; a learned ID can expand to several bytes.

Concatenation means joining lists in order without adding or removing entries. If a new ID merges left ID u and right ID v, its byte expansion is expansion(u) followed by expansion(v). This construction, rather than a guessed text label, defines what the ID means. A later rule can use an earlier rule’s ID; it cannot use itself or a rule not yet learned.

One learned rule can cause several replacements. The summary actualMerges counts rules learned, not the number of pair occurrences replaced. With k rules, the vocabulary has 256 base byte items, k learned pieces and one reserved EOS item: 257+k possible items, even when EOS is off. This item count describes the declared vocabulary; the lab does not allocate an embedding table.

Vocabulary item count is not highest ID plus one. At reset there are 259 possible items, yet EOS retains public ID 512 and leaves unused numeric gaps. Public token names are therefore not automatically dense embedding row indices. A later language model must declare an ID-to-compact-row map, assigning each active item its own consecutive table row; it must not infer 513 rows from the largest public ID. This chapter implements no embedding or row allocation.

Let C be the corpus byte count, B the target byte count, m the requested merge budget, k the actual rules learned, and e the EOS flag. The limits are C≤24, B≤24, m an integer from 0 through 4, and e either 0 or 1. The inequality k≤m allows training to stop early when fewer than two corpus tokens remain. Let L be the current corpus token count and T the final target token count, including optional EOS. A tensor here is simply a named numeric list. List shape [L] means one dimension of L positions, not a matrix. An axis names what those positions count: tokens, bytes, scalars or pair candidates. All stored numeric lists use int32, signed 32-bit integers that hold these permitted values exactly, with precision metadata 0. Empty arrays have no padded tensor.

Count, choose, concatenate, replace, recount

Training repeats four operations until its budget is used or there is no adjacent pair:

  1. Count pairs at every adjacent position in the current corpus list, including overlapping positions.
  2. Choose the greatest final frequency. For equal counts, choose the numerically lexicographically smallest ordered pair: compare left IDs as integers; if equal, compare right IDs as integers.
  3. Save a new rule with ID 256+rank and concatenate its operands’ actual byte expansions.
  4. Scan the current list left to right, replacing matching pairs without overlap. Start a fresh frequency table for the next round.

A count of one is eligible: this lab does not stop merely because no pair repeats. Numeric tuple order is independent of which pair was encountered first and of how decimal IDs look as strings. Counting and replacing answer different questions: counting measures adjacent occurrences; replacement must avoid consuming the same token twice.

In a replacement pass, position is an index in that pass’s current input token list, not an original byte offset. At a match, emit the new ID, set consumed=2 and nextPosition=position+2. Otherwise retain one token, set consumed=1 and nextPosition=position+1. The output becomes the next pass’s input. A merged token may represent many bytes but still occupies one token position.

Work the entire default training by hand

ASCII is the first 128 character codes, including basic Latin letters, digits and control codes; its scalars each use one equal-valued UTF-8 byte. ASCII a and b have byte values 97 and 98. The corpus starts at [97,98,97,98]. Here are all adjacent positions and count increments in round 0:

Position in current tokensLeft IDRight IDThis pair’s count after visiting
097981
198971
297982

The final candidates in numeric tuple order are (97,98):2 and (98,97):1. The first has the greatest frequency, so rank 0 learns (97,98)→256. Its expansion is [97] followed by [98], giving [97,98].

Replace at position 0: consume tokens 0 and 1, emit 256, and advance to position 2. Replace at position 2: consume tokens 2 and 3, emit 256, and advance to 4, the input list length. The output is [256,256]. The pair count was 2 and there are two replacement events in this example.

Round 1 counts afresh on [256,256]. Its only adjacent pair is (256,256):1. That count is eligible, so rank 1 learns (256,256)→257. Its byte expansion is [97,98] followed by [97,98], hence [97,98,97,98]. At current token position 0, consume two tokens, emit 257 and advance to 2. The final corpus is [257]. Two merges were requested and two were learned; the corpus token lengths were 4→2→1.

Notice the change of units: round 1 advances two token positions, although the consumed tokens jointly expand to four bytes. The rule ID 257 is a name, not a byte width or a character count.

Encode the separate target in learned rank order

Encoding keeps the learned rules fixed. It does not train again on target frequencies and does not choose the longest vocabulary prefix as IV-38 did. Convert ababab to [97,98,97,98,97,98], then apply each learned rule once as a complete left-to-right nonoverlapping pass:

Rank and ruleInput tokensMatch positions in this inputOutput tokens
0: (97,98)→256[97,98,97,98,97,98]0,2,4[256,256,256]
1: (256,256)→257[256,256,256]0[257,256]

Rank 0 advances 0→2→4→6, each time consuming two input tokens. Rank 1 replaces positions 0 and 1, advances to 2, then retains the final token 256 with consumed=1 and nextPosition=3. Its three-token input covers six bytes; position 2 is the third token, whose original bytes begin at byte offset 4. This is why saved position, consumed and nextPosition refer to tokens.

With e=0, the target has T=2 tokens. With e=1, append the reserved end-of-sequence (EOS) ID 512 after all rank passes, giving [257,256,512] and T=3. EOS names a control item with no text bytes. It is never inserted into corpus training. Literal text <eos> remains ordinary bytes; only the flag appends ID 512.

Read the saved lists without mixing their axes

At reset, CorpusBytes has shape [4] on axis Bytes, while SourceBytes has shape [6] on the same kind of axis. CorpusIDs has shape [1] on axis Tokens; TargetIDs has shape [2] on Tokens, or [3] with EOS. RuleIDs, RuleLeft and RuleRight each have shape [2] on Rules, aligned by rank: IDs [256,257], left operands [97,256], right operands [98,256]. Rule256Bytes has shape [2]; Rule257Bytes has shape [4], each on Bytes. Different expansion lengths remain separate lists.

The final round-0 candidate columns are TrainR0CandidateLeft=[97,98], TrainR0CandidateRight=[98,97] and TrainR0CandidateFrequency=[2,1]. Each has shape [2] on Candidates; matching positions across the three lists describe one pair and its frequency. Individual train_count_0_0 through train_count_0_2 steps instead save countBefore/countAfter for each increment. A partial count is not yet the final frequency used to select a winner; only the complete final candidate table becomes tensors.

TrainR0Before and TrainR0After hold the complete pass input and output; EncodeR0Before and EncodeR0After do the same for target rank 0. Each scalar replacement record saves position, currentID, nextID and the emitted id, consumed, nextPosition and outputLength. Together with the complete input list, these identify every visited pair and resulting output. There are no per-position output-prefix tensors. The sentinel nextID=−1 means no next token exists, never a real ID or padding item. The rule-concatenation step separately saves leftWidth/rightWidth, each leftByte/rightByte operand, and every resulting byte, so byte width cannot be confused with token position.

Actually decode both streams

Expand corpus ID 257 to [97,98,97,98], then strictly decode those bytes: each is an ASCII scalar, so the result is a,b,a,b, exactly abab. This is a reconstruction from the learned corpus ID, not a copy of the corpus string.

For the target, expand 257 to [97,98,97,98] and 256 to [97,98]. Concatenate them to [97,98,97,98,97,98]. Strict UTF-8 decoding reconstructs six scalars, a,b,a,b,a,b, producing ababab. Only after both decoders construct their strings are those results compared with the two original strings. With EOS on, the decoder validates and removes its single final 512 before decoding the concatenated content bytes. Reconstructed text stays the same.

Why is this reversible? Each replacement substitutes a name whose expansion equals the concatenation of exactly the two consumed expansions. All untouched tokens retain their expansions and order. Thus expanding the list before or after a replacement gives identical bytes. Repeat this argument for every replacement and every rank. Base byte IDs recover their bytes directly; learned expansions terminate because each rule refers only to bytes or earlier ranks. Strict UTF-8 decoding then recovers the validated original scalars.

Overlap: three counted occurrences, two replacements

Set corpus to aaaa and request one merge. Its byte tokens are [97,97,97,97]. The pair (97,97) occurs at positions 0,1,2, so its frequency is 3. Learn rule 256 with expansion [97,97].

The replacement pass consumes positions 0 and 1 together, emits 256 and advances to 2. It consumes 2 and 3, emits 256 and advances to 4. The result is [256,256]: two replacements, not three. The counted pair starting at 1 overlaps both chosen pairs and cannot also consume those tokens. Expanding two copies of [97,97] recovers four a bytes; three copies would incorrectly produce six.

Ties must compare numbers, not encounter order

Corpus abba has (97,98), (98,98) and (98,97), each once; (97,98) wins numerically. To detect an accidental “first pair wins” rule, try bbaa with one merge. Its encounter order is (98,98), (98,97), (97,97), again all count 1. The last-encountered (97,97) wins because its left ID 97 is smallest. Rule 256 names aa, so the final corpus tokens are [98,98,256]. Choosing the first encountered bb instead would produce [256,97,97], a different result under the wrong policy.

Rank order is not longest-prefix lookup

Use corpus bc bc ab, input abc and three merges. Space is byte 32, so the eight corpus bytes are [98,99,32,98,99,32,97,98]. Count all seven adjacent positions in round 0: (98,99) rises to 2, (99,32) rises to 2, while (32,98), (32,97) and (97,98) each occur once. Among the tied greatest counts, 98 is less than 99: bc wins.

RankInput tokensComplete final pair counts in numeric tuple orderLearned ruleOutput tokens
0[98,99,32,98,99,32,97,98](32,97):1; (32,98):1; (97,98):1; (98,99):2; (99,32):2(98,99)→256[256,32,256,32,97,98]
1[256,32,256,32,97,98](32,97):1; (32,256):1; (97,98):1; (256,32):2(256,32)→257[257,257,97,98]
2[257,257,97,98](97,98):1; (257,97):1; (257,257):1(97,98)→258[257,257,258]

The learned expansions are 256=[98,99], 257=[98,99,32] and 258=[97,98]. At rank 2, (97,98) beats both pairs beginning with 257 because 97 is numerically less than 257. Sorting decimal string keys could put "257" before "97"; that would violate the rule.

Now encode target [97,98,99]. Rank 0 merges the bc at token position 1, leaving [97,256]. Rank 1 needs (256,32), which is absent. Rank 2 needs (97,98), also absent: b is already inside ID 256. The final target is [97,256]. A longest dictionary prefix would instead choose ab/258 and then byte c/99, giving [258,99]. Both streams can reconstruct abc, but only the first obeys these BPE ranks. Reversibility alone does not prove the encoding policy was followed.

Why one full pass per rank is enough here

After a rule’s nonoverlapping pass, no occurrence of that exact pair remains. At any replaced location there is now a new ID, different from both old operands. A pass does not delete a region and join two untouched tokens: the replacement token remains between its neighbors.

A later rule emits an ID higher than every ID available to an earlier rule. Any newly changed adjacency therefore includes that later ID and cannot equal the earlier pair; unchanged adjacencies were already handled. Consequently a later merge cannot recreate an earlier-ranked match. Applying all matches of rank 0, then all matches of rank 1, and so on gives the same result as repeatedly choosing the lowest-ranked available pair, using the same left-to-right overlap policy. This argument relies on this lab’s fresh increasing IDs, exact pair rules and replacement behavior; it does not equate all tokenizer algorithms.

Unicode pieces and honest boundaries

A vocabulary piece need not be valid UTF-8 by itself. For example, é is bytes [195,169]; either byte alone fails strict UTF-8 decoding. A merge may also cover only part of a longer scalar or cross a scalar boundary. Piece displays therefore use ID plus the saved JSON byte expansion. Do not decode each piece separately or replace invalid pieces with a replacement character. Concatenate all content expansions, then strictly decode the complete stream, rejecting malformed leads, continuations, overlong encodings, surrogate values and out-of-range scalars.

For an actual learned example, use corpus and target 猫 with one merge. Its bytes are [231,140,171]. Adjacent pairs (231,140) and (140,171) each occur once; numeric tie order chooses (140,171)→256. Both corpus and target become [231,256]. Rule256Bytes=[140,171] contains only continuation bytes, which can follow a UTF-8 lead but cannot start a scalar. That piece alone is invalid text. Expanding both tokens first gives [231,140,171]; the strict decoder removes the prefixes and combines payloads 7,12,43 as 7·4096+12·64+43=29483, the scalar U+732B, reconstructing 猫. The invalid piece is useful stored bytes, not a corrupted character to repair.

Spaces, NUL (the U+0000 control scalar), case, a leading BOM (byte-order mark, U+FEFF) and combining forms remain data. There is no normalization, a rewrite between equivalent Unicode forms, or preliminary word splitting. Precomposed é and e followed by a combining accent may look similar but have different byte streams and may learn different rules. The byte vocabulary still covers valid text absent from the corpus; no unknown-word deletion is needed. A piece’s JSON expansion is its bracketed decimal byte list, not an independently decoded string.

With merges=0, there are no training rounds or target rank passes: the target keeps its byte IDs. With an empty or one-byte corpus, a positive budget learns zero rules because there is no adjacent pair; it stops once, without fictional merges. Requested and actual counts must remain distinct. An empty target produces [] with EOS off or [512] with it on, even when the corpus learned rules. No first target match is invented.

Do not decide that a corpus is too short by counting visible characters or scalars. Corpus é contains one scalar but two byte tokens, [195,169]. With target é, merges=4 and EOS off, its real first selection learns (195,169)→256. Both streams become [256]; only then does training stop because one current token remains. The summaries are corpusBytes=2, byteCount=2, actualMerges=1, tokenCount=1. A one-byte ASCII corpus such as a instead has no first selection. A single multibyte scalar is therefore a useful counterexample to a mistaken scalar-count no-rule branch.

Each field is limited to 24 actual UTF-8 bytes, independently. UTF-16, JavaScript’s string representation, uses one or two 16-bit storage units per scalar; its surrogate units are valid only in a correct high/low pair. The early UTF-16 storage-unit bound rejects necessarily oversized text, surrogate validation rejects invalid scalar representations, and the actual byte bound then catches multibyte overflow. All raw fields and numeric domains validate before corpus Unicode semantics and then target semantics. Invalid edits preserve their raw drafts but hide the successful result, trace, tensors and grading; no stale answer substitutes for an invalid state. Editing, resetting and selecting a saved step clear grades.

The private decoder also rejects malformed ID/rule storage, unknown or inactive IDs, invalid operand references, duplicate pairs and misplaced EOS. A dense array has an entry at every index. Arrays and rule objects require own data entries, stored directly rather than inherited, checked before reading values; an accessor that could run code during a read is not accepted as stored data. Old IV-37/38 helpers retain their separate contracts. This tokenizer demonstrates reversible rules on a tiny corpus; it provides no model-quality, compression-ratio, speed or language-coverage benchmark.

Why the complete trace fits without discarding operations

This is a manual size argument, not a timing measurement. For k actual rules, where 0≤k≤4, each successful training round shortens the corpus token list by at least one. At current length L, counting takes at most L−1 records, comparing candidates at most L−1, selecting one, and replacement at most L−1: together at most 3L−2. Summing over starting lengths at most 24,23,… gives at most 70k−3k(k−1)/2 records; explicit byte concatenations add at most k.

The two source scalar encoders add at most 48 records and target scans at most 24k. Both actual expansion-and-scalar decoders together add at most 96−k: final corpus tokens at most 24−k, target content tokens at most 24, and decoded scalars at most 24 for each string. Setup and final comparison add two, optional EOS append/strip add two, and terminal stop adds at most one. Total records are therefore at most 149+94k−3k(k−1)/2, which increases across k=0..4 to a maximum of 507, below the 512-record capacity. The decoder-only bound 92 applies at k=4; smaller k require the conditional 96−k bound. No steps need to be truncated.

Read the actual maintained Python

Read the complete executable Python / NumPy source

This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.

"""IV-39 — Byte-Pair Encoding: A Full Merge Trace.

Train adjacent byte-ID pairs on a separate, literal training corpus. Count
ALL adjacent occurrences, including overlaps, choose the greatest count,
then the lexicographically smallest NUMERIC (left ID, right ID) on ties.
Replace matches left to right without overlap. Recount after every rule.
Encode the target with the learned rules in increasing rank, not by taking
the longest dictionary prefix. Only the target can receive explicit EOS512.

Hand default: corpus abab starts [97,98,97,98]. Counts ab2,ba1 select ab256,
so [256,256] becomes rule257=[97,98,97,98]. Target ababab becomes
[256,256,256] then [257,256]; expanding BOTH IDs reconstructs six bytes.
Corpus aaaa has three adjacent aa occurrences but only two replacements.
Corpus bbaa encounters bb,ba,aa once each; numeric order chooses the LAST
encountered aa=(97,97), producing [98,98,256], not insertion-order bb.
Corpus 'bc bc ab' learns bc256,bc-space257,ab258. In its third round
(97,98) beats pairs starting257 numerically, not by decimal string keys.
Target abc becomes [97,256]; greedy longest-prefix ab258 would differ.

All source is authored without imports, execution, fixtures generation or
runtime validation. Keep bpe_reference.py AND token_reference.py beside this
wrapper. File-relative loading supports an arbitrary caller working directory.
"""
import importlib.util
from pathlib import Path

_bpe_spec = importlib.util.spec_from_file_location(
    "_p09_bpe_reference", Path(__file__).resolve().with_name("bpe_reference.py"))
_bpe = importlib.util.module_from_spec(_bpe_spec)
_bpe_spec.loader.exec_module(_bpe)

DEFAULT_IV39 = _bpe.DEFAULT_IV39


@_bpe._token.guarded
def derive_iv39(state):
    """Train a real corpus, encode a separate target, and decode both actual IDs."""
    token = _bpe._token
    s = _bpe.bpe_state(state)
    encoding_trace = token.TokenTrace()
    corpus = _bpe.encode_bounded(s["corpus"], "corpus", "corpus", encoding_trace)
    source = _bpe.encode_bounded(s["text"], "text", "source", encoding_trace)
    trace = token.TokenTrace()
    corpus_units, units = token.utf16_length(s["corpus"]), token.utf16_length(s["text"])
    trace.add("setup", "Declare learned byte-pair encoding and both exact inputs",
              "byte IDs=0..255; learned ID=256+rank; EOS=512; each text field<=24 UTF-8 bytes",
              "Validate every raw field before corpus then target Unicode semantics. Train on the corpus byte stream including spaces; encode the separate target using learned ranks. No normalization, word splitting, inferred EOS or pretrained vocabulary is used.",
              dict(requestedMerges=s["merges"], eos=s["eos"]),
              dict(corpusUnits=corpus_units, corpusScalars=len(corpus["codePoints"]), utf16Units=units,
                   scalarCount=len(source["codePoints"]), byteBound=_bpe.BYTE_BOUND,
                   mergeBase=_bpe.MERGE_BASE, mergeBound=_bpe.MERGE_BOUND, EOS=_bpe.EOS))
    # Scalar records were prepared during validation; keep their actual order.
    trace.steps.extend(encoding_trace.steps)
    tensors = []
    for stem, encoded in (("Corpus", corpus), ("Source", source)):
        for suffix, key, axis, provenance in (
            ("CodePoints", "codePoints", "Scalars", "Validated Unicode scalars in exact input order."),
            ("UTF16Offsets", "offsets", "Scalars", "Zero-based UTF-16 storage offset for each scalar."),
            ("UTF16Widths", "widths", "Scalars", "UTF-16 storage units consumed by each scalar."),
            ("ByteOffsets", "byteOffsets", "Scalars", "Zero-based UTF-8 byte offset for each scalar."),
            ("ByteWidths", "byteWidths", "Scalars", "Actual UTF-8 bytes emitted by each scalar."),
            ("Bytes", "bytes", "Bytes", "Manual UTF-8 encoding in source order, preserving all data."),
        ):
            _bpe.save_tensor(tensors, f"{stem}{suffix}", axis, encoded[key], provenance)
    trained = _bpe.train_bpe(corpus["bytes"], s["merges"], trace, tensors)
    ids = _bpe.encode_bpe(source["bytes"], trained["rules"], s["eos"], trace, tensors)
    # Corpus is NEVER EOS-trained. Both inverse paths expand real saved IDs.
    corpus_decoded = _bpe.decode_bpe_ids(trained["ids"], trained["rules"], 0, "corpus", trace)
    target_decoded = _bpe.decode_bpe_ids(ids, trained["rules"], s["eos"], "target", trace)
    corpus_equal = int(corpus_decoded["decoded"] == s["corpus"])
    equal = int(target_decoded["decoded"] == s["text"])
    if not (corpus_equal and equal):
        raise _bpe.NumericalFault("INVALID_INPUT", "Actual BPE reconstructions did not equal both original strings.")
    trace.add("roundtrip", "Compare both actual strict reconstructions with the original strings",
              "corpusEqual=(corpusDecoded===corpus); equal=(targetDecoded===text)",
              "Expand real corpus and target IDs separately, concatenate real bytes, strictly reconstruct Unicode scalars, and only then compare strings. Empty content reconstructs the empty string; optional target EOS emits no bytes.",
              dict(corpusOriginalUnits=corpus_units, corpusDecodedUnits=token.utf16_length(corpus_decoded["decoded"]),
                   corpusDecodedByteCount=len(corpus_decoded["bytes"]), originalUnits=units,
                   decodedUnits=token.utf16_length(target_decoded["decoded"]), decodedByteCount=len(target_decoded["bytes"])),
              dict(corpusTokens=len(trained["ids"]), tokenCount=len(ids), corpusEqual=corpus_equal, equal=equal))
    _bpe.save_tensor(tensors, "CorpusDecodedBytes", "Bytes", corpus_decoded["bytes"],
                     "Actual final corpus ID expansions passed to strict UTF-8 decoding.")
    _bpe.save_tensor(tensors, "TargetDecodedBytes", "Bytes", target_decoded["bytes"],
                     "Actual final target ID expansions passed to strict UTF-8 decoding.")
    expansions = {rule["id"]: rule["bytes"].tolist() for rule in trained["rules"]}

    def expansion(identifier):
        return [] if identifier == _bpe.EOS else [identifier] if identifier <= 255 else expansions[identifier]

    def labels(token_ids):
        return ["ID 512: EOS (explicit control), bytes []" if int(identifier) == _bpe.EOS else
                f"ID {int(identifier)}, bytes {token.json_text(expansion(int(identifier)))}" for identifier in token_ids]

    def expansion_labels(token_ids):
        return [token.json_text(expansion(int(identifier))) for identifier in token_ids]

    summary = dict(corpusBytes=len(corpus["bytes"]), byteCount=len(source["bytes"]),
                   actualMerges=len(trained["rules"]), tokenCount=len(ids), requestedMerges=s["merges"],
                   corpusTokens=len(trained["ids"]), eos=s["eos"], byteBound=_bpe.BYTE_BOUND,
                   vocabularyItems=256 + len(trained["rules"]) + 1, corpusEqual=corpus_equal, equal=equal)
    texts = dict(corpus=s["corpus"], input=s["text"], corpusDecoded=corpus_decoded["decoded"],
                 decoded=target_decoded["decoded"], corpusLabels=labels(trained["ids"]),
                 corpusExpansions=expansion_labels(trained["ids"]), targetLabels=labels(ids),
                 targetExpansions=expansion_labels(ids),
                 ruleLabels=[f"ID {rule['id']}, bytes {token.json_text(rule['bytes'].tolist())}" for rule in trained["rules"]],
                 ruleExpansions=[token.json_text(rule["bytes"].tolist()) for rule in trained["rules"]],
                 trainingStop="Zero merges requested: no training round or pair selection occurs." if s["merges"] == 0 else
                 "Stopped early: fewer than two current training tokens remain." if len(trained["rules"]) < s["merges"] else
                 "Requested merge budget completed.")
    return trace.result(summary, tensors, texts)


def source_self_check():
    """Deferred hand-literal record checks; never part of the normal CLI path."""
    assert __debug__, "Run later checks with assertions enabled."
    _bpe.source_self_check()
    result = derive_iv39(dict(DEFAULT_IV39))
    assert list(result) == ["status", "outputs", "steps", "tensors", "texts"]
    assert list(result["outputs"])[:11] == ["corpusBytes", "byteCount", "actualMerges", "tokenCount", "requestedMerges", "corpusTokens", "eos", "byteBound", "vocabularyItems", "corpusEqual", "equal"]
    assert [result["outputs"][key] for key in ("corpusBytes", "byteCount", "actualMerges", "tokenCount")] == [4, 6, 2, 2]
    assert len(result["steps"]) == 44 and len(result["tensors"]) == 37
    assert result["texts"]["corpusDecoded"] == "abab" and result["texts"]["decoded"] == "ababab"
    assert result["texts"]["targetLabels"] == ["ID 257, bytes [97,98,97,98]", "ID 256, bytes [97,98]"]
    # Tensor count:12source+1initial+10round+1corpus+3rules+2expansions+
    # 1targetinitial+4targetpasses+1targetfinal+2decoded=37. No program counted it.
    tensor_ids = [record["id"] for record in result["tensors"]]
    for merges, eos, steps in ((2, 1, 46), (3, 0, 45), (3, 1, 47), (4, 0, 45), (4, 1, 47)):
        case = derive_iv39(dict(corpus="abab", text="ababab", merges=merges, eos=eos))
        assert len(case["steps"]) == steps
        assert [record["id"] for record in case["tensors"]] == tensor_ids
    for eos in (0, 1):
        empty = derive_iv39(dict(corpus="", text="", merges=0, eos=eos))
        assert empty["outputs"]["tokenCount"] == eos
        assert len(empty["steps"]) == 2 + 2 * eos
        assert empty["texts"]["decoded"] == empty["texts"]["corpusDecoded"] == ""
    for patch, code in (
        (dict(corpus="\ud800", merges=float("nan")), "NONFINITE"),
        (dict(corpus="a" * 25, text="\ud800"), "UNSUPPORTED_SIZE"),
        (dict(corpus="\ud800", text="a" * 25), "INVALID_INPUT"),
        (dict(text="🦊" * 7), "UNSUPPORTED_SIZE"),
        (dict(text="🦊" * 9), "UNSUPPORTED_SIZE"),
    ):
        bad = derive_iv39({**DEFAULT_IV39, **patch})
        assert list(bad) == ["status", "code", "reason"] and bad["code"] == code


if __name__ == "__main__":
    # No args: defaults; one complete JSON state: replacement; '-': stdin JSON.
    _bpe._token.run(derive_iv39, DEFAULT_IV39)
Read the complete executable Python / NumPy source

This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.

"""IV-39: complete learned byte-pair encoding, authored without execution.

NumPy int32 arrays hold actual bytes, code points, offsets, IDs and rule
expansions. Python integers do scalar comparisons, counts and index arithmetic.
The unchanged token_reference.py supplies the manual UTF-8 codec and record
storage. No native codec supplies a production answer. A byte piece need not
be valid Unicode alone: concatenate all expansions before strict decoding.
"""
import importlib.util
from pathlib import Path
from types import MappingProxyType
import numpy as np

# File-relative loading works even when the caller has an unrelated cwd.
_token_spec = importlib.util.spec_from_file_location(
    "_p09_bpe_token_reference", Path(__file__).resolve().with_name("token_reference.py"))
_token = importlib.util.module_from_spec(_token_spec)
_token_spec.loader.exec_module(_token)

NumericalFault = _token.NumericalFault
BPE_BYTE_BOUND = 24
BYTE_BOUND = BPE_BYTE_BOUND
MERGE_BASE = 256
MERGE_BOUND = 4
EOS = 512
DEFAULT_IV39 = MappingProxyType(dict(corpus="abab", text="ababab", merges=2, eos=0))


def data_object(value, fields, label):
    """Exact built-in mappings have own data entries, never property getters."""
    if type(value) not in (dict, MappingProxyType):
        raise NumericalFault("INVALID_INPUT", f"{label} must be a plain object.")
    if any(type(key) is not str for key in value) or set(value) != set(fields):
        raise NumericalFault("INVALID_INPUT", f"{label} must have exactly {', '.join(fields)} as own fields.")


def dense_data(values, limit, label, numeric=True):
    """Reject custom indexing BEFORE reading entries; never narrow invalid data."""
    if type(values) is np.ndarray and numeric:
        if values.ndim != 1 or values.dtype.kind not in "iuf":
            raise NumericalFault("INVALID_INPUT", f"{label} must be a dense one-dimensional numeric array.")
    elif type(values) not in (list, tuple):
        raise NumericalFault("INVALID_INPUT", f"{label} must be an actual array.")
    if len(values) > limit:
        raise NumericalFault("UNSUPPORTED_SIZE", f"{label} exceeds {limit} entries.")


def budget(merges):
    if type(merges) not in (int, float):
        raise NumericalFault("NONFINITE", "merges must be an actual finite number.")
    # The reused integer validator catches finiteness OverflowError on huge ints.
    return _token.integer(merges, 0, MERGE_BOUND, "merges")


def eos_flag(eos):
    _token._flag(eos)
    return int(eos)


def bpe_state(state):
    """ALL raw strings/numbers precede corpus, then target Unicode semantics."""
    data_object(state, DEFAULT_IV39, "state")
    for key in ("corpus", "text"):
        if type(state[key]) is not str:
            raise NumericalFault("INVALID_INPUT", f"{key} must be an actual string, without coercion.")
    merges = budget(state["merges"])
    if type(state["eos"]) not in (int, float):
        raise NumericalFault("NONFINITE", "eos must be an actual finite number.")
    # Check finite before the flag domain, preserving NONFINITE error precedence.
    eos = _token.integer(state["eos"], 0, 1, "eos")
    return dict(corpus=state["corpus"], text=state["text"], merges=merges, eos=eos)


def encode_bounded(text, field, prefix, trace):
    """Early UTF-16 bound, all surrogate checks, then actual UTF-8 byte bound."""
    if type(text) is not str:
        raise NumericalFault("INVALID_INPUT", f"{field} must be an actual string, without coercion.")
    if _token.utf16_length(text) > BYTE_BOUND:
        raise NumericalFault("UNSUPPORTED_SIZE", f"{field}: more than 24 UTF-16 units necessarily exceeds this 24-byte field.")
    reason = f"{field}: the actual UTF-8 encoding exceeds 24 bytes; shorten this field explicitly."
    try:
        encoded = _token.utf8_encode(text, prefix, trace)
    except NumericalFault as error:
        # Nine foxes hit the inherited32-byte bound before this24-byte postcheck.
        if error.code == "UNSUPPORTED_SIZE":
            raise NumericalFault("UNSUPPORTED_SIZE", reason) from error
        raise
    if len(encoded["bytes"]) > BYTE_BOUND:
        raise NumericalFault("UNSUPPORTED_SIZE", reason)
    return encoded


def bytes_input(values):
    dense_data(values, BYTE_BOUND, "BPE bytes")
    return _token.int_array(values, high=255, label="BPE bytes", limit=BYTE_BOUND)


def rule_table(rules):
    """Validate a lossless, acyclic rule namespace before expanding caller IDs."""
    dense_data(rules, MERGE_BOUND, "BPE rules", numeric=False)
    # Inspect every object/container first; no arbitrary mapping/index getter runs.
    for rule in rules:
        data_object(rule, ("id", "left", "right", "bytes"), "rule")
        dense_data(rule["bytes"], BYTE_BOUND, "Rule bytes")
    expansions, pairs = {}, set()
    for rank, rule in enumerate(rules):
        expected_id = MERGE_BASE + rank
        identifier = int(_token.int_array([rule["id"]], high=259, label="Rule ID")[0])
        if identifier != expected_id:
            raise NumericalFault("INVALID_INPUT", f"Rule {rank} must have ID {expected_id}.")
        operands = _token.int_array([rule["left"], rule["right"]], high=expected_id - 1, label="Rule operands")
        left, right = int(operands[0]), int(operands[1])
        # IDs between255 and this ID must already be present, never forward/cyclic.
        if any(operand > 255 and operand not in expansions for operand in (left, right)):
            raise NumericalFault("INVALID_INPUT", "Each rule operand must be a byte ID or an earlier merge ID.")
        if (left, right) in pairs:
            raise NumericalFault("INVALID_INPUT", "Duplicate BPE rule pairs are not allowed.")
        pairs.add((left, right))
        stored = _token.int_array(rule["bytes"], high=255, label="Rule bytes", limit=BYTE_BOUND)
        left_bytes = np.array([left], dtype=np.int32) if left <= 255 else expansions[left]
        right_bytes = np.array([right], dtype=np.int32) if right <= 255 else expansions[right]
        expected = np.concatenate((left_bytes, right_bytes))
        if len(expected) > BYTE_BOUND:
            raise NumericalFault("UNSUPPORTED_SIZE", "A rule expansion exceeds 24 bytes.")
        if len(expected) != len(stored) or any(int(a) != int(b) for a, b in zip(expected, stored)):
            raise NumericalFault("INVALID_INPUT", "Rule bytes must equal the left expansion followed by the right expansion.")
        expansions[identifier] = expected
    return expansions


def save_tensor(tensors, identifier, axis, values, provenance):
    """Keep actual int32 storage; an empty stream has no fabricated tensor."""
    if len(values):
        tensors.append(_token.tensor(identifier, axis, values, provenance))


def replace_pass(ids, rule, rank, stage, trace, tensors):
    """Count positions in CURRENT input tokens, not original UTF-8 bytes."""
    stem = f"{'Train' if stage == 'train' else 'Encode'}R{rank}"
    save_tensor(tensors, f"{stem}Before", "Tokens", ids,
                "Complete current token list before this nonoverlapping left-to-right pass.")
    result, position = [], 0
    while position < len(ids):
        current_id = int(ids[position])
        next_id = int(ids[position + 1]) if position + 1 < len(ids) else -1
        matched = int(current_id == rule["left"] and next_id == rule["right"])
        consumed = 2 if matched else 1
        identifier = rule["id"] if matched else current_id
        next_position = position + consumed
        inputs = dict(rank=rank, position=position, inputLength=len(ids), left=rule["left"],
                      right=rule["right"], newID=rule["id"], currentID=current_id,
                      nextID=next_id, outputLength=len(result))
        result.append(identifier)
        trace.add(f"{stage}_replace_{rank}_{position}", f"{stage}: rank {rank}, current-token position {position}",
                  "matched=(currentID=left and nextID=right); emit matched?newID:currentID; consumed=matched?2:1; nextPosition=position+consumed",
                  "Positions index the current token list, not original bytes. A match consumes two tokens and emits one; a nonmatch copies one token. Advancing past both matched operands prevents overlapping replacements. The complete pass snapshots and position/consumed/nextPosition retain every scan; nextID -1 means no next token, never a token or padding item.",
                  inputs, dict(matched=matched, id=identifier, consumed=consumed,
                               nextPosition=next_position, outputLength=len(result)))
        position = next_position
    values = np.array(result, dtype=np.int32)
    save_tensor(tensors, f"{stem}After", "Tokens", values,
                "Complete actual output token list after this rank; no padding or truncation.")
    return values


def train_bpe(values, merges, trace, tensors):
    """Count overlaps, select numeric ties, concatenate bytes, replace disjointly."""
    merges = budget(merges)
    ids = bytes_input(values).copy()
    rules, expansions = [], {}
    save_tensor(tensors, "TrainInitialIDs", "Tokens", ids,
                "Initial training byte IDs, one ID for each actual corpus byte.")
    for rank in range(merges):
        if len(ids) < 2:
            trace.add("train_stop", "Stop: fewer than two training tokens remain", "length<2 means no adjacent pair exists",
                      "This is one real early stop, not a fabricated merge. A zero requested budget does not enter training at all.",
                      dict(rank=rank, length=len(ids), requestedMerges=merges), dict(actualMerges=len(rules)))
            break
        counts = {}
        # Advance by ONE here: unlike replacement, counting includes overlaps.
        for position in range(len(ids) - 1):
            left, right = int(ids[position]), int(ids[position + 1])
            count_before = counts.get((left, right), 0)
            counts[(left, right)] = count_before + 1
            trace.add(f"train_count_{rank}_{position}", f"Count round {rank} pair at current-token position {position}",
                      "frequency(left,right)=previous frequency+1; next counting position=position+1",
                      "Count every adjacent occurrence, including overlaps. The table starts empty each round. In aaaa, aa occurs at positions 0, 1 and 2 even though replacement will consume only two disjoint pairs.",
                      dict(rank=rank, position=position, left=left, right=right, countBefore=count_before),
                      dict(countAfter=counts[(left, right)], distinctPairs=len(counts)))
        # Sort NUMERIC tuples, never string keys or insertion order (bbaa anchor).
        candidates = sorted(counts)
        for suffix, entries, provenance in (
            ("Left", [pair[0] for pair in candidates], "Numeric tuple order: left ID, then right ID; aligned candidate columns."),
            ("Right", [pair[1] for pair in candidates], "Right ID in the same sorted candidate order."),
            ("Frequency", [counts[pair] for pair in candidates], "Actual adjacent-pair frequency, including overlapping occurrences."),
        ):
            save_tensor(tensors, f"TrainR{rank}Candidate{suffix}", "Candidates",
                        np.array(entries, dtype=np.int32), provenance)
        best = None
        best_frequency = 0
        for candidate_index, (left, right) in enumerate(candidates):
            frequency = counts[(left, right)]
            best_left, best_right = best if best is not None else (-1, -1)
            inputs = dict(candidateIndex=candidate_index, left=left, right=right, frequency=frequency,
                          bestLeft=best_left, bestRight=best_right, bestFrequency=best_frequency)
            frequency_greater = int(frequency > best_frequency)
            frequency_equal = int(frequency == best_frequency)
            lex_smaller = int(best is not None and (left, right) < best)
            take = int(best is None or frequency_greater or (frequency_equal and lex_smaller))
            if take:
                best, best_frequency = (left, right), frequency
            trace.add(f"train_compare_{rank}_{candidate_index}", f"Compare round {rank} candidate {candidate_index}",
                      "take=first candidate or greater frequency or (equal frequency and numerically smaller (left,right))",
                      "Compare integer IDs, left first and then right, not string keys or encounter order. Candidate columns use numeric tuple order. The first comparison uses best IDs -1 and frequency 0 as an explicit empty-best sentinel.",
                      inputs, dict(take=take, frequencyGreater=frequency_greater, frequencyEqual=frequency_equal,
                                   lexSmaller=lex_smaller, bestLeft=best[0], bestRight=best[1], bestFrequency=best_frequency))
        left, right = best
        identifier = MERGE_BASE + rank
        trace.add(f"train_select_{rank}", f"Select round {rank} winning pair",
                  "newID=256+rank; select greatest frequency, then smallest numeric pair",
                  "Frequency 1 is eligible. Requested merges are a budget; actual merges stop early only when no adjacent pair remains.",
                  dict(rank=rank, currentLength=len(ids), candidateCount=len(candidates)),
                  dict(id=identifier, left=left, right=right, frequency=best_frequency))
        left_bytes = np.array([left], dtype=np.int32) if left <= 255 else expansions[left]
        right_bytes = np.array([right], dtype=np.int32) if right <= 255 else expansions[right]
        expansion = np.concatenate((left_bytes, right_bytes))
        rule = dict(id=identifier, left=left, right=right, bytes=expansion)
        inputs = dict(id=identifier, left=left, right=right, leftWidth=len(left_bytes), rightWidth=len(right_bytes))
        inputs.update({f"leftByte{i}": int(byte) for i, byte in enumerate(left_bytes)})
        inputs.update({f"rightByte{i}": int(byte) for i, byte in enumerate(right_bytes)})
        outputs = dict(byteWidth=len(expansion))
        outputs.update({f"byte{i}": int(byte) for i, byte in enumerate(expansion)})
        trace.add(f"train_rule_{rank}", f"Build rule {rank} byte expansion", "new bytes=left bytes followed by right bytes",
                  "Both operands are bytes or earlier merge IDs. Their complete concatenation defines the new ID and cannot create a cycle. A piece may end inside a UTF-8 scalar, so its label uses ID and exact JSON bytes.",
                  inputs, outputs)
        rules.append(rule)
        expansions[identifier] = expansion.copy()
        ids = replace_pass(ids, rule, rank, "train", trace, tensors)
    save_tensor(tensors, "CorpusIDs", "Tokens", ids,
                "Final learned corpus token IDs; corpus training never contains EOS.")
    for identifier, key, provenance in (
        ("RuleIDs", "id", "Learned IDs in ascending rank, ID=256+rank."),
        ("RuleLeft", "left", "Left operand ID for each learned rank."),
        ("RuleRight", "right", "Right operand ID for each learned rank."),
    ):
        save_tensor(tensors, identifier, "Rules", np.array([rule[key] for rule in rules], dtype=np.int32), provenance)
    for rule in rules:
        save_tensor(tensors, f"Rule{rule['id']}Bytes", "Bytes", rule["bytes"],
                    "Actual concatenated operand bytes; the piece alone need not be valid UTF-8.")
    return dict(ids=ids, rules=rules)


def encode_bpe(values, rules, eos, trace, tensors):
    """Apply each learned rank once; only then append optional target EOS512.

    A later rule emits a higher ID and leaves a replacement token between any
    untouched neighbors, so it cannot create an earlier rule's lower-ID pair.
    """
    rule_table(rules)
    eos = eos_flag(eos)
    ids = bytes_input(values).copy()
    save_tensor(tensors, "EncodeInitialIDs", "Tokens", ids,
                "Initial target byte IDs before any ranked application.")
    for rank, rule in enumerate(rules):
        # Public rule fields may be integral floats; scalar trace fields are ints.
        actual = dict(id=int(rule["id"]), left=int(rule["left"]), right=int(rule["right"]))
        ids = replace_pass(ids, actual, rank, "encode", trace, tensors)
    ids = _token.append_eos(ids, eos, "target", trace)
    save_tensor(tensors, "TargetIDs", "Tokens", ids,
                "Final target token IDs after all learned ranks, then optional unique EOS tail.")
    return ids


def decode_bpe_ids(values, rules, eos, prefix, trace):
    """Expand the ACTUAL validated IDs, then strictly reconstruct Unicode."""
    expansions = rule_table(rules)
    eos = eos_flag(eos)
    dense_data(values, BYTE_BOUND + 1, "BPE token IDs")
    ids = _token.int_array(values, high=EOS, label="BPE token IDs", limit=BYTE_BOUND + 1)
    has_tail = len(ids) > 0 and int(ids[-1]) == EOS
    content = ids[:-1] if has_tail else ids
    if has_tail != (eos == 1) or any(int(value) == EOS for value in content):
        raise NumericalFault("INVALID_INPUT", "EOS must occur exactly once at the tail when eos=1, and nowhere when eos=0.")
    for stored in content:
        identifier = int(stored)
        if identifier > 255 and identifier not in expansions:
            raise NumericalFault("INVALID_INPUT", f"Unknown or inactive BPE ID {identifier}.")
    byte_values = []
    for index, stored in enumerate(content):
        identifier = int(stored)
        expansion = [identifier] if identifier <= 255 else expansions[identifier].tolist()
        byte_offset = len(byte_values)
        byte_values.extend(expansion)
        if len(byte_values) > BYTE_BOUND:
            raise NumericalFault("UNSUPPORTED_SIZE", "Decoded BPE expansions exceed 24 bytes.")
        outputs = dict(byteOffset=byte_offset, byteWidth=len(expansion))
        outputs.update({f"byte{i}": byte for i, byte in enumerate(expansion)})
        trace.add(f"{prefix}_expand_{index}", f"{prefix}: expand ID at token {index}", "ID → validated byte expansion",
                  "Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used.",
                  dict(index=index, id=identifier), outputs)
    if eos == 1:
        trace.add(f"{prefix}_strip_eos", f"{prefix}: strip explicit tail EOS", "EOS emits no text bytes",
                  "The decoder has validated the unique required tail marker. Its empty expansion is a control convention, not a lost source character.",
                  dict(index=len(ids) - 1, id=EOS), dict(stripped=1))
    actual_bytes = np.array(byte_values, dtype=np.int32)
    return dict(bytes=actual_bytes, decoded=_token.utf8_decode(actual_bytes, prefix, trace))


def source_self_check():
    """Hand-derived deferred assertions: NEVER called by import or normal CLI.

    The human resource hold forbids invoking this function now. These are
    source checks for later owner validation, not generated expected answers.
    """
    assert __debug__, "Run later checks with assertions enabled."

    def rejects(call, code="INVALID_INPUT"):
        try:
            call()
        except NumericalFault as error:
            assert error.code == code, (error.code, code)
            return error
        raise AssertionError("Invalid boundary was accepted")

    def train(values, merges):
        trace, tensors = _token.TokenTrace(), []
        result = train_bpe(values, merges, trace, tensors)
        return result, trace, tensors

    # Default: abab -> ab/ab -> abab; target ababab -> abab/ab.
    trained, trace, tensors = train([97, 98, 97, 98], 2)
    assert trained["ids"].tolist() == [257]
    assert [(rule["id"], rule["left"], rule["right"]) for rule in trained["rules"]] == [(256, 97, 98), (257, 256, 256)]
    assert [rule["bytes"].tolist() for rule in trained["rules"]] == [[97, 98], [97, 98, 97, 98]]
    ids = encode_bpe([97, 98, 97, 98, 97, 98], trained["rules"], 1, trace, tensors)
    assert ids.tolist() == [257, 256, 512]
    assert decode_bpe_ids(trained["ids"], trained["rules"], 0, "corpus", trace)["decoded"] == "abab"
    assert decode_bpe_ids(ids, trained["rules"], 1, "target", trace)["decoded"] == "ababab"
    assert ids.dtype == np.dtype(np.int32) and trained["ids"].dtype == np.dtype(np.int32)
    assert all(rule["bytes"].dtype == np.dtype(np.int32) for rule in trained["rules"])
    assert all(record["dtype"] == "int32" and record["precision"] == 0 for record in tensors)
    concat = next(step for step in trace.steps if step["id"] == "train_rule_1")
    assert list(concat["inputs"]) == ["id", "left", "right", "leftWidth", "rightWidth", "leftByte0", "leftByte1", "rightByte0", "rightByte1"]
    tail = next(step for step in trace.steps if step["id"] == "encode_replace_1_2")
    assert tail["inputs"]["nextID"] == -1
    assert tail["outputs"] == dict(matched=0, id=256, consumed=1, nextPosition=3, outputLength=2)

    # Count overlaps3, replace disjointly2; every emitted token remains lossless.
    overlap, overlap_trace, _ = train([97, 97, 97, 97], 1)
    assert overlap["ids"].tolist() == [256, 256]
    assert next(step for step in overlap_trace.steps if step["id"] == "train_count_0_2")["outputs"]["countAfter"] == 3
    assert len([step for step in overlap_trace.steps if step["id"].startswith("train_replace_")]) == 2
    last_tie, _, _ = train([98, 98, 97, 97], 1)
    assert (last_tie["rules"][0]["left"], last_tie["rules"][0]["right"]) == (97, 97)
    assert last_tie["ids"].tolist() == [98, 98, 256]

    # Numeric97 precedes257; rank application differs from greedy prefix ab.
    ranked, rank_trace, rank_tensors = train([98, 99, 32, 98, 99, 32, 97, 98], 3)
    assert [(rule["left"], rule["right"]) for rule in ranked["rules"]] == [(98, 99), (256, 32), (97, 98)]
    assert ranked["ids"].tolist() == [257, 257, 258]
    assert encode_bpe([97, 98, 99], ranked["rules"], 0, rank_trace, rank_tensors).tolist() == [97, 256]
    empty, empty_trace, empty_tensors = train([], 4)
    assert not empty["rules"] and empty["ids"].tolist() == []
    assert [step["id"] for step in empty_trace.steps] == ["train_stop"] and empty_tensors == []
    _, zero_trace, _ = train([97, 98], 0)
    assert zero_trace.steps == []
    assert encode_bpe([], [], 1, _token.TokenTrace(), []).tolist() == [512]

    # Malformed IDs/EOS/rules fail before any guessed/replacement decoding.
    for values, eos in (([], 1), ([512], 0), ([512, 65], 1), ([65, 512, 512], 1), ([256], 0), ([384], 0), ([1024], 0), ([True], 0), ([10**1000], 0)):
        rejects(lambda: decode_bpe_ids(values, [], eos, "target", _token.TokenTrace()))
    rejects(lambda: decode_bpe_ids([65] * 25, [], 0, "target", _token.TokenTrace()), "UNSUPPORTED_SIZE")
    for values in ([195], [192, 128], [237, 160, 128], [244, 144, 128, 128]):
        rejects(lambda: decode_bpe_ids(values, [], 0, "target", _token.TokenTrace()))
    assert decode_bpe_ids([239, 187, 191, 0], [], 0, "target", _token.TokenTrace())["decoded"] == "\ufeff\0"
    for bad in (
        [dict(id=257, left=97, right=98, bytes=[97, 98])],
        [dict(id=256, left=256, right=98, bytes=[97, 98])],
        [dict(id=256, left=97, right=98, bytes=[98, 97])],
        [dict(id=256, left=97, right=98, bytes=[97, 98]), dict(id=257, left=97, right=98, bytes=[97, 98])],
    ):
        rejects(lambda: rule_table(bad))

    # Both 7fox/28byte postcheck and 9fox/36byte inherited32 rejection say24.
    for text in ("🦊" * 7, "🦊" * 9):
        error = rejects(lambda: encode_bounded(text, "corpus", "corpus", _token.TokenTrace()), "UNSUPPORTED_SIZE")
        assert "24" in str(error) and "32" not in str(error)
    rejects(lambda: encode_bounded("🦊" * 7 + "\ud800", "corpus", "corpus", _token.TokenTrace()))
    rejects(lambda: bpe_state(dict(corpus=None, text="", merges=0, eos=float("nan"))))
    rejects(lambda: bpe_state(dict(corpus="\ud800", text="", merges=float("nan"), eos=0)), "NONFINITE")
    rejects(lambda: bpe_state(dict(corpus="", text="", merges=10**1000, eos=0)), "NONFINITE")
    rejects(lambda: bpe_state(dict(corpus="", text="", merges=0, eos=10**1000)), "NONFINITE")
    rejects(lambda: bpe_state(dict(corpus="", text="", merges=True, eos=0)), "NONFINITE")
    rejects(lambda: bpe_state(dict(corpus="", text="", merges=0, eos=0, extra=0)))
    rejects(lambda: bpe_state(dict(corpus="", text="", merges=0)))

    class AccessorState:
        @property
        def corpus(self):
            raise AssertionError("Getter must never run")

    class AccessorList(list):
        def __getitem__(self, index):
            raise AssertionError("Custom indexing must never run")

    rejects(lambda: bpe_state(AccessorState()))
    rejects(lambda: decode_bpe_ids(AccessorList([65]), [], 0, "target", _token.TokenTrace()))
    rejects(lambda: rule_table([dict(id=256, left=97, right=98, bytes=AccessorList([97, 98]))]))
Read the complete executable Python / NumPy source

This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.

"""Part IX: bounded integer tokenization, authored without execution.

NumPy int32 arrays store actual code points, offsets, bytes and IDs. Arithmetic
uses Python integers, so bit shifts never depend on NumPy scalar promotion.
UTF-8 is implemented below; no native codec supplies an encoded/decoded answer.
Empty streams, BOMs, noncharacters, spaces and NULs are ordinary valid data.
"""
import argparse
from functools import wraps
import json
import math
import sys
from types import MappingProxyType
import numpy as np

EOS = 512
BYTE_BOUND = 32
CHARACTER_BASE = 1024
IV37_DEFAULTS = MappingProxyType(dict(text="Aé🦊", eos=0))
IV38_DEFAULTS = MappingProxyType(dict(text="lower low", vocabLimit=8, eos=0))
# Fixed active-prefix dictionary: these pieces are authored, not trained.
SUBWORDS = (
    (384, "low", (108, 111, 119)),
    (385, "lower", (108, 111, 119, 101, 114)),
    (386, "lowest", (108, 111, 119, 101, 115, 116)),
    (387, "er", (101, 114)),
    (388, "est", (101, 115, 116)),
    (389, "ing", (105, 110, 103)),
    (390, "a", (97,)),
    (391, "ab", (97, 98)),
)


class NumericalFault(ValueError):
    def __init__(self, code, reason):
        super().__init__(reason)
        self.code = code


def guarded(derive):
    @wraps(derive)
    def call(state):
        try:
            return derive(state)
        except NumericalFault as error:
            return dict(status="unavailable", code=error.code, reason=str(error))
    return call


def integer(value, low, high, label):
    """Validate before conversion; Python bool is not a mathematical number here."""
    if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)):
        raise NumericalFault("NONFINITE", f"{label} must be an actual finite number.")
    try:
        finite = math.isfinite(value)
    except OverflowError:
        finite = False
    if not finite:
        raise NumericalFault("NONFINITE", f"{label} must be an actual finite number.")
    if value < low or value > high or int(value) != value:
        raise NumericalFault("INVALID_INPUT", f"{label} must be an integer from {low} to {high}.")
    return int(value)


def scalar_valid(cp):
    return 0 <= cp <= 0x10FFFF and not 0xD800 <= cp <= 0xDFFF


def utf16_units(cp):
    """Reconstruct the actual high/low units from a validated supplementary scalar."""
    if cp <= 0xFFFF:
        return [cp]
    return [0xD800 + ((cp - 0x10000) >> 10), 0xDC00 + ((cp - 0x10000) & 1023)]


def utf16_length(text):
    return sum(2 if ord(character) > 0xFFFF else 1 for character in text)


def text_state(state, chapter):
    """Exact raw fields and numeric domains precede ALL Unicode/size semantics."""
    if type(chapter) is not int or chapter not in (37, 38):
        raise NumericalFault("INVALID_INPUT", "Use token chapter 37 or 38.")
    defaults = IV37_DEFAULTS if chapter == 37 else IV38_DEFAULTS
    if type(state) not in (dict, MappingProxyType):
        raise NumericalFault("INVALID_INPUT", "Provide a plain object with exactly the named fields.")
    if set(state) != set(defaults):
        raise NumericalFault("INVALID_INPUT", "Provide every own field and no extra or symbol fields.")
    if type(state["text"]) is not str:
        raise NumericalFault("INVALID_INPUT", "text must be an actual string, without coercion.")
    result = dict(text=state["text"])
    for key in defaults:
        if key != "text":
            if type(state[key]) not in (int, float):
                raise NumericalFault("NONFINITE", f"{key} must be an actual finite number.")
            result[key] = integer(state[key], 0, 8 if key == "vocabLimit" else 1, key)
    return result


def int_array(values, low=0, high=0x7FFFFFFF, label="integer array", limit=BYTE_BOUND):
    """Check dense numeric storage BEFORE narrowing; integral-valued floats are legal."""
    if type(values) is np.ndarray:
        if values.ndim != 1 or values.dtype.kind not in "iuf":
            raise NumericalFault("INVALID_INPUT", f"{label} must be a dense one-dimensional numeric array.")
    elif type(values) not in (list, tuple):
        raise NumericalFault("INVALID_INPUT", f"{label} must be an actual array.")
    if len(values) > limit:
        raise NumericalFault("UNSUPPORTED_SIZE", f"{label} exceeds {limit} entries.")
    checked = []
    for index, value in enumerate(values):
        if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)):
            raise NumericalFault("INVALID_INPUT", f"{label}[{index}] must be an own integer from {low} to {high}.")
        try:
            finite = math.isfinite(value)
        except OverflowError:
            finite = False
        if not finite or value < low or value > high or int(value) != value:
            raise NumericalFault("INVALID_INPUT", f"{label}[{index}] must be an own integer from {low} to {high}.")
        checked.append(int(value))
    return np.array(checked, dtype=np.int32)


def utf8_encode(text, prefix="source", trace=None):
    """Scan valid scalars first; then split each into explicit UTF-8 payload groups."""
    if trace is None:
        trace = TokenTrace()
    if type(text) is not str:
        raise NumericalFault("INVALID_INPUT", "UTF-8 input must be an actual string.")
    if utf16_length(text) > BYTE_BOUND:
        raise NumericalFault("UNSUPPORTED_SIZE", "More than 32 UTF-16 units necessarily exceeds this 32-byte lab.")
    code_points, offsets, widths = [], [], []
    offset = 0
    # Python strings store scalars directly; explicit surrogate values are invalid.
    for character in text:
        cp = ord(character)
        if 0xD800 <= cp <= 0xDBFF:
            raise NumericalFault("INVALID_INPUT", f"Unpaired high surrogate at UTF-16 offset {offset}.")
        if 0xDC00 <= cp <= 0xDFFF:
            raise NumericalFault("INVALID_INPUT", f"Unpaired low surrogate at UTF-16 offset {offset}.")
        width = len(utf16_units(cp))
        code_points.append(cp)
        offsets.append(offset)
        widths.append(width)
        offset += width
    byte_values, byte_offsets, byte_widths = [], [], []
    for index, cp in enumerate(code_points):
        if cp <= 0x7F:
            expansion = [cp]
        elif cp <= 0x7FF:
            expansion = [0xC0 | (cp >> 6), 0x80 | (cp & 63)]
        elif cp <= 0xFFFF:
            expansion = [0xE0 | (cp >> 12), 0x80 | ((cp >> 6) & 63), 0x80 | (cp & 63)]
        else:
            expansion = [0xF0 | (cp >> 18), 0x80 | ((cp >> 12) & 63),
                         0x80 | ((cp >> 6) & 63), 0x80 | (cp & 63)]
        units = utf16_units(cp)
        inputs = dict(scalarIndex=index, utf16Offset=offsets[index], utf16Width=widths[index], codePoint=cp, unit0=units[0])
        if len(units) == 2:
            inputs["unit1"] = units[1]
        outputs = dict(byteOffset=len(byte_values), byteWidth=len(expansion))
        for j, byte in enumerate(expansion):
            mask = (31 if len(expansion) == 2 else 15 if len(expansion) == 3 else 7) if j == 0 else 63
            outputs[f"payload{j}"] = byte if len(expansion) == 1 else byte & mask
        outputs.update({f"byte{j}": byte for j, byte in enumerate(expansion)})
        trace.add(f"{prefix}_scalar_{index}", f"Encode scalar {index}: U+{cp:04X}",
                  "supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits",
                  "A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs.",
                  inputs, outputs)
        byte_offsets.append(len(byte_values))
        byte_widths.append(len(expansion))
        byte_values.extend(expansion)
    if len(byte_values) > BYTE_BOUND:
        raise NumericalFault("UNSUPPORTED_SIZE", "The actual UTF-8 encoding exceeds 32 bytes; shorten the input explicitly.")
    return dict(bytes=int_array(byte_values, high=255, label="UTF-8 bytes"), codePoints=int_array(code_points),
                offsets=int_array(offsets), widths=int_array(widths), byteOffsets=int_array(byte_offsets), byteWidths=int_array(byte_widths))


def utf8_decode(values, prefix="utf8", trace=None):
    """Remove prefixes, accumulate radix-64 digits, validate, then rebuild the text."""
    if trace is None:
        trace = TokenTrace()
    values = int_array(values, high=255, label="UTF-8 bytes")
    characters, offset = [], 0
    while offset < len(values):
        lead = int(values[offset])
        width = 1 if lead <= 0x7F else 2 if 0xC2 <= lead <= 0xDF else 3 if 0xE0 <= lead <= 0xEF else 4 if 0xF0 <= lead <= 0xF4 else 0
        if not width:
            raise NumericalFault("INVALID_INPUT", f"Invalid UTF-8 lead at byte {offset}.")
        if offset + width > len(values):
            raise NumericalFault("INVALID_INPUT", f"Truncated UTF-8 sequence at byte {offset}.")
        inputs = dict(scalarIndex=len(characters), byteOffset=offset, byteWidth=width)
        outputs, cp = {}, 0
        for j in range(width):
            byte = int(values[offset + j])
            if j > 0 and not 0x80 <= byte <= 0xBF:
                raise NumericalFault("INVALID_INPUT", f"Invalid continuation byte at {offset + j}.")
            inputs[f"byte{j}"] = byte
            mask = (31 if width == 2 else 15 if width == 3 else 7) if j == 0 else 63
            payload = byte if width == 1 else byte & mask
            outputs[f"payload{j}"] = payload
            cp = cp * 64 + payload
            outputs[f"accumulator{j}"] = cp
        minimum = 0 if width == 1 else 0x80 if width == 2 else 0x800 if width == 3 else 0x10000
        if cp < minimum or not scalar_valid(cp):
            raise NumericalFault("INVALID_INPUT", f"Overlong, surrogate or out-of-range scalar at byte {offset}.")
        units = utf16_units(cp)
        outputs.update(codePoint=cp, utf16Width=len(units))
        outputs.update({f"unit{j}": unit for j, unit in enumerate(units)})
        # chr uses the validated scalar; no source text is available to copy here.
        characters.append(chr(cp))
        trace.add(f"{prefix}_decode_{len(characters) - 1}", f"Decode UTF-8 scalar {len(characters) - 1}",
                  "accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar",
                  "Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved.",
                  inputs, outputs)
        offset += width
    return "".join(characters)


def _flag(eos):
    if type(eos) not in (int, float) or eos not in (0, 1):
        raise NumericalFault("INVALID_INPUT", "eos must be numeric 0 or 1.")


def _vocabulary(limit):
    try:
        if type(limit) not in (int, float):
            raise NumericalFault("INVALID_INPUT", "vocabLimit must be an integer from 0 to 8.")
        return integer(limit, 0, 8, "vocabLimit")
    except NumericalFault as error:
        raise NumericalFault("INVALID_INPUT", "vocabLimit must be an integer from 0 to 8.") from error


def _strip_eos(ids, eos):
    _flag(eos)
    ids = int_array(ids, high=CHARACTER_BASE + 0x10FFFF, label="Token IDs", limit=BYTE_BOUND + 1)
    has_tail = len(ids) > 0 and int(ids[-1]) == EOS
    content = ids[:-1].copy() if has_tail else ids.copy()
    if has_tail != (eos == 1) or any(int(value) == EOS for value in content):
        raise NumericalFault("INVALID_INPUT", "EOS must occur exactly once at the tail when eos=1, and nowhere when eos=0.")
    return ids, content


def append_eos(ids, eos, prefix, trace):
    """Return actual int32 storage with the optional reserved tail, never text matching."""
    _flag(eos)
    if eos == 1:
        index = len(ids)
        ids = np.concatenate((ids, np.array([EOS], dtype=np.int32)))
        trace.add(f"{prefix}_eos", f"{prefix}: append explicit EOS", "id=512",
                  "Only this flag appends EOS; literal text such as <eos> remains ordinary input.",
                  dict(index=index, eos=eos), dict(id=EOS))
    return ids


def _eos_record(ids, eos, prefix, trace):
    if eos == 1:
        trace.add(f"{prefix}_strip_eos", f"{prefix}: strip explicit tail EOS", "EOS emits no text bytes",
                  "The decoder has validated the whole ID stream and the required unique tail marker.",
                  dict(index=len(ids) - 1, id=EOS), dict(stripped=1))


def decode_byte_ids(ids, eos, prefix="byte", trace=None):
    return _decode_pieces(ids, eos, 0, False, prefix, TokenTrace() if trace is None else trace)


def decode_subword_ids(ids, eos, limit, prefix="subword", trace=None):
    limit = _vocabulary(limit)
    return _decode_pieces(ids, eos, limit, True, prefix, TokenTrace() if trace is None else trace)


def _decode_pieces(ids, eos, limit, subwords, prefix, trace):
    ids, content = _strip_eos(ids, eos)
    active = {identifier: expansion for identifier, _, expansion in SUBWORDS[:limit]} if subwords else {}
    byte_values = []
    for index, stored in enumerate(content):
        identifier = int(stored)
        if identifier <= 255:
            expansion = (identifier,)
        elif identifier in active:
            expansion = active[identifier]
        else:
            raise NumericalFault("INVALID_INPUT", f"Unknown or inactive {prefix} ID {identifier}.")
        byte_offset = len(byte_values)
        byte_values.extend(expansion)
        if len(byte_values) > BYTE_BOUND:
            raise NumericalFault("UNSUPPORTED_SIZE", "Decoded token expansions exceed 32 bytes.")
        outputs = dict(byteOffset=byte_offset, byteWidth=len(expansion))
        outputs.update({f"byte{j}": byte for j, byte in enumerate(expansion)})
        trace.add(f"{prefix}_expand_{index}", f"{prefix}: expand ID at token {index}", "ID → declared byte expansion",
                  "Fallback byte IDs equal their byte value; active subword IDs expand to their full declared bytes. A single fallback byte may be only part of a Unicode scalar.",
                  dict(index=index, id=identifier), outputs)
    _eos_record(ids, eos, prefix, trace)
    values = int_array(byte_values, high=255, label="UTF-8 bytes")
    return dict(bytes=values, decoded=utf8_decode(values, prefix, trace))


def decode_character_ids(ids, eos, prefix="char", trace=None):
    if trace is None:
        trace = TokenTrace()
    ids, content = _strip_eos(ids, eos)
    characters = []
    for index, stored in enumerate(content):
        identifier = int(stored)
        cp = identifier - CHARACTER_BASE
        if not scalar_valid(cp):
            raise NumericalFault("INVALID_INPUT", f"Character ID {identifier} does not name a Unicode scalar.")
        units = utf16_units(cp)
        outputs = dict(codePoint=cp, utf16Width=len(units))
        outputs.update({f"unit{j}": unit for j, unit in enumerate(units)})
        characters.append(chr(cp))
        trace.add(f"{prefix}_inverse_{index}", f"Character ID {index}: inverse mapping",
                  "codePoint=id−1024; reconstruct UTF-16 units",
                  "The scalar range excludes surrogate code points but includes noncharacters. The comparison vocabulary is algorithmic; no million-row matrix is allocated.",
                  dict(index=index, id=identifier), outputs)
    _eos_record(ids, eos, prefix, trace)
    decoded = "".join(characters)
    # External ID streams obey the same text bound; this private trace is omitted.
    utf8_encode(decoded)
    return decoded


def greedy_ids(values, limit, trace):
    """Choose longest matching byte expansion, then lowest ID; no match keeps a byte."""
    values = int_array(values, high=255, label="Greedy source bytes")
    limit = _vocabulary(limit)
    ids, offset = [], 0
    while offset < len(values):
        matches = []
        for identifier, _, expansion in SUBWORDS[:limit]:
            if offset + len(expansion) <= len(values) and all(int(values[offset + j]) == byte for j, byte in enumerate(expansion)):
                matches.append((identifier, len(expansion)))
        chosen, width = int(values[offset]), 1
        if matches:
            chosen, width = min(matches, key=lambda candidate: (-candidate[1], candidate[0]))
        inputs = dict(byteOffset=offset, remaining=len(values) - offset, candidateMatches=len(matches))
        for index, (identifier, match_width) in enumerate(matches):
            inputs[f"candidate{index}ID"] = identifier
            inputs[f"candidate{index}Width"] = match_width
        trace.add(f"subword_decision_{len(ids)}", f"Choose subword at byte offset {offset}",
                  "choose longest matching active byte expansion; tie: lowest subword ID; no match: current byte",
                  "Matched candidates are listed in fixed vocabulary order. An active one-byte entry is preferred to fallback when it matches. Advance by the actual chosen byte width; spaces and unmatched Unicode bytes remain in the stream.",
                  inputs, dict(id=chosen, byteWidth=width, nextByteOffset=offset + width))
        ids.append(chosen)
        offset += width
    return int_array(ids)


def json_text(value):
    """Match JSON string/array metadata without ASCII escaping or added spaces."""
    return json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":"))


def byte_labels(ids):
    return ["EOS (explicit control)" if int(value) == EOS else f"byte {int(value)}" for value in ids]


def byte_expansions(ids):
    return [json_text([] if int(value) == EOS else [int(value)]) for value in ids]


def numbers(values):
    return {key: integer(value, -0x80000000, 0x7FFFFFFF, key) for key, value in values.items()}


class TokenTrace:
    def __init__(self):
        self.steps = []

    def add(self, identifier, label, equation, explanation, inputs, outputs):
        inputs, outputs = numbers(inputs), numbers(outputs)
        if len(self.steps) >= 512:
            raise NumericalFault("UNSUPPORTED_SIZE", "At most 512 operations are supported.")
        self.steps.append(dict(id=identifier, label=label, equation=equation, explanation=explanation,
                               inputs=inputs, outputs=outputs))

    def result(self, summary, tensors, texts):
        # Include copied encoding steps too, after the signed first summary aliases.
        outputs = numbers(summary)
        for step in self.steps:
            outputs.update({f"{step['id']}_{key}": value for key, value in step["outputs"].items()})
        return dict(status="defined", outputs=outputs, steps=self.steps, tensors=tensors, texts=texts)


def tensor(identifier, axis, values, provenance):
    """Serialize actual nonempty int32 storage; empty streams yield no fake tensor."""
    if type(values) is not np.ndarray or values.dtype != np.dtype(np.int32) or values.ndim != 1:
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: require one-dimensional int32 storage.")
    if not 1 <= len(values) <= 64:
        raise NumericalFault("UNSUPPORTED_SIZE", f"{identifier}: dimensions must be 1–64.")
    if type(axis) is not str or not axis:
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: name the axis.")
    return dict(id=identifier, shape=[len(values)], axes=[axis], dtype="int32", values=values.tolist(),
                provenance=provenance, precision=0)


_JSON_INT = int


def run(derive, defaults):
    """No args: defaults; one JSON arg: full replacement; '-': JSON from stdin."""
    class ParseFault(ValueError):
        """Only locally owned JSON profile/conversion faults."""

    def _members(pairs):
        value = {}
        for key, member in pairs:
            if key in value:
                raise ParseFault("Duplicate JSON object members are not allowed.")
            value[key] = member
        return value

    def _constant(token):
        raise ParseFault(f"Nonstandard JSON constant {token} is not allowed.")

    def _integer(token):
        if token == "-0":
            return -0.0
        try:
            return _JSON_INT(token)
        except ValueError as fault:
            if type(fault) is not ValueError:
                raise
            raise ParseFault("JSON integer exceeds the interpreter's conversion capacity.") from fault

    parser = argparse.ArgumentParser(description=derive.__doc__)
    parser.add_argument("state", nargs="?")
    args = parser.parse_args()
    if args.state is not None:
        source = sys.stdin.read() if args.state == "-" else args.state
        try:
            state = json.loads(source, object_pairs_hook=_members,
                               parse_constant=_constant, parse_int=_integer)
        except (json.JSONDecodeError, ParseFault) as error:
            result = dict(status="unavailable", code="INVALID_INPUT", reason=str(error))
        else:
            result = derive(state)
    else:
        result = derive(dict(defaults))
    print(json.dumps(result, allow_nan=False, separators=(",", ":")))

These are the complete raw repository files iv39.py, bpe_reference.py and token_reference.py, not rewritten examples. Keep all three together: loading resolves helpers relative to each file’s __file__, rather than depending on the caller’s working directory. NumPy stores exact integer lists; explicit scalar loops specify counts, comparisons, replacement and Unicode reconstruction.

The UTF-8 helper’s utf8_encode records each validated scalar and its bytes. Its utf8_decode removes lead/continuation prefixes, combines six-bit payload groups with accumulator=previous·64+payload, validates the scalar and constructs the actual text. TokenTrace packages the saved scalar outputs, steps, tensors and textual metadata; it does not infer a reconstruction from the original input. Count and rank operations belong to the BPE helper, keeping IV-37/38’s fixed-vocabulary behavior separate.

Read derive_iv39 in the wrapper as the complete journey. bpe_state checks all raw controls; encode_bounded converts corpus first and target second while enforcing the 24-byte contract. train_bpe returns actual final corpus ids and learned rules. encode_bpe applies those rules to the separate source bytes, followed by optional target EOS. Two decode_bpe_ids calls reconstruct the corpus with EOS off and the target with its chosen flag. Only afterward are corpus_equal and equal calculated. The final trace.result(summary, tensors, texts) retains numeric evidence and actual reconstructed strings together.

Inside train_bpe, the dictionary counts uses numeric (left,right) tuple keys; its counting loop advances one position to include overlaps. sorted(counts) orders candidates numerically. The comparison loop saves each candidate and current best before choosing the winner. left_bytes and right_bytes supply the operands to np.concatenate; this joins bytes in order, without normalization. replace_pass instead advances by consumed=1 or 2 and saves every copied or merged ID, along with complete Before/After lists. encode_bpe reuses that pass in learned rank order; it never recounts target pairs. decode_bpe_ids checks the rule table and ID namespace, expands each actual ID and delegates only the complete byte stream to utf8_decode.

The saved operation order is setup, all corpus_scalar_i, all source_scalar_i, then each round’s train_count_r_p, train_compare_r_j, train_select_r, train_rule_r and train_replace_r_p. A genuine early stop, if needed, follows completed rounds. Target passes save encode_replace_r_p, then optional target_eos. Actual inverses save corpus_expand_i and corpus_decode_i, then target_expand_i, optional target_strip_eos, and target_decode_i, ending with roundtrip. Here r is rank, p is current input-token position, j is sorted candidate index, and i indexes the relevant scalar or content token. Widths, bytes, scalar payloads and reverse accumulators are saved numbers, not computed again from a view’s labels.

Five graded questions and how to correct a mistake

These outlines follow the lab’s actual five questions. Training corpus and Input text are independent editable fields. Requested learned merges (maximum budget) changes m; Append explicit end-of-sequence (EOS) to target only changes e. Editing any input, resetting or selecting a calculation step clears grades. The live question always uses the saved first training selection, even if the trace picker inspects another operation. The reset and counterexample questions specify their own inputs explicitly; changing your current text does not change those stated examples.

  1. learned-byte-pair: What does one rule mean? Choose the second option: a selected adjacent pair of current token IDs gets a new ID whose bytes are the left expansion followed by the right expansion. A larger ID does not mean a more meaningful word and cannot justify discarding spaces. A merge need not join two visible letters: it can cross a boundary or cover only part of a scalar. Its byte expansion, rather than its label or apparent meaning, makes the rule reversible.
  2. default-ranked-encoding: Encode and reconstruct the reset case. Choose the third option, [257,256]: rank 0 creates three copies of 256, rank 1 merges the first two and copies the third, and expansion joins four bytes then two. [257,257] would expand to eight bytes and invent two extra bytes. [256,256,256] reconstructs six bytes but incorrectly stops before applying learned rank 1. With EOS enabled a final 512 would be appended; the question explicitly says EOS off.
  3. live-first-merge: Explain the actual first selection or its absence. The second option is correct in all three branches. When train_select_0 exists, read its saved id, left, right and frequency; at reset these are 256,97,98,2. Choose greatest overlapping-pair frequency with numeric tuple tie-breaking, followed by disjoint replacements. The frequency does not authorize consuming overlapping tokens twice, and encounter order cannot replace the tie policy: bbaa chooses last-encountered aa. With zero requested merges, no selection exists because the budget skips training, even if adjacent byte pairs are available. No count, replacement or early-stop event is fabricated; the target retains its byte IDs plus only explicit EOS. This is not a malformed corpus that needs padding. With a positive budget and no first selection, the valid corpus has fewer than two initial byte tokens, so one real early stop reports actualMerges=0 and the target uses byte fallback. The budget is a maximum, not an instruction to invent rules. This branch must not use scalar count: with corpus and target é, budget 4 and EOS off, the real first selection is (195,169)→256, both streams are [256], and only then does training stop at actualMerges=1.
  4. overlap-count-versus-replace: Separate frequency from replacement count. For aaaa with one merge, choose the first option: frequency 3, then two disjoint replacements yielding [256,256]. Counting visits positions 0,1,2; replacement consumes 0/1 and 2/3. Frequency 2 incorrectly excludes overlapping counts. Three output copies of 256 incorrectly reuse middle bytes and would expand to six a bytes instead of four.
  5. rank-versus-longest: Transfer numeric ties and ranks to another corpus. For bc bc ab, three merges, target abc and EOS off, choose the third option: (97,98) wins round 2 over (257,97) and (257,257), while target rank 0 merges bc first, leaving [97,256]. Comparing string keys can misorder 257 and 97; insertion order is not the tie policy either. Choosing [258,99] because ab is a dictionary prefix switches to longest-prefix lookup. The actual higher-rank rules cannot undo bc or recreate their lower-ID operands, which explains both the counterexample and the one-pass rank proof.

Recap and the planned next-token bridge

  • Learn pair frequencies from the corpus; encode the separate target using fixed learned ranks.
  • Count every adjacent occurrence, break ties by numeric ID tuples, and replace left to right without overlap.
  • The default learns ab/256 then abab/257; target ababab becomes [257,256], with optional tail 512.
  • Expand actual IDs to bytes, concatenate everything, strictly decode, then compare with the originals.

The planned next chapter, IV-40 — Autoregressive Next-Token Prediction, asks which token comes next given earlier tokens. This chapter supplies the reversible IDs that define those positions; it does not yet assign next-token probabilities or train a language model.