The neural notebook
← All chapters

IV-38 / Part IX · Tokenization

Subwords and Vocabulary Trade-Offs

Compare actual character, byte and greedy subword streams, hand-decode each, and inspect vocabulary size, Unicode fallback and explicit EOS.

Review the ideas this chapter uses

Sending one ID for every byte works, but a familiar word can occupy many positions. Could we give common pieces their own IDs and use fewer positions? Yes, if encoder and decoder share the same piece vocabulary. We will compare three actual representations of one text, then account for what each gains and requires.

Learning objective: Compare character, byte and subword granularity on sample texts.

Compute it yourself

Subwords and Vocabulary Trade-Offs

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 32 UTF-8 bytes per text field and reports longer input explicitly.

byteCount9
characterTokens9
byteTokens9
subwordTokens3

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

byteCount 9. characterTokens 9. byteTokens 9. subwordTokens 3. Declare three independent token vocabularies. Every stream preserves the same exact input. The fixed dictionary is not trained, and character means scalar, not grapheme. All controls are validated before any text semantics.

Declare three independent token vocabularies

characterID=1024+cp; byteID=byte; active subwords=first vocabLimit entries

Every stream preserves the same exact input. The fixed dictionary is not trained, and character means scalar, not grapheme. All controls are validated before any text semantics.

Saved inputs

vocabLimit
8
eos
0

Saved outputs

utf16Units
9
scalarCount
9
byteBound
32
characterBase
1024
EOS
512

From exact text to reversible IDs

Original input, escaped: "lower low". Every table and reverse-decoding result below comes from this same saved computation. A token is one vocabulary item identified by an integer; a tensor is an array of numbers with a named shape.

Unicode scalars name code points. A grapheme is a perceived text unit that can contain several scalars, such as an accented letter built with a combining mark or an emoji joined by a zero-width joiner. This lab counts scalars and does not implement grapheme segmentation. An ID’s numeric size says nothing about semantic distance.

Every scalar’s real UTF-16 position and UTF-8 expansion

Scalar indexCode point (decimal)UTF-16 offsetUTF-16 widthByte offsetByte widthActual bytes
01080101108
11111111111
21192121119
31013131101
41144141114
532515132
61086161108
71117171111
81198181119

A UTF-8 byte has eight bits. Continuation bytes start with binary 10, leaving six payload bits: values 0..63. Therefore moving to the next payload group multiplies the previous accumulator by 64. Lead prefixes 0, 110, 1110 and 11110 identify widths 1, 2, 3 and 4; they are removed before reconstruction. Inspect the saved payload and accumulator fields for every scalar below.

Every scalar encoding, including payload groups and UTF-16 units (9 saved operations)

source_scalar_0: Encode scalar 0: U+006C

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.

SideSaved fieldExact integer
inputsscalarIndex0
inputsutf16Offset0
inputsutf16Width1
inputscodePoint108
inputsunit0108
outputsbyteOffset0
outputsbyteWidth1
outputspayload0108
outputsbyte0108

source_scalar_1: Encode scalar 1: U+006F

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.

SideSaved fieldExact integer
inputsscalarIndex1
inputsutf16Offset1
inputsutf16Width1
inputscodePoint111
inputsunit0111
outputsbyteOffset1
outputsbyteWidth1
outputspayload0111
outputsbyte0111

source_scalar_2: Encode scalar 2: U+0077

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.

SideSaved fieldExact integer
inputsscalarIndex2
inputsutf16Offset2
inputsutf16Width1
inputscodePoint119
inputsunit0119
outputsbyteOffset2
outputsbyteWidth1
outputspayload0119
outputsbyte0119

source_scalar_3: Encode scalar 3: U+0065

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.

SideSaved fieldExact integer
inputsscalarIndex3
inputsutf16Offset3
inputsutf16Width1
inputscodePoint101
inputsunit0101
outputsbyteOffset3
outputsbyteWidth1
outputspayload0101
outputsbyte0101

source_scalar_4: Encode scalar 4: U+0072

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.

SideSaved fieldExact integer
inputsscalarIndex4
inputsutf16Offset4
inputsutf16Width1
inputscodePoint114
inputsunit0114
outputsbyteOffset4
outputsbyteWidth1
outputspayload0114
outputsbyte0114

source_scalar_5: Encode scalar 5: U+0020

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.

SideSaved fieldExact integer
inputsscalarIndex5
inputsutf16Offset5
inputsutf16Width1
inputscodePoint32
inputsunit032
outputsbyteOffset5
outputsbyteWidth1
outputspayload032
outputsbyte032

source_scalar_6: Encode scalar 6: U+006C

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.

SideSaved fieldExact integer
inputsscalarIndex6
inputsutf16Offset6
inputsutf16Width1
inputscodePoint108
inputsunit0108
outputsbyteOffset6
outputsbyteWidth1
outputspayload0108
outputsbyte0108

source_scalar_7: Encode scalar 7: U+006F

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.

SideSaved fieldExact integer
inputsscalarIndex7
inputsutf16Offset7
inputsutf16Width1
inputscodePoint111
inputsunit0111
outputsbyteOffset7
outputsbyteWidth1
outputspayload0111
outputsbyte0111

source_scalar_8: Encode scalar 8: U+0077

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.

SideSaved fieldExact integer
inputsscalarIndex8
inputsutf16Offset8
inputsutf16Width1
inputscodePoint119
inputsunit0119
outputsbyteOffset8
outputsbyteWidth1
outputspayload0119
outputsbyte0119

Character / scalar vocabulary: every ID and byte expansion

Exact reconstructed text: "lower low". JSON quotes mark string boundaries; an empty string is "". EOS has an empty expansion and contributes no text.

Token index (zero based)Actual IDModel-saved piece labelUTF-8 byte expansion (decimal)
01132"l" U+006C[108]
11135"o" U+006F[111]
21143"w" U+0077[119]
31125"e" U+0065[101]
41138"r" U+0072[114]
51056" " U+0020[32]
61132"l" U+006C[108]
71135"o" U+006F[111]
81143"w" U+0077[119]

Byte vocabulary: every ID and byte expansion

Exact reconstructed text: "lower low". JSON quotes mark string boundaries; an empty string is "". EOS has an empty expansion and contributes no text.

Token index (zero based)Actual IDModel-saved piece labelUTF-8 byte expansion (decimal)
0108byte 108[108]
1111byte 111[111]
2119byte 119[119]
3101byte 101[101]
4114byte 114[114]
532byte 32[32]
6108byte 108[108]
7111byte 111[111]
8119byte 119[119]

Greedy subwords with byte fallback: every ID and byte expansion

