The neural notebook
← All chapters

IV-37 / Part IX · Tokenization

From Unicode Text to Token IDs

Separate visible characters, Unicode scalars, UTF-16 units, UTF-8 bytes and token IDs; hand-encode and strictly decode a complete multilingual example.

Review the ideas this chapter uses

A text box can display a letter and an emoji side by side, but a neural network receives numbers. Before looking up an embedding, we must agree on how text becomes a sequence of integer IDs, and how those IDs recover the original text. Different ways of counting the same text produce different answers. Here we will follow each representation without discarding any information.

Learning objective: Distinguish characters, code points, UTF-8 bytes and vocabulary IDs.

Compute it yourself

From Unicode Text to Token IDs

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.

utf16Units4
scalarCount3
byteCount7
tokenCount7

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

utf16Units 4. scalarCount 3. byteCount 7. tokenCount 7. Count exact text storage and declare byte IDs. UTF-16 units store the input string; Unicode scalars name code points; UTF-8 uses one to four bytes per scalar. Byte IDs equal byte values by this toy vocabulary declaration.

Count exact text storage and declare byte IDs

byte IDs=0..255; EOS=512; byteBound=32

UTF-16 units store the input string; Unicode scalars name code points; UTF-8 uses one to four bytes per scalar. Byte IDs equal byte values by this toy vocabulary declaration.

Saved inputs

eos
0

Saved outputs

utf16Units
4
scalarCount
3
byteBound
32
EOS
512

From exact text to reversible IDs

Original input, escaped: "Aé🦊". 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
065010165
12331112195, 169
21294182234240, 159, 166, 138

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 (3 saved operations)

source_scalar_0: Encode scalar 0: U+0041

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
inputscodePoint65
inputsunit065
outputsbyteOffset0
outputsbyteWidth1
outputspayload065
outputsbyte065

source_scalar_1: Encode scalar 1: U+00E9

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
inputscodePoint233
inputsunit0233
outputsbyteOffset1
outputsbyteWidth2
outputspayload03
outputspayload141
outputsbyte0195
outputsbyte1169

source_scalar_2: Encode scalar 2: U+1F98A

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
inputsutf16Width2
inputscodePoint129418
inputsunit055358
inputsunit156714
outputsbyteOffset3
outputsbyteWidth4
outputspayload00
outputspayload131
outputspayload238
outputspayload310
outputsbyte0240
outputsbyte1159
outputsbyte2166
outputsbyte3138

Byte vocabulary: every ID and byte expansion

Exact reconstructed text: "Aé🦊". 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)
065byte 65[65]
1195byte 195[195]
2169byte 169[169]
3240byte 240[240]
4159byte 159[159]
5166byte 166[166]
6138byte 138[138]

Bytes 0..255 use IDs 0..255 by declaration. The optional EOS item is ID 512; IDs 256..259 are reserved for later BPE and 384..391 for the separate toy subword dictionary. Literal <eos> remains ordinary text. An invalid ID, illegal EOS position or malformed byte sequence makes the whole computation unavailable.

Every byte-to-ID lookup and optional EOS append (7 saved operations)

byte_token_0: Byte 0 becomes its declared token ID

id=byte

This is a vocabulary lookup declaration, not a universal property of tokenizers or a measure of semantic similarity.

SideSaved fieldExact integer
inputsindex0
inputsbyte65
outputsid65

byte_token_1: Byte 1 becomes its declared token ID

id=byte

This is a vocabulary lookup declaration, not a universal property of tokenizers or a measure of semantic similarity.

SideSaved fieldExact integer
inputsindex1
inputsbyte195
outputsid195

byte_token_2: Byte 2 becomes its declared token ID

id=byte

This is a vocabulary lookup declaration, not a universal property of tokenizers or a measure of semantic similarity.

SideSaved fieldExact integer
inputsindex2
inputsbyte169
outputsid169

byte_token_3: Byte 3 becomes its declared token ID

id=byte

This is a vocabulary lookup declaration, not a universal property of tokenizers or a measure of semantic similarity.

SideSaved fieldExact integer
inputsindex3
inputsbyte240
outputsid240

byte_token_4: Byte 4 becomes its declared token ID

id=byte