Exact reconstructed text: "lower low". JSON quotes mark string boundaries; an empty string is "". EOS has an empty expansion and contributes no text.

Token index (zero based)Actual IDModel-saved piece labelUTF-8 byte expansion (decimal)
0385"lower"[108,111,119,101,114]
132byte 32[32]
2384"low"[108,111,119]

Vocabulary size and sequence length measure different things

SchemePossible vocabulary items, including reserved EOSTokens for this input, including EOS only if enabled
Unicode scalar11120659
Byte2579
Greedy subword plus bytes2653

There are 1,112,064 legal Unicode scalars: 0x110000 code points minus 0x800 surrogate code points. Character IDs add 1024 to each scalar, leaving unused holes; this is an algorithmic comparison vocabulary, with no million-row embedding matrix allocated. The byte scheme needs 256 possible bytes. The greedy scheme adds the active dictionary entries to those bytes. Each also reserves one EOS item.

The actual active fixed dictionary

Entry IDSaved piece labelActual byte expansion
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

At each byte offset, examine only active entries. Save every actual matching candidate, choose the longest byte expansion, break equal-length subword ties by lower ID, and advance by its byte width. A matching one-byte entry such as “a” is still a dictionary token. If none matches, emit the current byte ID and advance by one. No word splitting or whitespace deletion occurs.

Every character-ID mapping and optional EOS append (9 saved operations)

char_token_0: Character scalar 0 gets an algorithmic ID

id=1024+codePoint

This invertible namespace has holes for surrogate code points and does not allocate a dense embedding table.

SideSaved fieldExact integer
inputsindex0
inputscodePoint108
inputsutf16Offset0
outputsid1132

char_token_1: Character scalar 1 gets an algorithmic ID

id=1024+codePoint

This invertible namespace has holes for surrogate code points and does not allocate a dense embedding table.

SideSaved fieldExact integer
inputsindex1
inputscodePoint111
inputsutf16Offset1
outputsid1135

char_token_2: Character scalar 2 gets an algorithmic ID

id=1024+codePoint

This invertible namespace has holes for surrogate code points and does not allocate a dense embedding table.

SideSaved fieldExact integer
inputsindex2
inputscodePoint119
inputsutf16Offset2
outputsid1143

char_token_3: Character scalar 3 gets an algorithmic ID

id=1024+codePoint

This invertible namespace has holes for surrogate code points and does not allocate a dense embedding table.

SideSaved fieldExact integer
inputsindex3
inputscodePoint101
inputsutf16Offset3
outputsid1125

char_token_4: Character scalar 4 gets an algorithmic ID

id=1024+codePoint

This invertible namespace has holes for surrogate code points and does not allocate a dense embedding table.

SideSaved fieldExact integer
inputsindex4
inputscodePoint114
inputsutf16Offset4
outputsid1138

char_token_5: Character scalar 5 gets an algorithmic ID

id=1024+codePoint

This invertible namespace has holes for surrogate code points and does not allocate a dense embedding table.

SideSaved fieldExact integer
inputsindex5
inputscodePoint32
inputsutf16Offset5
outputsid1056

char_token_6: Character scalar 6 gets an algorithmic ID

id=1024+codePoint

This invertible namespace has holes for surrogate code points and does not allocate a dense embedding table.

SideSaved fieldExact integer
inputsindex6
inputscodePoint108
inputsutf16Offset6
outputsid1132

char_token_7: Character scalar 7 gets an algorithmic ID

id=1024+codePoint

This invertible namespace has holes for surrogate code points and does not allocate a dense embedding table.

SideSaved fieldExact integer
inputsindex7
inputscodePoint111
inputsutf16Offset7
outputsid1135

char_token_8: Character scalar 8 gets an algorithmic ID

id=1024+codePoint

This invertible namespace has holes for surrogate code points and does not allocate a dense embedding table.

SideSaved fieldExact integer
inputsindex8
inputscodePoint119
inputsutf16Offset8
outputsid1143
Every byte-ID mapping and optional EOS append (9 saved operations)

byte_token_0: Byte 0 gets its declared ID

id=byte

One Unicode scalar may contribute several byte tokens; every byte is retained.

SideSaved fieldExact integer
inputsindex0
inputsbyte108
outputsid108

byte_token_1: Byte 1 gets its declared ID

id=byte

One Unicode scalar may contribute several byte tokens; every byte is retained.

SideSaved fieldExact integer
inputsindex1
inputsbyte111
outputsid111

byte_token_2: Byte 2 gets its declared ID

id=byte

One Unicode scalar may contribute several byte tokens; every byte is retained.

SideSaved fieldExact integer
inputsindex2
inputsbyte119
outputsid119

byte_token_3: Byte 3 gets its declared ID

id=byte

One Unicode scalar may contribute several byte tokens; every byte is retained.

SideSaved fieldExact integer
inputsindex3
inputsbyte101
outputsid101

byte_token_4: Byte 4 gets its declared ID

id=byte

One Unicode scalar may contribute several byte tokens; every byte is retained.

SideSaved fieldExact integer
inputsindex4
inputsbyte114
outputsid114

byte_token_5: Byte 5 gets its declared ID

id=byte

One Unicode scalar may contribute several byte tokens; every byte is retained.

SideSaved fieldExact integer
inputsindex5
inputsbyte32
outputsid32

byte_token_6: Byte 6 gets its declared ID

id=byte

One Unicode scalar may contribute several byte tokens; every byte is retained.

SideSaved fieldExact integer
inputsindex6
inputsbyte108
outputsid108

byte_token_7: Byte 7 gets its declared ID

id=byte

One Unicode scalar may contribute several byte tokens; every byte is retained.

SideSaved fieldExact integer
inputsindex7
inputsbyte111
outputsid111

byte_token_8: Byte 8 gets its declared ID

id=byte

One Unicode scalar may contribute several byte tokens; every byte is retained.

SideSaved fieldExact integer
inputsindex8
inputsbyte119
outputsid119
Every greedy candidate list, actual choice and optional EOS append (3 saved operations)

subword_decision_0: Choose subword at byte offset 0

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.

SideSaved fieldExact integer
inputsbyteOffset0
inputsremaining9
inputscandidateMatches2
inputscandidate0ID384
inputscandidate0Width3
inputscandidate1ID385
inputscandidate1Width5
outputsid385
outputsbyteWidth5
outputsnextByteOffset5

subword_decision_1: Choose subword at byte offset 5

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.

SideSaved fieldExact integer
inputsbyteOffset5
inputsremaining4
inputscandidateMatches0
outputsid32
outputsbyteWidth1
outputsnextByteOffset6