This is a vocabulary lookup declaration, not a universal property of tokenizers or a measure of semantic similarity.

SideSaved fieldExact integer
inputsindex4
inputsbyte159
outputsid159

byte_token_5: Byte 5 becomes its declared token ID

id=byte

This is a vocabulary lookup declaration, not a universal property of tokenizers or a measure of semantic similarity.

SideSaved fieldExact integer
inputsindex5
inputsbyte166
outputsid166

byte_token_6: Byte 6 becomes its declared token ID

id=byte

This is a vocabulary lookup declaration, not a universal property of tokenizers or a measure of semantic similarity.

SideSaved fieldExact integer
inputsindex6
inputsbyte138
outputsid138
Every ID expansion and optional EOS strip (7 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
inputsid65
outputsbyteOffset0
outputsbyteWidth1
outputsbyte065

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
inputsid195
outputsbyteOffset1
outputsbyteWidth1
outputsbyte0195

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
inputsid169
outputsbyteOffset2
outputsbyteWidth1
outputsbyte0169

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
inputsid240
outputsbyteOffset3
outputsbyteWidth1
outputsbyte0240

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
inputsid159
outputsbyteOffset4
outputsbyteWidth1
outputsbyte0159

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
inputsid166
outputsbyteOffset5
outputsbyteWidth1
outputsbyte0166

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
inputsid138
outputsbyteOffset6
outputsbyteWidth1
outputsbyte0138
Every strict byte-to-Unicode reconstruction (3 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
inputsbyte065
outputspayload065
outputsaccumulator065
outputscodePoint65
outputsutf16Width1
outputsunit065

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
inputsbyteWidth2
inputsbyte0195
inputsbyte1169
outputspayload03
outputsaccumulator03
outputspayload141
outputsaccumulator1233
outputscodePoint233
outputsutf16Width1
outputsunit0233

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
inputsbyteOffset3
inputsbyteWidth4
inputsbyte0240
inputsbyte1159
inputsbyte2166
inputsbyte3138
outputspayload00
outputsaccumulator00
outputspayload131
outputsaccumulator131
outputspayload238
outputsaccumulator22022
outputspayload310
outputsaccumulator3129418
outputscodePoint129418
outputsutf16Width2
outputsunit055358
outputsunit156714
Actual roundtrip equality and counts after reconstruction (1 saved operations)

roundtrip: Compare actual reconstructed text with input

equal=(actualDecoded===input)

The decoder concatenated validated scalar reconstructions from expanded IDs. Empty input reconstructs the empty string; EOS contributes no text.

SideSaved fieldExact integer
inputsoriginalUnits4
inputsdecodedUnits4
inputsdecodedByteCount7
outputstokenCount7
outputsequal1

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=3 · int32 · precision 0 · Validated Unicode scalars in source order.

Zero-based storage indexExact integer
065
1233
2129418

UTF16Offsets

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

Zero-based storage indexExact integer
00
11
22

Bytes

Bytes=7 · int32 · precision 0 · Manual UTF-8 encoding in source byte order.

Zero-based storage indexExact integer
065
1195
2169
3240
4159
5166
6138

TokenIDs

Tokens=7 · int32 · precision 0 · Declared byte IDs, with explicit optional EOS tail.

Zero-based storage indexExact integer
065
1195
2169
3240
4159
5166
6138

DecodedBytes

Bytes=7 · int32 · precision 0 · Actual ID expansions passed into the strict UTF-8 decoder.

Zero-based storage indexExact integer
065
1195
2169
3240
4159
5166
6138

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 this lab mean by a Unicode scalar?
2. Scalar é is 233=3×64+41. Which actual UTF-8 bytes encode it?
3. Saved byte_token_0 has byte=65. Which ID and mechanism apply to this current first source byte?
4. Keep a valid text input fixed and switch EOS from off to on. What changes?
5. Compare precomposed é with e followed by a combining acute accent. What does exact preservation require?

The reset example Aé🦊 has three scalars but four UTF-16 units: A=65, é=233 and fox=129418. Its bytes are [65,195,169,240,159,166,138], so it has seven byte tokens with EOS off. Edit one symbol, add a space, or clear the text and inspect the actual new counts and reverse decoding.

For the fox, the UTF-16 pair is D83E,DD8A: high−D800=62 and low−DC00=394, so 62×1024+394+65536=129418. UTF-8 payload groups are [0,31,38,10]. Prefixes produce [F0,9F,A6,8A], decimal [240,159,166,138]. Reverse accumulation gives 0, then 31, then 31×64+38=2022, then 2022×64+10=129418. These same operands are saved in the encoding and decoding records.

This is a reversible toy byte vocabulary, with no embeddings or training. The next lesson compares scalar, byte and fixed subword vocabularies on the same exact text.

The authored default is Aé🦊: a capital A, an accented letter and a fox. Its result has 4 UTF-16 units, 3 Unicode scalars, 7 bytes and 7 byte-token IDs with EOS off. Edit the text, inspect a saved calculation step, then reset to follow the worked example. Turning EOS on appends one special ID; it does not add a visible character to the decoded text. Empty text is also a real input: its byte and scalar streams are empty, not padded with an invented letter.

Review IV-16 — Token IDs and Embedding Lookup Tables for how an ID selects an embedding row. Book II’s I.8 — Indexed quantities and summation introduces indexed lists; Book III’s III-41 — Composition and Learned Representations connects representations to neural composition. This lesson supplies the discrete input representation before any learned vector. No model is trained here.

Five things that “character” might mean

A character is a useful informal word for a written item. A grapheme cluster is a group of code points treated as a text unit by Unicode segmentation rules; it often corresponds to one perceived character. A visible accented letter may be one code point or a base letter plus a combining mark. Some emoji join several code points. This lab does not implement grapheme segmentation, so its scalar counter is not a universal count of perceived characters.

A code point is a Unicode number, written for example as U+0041. U+ announces the notation; the following digits are hexadecimal, or base 16. Hex digits A..F mean decimal 10..15. A Unicode scalar value is a code point from 0 through hexadecimal 10FFFF, excluding D800..DFFF. The excluded range contains surrogate code units used by UTF-16. Here a valid text’s CodePoints tensor lists scalars in source order.

UTF-16 represents a scalar with one or two 16-bit code units. A code unit is a storage item, not necessarily a whole character. JavaScript string offsets count these units, starting at zero. UTF-8 represents each scalar with one to four bytes, integers from 0 through 255. A byte has eight binary digits, or bits. Neither encoding learns anything about language: each follows a reversible storage rule.

A token is one item emitted by a tokenizer, and its ID is an integer naming a vocabulary item. This chapter declares a byte vocabulary: byte value 65 gets ID 65, and similarly for all 256 byte values. That equality is our explicit choice. Other tokenizers can assign different IDs to the same bytes. Nearby IDs do not imply nearby meanings; embedding coordinates are separate learned quantities.

Names, indices and shapes

Let S be the number of Unicode scalars, U the number of UTF-16 units, B the number of UTF-8 bytes, and T the number of emitted tokens. Lowercase i is a zero-based scalar index; j is a zero-based byte index. An offset says where an item begins in a storage sequence; a width says how many storage items it occupies. In this example scalar i=2 begins at UTF-16 offset 2 and occupies two units.

The one-dimensional tensors (named numeric lists here) are CodePoints [S] and UTF16Offsets [S], with a Scalars axis; Bytes [B] and DecodedBytes [B], with a Bytes axis; and TokenIDs [T], with a Tokens axis. Brackets describe list length, not a matrix multiplication. Their int32 storage means signed 32-bit integers; every permitted value fits exactly. Original and reconstructed strings are textual metadata in the same result. They are not coerced into a numeric tensor.

The flag eos is the integer 0 or 1. EOS means end of sequence. Its reserved ID is 512, outside the byte IDs 0..255. Thus T=B+eos. With empty input and eos=0, S=U=B=T=0; zero-length tensors are omitted, while the empty streams and counters remain meaningful. With eos=1, empty text emits only ID 512 and still decodes to empty text.

Start with the source scalars and UTF-16

The exact default scalars are U+0041=65, U+00E9=233 and U+1F98A=129418. The first two each occupy one UTF-16 unit. The fox occupies the pair D83E, DD8A, decimal units 55358 and 56714. These are two surrogate units representing one scalar, not two independently valid scalar values.

For a high surrogate h and low surrogate l, the supplementary scalar is

c=(h−D800) 1024+(l−DC00)+65536.c=(h-\mathrm{D800})\,1024+(l-\mathrm{DC00})+65536.

Here c names the scalar’s decimal value; h and l name the two units, and hexadecimal constants are written without U+ because these are storage units. For the fox, D83E−D800=55358−55296=62 and DD8A−DC00=56714−56320=394. Therefore c=62·1024+394+65536=63488+394+65536=129418. Going the other way, c−65536=63882=62·1024+394, recovering high 55296+62=55358=D83E and low 56320+394=56714=DD8A.

The scalar offsets are [0,1,2] and widths are [1,1,2]; the total is 1+1+2=4 UTF-16 units. A lone high or low surrogate has no scalar under this rule. The model rejects it instead of replacing it with a different character.

Why UTF-8 uses six-bit groups

Binary prefixes distinguish a starting byte from following bytes. ASCII names the first 128 character codes, including basic Latin letters, digits and control codes. An ASCII scalar from 0 through 127 fits in 0xxxxxxx. A two-byte scalar uses 110xxxxx 10xxxxxx; a three-byte scalar uses 1110xxxx 10xxxxxx 10xxxxxx; and a four-byte scalar uses 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. Each x is a payload bit taken from the scalar. A continuation byte begins with 10, leaving six payload bits, so its payload is between 0 and 63.

Six bits have 64 possible values because 2⁶=64. Splitting an integer into groups of six bits is therefore the same arithmetic as writing base-64 digits. This is the reason for the factors 64, 4096=64² and 262144=64³ below. It is not the Base64 file-to-text encoding, and it does not produce Base64 alphabet characters. UTF-8 adds binary marker prefixes to the groups instead.

For a nonnegative integer c, division by 64 gives a quotient q and remainder r with c=64q+r and 0≤r≤63. Repeated division obtains the higher groups. In code, a right shift by six removes one low group; masking with hexadecimal 3F keeps only the low six bits. A bitwise OR combines payload and prefix whose occupied bit positions do not overlap. The continuation marker is hexadecimal 80=128; the two-, three- and four-byte lead markers are C0=192, E0=224 and F0=240. Lead-byte payload capacity shrinks as more marker bits are needed.

The shortest permitted width depends on c: 0..127 uses one byte; 128..2047 uses two; 2048..65535 uses three, excluding surrogate scalars; and 65536..1114111 uses four. Thus é=233 belongs to the two-byte branch and the fox=129418 belongs to the four-byte branch. A prefix identifies a width, but a decoder must also check that the recovered scalar belongs in that width’s range.

Encode every default scalar

For A, c=65 is below 128. Its byte is simply 65, hexadecimal 41, binary 01000001.

For é, 233=3·64+41. The two payload groups are 3 and 41. Its lead byte is 192+3=195=C3, binary 11000011. Its continuation is 128+41=169=A9, binary 10101001. Together they encode exactly 233; neither byte alone names the accented letter.

For the fox, the four payload groups are 0,31,38,10:

129418=0⋅262144+31⋅4096+38⋅64+10=0+126976+2432+10.129418=0\cdot262144+31\cdot4096+38\cdot64+10 =0+126976+2432+10.

Attach the prefixes in order: 240+0=240=F0; 128+31=159=9F; 128+38=166=A6; 128+10=138=8A. Their binary forms are 11110000 10011111 10100110 10001010. These four bytes are one scalar’s UTF-8 representation.

Scalar index iScalar, decimalUTF-16 offset, widthUTF-8 byte offset, widthBytes and byte-token IDs
0A, 650, 10, 165
1é, 2331, 11, 2195, 169
2🦊, 1294182, 23, 4240, 159, 166, 138

Concatenating in scalar order gives Bytes and TokenIDs [65,195,169,240,159,166,138]. Concatenation means appending lists without reordering their contents. EOS on appends 512, making eight IDs; the seven text bytes stay unchanged.

Reverse all the way to text

Decoding starts from the actual IDs. For this vocabulary, each ordinary ID must be an integer from 0 through 255 and contributes its equal-valued byte. EOS is allowed exactly once at the tail when its flag is on; it contributes no byte. An unknown ID, a missing required EOS, an unexpected EOS or an interior EOS is invalid. The decoder does not copy the original string as its answer.

Read the recovered bytes from left to right. Byte 65 begins with 0, so it directly yields scalar 65, U+0041, and UTF-16 unit 0041. Byte 195=C3 begins with 110, so it requires exactly one continuation. Removing its three marker bits leaves payload 3. Byte 169=A9 has the required 10 prefix; removing that prefix leaves 41. Recombine 3·64+41=192+41=233, U+00E9, stored as one UTF-16 unit 00E9.

Byte 240=F0 begins with 11110, requiring three continuations. Their prefixes are valid; stripping them yields 0,31,38,10. Recombine 0·262144+31·4096+38·64+10=129418, U+1F98A. The supplementary-scalar calculation above reconstructs D83E, DD8A. Appending 0041, 00E9 and this pair constructs Aé🦊. Only after this reconstruction does the result compare the decoded text with the input.

Prefix recognition alone is insufficient. A strict decoder also rejects a missing continuation, a continuation used as a lead, a sequence using more bytes than necessary (overlong encoding), a surrogate scalar, or a value above U+10FFFF. For example C0,AF cannot be accepted as a longer spelling of slash. Rejecting malformed bytes preserves one canonical UTF-8 spelling for each scalar; silently substituting a replacement character would break exact round-trip evidence.

Experiments that expose counting mistakes

Try 猫, the cat character U+732B=29483. It is one scalar, with payload groups 7,12,43 because 7·4096+12·64+43=28672+768+43=29483. The three-byte lead 224+7=231=E7 and continuations 128+12=140=8C, 128+43=171=AB give [231,140,171]. Reverse those same groups to recover U+732B. One visible item can therefore require three byte tokens.

Compare precomposed é (U+00E9) with é (U+0065 followed by U+0301, the combining acute accent). The first has one scalar and bytes C3,A9. The second has two scalars: e gives 101=65 in hex; 769=12·64+1 gives CC,81 for the accent. Its bytes are [101,204,129]. Normalization is a transformation that can convert between some equivalent Unicode forms. This lab never applies it: these inputs can look alike yet retain different scalars, bytes and IDs. Retaining exact text is a different goal from treating similar spellings as equivalent.

A space, newline, the byte order mark U+FEFF and U+0000 are also data; this codec does not strip a leading U+FEFF. When edited, the browser text area converts carriage returns and CRLF line endings to line feeds before the lab receives its value; the codec preserves the string it receives. The Python CLI accepts JSON as an argument or from stdin: JSON escapes \r and \r\n inside a string produce carriage return and CRLF in the decoded input, which the codec preserves. NUL, U+0000, has byte and token ID 0; it is not an instruction to stop decoding. Literal <eos> is five ordinary ASCII characters and five byte IDs. It never turns into ID 512 by pattern recognition. The explicit EOS control alone adds that marker.

Input is bounded to 32 UTF-8 bytes. More than 32 UTF-16 units is rejected early; remaining inputs are checked for unpaired surrogates and then actual byte length. The bound is a teaching/display limit, not a limit on Unicode. Text is neither trimmed nor silently truncated. Invalid input makes the whole result unavailable, rather than leaving stale successful tables. Editing restarts the saved trace and clears grades; step navigation inspects recorded operations.

Read the maintained Python, not a copied demonstration

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-37 — From Unicode Text to Token IDs.

The declared byte vocabulary maps each UTF-8 byte to the same numeric ID.
That declaration does not make IDs semantic distances or Unicode scalars.
The optional EOS control appends ID512; literal '<eos>' is ordinary text.

Hand default: A=65; é=233=3*64+41 -> [195,169]. Fox U+1F98A is
129418=0*64**3+31*64**2+38*64+10 -> [240,159,166,138]. Its UTF-16
units are D83E,DD8A: 62*1024+394+65536=129418. Offsets [0,1,2] count
UTF-16 units; the input has 4 units, 3 scalars and 7 bytes. Decoder payload
accumulators for the fox are 0,31,2022,129418, not copied input characters.
Empty input is valid; no zero-length tensor is padded with invented values.

Keep token_reference.py beside this file. Loading uses __file__, so an absolute
script path or file-based import works independently of the process cwd.
All source, imports, NumPy operations and CLI paths remain UNRUN.
"""
import importlib.util
from pathlib import Path
from types import MappingProxyType

_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_IV37 = MappingProxyType(dict(_helper.IV37_DEFAULTS))


@_helper.guarded
def derive_iv37(state):
    """Validate, encode actual scalars/bytes/IDs, decode IDs, then compare strings."""
    s = _helper.text_state(state, 37)
    input_text, eos = s["text"], 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", "Count exact text storage and declare byte IDs", "byte IDs=0..255; EOS=512; byteBound=32",
              "UTF-16 units store the input string; Unicode scalars name code points; UTF-8 uses one to four bytes per scalar. Byte IDs equal byte values by this toy vocabulary declaration.",
              dict(eos=eos), dict(utf16Units=units, scalarCount=len(encoded["codePoints"]), byteBound=_helper.BYTE_BOUND, EOS=_helper.EOS))
    trace.steps.extend(encoding_trace.steps)
    # These are real NumPy int32 IDs, separate from the source byte storage.
    ids = encoded["bytes"].copy()
    for index, stored in enumerate(encoded["bytes"]):
        byte = int(stored)
        trace.add(f"byte_token_{index}", f"Byte {index} becomes its declared token ID", "id=byte",
                  "This is a vocabulary lookup declaration, not a universal property of tokenizers or a measure of semantic similarity.",
                  dict(index=index, byte=byte), dict(id=byte))
    ids = _helper.append_eos(ids, eos, "byte", trace)
    decoded = _helper.decode_byte_ids(ids, eos, "byte", trace)
    equal = int(decoded["decoded"] == input_text)
    if not equal:
        raise _helper.NumericalFault("INVALID_INPUT", "Actual byte reconstruction did not equal the original text.")
    trace.add("roundtrip", "Compare actual reconstructed text with input", "equal=(actualDecoded===input)",
              "The decoder concatenated validated scalar reconstructions from expanded IDs. Empty input reconstructs the empty string; EOS contributes no text.",
              dict(originalUnits=units, decodedUnits=_helper.utf16_length(decoded["decoded"]), decodedByteCount=len(decoded["bytes"])),
              dict(tokenCount=len(ids), equal=equal))
    tensors = []
    for identifier, axis, values, provenance in (
        ("CodePoints", "Scalars", encoded["codePoints"], "Validated Unicode scalars in source order."),
        ("UTF16Offsets", "Scalars", encoded["offsets"], "Zero-based source UTF-16 offset for each scalar."),
        ("Bytes", "Bytes", encoded["bytes"], "Manual UTF-8 encoding in source byte order."),
        ("TokenIDs", "Tokens", ids, "Declared byte IDs, with explicit optional EOS tail."),
        ("DecodedBytes", "Bytes", decoded["bytes"], "Actual ID expansions passed into the strict UTF-8 decoder."),
    ):
        if len(values):
            tensors.append(_helper.tensor(identifier, axis, values, provenance))
    summary = dict(utf16Units=units, scalarCount=len(encoded["codePoints"]), byteCount=len(encoded["bytes"]),
                   tokenCount=len(ids), eos=eos, EOS=_helper.EOS)
    texts = dict(input=input_text, decoded=decoded["decoded"], byteLabels=_helper.byte_labels(ids),
                 byteExpansions=_helper.byte_expansions(ids))
    return trace.result(summary, tensors, texts)


if __name__ == "__main__":
    _helper.run(derive_iv37, DEFAULT_IV37)
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=(",", ":")))

The first disclosure is the actual iv37.py wrapper; the second is its actual shared token_reference.py helper, both imported as raw text. Follow the wrapper’s setup, scalar encoding, byte-to-ID emission, optional EOS, token expansion, strict UTF-8 reconstruction and final equality comparison. The helper supplies the shared validation and integer codec operations. NumPy stores the integer arrays; explicit scalar arithmetic explains the encoding. Keep the helper with the wrapper when later using the source.

In that source, derive_iv37 coordinates the lesson. utf8_encode builds encoded["codePoints"], offsets, widths and bytes; the wrapper copies those bytes into actual ID storage and records each lookup. append_eos applies the explicit flag. decode_byte_ids expands those IDs and calls utf8_decode, whose scalar loop rebuilds the answer from payload accumulators. Finally TokenTrace.result puts the summary before the saved operation outputs. The helper is resolved beside the wrapper using the wrapper’s own file path; it is part of the example, not an installed tokenizer hiding the conversion.

Map each encoded scalar’s offset and width to the table above, each emitted ID to its byte, and the saved decoder operands to the reverse calculations. Original text, decoded text, counters, tensors and piece labels belong to one derived record. Labels are escaped display text, including whitespace; they do not change the underlying string. There is no second codec hidden in the view.

In the actual record order, setup comes first, then every source_scalar_i, every byte_token_j, optional byte_eos, every byte_expand_j, optional byte_strip_eos, every byte_decode_i, then roundtrip. A scalar record saves its original UTF-16 units, payload groups and emitted bytes. A decoder record saves each payload and its running accumulator, meaning the integer built so far: start at zero, then repeatedly compute previous·64+payload. For é the successive accumulators are 3 and 3·64+41=233. For the fox they are 0,31,31·64+38=2022,2022·64+10=129418. The final scalar is converted to actual UTF-16 units. These saved intermediate numbers are the reverse calculation, not rounded display guesses. Integer tensor precision metadata is 0; no floating-point approximation is needed for these bounded integers.

Five graded questions and how to correct a mistake

The lab grades these five questions immediately. For a live question, choose the value and its mechanism together: a distractor can repeat the right number while giving an incorrect reason. Use Calculation step to inspect saved operands; navigation clears grades but does not change the input. Reset example restores the authored text and EOS-off state.

  1. scalar-versus-grapheme: What does “Unicode scalar” mean? Choose a legal code point excluding surrogates. A scalar may occupy two UTF-16 units or several UTF-8 bytes. Counting the fox’s two storage units as two scalars confuses an encoding with the item encoded; counting an accented grapheme as always one scalar ignores combining sequences.
  2. utf8-e-233: Which bytes encode 233=3·64+41? Choose [195,169]: add the nonoverlapping lead prefix 192 to payload 3 and continuation prefix 128 to payload 41. [233] skips the required two-byte rule; [3,41] leaves out both prefixes. Reverse decoding removes those markers and recovers 3·64+41=233.
  3. live-byte-id: Read the current first source byte. With nonempty input, use byte_token_0: the correct option names its actual saved ID because this vocabulary declares id=byte. At reset that is 65; after an edit it follows the current byte. The same number paired with a semantic-similarity claim is incorrect. With empty input, the prompt instead uses actual byteCount=0 and tokenCount: there is no first source-byte token. The total is 0 with EOS off or 1 with EOS on, entirely from the explicit marker. No letter, padding byte or invisible pattern is invented. NUL is different: it supplies a real byte 0 and a real lookup record.
  4. explicit-eos: Predict switching EOS on. Hold valid text fixed. Exactly one ID 512 is appended, increasing tokenCount by one without changing source bytes or decoded text. A “byte 512” is impossible because bytes stop at 255. The marker has no literal-text expansion and does not append the five characters <eos>.
  5. normalization-counterexample: Preserve two similar-looking spellings. Keep precomposed é’s [195,169] distinct from e-plus-acute’s [101,204,129]. Both are valid; the combining mark is not rejected for being unfamiliar. Forcing both to the first sequence would normalize the input, contradicting this lab’s exact-preservation rule.

Recap and bridge

  • A perceived character, a scalar, a UTF-16 unit, a byte and a token are distinct units of counting.
  • UTF-8 packs scalar payload bits into marked bytes; decoding must validate both structure and scalar range.
  • Byte IDs equal byte values here by declaration; ID magnitude is not meaning.
  • Exact decoding preserves empty text, whitespace, NUL and distinct combining forms. EOS is an explicit separate marker.

Next, IV-38 — Subwords and Vocabulary Trade-Offs compares three real token streams for the same text and asks what shorter sequences cost in vocabulary size.