subword_decision_2: Choose subword at byte offset 6

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.

SideSaved fieldExact integer
inputsbyteOffset6
inputsremaining3
inputscandidateMatches1
inputscandidate0ID384
inputscandidate0Width3
outputsid384
outputsbyteWidth3
outputsnextByteOffset9
Every character-ID inverse and optional EOS strip (9 saved operations)

char_inverse_0: Character ID 0: 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.

SideSaved fieldExact integer
inputsindex0
inputsid1132
outputscodePoint108
outputsutf16Width1
outputsunit0108

char_inverse_1: Character ID 1: 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.

SideSaved fieldExact integer
inputsindex1
inputsid1135
outputscodePoint111
outputsutf16Width1
outputsunit0111

char_inverse_2: Character ID 2: 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.

SideSaved fieldExact integer
inputsindex2
inputsid1143
outputscodePoint119
outputsutf16Width1
outputsunit0119

char_inverse_3: Character ID 3: 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.

SideSaved fieldExact integer
inputsindex3
inputsid1125
outputscodePoint101
outputsutf16Width1
outputsunit0101

char_inverse_4: Character ID 4: 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.

SideSaved fieldExact integer
inputsindex4
inputsid1138
outputscodePoint114
outputsutf16Width1
outputsunit0114

char_inverse_5: Character ID 5: 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.

SideSaved fieldExact integer
inputsindex5
inputsid1056
outputscodePoint32
outputsutf16Width1
outputsunit032

char_inverse_6: Character ID 6: 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.

SideSaved fieldExact integer
inputsindex6
inputsid1132
outputscodePoint108
outputsutf16Width1
outputsunit0108

char_inverse_7: Character ID 7: 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.

SideSaved fieldExact integer
inputsindex7
inputsid1135
outputscodePoint111
outputsutf16Width1
outputsunit0111

char_inverse_8: Character ID 8: 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.

SideSaved fieldExact integer
inputsindex8
inputsid1143
outputscodePoint119
outputsutf16Width1
outputsunit0119
Every byte-ID expansion and optional EOS strip (9 saved operations)

byte_expand_0: byte: expand ID at token 0

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.

SideSaved fieldExact integer
inputsindex0
inputsid108
outputsbyteOffset0
outputsbyteWidth1
outputsbyte0108

byte_expand_1: byte: expand ID at token 1

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.

SideSaved fieldExact integer
inputsindex1
inputsid111
outputsbyteOffset1
outputsbyteWidth1
outputsbyte0111

byte_expand_2: byte: expand ID at token 2

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.

SideSaved fieldExact integer
inputsindex2
inputsid119
outputsbyteOffset2
outputsbyteWidth1
outputsbyte0119

byte_expand_3: byte: expand ID at token 3

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.

SideSaved fieldExact integer
inputsindex3
inputsid101
outputsbyteOffset3
outputsbyteWidth1
outputsbyte0101

byte_expand_4: byte: expand ID at token 4

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.

SideSaved fieldExact integer
inputsindex4
inputsid114
outputsbyteOffset4
outputsbyteWidth1
outputsbyte0114

byte_expand_5: byte: expand ID at token 5

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.

SideSaved fieldExact integer
inputsindex5
inputsid32
outputsbyteOffset5
outputsbyteWidth1
outputsbyte032

byte_expand_6: byte: expand ID at token 6

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.

SideSaved fieldExact integer
inputsindex6
inputsid108
outputsbyteOffset6
outputsbyteWidth1
outputsbyte0108

byte_expand_7: byte: expand ID at token 7

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.

SideSaved fieldExact integer
inputsindex7
inputsid111
outputsbyteOffset7
outputsbyteWidth1
outputsbyte0111

byte_expand_8: byte: expand ID at token 8

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.

SideSaved fieldExact integer
inputsindex8
inputsid119
outputsbyteOffset8
outputsbyteWidth1
outputsbyte0119
Every byte-stream strict UTF-8 reconstruction (9 saved operations)

byte_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.

SideSaved fieldExact integer
inputsscalarIndex0
inputsbyteOffset0
inputsbyteWidth1
inputsbyte0108
outputspayload0108
outputsaccumulator0108
outputscodePoint108
outputsutf16Width1
outputsunit0108

byte_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.

SideSaved fieldExact integer
inputsscalarIndex1
inputsbyteOffset1
inputsbyteWidth1
inputsbyte0111
outputspayload0111
outputsaccumulator0111
outputscodePoint111
outputsutf16Width1
outputsunit0111

byte_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.

SideSaved fieldExact integer
inputsscalarIndex2
inputsbyteOffset2
inputsbyteWidth1
inputsbyte0119
outputspayload0119
outputsaccumulator0119
outputscodePoint119
outputsutf16Width1
outputsunit0119

byte_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.

SideSaved fieldExact integer
inputsscalarIndex3
inputsbyteOffset3
inputsbyteWidth1
inputsbyte0101
outputspayload0101
outputsaccumulator0101
outputscodePoint101
outputsutf16Width1
outputsunit0101

byte_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.

SideSaved fieldExact integer
inputsscalarIndex4
inputsbyteOffset4
inputsbyteWidth1
inputsbyte0114
outputspayload0114
outputsaccumulator0114
outputscodePoint114
outputsutf16Width1
outputsunit0114

byte_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.

SideSaved fieldExact integer
inputsscalarIndex5
inputsbyteOffset5
inputsbyteWidth1
inputsbyte032
outputspayload032
outputsaccumulator032
outputscodePoint32
outputsutf16Width1
outputsunit032

byte_decode_6: Decode UTF-8 scalar 6

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.

SideSaved fieldExact integer
inputsscalarIndex6
inputsbyteOffset6
inputsbyteWidth1
inputsbyte0108
outputspayload0108
outputsaccumulator0108
outputscodePoint108
outputsutf16Width1
outputsunit0108

byte_decode_7: Decode UTF-8 scalar 7

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.

SideSaved fieldExact integer
inputsscalarIndex7
inputsbyteOffset7
inputsbyteWidth1
inputsbyte0111
outputspayload0111
outputsaccumulator0111
outputscodePoint111
outputsutf16Width1
outputsunit0111

byte_decode_8: Decode UTF-8 scalar 8

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.

SideSaved fieldExact integer
inputsscalarIndex8
inputsbyteOffset8
inputsbyteWidth1
inputsbyte0119
outputspayload0119
outputsaccumulator0119
outputscodePoint119
outputsutf16Width1
outputsunit0119
Every subword expansion and optional EOS strip (3 saved operations)

subword_expand_0: subword: expand ID at token 0

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.

SideSaved fieldExact integer
inputsindex0
inputsid385
outputsbyteOffset0
outputsbyteWidth5
outputsbyte0108
outputsbyte1111
outputsbyte2119
outputsbyte3101
outputsbyte4114

subword_expand_1: subword: expand ID at token 1

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.

SideSaved fieldExact integer
inputsindex1
inputsid32
outputsbyteOffset5
outputsbyteWidth1
outputsbyte032

subword_expand_2: subword: expand ID at token 2

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.

SideSaved fieldExact integer
inputsindex2
inputsid384
outputsbyteOffset6
outputsbyteWidth3
outputsbyte0108
outputsbyte1111
outputsbyte2119
Every subword-stream strict UTF-8 reconstruction (9 saved operations)

subword_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.

SideSaved fieldExact integer
inputsscalarIndex0
inputsbyteOffset0
inputsbyteWidth1
inputsbyte0108
outputspayload0108
outputsaccumulator0108
outputscodePoint108
outputsutf16Width1
outputsunit0108

subword_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.

SideSaved fieldExact integer
inputsscalarIndex1
inputsbyteOffset1
inputsbyteWidth1
inputsbyte0111
outputspayload0111
outputsaccumulator0111
outputscodePoint111
outputsutf16Width1
outputsunit0111

subword_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.

SideSaved fieldExact integer
inputsscalarIndex2
inputsbyteOffset2
inputsbyteWidth1
inputsbyte0119
outputspayload0119
outputsaccumulator0119
outputscodePoint119
outputsutf16Width1
outputsunit0119

subword_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.

SideSaved fieldExact integer
inputsscalarIndex3
inputsbyteOffset3
inputsbyteWidth1
inputsbyte0101
outputspayload0101
outputsaccumulator0101
outputscodePoint101
outputsutf16Width1
outputsunit0101

subword_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.

SideSaved fieldExact integer
inputsscalarIndex4
inputsbyteOffset4
inputsbyteWidth1
inputsbyte0114
outputspayload0114
outputsaccumulator0114
outputscodePoint114
outputsutf16Width1
outputsunit0114

subword_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.

SideSaved fieldExact integer
inputsscalarIndex5
inputsbyteOffset5
inputsbyteWidth1
inputsbyte032
outputspayload032
outputsaccumulator032
outputscodePoint32
outputsutf16Width1
outputsunit032

subword_decode_6: Decode UTF-8 scalar 6

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.

SideSaved fieldExact integer
inputsscalarIndex6
inputsbyteOffset6
inputsbyteWidth1
inputsbyte0108
outputspayload0108
outputsaccumulator0108
outputscodePoint108
outputsutf16Width1
outputsunit0108

subword_decode_7: Decode UTF-8 scalar 7

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.

SideSaved fieldExact integer
inputsscalarIndex7
inputsbyteOffset7
inputsbyteWidth1
inputsbyte0111
outputspayload0111
outputsaccumulator0111
outputscodePoint111
outputsutf16Width1
outputsunit0111

subword_decode_8: Decode UTF-8 scalar 8

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.

SideSaved fieldExact integer
inputsscalarIndex8
inputsbyteOffset8
inputsbyteWidth1
inputsbyte0119
outputspayload0119
outputsaccumulator0119
outputscodePoint119
outputsutf16Width1
outputsunit0119

Try “猫”: one scalar needs three UTF-8 bytes and, with this ASCII dictionary, three fallback subword tokens. A fallback byte need not be valid text on its own; the decoder concatenates all expansions before strict UTF-8 decoding. A larger fixed dictionary is not a claim about model quality, speed or the best tokenization for every language. This greedy dictionary lookup differs from the ranked pair-merge algorithm introduced in IV-39.

Actual roundtrip equality and counts after reconstruction (1 saved operations)

roundtrip: Compare all three actual reconstructions

eachEqual=(actualDecoded===input)

Three decoders independently reconstruct text from actual IDs. Token counts include explicit EOS; source byte and scalar counts do not.

SideSaved fieldExact integer
inputsoriginalUnits9
inputscharacterDecodedUnits9
inputsbyteDecodedUnits9
inputssubwordDecodedUnits9
outputscharacterTokens9
outputsbyteTokens9
outputssubwordTokens3
outputscharacterEqual1
outputsbyteEqual1
outputssubwordEqual1

Zero bytes does not mean a hidden zero byte: empty text has empty content streams. Enabling EOS adds one token to each stream but no text. U+0000 is different: it is an actual scalar encoded as byte 0. U+FEFF is ordinary data here. Noncharacters such as U+FFFF are valid scalars; surrogate code points are not.

“é” uses scalar 233 and bytes [195,169]. “e” plus a combining acute uses two scalars and bytes [101,204,129]. They can look alike while remaining different input. The lab preserves this distinction, performs no normalization, and reports malformed surrogate input instead of silently inserting a replacement character.

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.

CodePoints

Scalars=9 · int32 · precision 0 · Validated source scalars, not grapheme clusters.

Zero-based storage indexExact integer
0108
1111
2119
3101
4114
532
6108
7111
8119

Bytes

Bytes=9 · int32 · precision 0 · Manual UTF-8 encoding shared by the byte and greedy encoders.

Zero-based storage indexExact integer
0108
1111
2119
3101
4114
532
6108
7111
8119

CharacterIDs

CharacterTokens=9 · int32 · precision 0 · 1024 plus each scalar, followed by explicit optional EOS.

Zero-based storage indexExact integer
01132
11135
21143
31125
41138
51056
61132
71135
81143

ByteIDs

ByteTokens=9 · int32 · precision 0 · Byte-valued IDs, followed by explicit optional EOS.

Zero-based storage indexExact integer
0108
1111
2119
3101
4114
532
6108
7111
8119

SubwordIDs

SubwordTokens=3 · int32 · precision 0 · Actual longest-match decisions with byte fallback and explicit optional EOS.

Zero-based storage indexExact integer
0385
132
2384

Vocab384Bytes

PieceBytes=3 · int32 · precision 0 · Fixed authored dictionary entry; no learned parameters.

Zero-based storage indexExact integer
0108
1111
2119

Vocab385Bytes

PieceBytes=5 · int32 · precision 0 · Fixed authored dictionary entry; no learned parameters.

Zero-based storage indexExact integer
0108
1111
2119
3101
4114

Vocab386Bytes

PieceBytes=6 · int32 · precision 0 · Fixed authored dictionary entry; no learned parameters.

Zero-based storage indexExact integer
0108
1111
2119
3101
4115
5116

Vocab387Bytes

PieceBytes=2 · int32 · precision 0 · Fixed authored dictionary entry; no learned parameters.

Zero-based storage indexExact integer
0101
1114

Vocab388Bytes

PieceBytes=3 · int32 · precision 0 · Fixed authored dictionary entry; no learned parameters.

Zero-based storage indexExact integer
0101
1115
2116

Vocab389Bytes

PieceBytes=3 · int32 · precision 0 · Fixed authored dictionary entry; no learned parameters.

Zero-based storage indexExact integer
0105
1110
2103

Vocab390Bytes

PieceBytes=1 · int32 · precision 0 · Fixed authored dictionary entry; no learned parameters.

Zero-based storage indexExact integer
097

Vocab391Bytes

PieceBytes=2 · int32 · precision 0 · Fixed authored dictionary entry; no learned parameters.

Zero-based storage indexExact integer
097
198

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 is compared by the three streams in this lab?
2. For lower low, all eight subwords active and EOS off, which greedy ID sequence is produced?
3. Saved subword_decision_0 starts at byteOffset=0 with candidateMatches=2. Which current choice and mechanism are correct?
4. Keep lower low fixed with EOS off. Set vocabLimit from 8 to 1. What happens?
5. With the fixed ASCII dictionary and EOS off, how is 猫 represented by the three schemes?

At reset, lower low has bytes [108,111,119,101,114,32,108,111,119]. Scalar IDs add 1024, giving [1132,1135,1143,1125,1138,1056,1132,1135,1143]. Byte IDs equal the nine source bytes. The actual greedy stream [385,32,384] uses lower, a preserved space byte, then low. Reverse expansions concatenate five, one and three bytes before strict UTF-8 decoding.

Try prefix length 1, then 0: the greedy counts become five and nine with EOS off. Try a, then ab at prefix lengths 7 and 8 to see a real one-byte dictionary entry compete with a longer matching entry. Try é, 猫, a combining accent, a line break, or empty text. Every stream remains visible and every actual reconstruction is checked.

The fixed dictionary illustrates a trade-off, not an optimal tokenizer or a trained model. Larger possible vocabulary and shorter sequences are different quantities; no embedding-memory, speed or accuracy benchmark is being claimed. The next chapter learns ranked byte-pair merges, whose training and encoding rules differ from this longest-prefix lookup.

Reset starts with lower low, eight active subword entries and EOS off. The lab computes all three streams: 9 character tokens, 9 byte tokens and 3 greedy subword tokens. Reduce the active entry count to 1: the same text now needs 5 subword tokens. Nothing about the text’s meaning changed. We changed which byte sequences have a shared short name.

Review IV-37 — From Unicode Text to Token IDs for scalars, strict UTF-8 and the difference between bytes and IDs. IV-16 — Token IDs and Embedding Lookup Tables explains the later embedding lookup. Book II’s II.9 — Matrix × vector helps connect vocabulary rows to vector lookup; Book III’s III-18 — Distance Metrics and Curse of Dimensionality explains why representation choices matter when comparing data. The vocabularies here are authored teaching rules, with no corpus training, benchmark or model-quality measurement.

Vocabulary before the comparison

A vocabulary specifies the items an ID may name. A character tokenizer in this chapter emits one ID per Unicode scalar, not per grapheme cluster. A byte tokenizer emits one ID per UTF-8 byte. A subword is a reusable text piece that can be shorter than a word, equal to a word, or cross a boundary in other designs. Here a piece is explicitly a fixed byte sequence; the encoder does not split on spaces first.

Segmentation means choosing the successive pieces that cover the input. Greedy means making the best local choice under a declared rule without exploring all future segmentations. Our rule is: at the current byte offset, choose the matching active entry with the longest byte expansion; break a length tie by the lowest ID. If no entry matches, emit the current byte’s ID and advance one byte. This is byte fallback: unfamiliar text remains representable instead of being dropped or replaced by an unknown-word symbol.

An active prefix of length N means the first N entries in the fixed ordered table below. It does not mean “the N most frequent items in your text.” Entries do not learn or reorder when you type. A longer active prefix may make more matches possible; this is a controlled comparison of this one segmentation algorithm, not an accuracy experiment.

Let S count scalars, B count bytes, and G count greedy tokens before EOS. Let N=vocabLimit be the active entry count, an integer from 0 through 8. The flag e=eos is 0 or 1. Stream lengths are Tchar=S+e, Tbyte=B+e and Tsub=G+e. Each T is a number of sequence positions. An ID is an item name at one position; its decimal digits do not determine how much text it expands to.

Shapes and the three ID namespaces

The tensors here are named numeric lists: CodePoints [S] contains scalars and Bytes [B] contains their UTF-8 encoding. CharacterIDs [Tchar], ByteIDs [Tbyte] and SubwordIDs [Tsub] are separate one-dimensional streams. Each axis counts its named scalars, bytes or stream tokens. For every active entry, Vocab384Bytes through Vocab391Bytes, as applicable, is a separate one-dimensional byte-expansion tensor; entries of different widths are not padded into a fake rectangle. All numeric storage is int32, and the original, piece labels and independently decoded texts live beside it in the same result.

The exact stream axis names are CharacterTokens, ByteTokens and SubwordTokens; each active vocabulary expansion uses PieceBytes. Empty source and ID tensors are omitted independently, while active dictionary tensors still exist because the dictionary is a property of N, not of whether the text contains a match. Tensor precision metadata is 0: all values here are exact integers.

The byte IDs are 0..255. The eight possible extra subword IDs are 384..391. Character IDs use the rule ID=1024+c, where c is a valid Unicode scalar’s decimal number. To reverse a character ID, subtract 1024 and validate the scalar. The character namespace consequently has unused holes for the forbidden surrogate values. Reserved EOS=512 belongs to none of those ordinary namespaces. IDs 256..259 are reserved for the following byte-pair encoding (BPE) lesson and are not valid pieces in this lesson.

There are 0x110000−0x800=1,112,064 possible Unicode scalars: 1,114,112 code-point positions minus 2,048 surrogate positions. The character comparison therefore has 1,112,065 possible items including EOS. The byte vocabulary has 256+1=257; the subword vocabulary has 256+N+1=257+N. These item counts include the one reserved EOS item even when its flag is off. They are theoretical vocabulary sizes, not allocated embedding matrices. The lab applies the character ID formula when needed; it never constructs a million-row table or trains its rows.

The complete fixed piece table

Active when N is at leastIDPieceDecimal byte expansionWidth
1384low108,111,1193
2385lower108,111,119,101,1145
3386lowest108,111,119,101,115,1166
4387er101,1142
5388est101,115,1163
6389ing105,110,1033
7390a971
8391ab97,982

An entry can match only if every byte in its expansion equals the input from the current offset. In lower, lowest fails because its fifth byte would require s=115 where the input has r=114. “Longest” therefore means longest matching entry, not the longest word in the table. Case is preserved: uppercase LOW does not match lowercase low.

Encode all three default streams by hand

The default has nine ASCII scalars and nine equal-valued UTF-8 bytes. A space is the sixth item at zero-based offset 5; it is not a separator to discard.

OffsetItemScalar / byteCharacter ID = 1024 + scalar
0l1081132
1o1111135
2w1191143
3e1011125
4r1141138
5space321056
6l1081132
7o1111135
8w1191143

The character stream is [1132,1135,1143,1125,1138,1056,1132,1135,1143]. The byte stream is [108,111,119,101,114,32,108,111,119]. Each has nine tokens, although they use different ID systems.

Now scan the bytes greedily with all eight entries active. At byte offset 0, both low/384 of width 3 and lower/385 of width 5 match. Lowest/386 does not. Choose 385, emit it, and advance from 0 to 5. At offset 5 no active entry starts with space, so emit fallback byte ID 32 and advance to 6. At offset 6, low/384 matches all three remaining bytes; longer entries cannot fit. Emit 384 and advance to 9, the byte count. Stop. The subword stream is [385,32,384], with lengths 5+1+3=9 bytes covered and 3 tokens.

The trace records the current offset, remaining bytes, matched candidates and selected ID/width for each actual decision. It does not infer the answer from a displayed word label. Selecting a trace step inspects that saved decision; editing input or N recomputes the streams and resets trace position and grades.

Decode all three, including the space

Character decoding subtracts 1024 from every ordinary ID: 1132−1024=108, 1135−1024=111, 1143−1024=119, 1125−1024=101, 1138−1024=114, 1056−1024=32, then 108,111,119 again. Validate each scalar and construct l,o,w,e,r,space,l,o,w in that order. The output is exactly lower low.

Byte decoding expands each byte ID to its equal-valued byte. All nine are ASCII, whose one-byte UTF-8 form begins with 0. Strict decoding consequently reconstructs the same nine scalars and the same text. This is its own decode path, not a copy of the character decoder’s output.

Subword decoding expands ID 385 to [108,111,119,101,114], ID 32 to [32], and ID 384 to [108,111,119]. Concatenate the expansions first, obtaining all nine original bytes, then strictly decode that complete byte stream. No extra spaces are inserted and none are deleted. Again the result is lower low. The final comparison checks the three actual reconstructed strings against the original; a failure makes the result unavailable rather than manufacturing equality.

With EOS enabled, each stream appends 512. Their counts become 10,10,4; all decoded texts remain unchanged. Each decoder permits the marker only once at the tail, requires it when eos=1, and forbids it when eos=0. Literal <eos> remains five ordinary input characters; the flag alone appends the special ID. Inactive subword IDs are invalid even if they exist later in the fixed table. Unknown IDs, illegal EOS positions and malformed UTF-8 are errors, with no replacement string or unknown-token shortcut.

Shrink the vocabulary and account for every token

Set N=1. Only low/384 is active. At offset 0 it covers low, advancing to 3. There is no entry for the following e, so byte ID 101 advances to 4; r gives fallback 114 and advances to 5. Space gives 32 and advances to 6. The last low gives 384 and advances to 9. Thus the actual stream is [384,101,114,32,384], with widths 3+1+1+1+3=9 and 5 tokens. Expanding those five IDs reconstructs precisely the same nine bytes.

With N=0, no extra entry is active: the greedy algorithm emits all nine byte IDs. There are still 256 ordinary byte items available, plus the reserved EOS item; “zero entries” does not mean “no vocabulary.” At N=8, possible vocabulary items are 265 rather than 258 at N=1. This example exchanges seven additional possible pieces for two fewer sequence positions. It does not measure an embedding’s memory footprint: none is allocated here.

For fixed embedding width D, a conventional learned vocabulary table with V rows would have shape [V,D] and contain V·D stored numbers, where D is the number of features per row. Fewer sequence positions can also reduce later attention work, which compares positions with one another. These are reasons vocabulary choices matter. They do not establish actual storage, speed or model accuracy for this lab; those would depend on a real model, implementation and evaluation data.

Unicode fallback and counterexamples

Try 猫. As derived in IV-37, its one scalar U+732B=29483 encodes as decimal bytes [231,140,171], hex E7,8C,AB. The character ID is 1024+29483=30507: one character token. The byte stream has three IDs. No declared subword matches those bytes, so greedy fallback also emits three IDs, [231,140,171]. Neither first byte alone nor an individual continuation byte forms the character. Concatenating the three and strictly decoding gives payload calculation 7·4096+12·64+43=29483 and reconstructs 猫.

Similarly precomposed é has one scalar and two bytes, C3,A9. The decomposed sequence é, U+0065 then U+0301, has two scalars and three bytes, 65,CC,81 in hex. The raw text is never normalized. In this vocabulary neither form has a complete matching subword, so fallback preserves its distinct bytes. One perceived character need not be one scalar token, and one subword token need not be one whole word. A multi-scalar emoji sequence exposes the same distinction.

A greedy longest match is not a global search for the fewest tokens: it does not try every possible future segmentation. Increasing the active prefix changes available candidates; no general claim about model quality or all languages follows. Token counts on these few strings cannot tell us whether a trained system handles a language well. The fixed list is deliberately tiny and does not model a production tokenizer’s normalization, pre-segmentation or vocabulary training.

Empty text has zero tokens in all streams with EOS off, and one EOS token in each with it on. It needs no fabricated first token, padding or tokens-per-character ratio with a zero denominator. NUL has ordinary byte ID 0 and is not an end marker. Whitespace and control characters are preserved and displayed with escaped labels. The shared 32-byte bound rejects oversized input rather than truncating it. N and eos must be supported integers; all raw fields validate before a successful result is shown.

Follow the maintained wrapper and helper

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-38 — Subwords and Vocabulary Trade-Offs.

Compute THREE real streams for the same exact text: character ID=1024+scalar,
byte ID=byte, and longest active byte piece with byte fallback. Every stream
is decoded independently from its actual IDs. This fixed dictionary is not
trained BPE; IV-39 will add learned pair ranks under a separate signed packet.

Hand default 'lower low': bytes [108,111,119,101,114,32,108,111,119].
At byte offset0 both low(ID384,width3) and lower(ID385,width5) match; choose
385. At offset5 the space falls back to32; at offset6 choose384. Result:
[385,32,384], compared with nine byte tokens and nine character tokens.
vocabLimit1 gives [384,101,114,32,384]; limit0 gives all nine bytes.
'猫' has one scalar U+732B=29483=7*4096+12*64+43, three bytes [231,140,171]
and three byte-fallback pieces. NFC é and e+combining-acute remain different.
Possible vocabulary sizes include reserved EOS: 1112065 / 257 / (257+limit).
These counts do not allocate an embedding matrix or prove model quality.

All code is authored source. No import, calculation, test or CLI was executed.
Keep token_reference.py beside this file; paths resolve from __file__.
"""
import importlib.util
from pathlib import Path
from types import MappingProxyType
import numpy as np

_helper_spec = importlib.util.spec_from_file_location(
    "_p09_token_reference", Path(__file__).resolve().with_name("token_reference.py"))
_helper = importlib.util.module_from_spec(_helper_spec)
_helper_spec.loader.exec_module(_helper)

DEFAULT_IV38 = MappingProxyType(dict(_helper.IV38_DEFAULTS))


@_helper.guarded
def derive_iv38(state):
    """Encode three vocabularies, save greedy decisions, decode each actual stream."""
    s = _helper.text_state(state, 38)
    input_text, limit, eos = s["text"], s["vocabLimit"], s["eos"]
    encoding_trace = _helper.TokenTrace()
    encoded = _helper.utf8_encode(input_text, "source", encoding_trace)
    units = _helper.utf16_length(input_text)
    trace = _helper.TokenTrace()
    trace.add("setup", "Declare three independent token vocabularies", "characterID=1024+cp; byteID=byte; active subwords=first vocabLimit entries",
              "Every stream preserves the same exact input. The fixed dictionary is not trained, and character means scalar, not grapheme. All controls are validated before any text semantics.",
              dict(vocabLimit=limit, eos=eos),
              dict(utf16Units=units, scalarCount=len(encoded["codePoints"]), byteBound=_helper.BYTE_BOUND,
                   characterBase=_helper.CHARACTER_BASE, EOS=_helper.EOS))
    trace.steps.extend(encoding_trace.steps)
    # Add the namespace base with Python ints, then store the actual int32 IDs.
    character_ids = np.array([_helper.CHARACTER_BASE + int(cp) for cp in encoded["codePoints"]], dtype=np.int32)
    for index, stored in enumerate(encoded["codePoints"]):
        cp = int(stored)
        trace.add(f"char_token_{index}", f"Character scalar {index} gets an algorithmic ID", "id=1024+codePoint",
                  "This invertible namespace has holes for surrogate code points and does not allocate a dense embedding table.",
                  dict(index=index, codePoint=cp, utf16Offset=int(encoded["offsets"][index])), dict(id=int(character_ids[index])))
    character_ids = _helper.append_eos(character_ids, eos, "char", trace)
    byte_ids = encoded["bytes"].copy()
    for index, stored in enumerate(encoded["bytes"]):
        byte = int(stored)
        trace.add(f"byte_token_{index}", f"Byte {index} gets its declared ID", "id=byte",
                  "One Unicode scalar may contribute several byte tokens; every byte is retained.",
                  dict(index=index, byte=byte), dict(id=byte))
    byte_ids = _helper.append_eos(byte_ids, eos, "byte", trace)
    subword_ids = _helper.greedy_ids(encoded["bytes"], limit, trace)
    subword_ids = _helper.append_eos(subword_ids, eos, "subword", trace)
    character_decoded = _helper.decode_character_ids(character_ids, eos, "char", trace)
    byte_decoded = _helper.decode_byte_ids(byte_ids, eos, "byte", trace)
    subword_decoded = _helper.decode_subword_ids(subword_ids, eos, limit, "subword", trace)
    character_equal = int(character_decoded == input_text)
    byte_equal = int(byte_decoded["decoded"] == input_text)
    subword_equal = int(subword_decoded["decoded"] == input_text)
    if not (character_equal and byte_equal and subword_equal):
        raise _helper.NumericalFault("INVALID_INPUT", "An actual token stream did not reconstruct the original text.")
    trace.add("roundtrip", "Compare all three actual reconstructions", "eachEqual=(actualDecoded===input)",
              "Three decoders independently reconstruct text from actual IDs. Token counts include explicit EOS; source byte and scalar counts do not.",
              dict(originalUnits=units, characterDecodedUnits=_helper.utf16_length(character_decoded),
                   byteDecodedUnits=_helper.utf16_length(byte_decoded["decoded"]), subwordDecodedUnits=_helper.utf16_length(subword_decoded["decoded"])),
              dict(characterTokens=len(character_ids), byteTokens=len(byte_ids), subwordTokens=len(subword_ids),
                   characterEqual=character_equal, byteEqual=byte_equal, subwordEqual=subword_equal))
    character_labels, character_expansions = [], []
    for index, character in enumerate(input_text):
        cp = int(encoded["codePoints"][index])
        character_labels.append(f"{_helper.json_text(character)} U+{cp:04X}")
        start, width = int(encoded["byteOffsets"][index]), int(encoded["byteWidths"][index])
        character_expansions.append(_helper.json_text(encoded["bytes"][start:start + width].tolist()))
    if eos == 1:
        character_labels.append("EOS (explicit control)")
        character_expansions.append("[]")
    tensors = []
    for identifier, axis, values, provenance in (
        ("CodePoints", "Scalars", encoded["codePoints"], "Validated source scalars, not grapheme clusters."),
        ("Bytes", "Bytes", encoded["bytes"], "Manual UTF-8 encoding shared by the byte and greedy encoders."),
        ("CharacterIDs", "CharacterTokens", character_ids, "1024 plus each scalar, followed by explicit optional EOS."),
        ("ByteIDs", "ByteTokens", byte_ids, "Byte-valued IDs, followed by explicit optional EOS."),
        ("SubwordIDs", "SubwordTokens", subword_ids, "Actual longest-match decisions with byte fallback and explicit optional EOS."),
    ):
        if len(values):
            tensors.append(_helper.tensor(identifier, axis, values, provenance))
    for identifier, _, expansion in _helper.SUBWORDS[:limit]:
        values = np.array(expansion, dtype=np.int32)
        tensors.append(_helper.tensor(f"Vocab{identifier}Bytes", "PieceBytes", values,
                                      "Fixed authored dictionary entry; no learned parameters."))
    labels = {identifier: label for identifier, label, _ in _helper.SUBWORDS[:limit]}
    expansions = {identifier: expansion for identifier, _, expansion in _helper.SUBWORDS[:limit]}
    subword_labels, subword_expansions = [], []
    for stored in subword_ids:
        identifier = int(stored)
        subword_labels.append("EOS (explicit control)" if identifier == _helper.EOS else
                              f"byte {identifier}" if identifier <= 255 else _helper.json_text(labels[identifier]))
        expansion = [] if identifier == _helper.EOS else [identifier] if identifier <= 255 else expansions[identifier]
        subword_expansions.append(_helper.json_text(expansion))
    summary = dict(byteCount=len(encoded["bytes"]), characterTokens=len(character_ids), byteTokens=len(byte_ids), subwordTokens=len(subword_ids),
                   scalarCount=len(encoded["codePoints"]), utf16Units=units, activeSubwordEntries=limit,
                   characterVocabularyItems=1112065, byteVocabularyItems=257, subwordVocabularyItems=257 + limit, eos=eos, EOS=_helper.EOS)
    texts = dict(input=input_text, characterDecoded=character_decoded, byteDecoded=byte_decoded["decoded"], subwordDecoded=subword_decoded["decoded"],
                 characterLabels=character_labels, characterExpansions=character_expansions,
                 byteLabels=_helper.byte_labels(byte_ids), byteExpansions=_helper.byte_expansions(byte_ids),
                 subwordLabels=subword_labels, subwordExpansions=subword_expansions,
                 vocabularyLabels=[_helper.json_text(label) for _, label, _ in _helper.SUBWORDS[:limit]])
    return trace.result(summary, tensors, texts)


if __name__ == "__main__":
    _helper.run(derive_iv38, DEFAULT_IV38)
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 disclosures load the actual iv38.py wrapper and token_reference.py helper as raw repository text. The wrapper creates all three streams, records real greedy decisions, decodes the three independently and saves counts and equality flags. The helper supplies strict Unicode conversion, ID validation and shared result construction. NumPy stores the integer arrays; scalar loops and explicit byte expansions specify the algorithm.

Read derive_iv38 as the orchestration: utf8_encode supplies the shared source bytes; the wrapper adds 1024 to each scalar for character IDs and copies bytes for byte IDs; greedy_ids scans active pieces. Each stream gets its own optional append_eos. The three inverse calls are decode_character_ids, decode_byte_ids and decode_subword_ids. The latter two expand IDs and call utf8_decode on concatenated bytes. Only after those calls does the wrapper calculate the three equality flags and build the ordered tensors/texts. TokenTrace.result packages that evidence. Keep the helper beside the wrapper; its loading path is resolved from the wrapper file itself.

Follow the encoder’s scalar order, the byte order, then each greedy offset. During decoding, distinguish a token’s expansion from a Unicode scalar: byte fallback can split one scalar across several tokens, so UTF-8 decoding happens after concatenation. Read piece labels as metadata from the same result, not as an alternative source of bytes. Invalid state discards the whole successful record, so a previous decoded answer is not evidence for a new invalid input.

The saved order is setup, source_scalar_i, char_token_i, byte_token_j, subword_decision_k, then char_inverse_i, the byte stream’s byte_expand_j and byte_decode_i, the subword stream’s subword_expand_k and subword_decode_i, and finally roundtrip. Here i indexes scalars, j byte tokens and k subword tokens. Each optional EOS emission follows its encoder’s content; each optional strip follows that decoder’s content inverses or expansions and precedes UTF-8 decoding. A greedy record saves candidateMatches, each matching candidate’s ID and width, then id, byteWidth and nextByteOffset. At reset decision 0 therefore saves candidates 384/3 and 385/5 and advances to 5. Reading these operands explains the choice without re-running matching in the view.

Five graded questions and how to correct a mistake

These are the actual five questions in the lab, with explanations for the wrong turns. Select the value and mechanism together in the live question. Its saved first decision remains the question’s target even when Calculation step inspects another operation. Active prefix of the fixed subword dictionary changes N; Append explicit end-of-sequence (EOS) controls the optional marker. Editing either control or the text clears grades and restarts the trace.

  1. three-streams: What is being compared? Choose three actually computed ID sequences for the same exact text, each decoded with its declared vocabulary. They are not three display styles for one sequence, nor three trained models ranked by language accuracy. Counts compare representation rules; they do not establish predictive quality.
  2. longest-reset: Encode the specified reset example. For lower low, all eight entries active and EOS off, choose [385,32,384]. Lower beats low at offset 0 because five matching bytes exceed three; the space survives as 32; low covers the last three bytes. [384,101,114,32,384] uses a shorter first match and is instead the correct prefix-1 result. [385,384] improperly deletes the space. This question explicitly specifies the reset state even if your current editable text differs.
  3. live-subword-choice: Explain the actual first decision. Read subword_decision_0’s matched candidates, chosen ID and byteWidth. At reset it has offset 0, two matches, ID 385 and width 5. The correct option uses longest active matching expansion, lowest ID on an equal length, or one-byte fallback when nothing matches. The ID is not a character count to skip, and unmatched input never automatically becomes EOS. With empty text, the prompt instead asks why no first decision exists: there are zero source bytes to consume, and subwordTokens is 0 with EOS off or 1 with EOS on. That marker requires no greedy content decision. An active dictionary may still be shown; possible items and items emitted for this input are separate quantities.
  4. vocabulary-prefix: Predict shrinking 8 entries to 1. Keep lower low and EOS off. Choose [384,101,114,32,384], five tokens: low remains, while e and r use byte fallback. Inactive lower/385 cannot remain available merely because it matched before the edit. The result stays defined because fallback covers the bytes; complete words need not be present in the dictionary.
  5. unicode-fallback: Transfer the rules to 猫. With the fixed ASCII dictionary and EOS off, choose counts 1/3/3 for character/byte/subword streams. One scalar uses one character ID, but its UTF-8 bytes are [231,140,171] and all three need fallback. Counting one byte per visible item is wrong; deleting unfamiliar text is wrong. Concatenate the fallback bytes before strict decoding to reconstruct the scalar.

Recap and the planned BPE bridge

  • The same text can have different sequence lengths under scalar, byte and subword rules.
  • The default’s three streams have counts 9/9/3; only low active gives five greedy tokens.
  • Byte fallback preserves valid unfamiliar Unicode, spaces and combining forms within the stated bounds.
  • Vocabulary item counts include reserved EOS and describe possibilities, not allocated weights or measured quality.

The planned next chapter, IV-39 — Byte-Pair Encoding: A Full Merge Trace, will learn byte-pair merges from a tiny corpus and apply their merge ranks. Ranked BPE is a different algorithm from this chapter’s longest matching fixed piece. This chapter supplies the representation and reversibility foundation; it does not implement the next chapter’s merge training.