The neural notebook
← All chapters

IV-51 / Part XIII · Training Language Models

Training Data, Packing and Causal Boundaries

Pack two authored toy documents into six slots, derive every causal permission and shifted-target mask, and distinguish document isolation, chunk cuts, EOS and PAD.

Review the ideas this chapter uses

Two short documents need not each occupy a mostly empty training block. Packing places their tokens in shared storage. But sharing storage raises two separate decisions: may one document read the other, and which next-token pairs belong to the task? We will make those decisions explicit before a neural network receives anything.

Learning objective: Turn short documents into training chunks and loss masks.

Compute it yourself

Training Data, Packing and Causal Boundaries

Turn two short documents into six storage slots, then inspect which earlier slots each query may read and which adjacent targets would be included. Change chunk size or document isolation to see their separate boundary effects. This lab computes exact integer IDs and boolean masks; it computes no neural predictions, loss or training update.

packedTokens6
paddingSlots0
allowedCells12
validTargets4

Use one or two raw a/b letters per document, at most two UTF-8 bytes. Empty text is UNAVAILABLE. Spaces, case changes and other letters are rejected; nothing is trimmed, normalized or cropped. Both string types and all eight numeric fields validate before document A then B semantics. Every requested mask validates even when its pair is structurally excluded.

Use one or two raw a/b letters per document, at most two UTF-8 bytes. Empty text is UNAVAILABLE. Spaces, case changes and other letters are rejected; nothing is trimmed, normalized or cropped. Both string types and all eight numeric fields validate before document A then B semantics. Every requested mask validates even when its pair is structurally excluded.

Five requested target masks
Exact starting inputs for this saved calculation

packedTokens 6. paddingSlots 0. allowedCells 12. validTargets 4. Declare the two-document packing policy. Validate all ten own data fields, both string types and all eight numeric domains before docA then docB Unicode/domain semantics. The tokenizer full-byte vocabulary differs from the restricted active classes.

Declare the two-document packing policy

slots=6; C=6/S; V=3+merges; two EOS-off tokenizers then two explicit EOS markers

Validate all ten own data fields, both string types and all eight numeric domains before docA then docB Unicode/domain semantics. The tokenizer full-byte vocabulary differs from the restricted active classes.

Saved inputs

merges
0
blockSize
6
isolate
1
m0
1
m1
1
m2
1
m3
1
m4
1

Saved outputs

slots
6
chunks
1
classCount
3
byteBound
2
tokenizerCalls
2
EOS
512
PAD
768

Two documents, six physical slots

Two genuine IV39 calls, each with fixed corpus abab, requested merges and EOS off; both complete records are retained under docA_/docB_. No normalization, cropping or retokenization.

docA: exact text "ab"

Actual source bytes [97,98]; content IDs [97,98]; explicit-EOS sequence [97,98,512]. Strict content reconstruction "ab".

docA: actual tokenizer rules and expansions

Fixed corpus "abab"; rules []; rule expansions []; content labels ["ID 97, bytes [97]","ID 98, bytes [98]"]; content expansions ["[97]","[98]"]. Zero merges requested: no training round or pair selection occurs.

docB: exact text "ba"

Actual source bytes [98,97]; content IDs [98,97]; explicit-EOS sequence [98,97,512]. Strict content reconstruction "ba".

docB: actual tokenizer rules and expansions

Fixed corpus "abab"; rules []; rule expansions []; content labels ["ID 98, bytes [98]","ID 97, bytes [97]"]; content expansions ["[98]","[97]"]. Zero merges requested: no training round or pair selection occurs.

Append exactly one explicit EOS512 after each content stream. EOS is a real shifted target and does not itself forbid attention. PAD768 is physical storage only, outside the active classes. Active prediction classes [97,98,512].

Isolation: allow only valid causal keys in the same chunk and document; positionID is document-local. Each document first piece is given.

Slot shape [Chunk, Slot]=[1, 6]. Read the six rows in storage order. Document IDs are 0 for docA and 1 for docB; -1 is a PAD sentinel. Global slots keep counting across chunks. Document positions restart for each document; chunk positions restart for each chunk. The saved positionID records the selected policy.

Six saved slots, flattened from Chunk × Slot
Zero-based storage rowSlotIDsSlotGlobalIndicesSlotDocIDsSlotDocPositionsSlotChunkIDsSlotChunkPositionsSlotPositionIDsSlotValid
097000000true
198101011true
2512202022true
398310030true
497411041true
5512512052true
Six saved slots, flattened from Chunk × Slot: saved tensor metadata
SlotIDs
Shape [1,6]; axes Chunk, Slot; dtype int32; precision 0. Six physical slots, row-major; actual document/chunk identities and declared position policy.
SlotGlobalIndices
Shape [1,6]; axes Chunk, Slot; dtype int32; precision 0. Six physical slots, row-major; actual document/chunk identities and declared position policy.
SlotDocIDs
Shape [1,6]; axes Chunk, Slot; dtype int32; precision 0. Six physical slots, row-major; actual document/chunk identities and declared position policy.
SlotDocPositions
Shape [1,6]; axes Chunk, Slot; dtype int32; precision 0. Six physical slots, row-major; actual document/chunk identities and declared position policy.
SlotChunkIDs
Shape [1,6]; axes Chunk, Slot; dtype int32; precision 0. Six physical slots, row-major; actual document/chunk identities and declared position policy.
SlotChunkPositions
Shape [1,6]; axes Chunk, Slot; dtype int32; precision 0. Six physical slots, row-major; actual document/chunk identities and declared position policy.
SlotPositionIDs
Shape [1,6]; axes Chunk, Slot; dtype int32; precision 0. Six physical slots, row-major; actual document/chunk identities and declared position policy.
SlotValid
Shape [1,6]; axes Chunk, Slot; dtype bool; precision 0. Six physical slots, row-major; actual document/chunk identities and declared position policy.

Permission is a saved boolean for each query and key

A query is the slot asking for context; a key is a slot it may read. Shape [Chunk, Query, Key]=[1,6,6]. Each row names its chunk and global query; columns name local keys in that same chunk. The word true means allowed; false means forbidden. There are no cross-chunk columns.

All Allowed tensor cells, with global query rows and local key columns
Chunk / global query / local queryLocal key 0Local key 1Local key 2Local key 3Local key 4Local key 5
Chunk 0 / query 0 / local 0truefalsefalsefalsefalsefalse
Chunk 0 / query 1 / local 1truetruefalsefalsefalsefalse
Chunk 0 / query 2 / local 2truetruetruefalsefalsefalse
Chunk 0 / query 3 / local 3falsefalsefalsetruefalsefalse
Chunk 0 / query 4 / local 4falsefalsefalsetruetruefalse
Chunk 0 / query 5 / local 5falsefalsefalsetruetruetrue

PAD query and key permissions are all false storage policy. No softmax is called; incorrectly querying such a row would meet the old FULLY_MASKED_ROW condition.

Saved query 3, chunk 0, local key 0, global key 0: allowed=false. Query valid=1; key valid=1; causal=1; same document=0; isolation gate=0.

All saved operands and gate results for this query

allowed_3: Save every key gate for global query 3

allowed=qValid AND kValid AND (localKey<=localQuery) AND (!isolate OR sameDoc)

One grouped row retains all S local key operands and results, including future, cross-document and PAD failures. Chunk membership is fixed by construction; no key outside this chunk is inspected.

Saved inputs
globalQuery
3
chunkID
0
queryPosition
3
queryID
98
queryDocID
1
queryValid
1
isolate
1
key0GlobalIndex
0
key0Position
0
key0ID
97
key0DocID
0
key0Valid
1
key1GlobalIndex
1
key1Position
1
key1ID
98
key1DocID
0
key1Valid
1
key2GlobalIndex
2
key2Position
2
key2ID
512
key2DocID
0
key2Valid
1
key3GlobalIndex
3
key3Position
3
key3ID
98
key3DocID
1
key3Valid
1
key4GlobalIndex
4
key4Position
4
key4ID
97
key4DocID
1
key4Valid
1
key5GlobalIndex
5
key5Position
5
key5ID
512
key5DocID
1
key5Valid
1
Saved outputs
key0Causal
1
key0SameDoc
0
key0IsolationGate
0
key0Allowed
0
key1Causal
1
key1SameDoc
0
key1IsolationGate
0
key1Allowed
0
key2Causal
1
key2SameDoc
0
key2IsolationGate
0
key2Allowed
0
key3Causal
1
key3SameDoc
1
key3IsolationGate
1
key3Allowed
1
key4Causal
0
key4SameDoc
1
key4IsolationGate
1
key4Allowed
0
key5Causal
0
key5SameDoc
1
key5IsolationGate
1
key5Allowed
0
rowAllowed
1
allowedRunning
7

Five physical input → target pairs

Five physical pairs i to i+1 are always retained. Cross-chunk, PAD and (when isolated) cross-document pairs are structurally masked; requested masks can only remove rows. targetRow -1 is metadata and is never gathered. The input is global slot i; the target is the following slot i+1. These five rows remain visible even when excluded. A requested mask is your numeric 0/1 switch; the structural mask records validity and boundaries; the effective mask says whether this row would contribute to a later objective.

All five saved input and target identities and positions
Zero-based storage rowInputIDsTargetIDsInputDocIDsTargetDocIDsInputDocPositionsTargetDocPositionsInputChunkIDsTargetChunkIDsInputChunkPositionsTargetChunkPositionsInputPositionIDsTargetPositionIDs
097980001000101
1985120012001212
2512980120002320
398971101003401
4975121112004512
All five saved input and target identities and positions: saved tensor metadata
InputIDs
Shape [5]; axes PredictionRow; dtype int32; precision 0. All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.
TargetIDs
Shape [5]; axes PredictionRow; dtype int32; precision 0. All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.
InputDocIDs
Shape [5]; axes PredictionRow; dtype int32; precision 0. All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.
TargetDocIDs
Shape [5]; axes PredictionRow; dtype int32; precision 0. All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.
InputDocPositions
Shape [5]; axes PredictionRow; dtype int32; precision 0. All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.
TargetDocPositions
Shape [5]; axes PredictionRow; dtype int32; precision 0. All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.
InputChunkIDs
Shape [5]; axes PredictionRow; dtype int32; precision 0. All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.
TargetChunkIDs
Shape [5]; axes PredictionRow; dtype int32; precision 0. All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.
InputChunkPositions
Shape [5]; axes PredictionRow; dtype int32; precision 0. All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.
TargetChunkPositions
Shape [5]; axes PredictionRow; dtype int32; precision 0. All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.
InputPositionIDs
Shape [5]; axes PredictionRow; dtype int32; precision 0. All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.
TargetPositionIDs
Shape [5]; axes PredictionRow; dtype int32; precision 0. All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.
All five saved target gates and ascending counts
Zero-based storage rowRequestedMaskInputValidTargetValidSameChunkSameDocIsolationGateStructuralMaskEffectiveMaskTargetRowsValidTargetsRunning
01truetruetruetruetruetruetrue11
11truetruetruetruetruetruetrue22
21truetruetruefalsefalsefalsefalse12
31truetruetruetruetruetruetrue03
41truetruetruetruetruetruetrue24
All five saved target gates and ascending counts: saved tensor metadata
RequestedMask
Shape [5]; axes PredictionRow; dtype int32; precision 0. All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.
InputValid
Shape [5]; axes PredictionRow; dtype bool; precision 0. All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.
TargetValid
Shape [5]; axes PredictionRow; dtype bool; precision 0. All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.
SameChunk
Shape [5]; axes PredictionRow; dtype bool; precision 0. All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.
SameDoc
Shape [5]; axes PredictionRow; dtype bool; precision 0. All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.
IsolationGate
Shape [5]; axes PredictionRow; dtype bool; precision 0. All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.
StructuralMask
Shape [5]; axes PredictionRow; dtype bool; precision 0. All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.
EffectiveMask
Shape [5]; axes PredictionRow; dtype bool; precision 0. All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.
TargetRows
Shape [5]; axes PredictionRow; dtype int32; precision 0. All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.
ValidTargetsRunning
Shape [5]; axes PredictionRow; dtype int32; precision 0. All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.

Saved row 2: structuralMask=0, requestedMask=1, effectiveMask=0, target compact row=1. Outside-chunk target IDs stay visible. A PAD target has row -1 metadata, which is never gathered.

All saved operands and products for this prediction row

alignment_2: Align physical input 2 with target 3

structural=inputValid*targetValid*sameChunk*isolationGate; effective=requestedMask*structural; running+=effective

Keep the actual outside-chunk or cross-document target ID visible even when excluded. EOS can be a real target. PAD has targetRow -1 metadata, never a gather. Requested masks cannot restore a structurally excluded pair.

Saved inputs
row
2
inputGlobalIndex
2
targetGlobalIndex
3
isolate
1
requestedMask
1
inputID
512
targetID
98
inputDocID
0
targetDocID
1
inputDocPosition
2
targetDocPosition
0
inputChunkID
0
targetChunkID
0
inputChunkPosition
2
targetChunkPosition
3
inputPositionID
2
targetPositionID
0
Saved outputs
inputValid
1
targetValid
1
sameChunk
1
sameDoc
0
isolationGate
0
structuralMask
0
effectiveMask
0
targetRow
1
validTargetsRunning
2

Inspection selectors only read this saved record. They leave inputs, trace selection and graded answers unchanged.

Selected trace operation: setup. The same saved operation is marked current wherever shown here.

Integer packing and boolean permissions only: no neural forward, probabilities, NLL, objective, gradients, optimizer or training is computed. All-zero masks give a valid packing record with validTargets=0; IV52 must separately reject an undefined all-masked mean.

Both complete tokenizer traces and explicit separator append steps

docA_setup: Declare learned byte-pair encoding and both exact inputs

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

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

Saved inputs
requestedMerges
0
eos
0
Saved outputs
corpusUnits
4
corpusScalars
4
utf16Units
2
scalarCount
2
byteBound
24
mergeBase
256
mergeBound
4
EOS
512

docA_corpus_scalar_0: Encode scalar 0: U+0061

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

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

Saved inputs
scalarIndex
0
utf16Offset
0
utf16Width
1
codePoint
97
unit0
97
Saved outputs
byteOffset
0
byteWidth
1
payload0
97
byte0
97

docA_corpus_scalar_1: Encode scalar 1: U+0062

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

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

Saved inputs
scalarIndex
1
utf16Offset
1
utf16Width
1
codePoint
98
unit0
98
Saved outputs
byteOffset
1
byteWidth
1
payload0
98
byte0
98

docA_corpus_scalar_2: Encode scalar 2: U+0061

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

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

Saved inputs
scalarIndex
2
utf16Offset
2
utf16Width
1
codePoint
97
unit0
97
Saved outputs
byteOffset
2
byteWidth
1
payload0
97
byte0
97

docA_corpus_scalar_3: Encode scalar 3: U+0062

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

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

Saved inputs
scalarIndex
3
utf16Offset
3
utf16Width
1
codePoint
98
unit0
98
Saved outputs
byteOffset
3
byteWidth
1
payload0
98
byte0
98

docA_source_scalar_0: Encode scalar 0: U+0061

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

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

Saved inputs
scalarIndex
0
utf16Offset
0
utf16Width
1
codePoint
97
unit0
97
Saved outputs
byteOffset
0
byteWidth
1
payload0
97
byte0
97

docA_source_scalar_1: Encode scalar 1: U+0062

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

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

Saved inputs
scalarIndex
1
utf16Offset
1
utf16Width
1
codePoint
98
unit0
98
Saved outputs
byteOffset
1
byteWidth
1
payload0
98
byte0
98

docA_corpus_expand_0: corpus: expand ID at token 0

ID → validated byte expansion

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

Saved inputs
index
0
id
97
Saved outputs
byteOffset
0
byteWidth
1
byte0
97

docA_corpus_expand_1: corpus: expand ID at token 1

ID → validated byte expansion

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

Saved inputs
index
1
id
98
Saved outputs
byteOffset
1
byteWidth
1
byte0
98

docA_corpus_expand_2: corpus: expand ID at token 2

ID → validated byte expansion

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

Saved inputs
index
2
id
97
Saved outputs
byteOffset
2
byteWidth
1
byte0
97

docA_corpus_expand_3: corpus: expand ID at token 3

ID → validated byte expansion

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

Saved inputs
index
3
id
98
Saved outputs
byteOffset
3
byteWidth
1
byte0
98

docA_corpus_decode_0: Decode UTF-8 scalar 0

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

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

Saved inputs
scalarIndex
0
byteOffset
0
byteWidth
1
byte0
97
Saved outputs
payload0
97
accumulator0
97
codePoint
97
utf16Width
1
unit0
97

docA_corpus_decode_1: Decode UTF-8 scalar 1

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

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

Saved inputs
scalarIndex
1
byteOffset
1
byteWidth
1
byte0
98
Saved outputs
payload0
98
accumulator0
98
codePoint
98
utf16Width
1
unit0
98

docA_corpus_decode_2: Decode UTF-8 scalar 2

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

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

Saved inputs
scalarIndex
2
byteOffset
2
byteWidth
1
byte0
97
Saved outputs
payload0
97
accumulator0
97
codePoint
97
utf16Width
1
unit0
97

docA_corpus_decode_3: Decode UTF-8 scalar 3

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

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

Saved inputs
scalarIndex
3
byteOffset
3
byteWidth
1
byte0
98
Saved outputs
payload0
98
accumulator0
98
codePoint
98
utf16Width
1
unit0
98

docA_target_expand_0: target: expand ID at token 0

ID → validated byte expansion

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

Saved inputs
index
0
id
97
Saved outputs
byteOffset
0
byteWidth
1
byte0
97

docA_target_expand_1: target: expand ID at token 1

ID → validated byte expansion

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

Saved inputs
index
1
id
98
Saved outputs
byteOffset
1
byteWidth
1
byte0
98

docA_target_decode_0: Decode UTF-8 scalar 0

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

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

Saved inputs
scalarIndex
0
byteOffset
0
byteWidth
1
byte0
97
Saved outputs
payload0
97
accumulator0
97
codePoint
97
utf16Width
1
unit0
97

docA_target_decode_1: Decode UTF-8 scalar 1

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

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

Saved inputs
scalarIndex
1
byteOffset
1
byteWidth
1
byte0
98
Saved outputs
payload0
98
accumulator0
98
codePoint
98
utf16Width
1
unit0
98

docA_roundtrip: Compare both actual strict reconstructions with the original strings

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

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

Saved inputs
corpusOriginalUnits
4
corpusDecodedUnits
4
corpusDecodedByteCount
4
originalUnits
2
decodedUnits
2
decodedByteCount
2
Saved outputs
corpusTokens
4
tokenCount
2
corpusEqual
1
equal
1

docA_append_eos: docA: append one explicit document separator

sequenceIDs=[...actual EOS-off TargetIDs,512]

The content IDs come from the genuine old tokenizer. Its EOS flag was zero; this separate append creates exactly one separator without retokenizing.

Saved inputs
docID
0
contentTokens
2
tokenizerEOS
0
Saved outputs
eosPosition
2
eosID
512
sequenceTokens
3

docB_setup: Declare learned byte-pair encoding and both exact inputs

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

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

Saved inputs
requestedMerges
0
eos
0
Saved outputs
corpusUnits
4
corpusScalars
4
utf16Units
2
scalarCount
2
byteBound
24
mergeBase
256
mergeBound
4
EOS
512

docB_corpus_scalar_0: Encode scalar 0: U+0061

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

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

Saved inputs
scalarIndex
0
utf16Offset
0
utf16Width
1
codePoint
97
unit0
97
Saved outputs
byteOffset
0
byteWidth
1
payload0
97
byte0
97

docB_corpus_scalar_1: Encode scalar 1: U+0062

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

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

Saved inputs
scalarIndex
1
utf16Offset
1
utf16Width
1
codePoint
98
unit0
98
Saved outputs
byteOffset
1
byteWidth
1
payload0
98
byte0
98

docB_corpus_scalar_2: Encode scalar 2: U+0061

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

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

Saved inputs
scalarIndex
2
utf16Offset
2
utf16Width
1
codePoint
97
unit0
97
Saved outputs
byteOffset
2
byteWidth
1
payload0
97
byte0
97

docB_corpus_scalar_3: Encode scalar 3: U+0062

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

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

Saved inputs
scalarIndex
3
utf16Offset
3
utf16Width
1
codePoint
98
unit0
98
Saved outputs
byteOffset
3
byteWidth
1
payload0
98
byte0
98

docB_source_scalar_0: Encode scalar 0: U+0062

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

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

Saved inputs
scalarIndex
0
utf16Offset
0
utf16Width
1
codePoint
98
unit0
98
Saved outputs
byteOffset
0
byteWidth
1
payload0
98
byte0
98

docB_source_scalar_1: Encode scalar 1: U+0061

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

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

Saved inputs
scalarIndex
1
utf16Offset
1
utf16Width
1
codePoint
97
unit0
97
Saved outputs
byteOffset
1
byteWidth
1
payload0
97
byte0
97

docB_corpus_expand_0: corpus: expand ID at token 0

ID → validated byte expansion

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

Saved inputs
index
0
id
97
Saved outputs
byteOffset
0
byteWidth
1
byte0
97

docB_corpus_expand_1: corpus: expand ID at token 1

ID → validated byte expansion

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

Saved inputs
index
1
id
98
Saved outputs
byteOffset
1
byteWidth
1
byte0
98

docB_corpus_expand_2: corpus: expand ID at token 2

ID → validated byte expansion

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

Saved inputs
index
2
id
97
Saved outputs
byteOffset
2
byteWidth
1
byte0
97

docB_corpus_expand_3: corpus: expand ID at token 3

ID → validated byte expansion

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

Saved inputs
index
3
id
98
Saved outputs
byteOffset
3
byteWidth
1
byte0
98

docB_corpus_decode_0: Decode UTF-8 scalar 0

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

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

Saved inputs
scalarIndex
0
byteOffset
0
byteWidth
1
byte0
97
Saved outputs
payload0
97
accumulator0
97
codePoint
97
utf16Width
1
unit0
97

docB_corpus_decode_1: Decode UTF-8 scalar 1

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

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

Saved inputs
scalarIndex
1
byteOffset
1
byteWidth
1
byte0
98
Saved outputs
payload0
98
accumulator0
98
codePoint
98
utf16Width
1
unit0
98

docB_corpus_decode_2: Decode UTF-8 scalar 2

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

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

Saved inputs
scalarIndex
2
byteOffset
2
byteWidth
1
byte0
97
Saved outputs
payload0
97
accumulator0
97
codePoint
97
utf16Width
1
unit0
97

docB_corpus_decode_3: Decode UTF-8 scalar 3

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

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

Saved inputs
scalarIndex
3
byteOffset
3
byteWidth
1
byte0
98
Saved outputs
payload0
98
accumulator0
98
codePoint
98
utf16Width
1
unit0
98

docB_target_expand_0: target: expand ID at token 0

ID → validated byte expansion

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

Saved inputs
index
0
id
98
Saved outputs
byteOffset
0
byteWidth
1
byte0
98

docB_target_expand_1: target: expand ID at token 1

ID → validated byte expansion

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

Saved inputs
index
1
id
97
Saved outputs
byteOffset
1
byteWidth
1
byte0
97

docB_target_decode_0: Decode UTF-8 scalar 0

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

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

Saved inputs
scalarIndex
0
byteOffset
0
byteWidth
1
byte0
98
Saved outputs
payload0
98
accumulator0
98
codePoint
98
utf16Width
1
unit0
98

docB_target_decode_1: Decode UTF-8 scalar 1

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

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

Saved inputs
scalarIndex
1
byteOffset
1
byteWidth
1
byte0
97
Saved outputs
payload0
97
accumulator0
97
codePoint
97
utf16Width
1
unit0
97

docB_roundtrip: Compare both actual strict reconstructions with the original strings

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

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

Saved inputs
corpusOriginalUnits
4
corpusDecodedUnits
4
corpusDecodedByteCount
4
originalUnits
2
decodedUnits
2
decodedByteCount
2
Saved outputs
corpusTokens
4
tokenCount
2
corpusEqual
1
equal
1

docB_append_eos: docB: append one explicit document separator

sequenceIDs=[...actual EOS-off TargetIDs,512]

The content IDs come from the genuine old tokenizer. Its EOS flag was zero; this separate append creates exactly one separator without retokenizing.

Saved inputs
docID
1
contentTokens
2
tokenizerEOS
0
Saved outputs
eosPosition
2
eosID
512
sequenceTokens
3
Saved packing setup and final reductions

setup: Declare the two-document packing policy

slots=6; C=6/S; V=3+merges; two EOS-off tokenizers then two explicit EOS markers

Validate all ten own data fields, both string types and all eight numeric domains before docA then docB Unicode/domain semantics. The tokenizer full-byte vocabulary differs from the restricted active classes.

Saved inputs
merges
0
blockSize
6
isolate
1
m0
1
m1
1
m2
1
m3
1
m4
1
Saved outputs
slots
6
chunks
1
classCount
3
byteBound
2
tokenizerCalls
2
EOS
512
PAD
768

counts: Finish the actual ascending-order integer reductions

packedTokens=len(Asequence)+len(Bsequence); paddingSlots=6-packedTokens; allowedCells=sum(Allowed); validTargets=sum(EffectiveMask)

Both sums accumulate actual saved cell/row results in row-major or ascending prediction-row order. validTargets is a metadata count, not a computed objective.

Saved inputs
docASequenceTokens
3
docBSequenceTokens
3
physicalSlots
6
predictionRows
5
Saved outputs
packedTokens
6
paddingSlots
0
allowedCells
12
validTargets
4

finish: Retain every old record and disclose the computation boundary

tokenizerCalls=2; appendedEOS=2; neuralCalls=0; objectiveComputed=0

All tensors and six-field steps from both actual old tokenizers remain inspectable with unique scopes; no issuance history, hidden state, prediction or training claim exists.

Saved inputs
tokenizerFrames
40
tokenizerTensors
36
Saved outputs
tokenizerCalls
2
appendedEOS
2
neuralCalls
0
objectiveComputed
0

Authored toy documents; fixed authored corpus abab. Exact int32 arithmetic and boolean predicates, no random stream or external corpus. Every integer, boolean, axis, precision and provenance string is retained in the complete inspector below. Boolean tables use true/false; trace gate operands use numeric 0/1.

Inspect all stored values, text metadata and tensor storage

Every scalar output, including flattened operation outputs

Exact text evidence from the same record

These are the stored values, shown without display rounding. Each tensor names its axes, dtype and display precision. Empty arrays are omitted rather than padded.

docA_CorpusCodePoints

Scalars=4 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Validated Unicode scalars in exact input order.

Zero-based storage indexStored value
097
198
297
398

docA_CorpusUTF16Offsets

Scalars=4 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Zero-based UTF-16 storage offset for each scalar.

Zero-based storage indexStored value
00
11
22
33

docA_CorpusUTF16Widths

Scalars=4 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. UTF-16 storage units consumed by each scalar.

Zero-based storage indexStored value
01
11
21
31

docA_CorpusByteOffsets

Scalars=4 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Zero-based UTF-8 byte offset for each scalar.

Zero-based storage indexStored value
00
11
22
33

docA_CorpusByteWidths

Scalars=4 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Actual UTF-8 bytes emitted by each scalar.

Zero-based storage indexStored value
01
11
21
31

docA_CorpusBytes

Bytes=4 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Manual UTF-8 encoding in source order, preserving all data.

Zero-based storage indexStored value
097
198
297
398

docA_SourceCodePoints

Scalars=2 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Validated Unicode scalars in exact input order.

Zero-based storage indexStored value
097
198

docA_SourceUTF16Offsets

Scalars=2 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Zero-based UTF-16 storage offset for each scalar.

Zero-based storage indexStored value
00
11

docA_SourceUTF16Widths

Scalars=2 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. UTF-16 storage units consumed by each scalar.

Zero-based storage indexStored value
01
11

docA_SourceByteOffsets

Scalars=2 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Zero-based UTF-8 byte offset for each scalar.

Zero-based storage indexStored value
00
11

docA_SourceByteWidths

Scalars=2 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Actual UTF-8 bytes emitted by each scalar.

Zero-based storage indexStored value
01
11

docA_SourceBytes

Bytes=2 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Manual UTF-8 encoding in source order, preserving all data.

Zero-based storage indexStored value
097
198

docA_TrainInitialIDs

Tokens=4 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Initial training byte IDs, one ID for each actual corpus byte.

Zero-based storage indexStored value
097
198
297
398

docA_CorpusIDs

Tokens=4 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Final learned corpus token IDs; corpus training never contains EOS.

Zero-based storage indexStored value
097
198
297
398

docA_EncodeInitialIDs

Tokens=2 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Initial target byte IDs before any ranked application.

Zero-based storage indexStored value
097
198

docA_TargetIDs

Tokens=2 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Final target token IDs after all learned ranks, then optional unique EOS tail.

Zero-based storage indexStored value
097
198

docA_CorpusDecodedBytes

Bytes=4 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Actual final corpus ID expansions passed to strict UTF-8 decoding.

Zero-based storage indexStored value
097
198
297
398

docA_TargetDecodedBytes

Bytes=2 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Actual final target ID expansions passed to strict UTF-8 decoding.

Zero-based storage indexStored value
097
198

docB_CorpusCodePoints

Scalars=4 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Validated Unicode scalars in exact input order.

Zero-based storage indexStored value
097
198
297
398

docB_CorpusUTF16Offsets

Scalars=4 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Zero-based UTF-16 storage offset for each scalar.

Zero-based storage indexStored value
00
11
22
33

docB_CorpusUTF16Widths

Scalars=4 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. UTF-16 storage units consumed by each scalar.

Zero-based storage indexStored value
01
11
21
31

docB_CorpusByteOffsets

Scalars=4 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Zero-based UTF-8 byte offset for each scalar.

Zero-based storage indexStored value
00
11
22
33

docB_CorpusByteWidths

Scalars=4 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Actual UTF-8 bytes emitted by each scalar.

Zero-based storage indexStored value
01
11
21
31

docB_CorpusBytes

Bytes=4 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Manual UTF-8 encoding in source order, preserving all data.

Zero-based storage indexStored value
097
198
297
398

docB_SourceCodePoints

Scalars=2 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Validated Unicode scalars in exact input order.

Zero-based storage indexStored value
098
197

docB_SourceUTF16Offsets

Scalars=2 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Zero-based UTF-16 storage offset for each scalar.

Zero-based storage indexStored value
00
11

docB_SourceUTF16Widths

Scalars=2 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. UTF-16 storage units consumed by each scalar.

Zero-based storage indexStored value
01
11

docB_SourceByteOffsets

Scalars=2 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Zero-based UTF-8 byte offset for each scalar.

Zero-based storage indexStored value
00
11

docB_SourceByteWidths

Scalars=2 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Actual UTF-8 bytes emitted by each scalar.

Zero-based storage indexStored value
01
11

docB_SourceBytes

Bytes=2 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Manual UTF-8 encoding in source order, preserving all data.

Zero-based storage indexStored value
098
197

docB_TrainInitialIDs

Tokens=4 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Initial training byte IDs, one ID for each actual corpus byte.

Zero-based storage indexStored value
097
198
297
398

docB_CorpusIDs

Tokens=4 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Final learned corpus token IDs; corpus training never contains EOS.

Zero-based storage indexStored value
097
198
297
398

docB_EncodeInitialIDs

Tokens=2 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Initial target byte IDs before any ranked application.

Zero-based storage indexStored value
098
197

docB_TargetIDs

Tokens=2 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Final target token IDs after all learned ranks, then optional unique EOS tail.

Zero-based storage indexStored value
098
197

docB_CorpusDecodedBytes

Bytes=4 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Actual final corpus ID expansions passed to strict UTF-8 decoding.

Zero-based storage indexStored value
097
198
297
398

docB_TargetDecodedBytes

Bytes=2 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Actual final target ID expansions passed to strict UTF-8 decoding.

Zero-based storage indexStored value
098
197

ActiveIDs

Class=3 · int32 · precision 0 · Restricted prediction-class public IDs; PAD excluded; not the full tokenizer vocabulary.

Zero-based storage indexStored value
097
198
2512

docA_ContentIDs

ContentPosition=2 · int32 · precision 0 · Actual old EOS-off TargetIDs, copied without lookup or retokenization.

Zero-based storage indexStored value
097
198

docA_SequenceIDs

DocumentPosition=3 · int32 · precision 0 · Actual content IDs followed by exactly one explicit EOS512.

Zero-based storage indexStored value
097
198
2512

docB_ContentIDs

ContentPosition=2 · int32 · precision 0 · Actual old EOS-off TargetIDs, copied without lookup or retokenization.

Zero-based storage indexStored value
098
197

docB_SequenceIDs

DocumentPosition=3 · int32 · precision 0 · Actual content IDs followed by exactly one explicit EOS512.

Zero-based storage indexStored value
098
197
2512

SlotIDs

Chunk=1 × Slot=6 · int32 · precision 0 · Six physical slots, row-major; actual document/chunk identities and declared position policy.

Zero-based storage indexStored value
097
198
2512
398
497
5512

SlotGlobalIndices

Chunk=1 × Slot=6 · int32 · precision 0 · Six physical slots, row-major; actual document/chunk identities and declared position policy.

Zero-based storage indexStored value
00
11
22
33
44
55

SlotDocIDs

Chunk=1 × Slot=6 · int32 · precision 0 · Six physical slots, row-major; actual document/chunk identities and declared position policy.

Zero-based storage indexStored value
00
10
20
31
41
51

SlotDocPositions

Chunk=1 × Slot=6 · int32 · precision 0 · Six physical slots, row-major; actual document/chunk identities and declared position policy.

Zero-based storage indexStored value
00
11
22
30
41
52

SlotChunkIDs

Chunk=1 × Slot=6 · int32 · precision 0 · Six physical slots, row-major; actual document/chunk identities and declared position policy.

Zero-based storage indexStored value
00
10
20
30
40
50

SlotChunkPositions

Chunk=1 × Slot=6 · int32 · precision 0 · Six physical slots, row-major; actual document/chunk identities and declared position policy.

Zero-based storage indexStored value
00
11
22
33
44
55

SlotPositionIDs

Chunk=1 × Slot=6 · int32 · precision 0 · Six physical slots, row-major; actual document/chunk identities and declared position policy.

Zero-based storage indexStored value
00
11
22
30
41
52

SlotValid

Chunk=1 × Slot=6 · bool · precision 0 · Six physical slots, row-major; actual document/chunk identities and declared position policy.

Zero-based storage indexStored value
0true
1true
2true
3true
4true
5true

Allowed

Chunk=1 × Query=6 × Key=6 · bool · precision 0 · Actual conjunction of both validity flags, local causality and the declared document gate. No attention probabilities computed.

Zero-based storage indexStored value
0true
1false
2false
3false
4false
5false
6true
7true
8false
9false
10false
11false
12true
13true
14true
15false
16false
17false
18false
19false
20false
21true
22false
23false
24false
25false
26false
27true
28true
29false
30false
31false
32false
33true
34true
35true

InputIDs

PredictionRow=5 · int32 · precision 0 · All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.

Zero-based storage indexStored value
097
198
2512
398
497

TargetIDs

PredictionRow=5 · int32 · precision 0 · All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.

Zero-based storage indexStored value
098
1512
298
397
4512

InputDocIDs

PredictionRow=5 · int32 · precision 0 · All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.

Zero-based storage indexStored value
00
10
20
31
41

TargetDocIDs

PredictionRow=5 · int32 · precision 0 · All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.

Zero-based storage indexStored value
00
10
21
31
41

InputDocPositions

PredictionRow=5 · int32 · precision 0 · All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.

Zero-based storage indexStored value
00
11
22
30
41

TargetDocPositions

PredictionRow=5 · int32 · precision 0 · All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.

Zero-based storage indexStored value
01
12
20
31
42

InputChunkIDs

PredictionRow=5 · int32 · precision 0 · All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.

Zero-based storage indexStored value
00
10
20
30
40

TargetChunkIDs

PredictionRow=5 · int32 · precision 0 · All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.

Zero-based storage indexStored value
00
10
20
30
40

InputChunkPositions

PredictionRow=5 · int32 · precision 0 · All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.

Zero-based storage indexStored value
00
11
22
33
44

TargetChunkPositions

PredictionRow=5 · int32 · precision 0 · All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.

Zero-based storage indexStored value
01
12
23
34
45

InputPositionIDs

PredictionRow=5 · int32 · precision 0 · All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.

Zero-based storage indexStored value
00
11
22
30
41

TargetPositionIDs

PredictionRow=5 · int32 · precision 0 · All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.

Zero-based storage indexStored value
01
12
20
31
42

RequestedMask

PredictionRow=5 · int32 · precision 0 · All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.

Zero-based storage indexStored value
01
11
21
31
41

InputValid

PredictionRow=5 · bool · precision 0 · All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.

Zero-based storage indexStored value
0true
1true
2true
3true
4true

TargetValid

PredictionRow=5 · bool · precision 0 · All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.

Zero-based storage indexStored value
0true
1true
2true
3true
4true

SameChunk

PredictionRow=5 · bool · precision 0 · All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.

Zero-based storage indexStored value
0true
1true
2true
3true
4true

SameDoc

PredictionRow=5 · bool · precision 0 · All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.

Zero-based storage indexStored value
0true
1true
2false
3true
4true

IsolationGate

PredictionRow=5 · bool · precision 0 · All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.

Zero-based storage indexStored value
0true
1true
2false
3true
4true

StructuralMask

PredictionRow=5 · bool · precision 0 · All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.

Zero-based storage indexStored value
0true
1true
2false
3true
4true

EffectiveMask

PredictionRow=5 · bool · precision 0 · All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.

Zero-based storage indexStored value
0true
1true
2false
3true
4true

TargetRows

PredictionRow=5 · int32 · precision 0 · All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.

Zero-based storage indexStored value
01
12
21
30
42

ValidTargetsRunning

PredictionRow=5 · int32 · precision 0 · All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.

Zero-based storage indexStored value
01
12
22
33
44

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 appending EOS512 after each document do by itself?
2. At reset (ab, ba, no merges, one six-slot chunk, isolation on, all requested masks 1), which storage and target count are correct?
3. Current packedTokens=6, paddingSlots=0, allowedCells=12, validTargets=4. Which interpretation uses the saved counts correctly?
4. Inspect saved global query3 (chunk 0) and local key0 (global 0). The saved key0Allowed is 0. Which explanation matches this cell?
5. Transfer: use ab / ba, one merge, chunk size3, isolation on, all requested masks1. Does the same-document b → a pair at physical row2 contribute?

At reset, ab and ba become [97,98,512] and [98,97,512]. Isolation gives two three-slot causal triangles: 12 allowed cells. Five adjacent physical pairs have effective masks [1,1,0,1,1], so four targets are included. Each isolated document’s first piece is given; each EOS is a real target when its preceding pair is retained.

Turn isolation off while keeping chunk size6: permission count becomes21 and the EOS-to-next-document-first-piece pair is included, giving five targets. This explicitly permits earlier-document conditioning. A separator alone never guarantees isolation. With chunk size3, the reset document boundary also cuts the chunk, so that pair stays excluded under either document policy.

Request one merge: the genuine old BPE calls learn ab as ID256 from fixed corpus abab. The packed IDs become [256,512,98,97,512,768]. With chunk size3 and isolation on, the b-to-a pair in docB crosses the chunk boundary and is excluded despite matching document IDs. Query and key PAD permissions are false storage policy; PAD has no prediction class. Setting all masks to0 is valid here. The next chapter must check separately whether a mean training objective has any included rows.

Input edits, reset and trace navigation clear answers. The three inspection selectors only display saved cells and pairs. The complete inspector retains exact int32 and boolean values, named axes, both actual tokenizer records and provenance; no displayed value feeds a hidden computation.

Reset uses document A=ab, document B=ba, zero BPE merges, one six-slot chunk, document isolation on and all five requested target masks on. The first four summaries are 6 packed tokens, 0 padding slots, 12 allowed attention cells and 4 eligible targets. Turn isolation off: the same six tokens now permit 21 cells and 5 targets. These are integer counts and boolean permissions; no neural forward calculation, attention probabilities, loss or training update is computed.

Use Saved global query (inspection only) and Saved local key in this query’s chunk to select an existing permission cell. At reset, query 3/key 0 exposes the causal-but-cross-document failure. Saved prediction row (inspection only) starts at row 2, showing the actual EOS→b target and its excluded structural product. Open each saved-operands disclosure to read the complete gate inputs rather than infer permission from a color.

Editing a document, merge count, chunk size, isolation choice or requested mask recomputes the result and clears graded answers. Reset example restores the default. Previous step, Next step and Calculation step select saved trace operations and also clear answers. The three inspection selectors only choose evidence: they preserve the input state, trace cursor and graded answers. An invalid input shows a reason and removes the unavailable result and its questions.

The documents and the fixed tokenizer-training corpus abab were authored for this lesson. They are tiny strings for inspecting boundaries, not a downloaded corpus or evidence about language-model quality. Review IV-39 — Byte-Pair Encoding: A Full Merge Trace for actual byte-pair encoding (BPE) and IV-41 — Teacher Forcing and Shifted Targets for shifted targets. Book II’s I.8 — Indexed quantities and summation explains indices and sums; Book III’s III-02 — Samples, Features, Labels and Targets distinguishes inputs from targets. III-04 — Training, Validation, Testing and Generalization supplies the broader training/validation/test distinction: a context boundary inside a packed example does not by itself prevent evaluation-data leakage.

Give tokens, storage and targets different names

A document is one source string. A token is a piece represented by an integer ID; a token can contain more than one character. Tokenization converts text into those pieces. A chunk is one fixed-width block of physical slots. Context is the set of input positions a prediction is permitted to use. Causal context excludes future inputs. Isolation additionally excludes other documents, even when their earlier tokens share a chunk.

A mask is a set of permissions or inclusion choices. Here true means permitted and false means forbidden. We sometimes write 1 and 0 in hand tables so their sums are easy to count. An attention mask chooses keys an input query may read. A target mask chooses next-token pairs eligible for later scoring. Neither is a probability.

A query identifies the input position whose attention row we inspect; a key identifies a candidate context position in that row. This chapter saves only permission flags, not query/key feature vectors or dot products. A tensor is an array with named axes. Shape [C,S,S] means C chunks, S query positions per chunk and S candidate keys per query. Its last two axes have different jobs even when they have the same length.

Raw fieldMeaningPermitted valuesReset
docA, docBExact source strings, separately tokenizedNonempty raw a/b strings, at most 2 UTF-8 bytes eachab, ba
mergesRequested BPE rule count, on fixed corpus ababInteger 0,1,20
blockSize, written SSlots in one chunk3 or 66
isolateDocument boundary policyNumeric 1 for isolation, 0 for concatenation1
m0 through m4Requested inclusion for physical pair i→i+1Each numeric 0 or 1All 1

A byte is an eight-bit storage unit; UTF-8 encodes Unicode text as bytes. This lesson accepts only a and b, each one byte. The bounds still validate actual encoding: text is never trimmed, normalized, shortened or replaced with an unknown-token marker. A numeric string such as "1" and a boolean such as true are not numeric 1 at the raw-state boundary.

Tokenize first, then append one separator

Each document makes a genuine IV39 call with corpus='abab', the requested merges and eos=0. The two calls train the same rules separately; both complete traces are retained as docA_… and docB_…. This is two calls, not one shared training call. Old trace statements about a 24-byte input bound and four possible merges describe the reused tokenizer. Our outer lesson narrows each document to 2 bytes and the request to two merges.

At zero merges, A becomes [97,98] and B becomes [98,97]: 97 is a and 98 is b. Append exactly one EOS/512 to each result, giving [97,98,512] and [98,97,512]. EOS, end of sequence, is an explicit separator/control token and can be a real next-token target. It does not automatically change an attention permission.

PAD/768 means an unused physical slot. PAD is outside the prediction classes. The restricted active ID list is the first V=3+merges entries of [97,98,512,256,257]; V counts classes, not slots. At zero merges its compact class rows are 0,1,2. At one merge ID 256 occupies row 3; at two merges ID 257 occupies row 4. These compact rows differ from public token IDs and from the tokenizer’s full byte vocabulary.

Here is the actual rule arithmetic. Corpus abab starts [97,98,97,98]. Adjacent pair (97,98) occurs twice; (98,97) occurs once. The first rule replaces a,b with ID 256, leaving [256,256]. The second rule replaces that pair with ID 257, whose byte expansion is abab. Applying those ranked rules to A=ab gives [256] at either one or two merges. B=ba remains [98,97]; it contains neither learned pair. Thus the merged document sequences are [256,512] and [98,97,512]. A larger merge budget need not shorten either input further. Learning these BPE rules means counting and replacing pairs; it does not update neural-network parameters.

Six slots, two kinds of position

Concatenate A’s complete sequence, then B’s, and fill only the remaining tail with PAD. There are always six slots. Write C=6/S for the number of chunks: S=6 gives C=1; S=3 gives C=2. Storage is row-major: finish the first chunk’s slots before the second chunk. No token is dropped to obtain those shapes.

For global slot index g=0,…,5, chunkID=floor(g/S) and chunkPosition=g%S. floor means round down; % gives the remainder after division. docID is 0 for A and 1 for B. docPosition starts at 0 independently in each document and includes EOS. For PAD, docID and docPosition are −1 and valid is false. Physical chunk identities still exist for PAD storage.

The declared positionID policy is docPosition under isolation and chunkPosition under concatenation; PAD has −1. This is saved data policy. We do not claim an uncalled decoder has consumed these positions or masks.

At reset the slot identities are:

Global slotIDdocIDdocPositionChunk ID / local slotpositionID isolated / concat
097000 / 00 / 0
198010 / 11 / 1
2512020 / 22 / 2
398100 / 30 / 3
497110 / 41 / 4
5512120 / 52 / 5

Every reset slot is valid. Notice that the two occurrences of ID 98 belong to different documents; token identity alone cannot decide isolation.

Saved tensor familyShape and named axesMeaning / dtype
ActiveIDs[V], ClassPublic class IDs; int32
docA_ContentIDs, docB_ContentIDs[NA], [NB], ContentPositionActual EOS-off tokens, each N is 1 or 2; int32
docA_SequenceIDs, docB_SequenceIDs[NA+1], [NB+1], DocumentPositionEach content stream plus one EOS; int32
SlotIDs, SlotGlobalIndices, SlotDocIDs, SlotDocPositions, SlotChunkIDs, SlotChunkPositions, SlotPositionIDs[C,S], Chunk, SlotAll six physical positions; int32
SlotValid[C,S], Chunk, SlotWhether a real token occupies each slot; bool
Allowed[C,S,S], Chunk, Query, KeyEvery key permission, including false cells; bool
InputIDs/TargetIDs and input/target document, chunk and position columns[5], PredictionRowAll physical pairs, including excluded targets; int32
RequestedMask, TargetRows, ValidTargetsRunning[5], PredictionRowRequested 0/1, compact target row and running count; int32
InputValid, TargetValid, SameChunk, SameDoc, IsolationGate, StructuralMask, EffectiveMask[5], PredictionRowSaved target eligibility predicates; bool

NA and NB count content tokens in A and B, excluding EOS. All arrays introduced here use exact int32 IDs/counts or booleans, with display precision 0. A dtype is the stored kind of value: int32 means a signed 32-bit whole number, and bool means true or false. Display precision 0 shows whole numbers without decimal rounding. The two retained tokenizer records also expose their original shapes, bytes, rules, expansions and provenance. There is no feature axis, batch of neural outputs or probability tensor in this lesson.

Derive the attention permissions

Choose chunk c, local query q and local key k, each local index starting at 0. Their global slots are c*S+q and c*S+k. Let Qvalid and Kvalid be the two stored validity flags, and sameDoc compare their docIDs. Then

causal = (k <= q)
isolationGate = (isolate == 0) OR sameDoc
allowed[c,q,k] = Qvalid AND Kvalid AND causal AND isolationGate

AND requires every operand to be true; OR requires at least one. Chunk membership is fixed before this rule: k never ranges outside c’s chunk. Causality alone cannot prevent cross-document context. At reset, global q=3 is B’s first b and k=0 is A’s a. Both are valid and 0≤3, but their docIDs differ, so isolation forbids the cell.

The complete reset grid below uses global row/column labels because there is one chunk. Rows are queries; columns are keys. A1 means A’s b at document position 1; AE means A’s EOS. One means allowed.

Query / keyA0A1AEB0B1BERow count
A01000001
A11100002
AE1110003
B00001001
B10001102
BE0001113

Each three-token document contributes 1+2+3=6 cells, giving 12. With isolation off, successive rows allow 1,2,3,4,5,6 keys: 21 altogether. In particular B’s first row may read all three A tokens. EOS is still present in both modes; only the explicit gate changes that context.

With S=3, reset chunks are [97,98,512] and [98,97,512]. Each has one six-cell triangle, so the total is 12 in either isolation mode. Turning isolation off cannot restore cross-chunk context. The shape is [2,3,3], containing 18 stored booleans rather than the 36 in [1,6,6]; 12 are true in either case.

Shift targets without admitting future context

There are always five physical prediction rows, i=0,…,4. Input is slot i and target is slot i+1. The last slot has no following stored target. Saving a target for comparison does not permit the input query to read it; the causal attention gate still forbids a future key.

For each pair, save inputValid, targetValid, sameChunk and sameDoc. The structural mask enforces the task’s boundaries; the requested mask can only remove an otherwise eligible pair:

isolationGate = (isolate == 0) OR sameDoc
structuralMask = inputValid * targetValid * sameChunk * isolationGate
effectiveMask = m_i * structuralMask
validTargets = sum of effectiveMask in rows 0,1,2,3,4

Here multiplication uses 0/1 flags, so it has the same truth table as AND. validTargets counts eligible targets; it is not a loss value. targetRow maps a valid target ID to its compact class even if that pair is excluded. For a PAD target it is −1, metadata that must never be gathered as a class index.

At reset all requests are 1 and both slots of every pair are valid. Row 2 therefore has structural product 1×1×1×0=0 under isolation, while row 0 has 1×1×1×1=1:

iInput→targetSame chunkSame documentStructural / effectiveTarget class
0a97→b98111 / 11
1b98→EOS512111 / 12
2EOS512→b98100 / 01
3b98→a97111 / 10
4a97→EOS512111 / 12

The mask [1,1,0,1,1] gives running counts [1,2,2,3,4]. Each isolated document’s first piece is given; each EOS is eligible through its preceding content pair. Under concatenation, row 2 also becomes eligible, giving five targets. That defines a different conditioning task: B’s first token may follow A’s EOS and use A’s earlier context.

With S=3, row 2 crosses chunks. Its actual target b98 remains visible, but sameChunk=0 excludes it even with isolation off. Changing a loss request cannot bridge that cut. Setting m0=0 at reset changes only effective row 0 to 0 and the count to 3; tokens, positions and attention permissions remain unchanged.

A merge moves the chunk boundary inside a document

Use merges=1 or 2 with the original documents. The six physical slots are now [256,512,98,97,512,768]; five are real and one is PAD. The docIDs are [0,0,1,1,1,-1] and docPositions [0,1,0,1,2,-1].

At S=6, isolated positionIDs equal those docPositions. Concatenated positionIDs are [0,1,2,3,4,-1]. Isolated attention has a two-token triangle 3 plus a three-token triangle 6, totaling 9. Concatenation has a five-token triangle 1+2+3+4+5=15. PAD adds no allowed cell.

Now set S=3. Chunks become [256,512,98] and [97,512,768]. B’s b is the last token of chunk 0, while its a is first in chunk 1. Isolated positionIDs remain [0,1,0,1,2,-1]; concatenated positionIDs become [0,1,2,0,1,-1].

The full local query-row patterns under isolation are chunk 0=[100,110,001] and chunk 1=[100,110,000], where each three-character row lists keys 0,1,2. Chunk 0 contributes 1+2+1=4 cells; chunk 1 contributes 1+2+0=3, total 7. Under concatenation chunk 0 becomes [100,110,111], contributing 6; chunk 1 still contributes 3, total 9. B’s first token in chunk 1 cannot read its own preceding b in chunk 0.

Merged physical rowPairS=6 isolated / concat effectiveS=3 isolated / concat effective
0ab256→EOS5121 / 11 / 1
1EOS512→b980 / 10 / 1
2b98→a971 / 10 / 0
3a97→EOS5121 / 11 / 1
4EOS512→PAD7680 / 00 / 0

All requested masks are 1 in this table. Counts are 3/4 at S=6 and 2/3 at S=3. Row 2 is the counterexample to “same document means every target survives”: sameDoc=1 but sameChunk=0. Row 1 is the counterexample to “EOS automatically blocks reading or scoring the next document.” The selected policy, not the separator ID alone, decides.

Padding and empty masks are defined storage cases

Every PAD query row is all false, and every PAD key column is false. These are storage permissions, not softmax rows. Softmax converts allowed numerical scores to probabilities by dividing by their positive exponential sum. If an attention kernel were incorrectly asked to process an all-false row, no allowed term would exist: the old contract returns FULLY_MASKED_ROW. It must not invent a uniform row, a valid zero-probability distribution or an unmasked PAD key.

In contrast, set all five requested masks to 0. The packing record remains defined with validTargets=0: its documents, slots and permission flags still make sense. There is no objective 0, mean 0 or perplexity 1 here. A later mean loss would need a nonzero target count and must reject an all-masked denominator separately. The name “loss mask” describes intended later use; no logits, probabilities P, negative log-likelihood (NLL), gradients, optimizer state or training are calculated in IV51. IV41 requested an actual mean; this chapter requests bookkeeping. That difference explains why a zero count is allowed here without defining an empty mean.

Invalid data stays visible as an error

The raw record has exactly the ten fields above. Own names and data descriptors are checked before reading values; both document string types precede numeric validation. All eight numeric fields validate in default order: merges, blockSize, isolate, m0,…,m4. This includes inactive requests. A nonfinite or nonnumeric numeric field returns NONFINITE; a finite number outside its permitted domain returns INVALID_INPUT. Only then are A’s semantics checked, followed by B’s.

For each document the outer UTF-16 storage-unit bound precedes the strict reused Unicode codec, then the actual 2-byte UTF-8 bound, the raw a/b alphabet and nonemptiness. For example, aaa is UNSUPPORTED_SIZE; an unpaired surrogate within the outer bound is INVALID_INPUT; an emoji occupying two UTF-16 units still exceeds two actual UTF-8 bytes; é fits two bytes but fails this lesson’s alphabet with UNAVAILABLE; an empty document is UNAVAILABLE. Nothing is silently repaired. If m4=2 and A contains an invalid surrogate, the numeric-domain error is found first.

These restrictions make every cell inspectable. They are not a production data pipeline: there is no shuffling, sampling, overlapping window, automatic context carry, corpus split, corpus-quality measurement or claim that packing alone trains a model. Isolation promises no cross-document context inside this declared packing record; it is not a privacy or generalization guarantee.

Follow one saved record

The public helper tokenizePackingDocument(text, merges, field) accepts an actual string, merge count and document label (docA by default, or docB). It returns detached, frozen contentIDs, sequenceIDs, activeIDs and the complete old tokenizer result. The content IDs are copied from real EOS-off TargetIDs; only sequenceIDs adds EOS. Invalid input raises a typed numerical fault. There is no hidden token history or second tokenization to obtain these IDs. IV52 can reuse this data helper without treating a copied default token list as tokenization.

The chapter derivation validates the complete state before calling that helper once for A and once for B. It then saves setup, both tokenizer traces and explicit separators, six slot records, six grouped query rows, five alignment records, counts and finish. Select an allowed_… record to read every local key operand and its causal, document and final gates; select alignment_… to read the actual target plus the structural product. Scalar trace flags use exact 0/1; permission and gate tensors use actual booleans.

A defined public result has ordered sections status, outputs, steps, tensors, texts. The first four outputs are the visible counts; later outputs include every saved step result under its step-ID prefix. Each step retains its ID, label, equation, explanation, inputs and outputs. Tensors carry shapes, named axes, dtype, exact values and provenance; texts retain both source documents, both tokenizer reconstructions and the declared policies. This makes a false cell or excluded target inspectable instead of merely coloring it differently.

Read the complete Python dependency closure

The five panels below display the maintained project files through raw-source imports. Preserve their relative directories under code/python: IV51 loads the adjacent packing helper; packing loads p09/iv39.py; IV39 loads adjacent BPE source; BPE loads adjacent token source. Python’s standard library and NumPy are requirements, not additional hidden project files. Reading a panel does not execute it.

Chapter entry — code/python/p13/iv51.py: the complete ordered public record, integer aliases, copied old tokenizer evidence, tensors, policy texts and CLI entry.

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-51 — Training Data, Packing and Causal Boundaries.

Two actual IV39 EOS-off tokenizers feed NumPy int32 slots and bool gates.
Keep this file, packing_reference.py and the three p09 sources in their relative
layout. No native codec, neural forward, objective or training supplies answers.
No import or query runs a check leaf. --self-check is explicit and deferred.
"""
from copy import deepcopy
import importlib.util
from pathlib import Path
import numpy as np

_spec = importlib.util.spec_from_file_location(
    "_p13_iv51_packing", Path(__file__).resolve().with_name("packing_reference.py"))
if _spec is None or _spec.loader is None:
    raise ImportError("Cannot load adjacent packing_reference.py")
_packing = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_packing)
DEFAULT_IV51 = _packing.DEFAULT_IV51


@_packing.guarded
def derive_iv51(state):
    """Return the complete detached ordered integer/bool packing record."""
    tokenized = _packing.tokenize_documents(state)
    s, documents = tokenized["state"], (tokenized["docA"], tokenized["docB"])
    a = _packing.pack_arrays(tokenized)
    width, chunks = s["blockSize"], 6 // s["blockSize"]
    trace, tensors = _packing._token.TokenTrace(), []
    texts = dict(
        docA=s["docA"], docB=s["docB"],
        tokenizerPolicy="Two genuine IV39 calls, each with fixed corpus abab, requested merges and EOS off; both complete records are retained under docA_/docB_. No normalization, cropping or retokenization.",
        separatorPolicy="Append exactly one explicit EOS512 after each content stream. EOS is a real shifted target and does not itself forbid attention. PAD768 is physical storage only, outside the active classes.",
        contextPolicy="Isolation: allow only valid causal keys in the same chunk and document; positionID is document-local. Each document first piece is given." if s["isolate"] else "Concatenation: allow valid causal keys in the same chunk, including earlier documents; positionID is chunk-local. Within-chunk EOS to next-document first-piece targets may be included.",
        targetPolicy="Five physical pairs i to i+1 are always retained. Cross-chunk, PAD and (when isolated) cross-document pairs are structurally masked; requested masks can only remove rows. targetRow -1 is metadata and is never gathered.",
        paddingPolicy="PAD query and key permissions are all false storage policy. No softmax is called; incorrectly querying such a row would meet the old FULLY_MASKED_ROW condition.",
        objectivePolicy="Integer packing and boolean permissions only: no neural forward, probabilities, NLL, objective, gradients, optimizer or training is computed. All-zero masks give a valid packing record with validTargets=0; IV52 must separately reject an undefined all-masked mean.",
        provenance="Authored toy documents; fixed authored corpus abab. Exact int32 arithmetic and boolean predicates, no random stream or external corpus.",
        modelVocabulary=[f"compact row {row}: public ID {int(identifier)}" for row, identifier in enumerate(a["activeIDs"])],
    )
    trace.add("setup", "Declare the two-document packing policy", "slots=6; C=6/S; V=3+merges; two EOS-off tokenizers then two explicit EOS markers",
              "Validate all ten own data fields, both string types and all eight numeric domains before docA then docB Unicode/domain semantics. The tokenizer full-byte vocabulary differs from the restricted active classes.",
              {key: s[key] for key in tuple(DEFAULT_IV51)[2:]},
              dict(slots=6, chunks=chunks, classCount=len(a["activeIDs"]), byteBound=2,
                   tokenizerCalls=2, EOS=_packing.EOS, PAD=_packing.PAD))
    tokenizer_summary = {}
    for doc_id, doc in enumerate(documents):
        prefix = "docA" if doc_id == 0 else "docB"
        old = doc["record"]
        for step in old["steps"]:
            trace.add(f"{prefix}_{step['id']}", step["label"], step["equation"], step["explanation"],
                      step["inputs"], step["outputs"])
        for original in old["tensors"]:
            record = deepcopy(original)
            record["id"] = f"{prefix}_{original['id']}"
            record["provenance"] = f"Actual {prefix} IV39 call; fixed corpus abab, EOS off. {original['provenance']}"
            tensors.append(record)
        for key in ("corpusBytes", "byteCount", "actualMerges", "tokenCount", "requestedMerges",
                    "corpusTokens", "eos", "byteBound", "vocabularyItems", "corpusEqual", "equal"):
            tokenizer_summary[f"{prefix}_{key}"] = old["outputs"][key]
        for key, value in old["texts"].items():
            texts[f"{prefix}_{key}"] = deepcopy(value)
        trace.add(f"{prefix}_append_eos", f"{prefix}: append one explicit document separator", "sequenceIDs=[...actual EOS-off TargetIDs,512]",
                  "The content IDs come from the genuine old tokenizer. Its EOS flag was zero; this separate append creates exactly one separator without retokenizing.",
                  dict(docID=doc_id, contentTokens=len(doc["contentIDs"]), tokenizerEOS=old["outputs"]["eos"]),
                  dict(eosPosition=len(doc["contentIDs"]), eosID=_packing.EOS, sequenceTokens=len(doc["sequenceIDs"])))

    def save(identifier, shape, axes, values, provenance):
        # Every source array is int32 or bool; JSON storage is explicitly flat.
        tensors.append(dict(id=identifier, shape=list(shape), axes=list(axes),
                            dtype="bool" if values.dtype == np.dtype(np.bool_) else "int32",
                            values=values.reshape(-1).tolist(), provenance=provenance, precision=0))

    save("ActiveIDs", [len(a["activeIDs"])], ["Class"], a["activeIDs"],
         "Restricted prediction-class public IDs; PAD excluded; not the full tokenizer vocabulary.")
    for prefix, doc in zip(("docA", "docB"), documents):
        save(f"{prefix}_ContentIDs", [len(doc["contentIDs"])], ["ContentPosition"], doc["contentIDs"],
             "Actual old EOS-off TargetIDs, copied without lookup or retokenization.")
        save(f"{prefix}_SequenceIDs", [len(doc["sequenceIDs"])], ["DocumentPosition"], doc["sequenceIDs"],
             "Actual content IDs followed by exactly one explicit EOS512.")
    slot_columns = dict(SlotIDs=a["slots"].reshape(6), SlotGlobalIndices=a["globalIndices"],
                        SlotDocIDs=a["docIDs"], SlotDocPositions=a["docPositions"],
                        SlotChunkIDs=a["chunkIDs"], SlotChunkPositions=a["chunkPositions"],
                        SlotPositionIDs=a["positionIDs"], SlotValid=a["valid"])
    for i in range(6):
        trace.add(f"slot_{i}", f"Store physical slot {i}", "chunkID=floor(i/S); chunkPosition=i%S; positionID=valid?(isolate?docPosition:chunkPosition):-1",
                  "Copy the complete concatenated document streams in row-major order, then fill only the physical tail with PAD. Document and position sentinels -1 never name a token or a gather row.",
                  dict(globalIndex=i, packedTokens=a["packedTokens"], blockSize=width, isolate=s["isolate"]),
                  dict(id=int(slot_columns["SlotIDs"][i]), docID=int(a["docIDs"][i]), docPosition=int(a["docPositions"][i]),
                       chunkID=int(a["chunkIDs"][i]), chunkPosition=int(a["chunkPositions"][i]),
                       positionID=int(a["positionIDs"][i]), valid=int(a["valid"][i])))
    for identifier, values in slot_columns.items():
        save(identifier, [chunks, width], ["Chunk", "Slot"], values,
             "Six physical slots, row-major; actual document/chunk identities and declared position policy.")
    allowed_running = 0
    for q in range(6):
        chunk, local_q = int(a["chunkIDs"][q]), int(a["chunkPositions"][q])
        inputs = dict(globalQuery=q, chunkID=chunk, queryPosition=local_q,
                      queryID=int(slot_columns["SlotIDs"][q]), queryDocID=int(a["docIDs"][q]),
                      queryValid=int(a["valid"][q]), isolate=s["isolate"])
        outputs, row_allowed = {}, 0
        for k in range(width):
            global_key = chunk * width + k
            same_doc = int(a["docIDs"][q] == a["docIDs"][global_key])
            permit = int(a["allowed"][chunk, local_q, k])
            inputs.update({f"key{k}GlobalIndex": global_key, f"key{k}Position": k,
                           f"key{k}ID": int(slot_columns["SlotIDs"][global_key]),
                           f"key{k}DocID": int(a["docIDs"][global_key]), f"key{k}Valid": int(a["valid"][global_key])})
            outputs.update({f"key{k}Causal": int(k <= local_q), f"key{k}SameDoc": same_doc,
                            f"key{k}IsolationGate": int(not s["isolate"] or same_doc), f"key{k}Allowed": permit})
            row_allowed += permit
        allowed_running += row_allowed
        outputs.update(rowAllowed=row_allowed, allowedRunning=allowed_running)
        trace.add(f"allowed_{q}", f"Save every key gate for global query {q}", "allowed=qValid AND kValid AND (localKey<=localQuery) AND (!isolate OR sameDoc)",
                  "One grouped row retains all S local key operands and results, including future, cross-document and PAD failures. Chunk membership is fixed by construction; no key outside this chunk is inspected.", inputs, outputs)
    save("Allowed", [chunks, width, width], ["Chunk", "Query", "Key"], a["allowed"],
         "Actual conjunction of both validity flags, local causality and the declared document gate. No attention probabilities computed.")
    metadata = (("ID", "SlotIDs"), ("DocID", "SlotDocIDs"), ("DocPosition", "SlotDocPositions"),
                ("ChunkID", "SlotChunkIDs"), ("ChunkPosition", "SlotChunkPositions"), ("PositionID", "SlotPositionIDs"))
    alignment = {}
    for name, column in metadata:
        alignment[f"Input{name}s"] = slot_columns[column][:-1].copy()
        alignment[f"Target{name}s"] = slot_columns[column][1:].copy()
    alignment.update(RequestedMask=a["requestedMask"], InputValid=a["inputValid"], TargetValid=a["targetValid"],
                     SameChunk=a["sameChunk"], SameDoc=a["sameDoc"], IsolationGate=a["isolationGate"],
                     StructuralMask=a["structuralMask"], EffectiveMask=a["effectiveMask"],
                     TargetRows=a["targetRows"], ValidTargetsRunning=a["validTargetsRunning"])
    for i in range(5):
        inputs = dict(row=i, inputGlobalIndex=i, targetGlobalIndex=i + 1, isolate=s["isolate"],
                      requestedMask=int(a["requestedMask"][i]))
        for name, column in metadata:
            inputs[f"input{name}"] = int(slot_columns[column][i])
            inputs[f"target{name}"] = int(slot_columns[column][i + 1])
        outputs = dict(inputValid=int(a["inputValid"][i]), targetValid=int(a["targetValid"][i]),
                       sameChunk=int(a["sameChunk"][i]), sameDoc=int(a["sameDoc"][i]),
                       isolationGate=int(a["isolationGate"][i]), structuralMask=int(a["structuralMask"][i]),
                       effectiveMask=int(a["effectiveMask"][i]), targetRow=int(a["targetRows"][i]),
                       validTargetsRunning=int(a["validTargetsRunning"][i]))
        trace.add(f"alignment_{i}", f"Align physical input {i} with target {i + 1}", "structural=inputValid*targetValid*sameChunk*isolationGate; effective=requestedMask*structural; running+=effective",
                  "Keep the actual outside-chunk or cross-document target ID visible even when excluded. EOS can be a real target. PAD has targetRow -1 metadata, never a gather. Requested masks cannot restore a structurally excluded pair.", inputs, outputs)
    for identifier, values in alignment.items():
        save(identifier, [5], ["PredictionRow"], values,
             "All five physical shifted pairs, including excluded rows; copied saved operands and exact gate products.")
    trace.add("counts", "Finish the actual ascending-order integer reductions", "packedTokens=len(Asequence)+len(Bsequence); paddingSlots=6-packedTokens; allowedCells=sum(Allowed); validTargets=sum(EffectiveMask)",
              "Both sums accumulate actual saved cell/row results in row-major or ascending prediction-row order. validTargets is a metadata count, not a computed objective.",
              dict(docASequenceTokens=len(documents[0]["sequenceIDs"]), docBSequenceTokens=len(documents[1]["sequenceIDs"]), physicalSlots=6, predictionRows=5),
              {key: a[key] for key in ("packedTokens", "paddingSlots", "allowedCells", "validTargets")})
    trace.add("finish", "Retain every old record and disclose the computation boundary", "tokenizerCalls=2; appendedEOS=2; neuralCalls=0; objectiveComputed=0",
              "All tensors and six-field steps from both actual old tokenizers remain inspectable with unique scopes; no issuance history, hidden state, prediction or training claim exists.",
              dict(tokenizerFrames=sum(len(doc["record"]["steps"]) for doc in documents),
                   tokenizerTensors=sum(len(doc["record"]["tensors"]) for doc in documents)),
              dict(tokenizerCalls=2, appendedEOS=2, neuralCalls=0, objectiveComputed=0))
    summary = dict(packedTokens=a["packedTokens"], paddingSlots=a["paddingSlots"], allowedCells=a["allowedCells"], validTargets=a["validTargets"],
                   merges=s["merges"], blockSize=width, isolate=s["isolate"], chunks=chunks, classCount=len(a["activeIDs"]),
                   byteBound=2, physicalSlots=6, predictionRows=5, tokenizerCalls=2, appendedEOS=2, neuralCalls=0, objectiveComputed=0,
                   docAContentTokens=len(documents[0]["contentIDs"]), docBContentTokens=len(documents[1]["contentIDs"]),
                   frames=len(trace.steps), tensorCount=len(tensors))
    summary.update(tokenizer_summary)
    return deepcopy(trace.result(summary, tensors, texts))


def source_self_check():
    """Deferred public-record assertions; no old/new check leaf is called."""
    assert __debug__, "Run later checks with assertions enabled."
    default = derive_iv51(dict(DEFAULT_IV51))
    assert list(default) == ["status", "outputs", "steps", "tensors", "texts"]
    summary_keys = ["packedTokens", "paddingSlots", "allowedCells", "validTargets", "merges", "blockSize", "isolate", "chunks", "classCount", "byteBound", "physicalSlots", "predictionRows", "tokenizerCalls", "appendedEOS", "neuralCalls", "objectiveComputed", "docAContentTokens", "docBContentTokens", "frames", "tensorCount"]
    for prefix in ("docA", "docB"):
        summary_keys.extend(f"{prefix}_{key}" for key in ("corpusBytes", "byteCount", "actualMerges", "tokenCount", "requestedMerges", "corpusTokens", "eos", "byteBound", "vocabularyItems", "corpusEqual", "equal"))
    assert list(default["outputs"])[:42] == summary_keys
    assert len(default["outputs"]) == 474 and len(default["texts"]) == 32
    for patch, frames, tensor_count, allowed, effective in (
        ({}, 62, 72, 12, [1, 1, 0, 1, 1]),
        (dict(docA="a", docB="b"), 56, 72, 6, [1, 0, 1, 0, 0]),
        (dict(isolate=0), 62, 72, 21, [1, 1, 1, 1, 1]),
        (dict(blockSize=3), 62, 72, 12, [1, 1, 0, 1, 1]),
        (dict(merges=1), 78, 94, 9, [1, 0, 1, 1, 0]),
        (dict(merges=2), 89, 110, 9, [1, 0, 1, 1, 0]),
        (dict(merges=2, blockSize=3), 89, 110, 7, [1, 0, 0, 1, 0]),
        (dict(merges=2, blockSize=3, isolate=0), 89, 110, 9, [1, 1, 0, 1, 0]),
        (dict(merges=2, docA="aa", docB="bb"), 92, 110, 12, [1, 1, 0, 1, 1]),
    ):
        record = derive_iv51({**DEFAULT_IV51, **patch})
        assert record["status"] == "defined"
        assert len(record["steps"]) == record["outputs"]["frames"] == frames
        assert len(record["tensors"]) == record["outputs"]["tensorCount"] == tensor_count
        assert record["outputs"]["allowedCells"] == allowed
        assert record["outputs"]["validTargets"] == sum(effective)
        tensors = {item["id"]: item for item in record["tensors"]}
        assert tensors["EffectiveMask"]["values"] == [bool(value) for value in effective]
        assert tensors["RequestedMask"]["dtype"] == "int32"
        assert tensors["Allowed"]["dtype"] == "bool"
        for item in record["tensors"]:
            assert list(item) == ["id", "shape", "axes", "dtype", "values", "provenance", "precision"]
            assert item["precision"] == 0 and item["dtype"] in ("int32", "bool")
            assert all(type(value) is (bool if item["dtype"] == "bool" else int) for value in item["values"])
        aliases = []
        for step in record["steps"]:
            assert list(step) == ["id", "label", "equation", "explanation", "inputs", "outputs"]
            for key, value in step["outputs"].items():
                alias = f"{step['id']}_{key}"
                aliases.append(alias)
                assert type(value) is int and record["outputs"][alias] == value
        assert list(record["outputs"])[42:] == aliases
    merged = derive_iv51({**DEFAULT_IV51, "merges": 2, "blockSize": 3})
    cells = {item["id"]: item for item in merged["tensors"]}
    assert cells["SlotIDs"]["values"] == [256, 512, 98, 97, 512, 768]
    assert cells["TargetRows"]["values"] == [2, 1, 0, 2, -1]
    cut = next(step for step in merged["steps"] if step["id"] == "alignment_2")
    assert cut["outputs"]["sameDoc"] == 1 and cut["outputs"]["sameChunk"] == cut["outputs"]["effectiveMask"] == 0
    zero = derive_iv51({**DEFAULT_IV51, **{f"m{i}": 0 for i in range(5)}})
    assert zero["outputs"]["validTargets"] == 0 and zero["outputs"]["allowedCells"] == 12
    # Mutating a returned snapshot must not affect a later call or the raw state.
    raw = dict(DEFAULT_IV51)
    default["tensors"][0]["values"][0] = -999
    assert raw == dict(DEFAULT_IV51) and derive_iv51(raw)["tensors"][0]["values"][0] == 97
    for patch, code, reason in (
        (dict(docB=None, merges=float("nan")), "INVALID_INPUT", "docB must be an actual string, without coercion."),
        (dict(docA="\ud800", m4=2), "INVALID_INPUT", "m4 must be numeric 0 or 1."),
        (dict(merges=10**1000), "INVALID_INPUT", "merges must be an integer from 0 to 2."),
        (dict(blockSize=2), "INVALID_INPUT", "blockSize must be 3 or 6."),
        (dict(m0=True), "NONFINITE", "m0 must be an actual finite number."),
        (dict(docA="aaa\ud800"), "UNSUPPORTED_SIZE", "docA: more than 2 UTF-16 units necessarily exceeds this 2-byte field."),
        (dict(docA="\ud800"), "INVALID_INPUT", "docA: Unpaired high surrogate at UTF-16 offset 0."),
        (dict(docA="🦊"), "UNSUPPORTED_SIZE", "docA: the actual UTF-8 encoding exceeds 2 bytes; shorten this field explicitly."),
        (dict(docA="é"), "UNAVAILABLE", "docA: only raw a/b letters are supported; no trimming or normalization is performed."),
        (dict(docA="", docB="aaa"), "UNAVAILABLE", "docA: provide a nonempty document; its first content piece is given."),
    ):
        result = derive_iv51({**DEFAULT_IV51, **patch})
        assert list(result) == ["status", "code", "reason"]
        assert result == dict(status="unavailable", code=code, reason=reason)
    for raw in ('{"docA":"ab","docA":"ba"}', '{"extra":{"x":1,"x":2}}', 'NaN', 'Infinity', '-Infinity'):
        try:
            _packing.json.loads(raw, object_pairs_hook=_packing._json_object, parse_constant=_packing._json_constant)
        except ValueError:
            pass
        else:
            raise AssertionError("Strict JSON parser accepted duplicate keys or a non-JSON constant")


    original_pack = _packing.pack_arrays

    def fail_unexpectedly(_):
        raise RuntimeError("unexpected implementation failure")

    try:
        _packing.pack_arrays = fail_unexpectedly
        try:
            derive_iv51(dict(DEFAULT_IV51))
        except RuntimeError as error:
            assert str(error) == "unexpected implementation failure"
        else:
            raise AssertionError("Unknown error was converted to an unavailable record")
    finally:
        _packing.pack_arrays = original_pack


if __name__ == "__main__":
    _packing.run(derive_iv51, DEFAULT_IV51, source_self_check)

Packing mechanics — code/python/p13/packing_reference.py: packing_state validates raw fields; tokenize_documents calls A then B; pack_arrays creates actual NumPy int32/bool arrays. Follow slots, docIDs, positionIDs, allowed, structuralMask, effectiveMask and validTargets against the tables above.

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-51 integer/bool packing mechanics; authored under the execution hold.

Reuse TWO actual IV-39 EOS-off calls. The old manual UTF codec, BPE decisions,
integer traces, tensors and prose remain available in each returned old record.
No neural model, native-codec answer, objective or training is computed here.
"""
import argparse
from copy import deepcopy
import importlib.util
import json
import math
from pathlib import Path
import sys
from types import MappingProxyType
import numpy as np

_path = Path(__file__).resolve().parents[1] / "p09" / "iv39.py"
_spec = importlib.util.spec_from_file_location("_p13_packing_iv39", _path)
if _spec is None or _spec.loader is None:
    raise ImportError(f"Cannot load IV-39 source: {_path}")
_iv39 = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_iv39)
_token = _iv39._bpe._token
NumericalFault = _token.NumericalFault
guarded = _token.guarded
EOS = _token.EOS
PAD = 768
DEFAULT_IV51 = MappingProxyType(dict(docA="ab", docB="ba", merges=0, blockSize=6,
                                    isolate=1, m0=1, m1=1, m2=1, m3=1, m4=1))


def integer(value, low, high, label):
    """Actual JSON-number types only; finite huge ints fail domain, not finiteness."""
    if type(value) not in (int, float) or (type(value) is float and not math.isfinite(value)):
        raise NumericalFault("NONFINITE", f"{label} must be an actual finite number.")
    # Compare Python ints before int/float conversion, including arbitrary precision.
    if value < low or value > high or int(value) != value:
        reason = ("merges must be an integer from 0 to 2." if label == "merges" else
                  "blockSize must be 3 or 6." if label == "blockSize" else
                  f"{label} must be numeric 0 or 1.")
        raise NumericalFault("INVALID_INPUT", reason)
    return int(value)


def packing_state(state):
    """Own field names first, BOTH string types, ALL numeric fields, then semantics."""
    if type(state) is not dict:
        raise NumericalFault("INVALID_INPUT", "state must be a plain object.")
    if any(type(key) is not str for key in state) or set(state) != set(DEFAULT_IV51):
        raise NumericalFault("INVALID_INPUT", "state must have exactly docA, docB, merges, blockSize, isolate, m0, m1, m2, m3, m4 as own fields.")
    for field in ("docA", "docB"):
        if type(state[field]) is not str:
            raise NumericalFault("INVALID_INPUT", f"{field} must be an actual string, without coercion.")
    result = dict(docA=state["docA"], docB=state["docB"])
    for field in tuple(DEFAULT_IV51)[2:]:
        low, high = (0, 2) if field == "merges" else (3, 6) if field == "blockSize" else (0, 1)
        value = integer(state[field], low, high, field)
        if field == "blockSize" and value not in (3, 6):
            raise NumericalFault("INVALID_INPUT", "blockSize must be 3 or 6.")
        result[field] = value
    return result


def _tokenize_document(text, merges, field):
    """Outer two-unit bound precedes strict old codec; inspect actual old bytes/IDs."""
    if _token.utf16_length(text) > 2:
        raise NumericalFault("UNSUPPORTED_SIZE", f"{field}: more than 2 UTF-16 units necessarily exceeds this 2-byte field.")
    record = _iv39.derive_iv39(dict(corpus="abab", text=text, merges=merges, eos=0))
    if record["status"] == "unavailable":
        raise NumericalFault(record["code"], f"{field}: {record['reason']}")
    source_bytes = next(tensor["values"] for tensor in record["tensors"] if tensor["id"] == "SourceBytes") if text else []
    if len(source_bytes) > 2:
        raise NumericalFault("UNSUPPORTED_SIZE", f"{field}: the actual UTF-8 encoding exceeds 2 bytes; shorten this field explicitly.")
    if any(character not in "ab" for character in text):
        raise NumericalFault("UNAVAILABLE", f"{field}: only raw a/b letters are supported; no trimming or normalization is performed.")
    if not text:
        raise NumericalFault("UNAVAILABLE", f"{field}: provide a nonempty document; its first content piece is given.")
    ids = next(tensor["values"] for tensor in record["tensors"] if tensor["id"] == "TargetIDs")
    content = np.array(ids, dtype=np.int32)
    # EOS was disabled in the actual tokenizer and is appended exactly once here.
    sequence = np.concatenate((content, np.array([EOS], dtype=np.int32)))
    return dict(record=deepcopy(record), contentIDs=content, sequenceIDs=sequence)


def tokenize_documents(state):
    """Validate raw10, then A and B; return real old records and int32 sequences."""
    state = packing_state(state)
    doc_a = _tokenize_document(state["docA"], state["merges"], "docA")
    doc_b = _tokenize_document(state["docB"], state["merges"], "docB")
    return dict(state=state, docA=doc_a, docB=doc_b)


def pack_arrays(tokenized):
    """Build six physical slots, chunk permissions and five shifted target rows.

    Private input is the actual tokenize_documents result, not untrusted IDs.
    Every new counter/ID array is int32; permission and loss gates are bool.
    """
    state = tokenized["state"]
    width, isolate = state["blockSize"], state["isolate"]
    chunks = 6 // width
    sequences = (tokenized["docA"]["sequenceIDs"], tokenized["docB"]["sequenceIDs"])
    count = sum(len(sequence) for sequence in sequences)
    slots = np.full(6, PAD, dtype=np.int32)
    doc_ids = np.full(6, -1, dtype=np.int32)
    doc_positions = np.full(6, -1, dtype=np.int32)
    global_indices = np.arange(6, dtype=np.int32)
    chunk_ids = np.array([index // width for index in range(6)], dtype=np.int32)
    chunk_positions = np.array([index % width for index in range(6)], dtype=np.int32)
    valid = np.zeros(6, dtype=np.bool_)
    offset = 0
    for doc_id, sequence in enumerate(sequences):
        for position, identifier in enumerate(sequence):
            slots[offset] = identifier
            doc_ids[offset], doc_positions[offset], valid[offset] = doc_id, position, True
            offset += 1
    positions = np.full(6, -1, dtype=np.int32)
    for index in range(6):
        if valid[index]:
            positions[index] = doc_positions[index] if isolate else chunk_positions[index]
    allowed = np.zeros((chunks, width, width), dtype=np.bool_)
    for chunk in range(chunks):
        for query in range(width):
            q = chunk * width + query
            for key in range(width):
                k = chunk * width + key
                allowed[chunk, query, key] = bool(valid[q] and valid[k] and key <= query
                                                 and (not isolate or doc_ids[q] == doc_ids[k]))
    requested = np.array([state[f"m{index}"] for index in range(5)], dtype=np.int32)
    input_valid, target_valid = valid[:-1].copy(), valid[1:].copy()
    same_chunk = np.array([chunk_ids[i] == chunk_ids[i + 1] for i in range(5)], dtype=np.bool_)
    same_doc = np.array([doc_ids[i] == doc_ids[i + 1] for i in range(5)], dtype=np.bool_)
    isolation_gate = np.array([not isolate or value for value in same_doc], dtype=np.bool_)
    valid_targets_running = np.zeros(5, dtype=np.int32)
    structural = np.zeros(5, dtype=np.bool_)
    effective = np.zeros(5, dtype=np.bool_)
    active_ids = np.array([97, 98, EOS, 256, 257][:3 + state["merges"]], dtype=np.int32)
    target_rows = np.full(5, -1, dtype=np.int32)
    allowed_cells, valid_targets = 0, 0
    # Both reductions preserve the declared ascending row-major order.
    for chunk in range(chunks):
        for query in range(width):
            for key in range(width):
                allowed_cells += int(allowed[chunk, query, key])
    for i in range(5):
        structural[i] = bool(input_valid[i] and target_valid[i] and same_chunk[i]
                             and (isolation_gate[i]))
        effective[i] = bool(requested[i] and structural[i])
        valid_targets += int(effective[i])
        valid_targets_running[i] = valid_targets
        if target_valid[i]:
            target_rows[i] = active_ids.tolist().index(int(slots[i + 1]))
    return dict(slots=slots.reshape(chunks, width).copy(), globalIndices=global_indices,
                docIDs=doc_ids, docPositions=doc_positions, chunkIDs=chunk_ids,
                chunkPositions=chunk_positions, positionIDs=positions, valid=valid,
                allowed=allowed, activeIDs=active_ids, requestedMask=requested,
                inputValid=input_valid, targetValid=target_valid, sameChunk=same_chunk,
                sameDoc=same_doc, isolationGate=isolation_gate, structuralMask=structural, effectiveMask=effective,
                targetRows=target_rows, validTargetsRunning=valid_targets_running, packedTokens=count, paddingSlots=6-count,
                allowedCells=allowed_cells, validTargets=valid_targets)


def _json_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError(f"Duplicate JSON key: {key}")
        result[key] = value
    return result


def _json_constant(value):
    raise ValueError(f"Invalid JSON constant: {value}")


_JSON_INT = int


def _json_integer(token):
    return -0.0 if token == "-0" else _JSON_INT(token)


def run(derive, defaults, self_check):
    """No args/defaults, complete JSON replacement or '-' stdin; checks explicit."""
    parser = argparse.ArgumentParser(description=derive.__doc__)
    parser.add_argument("state", nargs="?")
    parser.add_argument("--self-check", action="store_true")
    args = parser.parse_args()
    if args.self_check:
        if args.state is not None:
            parser.error("--self-check cannot be combined with a state query")
        self_check()  # Outside query handling: assertion/unknown errors propagate.
        return
    try:
        if args.state is None:
            state = dict(defaults)
        else:
            raw = sys.stdin.read() if args.state == "-" else args.state
            state = json.loads(raw, object_pairs_hook=_json_object,
                               parse_constant=_json_constant, parse_int=_json_integer)
    except (ValueError, OSError) as error:
        result = dict(status="unavailable", code="INVALID_INPUT", reason=str(error))
    else:
        # Parsing alone is caught above; unknown implementation failures stay errors.
        result = derive(state)
    print(json.dumps(result, allow_nan=False, ensure_ascii=False, separators=(",", ":")))


def source_self_check():
    """DEFERRED explicit mechanics leaf; never calls an old or new check leaf."""
    assert __debug__, "Run later checks with assertions enabled."
    for merges, width, isolate, expected_slots, allowed, mask in (
        (0, 6, 1, [97, 98, 512, 98, 97, 512], 12, [1, 1, 0, 1, 1]),
        (0, 6, 0, [97, 98, 512, 98, 97, 512], 21, [1, 1, 1, 1, 1]),
        (0, 3, 0, [97, 98, 512, 98, 97, 512], 12, [1, 1, 0, 1, 1]),
        (1, 6, 1, [256, 512, 98, 97, 512, 768], 9, [1, 0, 1, 1, 0]),
        (2, 6, 0, [256, 512, 98, 97, 512, 768], 15, [1, 1, 1, 1, 0]),
        (2, 3, 1, [256, 512, 98, 97, 512, 768], 7, [1, 0, 0, 1, 0]),
        (1, 3, 0, [256, 512, 98, 97, 512, 768], 9, [1, 1, 0, 1, 0]),
    ):
        actual = pack_arrays(tokenize_documents({**DEFAULT_IV51, "merges": merges, "blockSize": width, "isolate": isolate}))
        assert actual["slots"].reshape(6).tolist() == expected_slots
        assert actual["allowedCells"] == allowed and actual["effectiveMask"].tolist() == mask
        assert actual["validTargets"] == sum(mask)
        for value in actual.values():
            if type(value) is np.ndarray:
                assert value.dtype in (np.dtype(np.int32), np.dtype(np.bool_))
    for patch, code in ((dict(merges=10**1000), "INVALID_INPUT"),
                        (dict(m4=True), "NONFINITE"), (dict(docB=None, merges=float("nan")), "INVALID_INPUT"),
                        (dict(docA="\ud800", m4=2), "INVALID_INPUT"),
                        (dict(docA="aaa\ud800"), "UNSUPPORTED_SIZE"),
                        (dict(docA="\ud800"), "INVALID_INPUT"), (dict(docA="🦊"), "UNSUPPORTED_SIZE"),
                        (dict(docA="é"), "UNAVAILABLE"), (dict(docA=""), "UNAVAILABLE")):
        result = guarded(tokenize_documents)({**DEFAULT_IV51, **patch})
        assert result["status"] == "unavailable" and result["code"] == code
    zero = pack_arrays(tokenize_documents({**DEFAULT_IV51, **{f"m{i}": 0 for i in range(5)}}))
    assert zero["validTargets"] == 0

    class HostileDict(dict):
        def __iter__(self):
            raise AssertionError("Raw guard must reject before iteration")

        def __getitem__(self, key):
            raise AssertionError("Raw guard must reject before item access")

    # A proxy may wrap hostile user code; only an exact dict is public raw state.
    for raw in (HostileDict(DEFAULT_IV51), MappingProxyType(HostileDict(DEFAULT_IV51)),
                MappingProxyType(dict(DEFAULT_IV51))):
        rejected = guarded(tokenize_documents)(raw)
        assert rejected == dict(status="unavailable", code="INVALID_INPUT",
                                reason="state must be a plain object.")

Actual reused tokenizer composition — code/python/p09/iv39.py: each call trains on abab, encodes its own document with EOS off, reconstructs actual strings and saves its full evidence.

Read the complete executable Python / NumPy source

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

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

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

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

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

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

DEFAULT_IV39 = _bpe.DEFAULT_IV39


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

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

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

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

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


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


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

Actual BPE operations — code/python/p09/bpe_reference.py: pair counting, numeric tie order, left-to-right nonoverlapping replacements, ranked encoding and inverse expansions.

Read the complete executable Python / NumPy source

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

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

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

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

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


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


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


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


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


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


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


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


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


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


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


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


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

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


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


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

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

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

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

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

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

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

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

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

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

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

    rejects(lambda: bpe_state(AccessorState()))
    rejects(lambda: decode_bpe_ids(AccessorList([65]), [], 0, "target", _token.TokenTrace()))
    rejects(lambda: rule_table([dict(id=256, left=97, right=98, bytes=AccessorList([97, 98]))]))

Actual strict codec and integer records — code/python/p09/token_reference.py: manual UTF-8 encoding/decoding, Unicode checks, exact scalar traces and tensor serialization.

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=(",", ":")))

Trace the actual entry point and CLI

In derive_iv51, tokenize_documents first checks every raw field, then tokenizes A and B in order. pack_arrays allocates six int32 slots and bool permissions, fills the real-token prefix, sets positions, visits every chunk/query/key cell and then visits all five target pairs. allowed_cells adds one for each true permission; valid_targets_running records the ascending effective-mask count. No matrix multiplication or neural call is hidden in those loops.

The wrapper copies both complete old records, adds its actual outer steps and saves the new arrays as flat JSON lists with explicit shapes. TokenTrace.result appends each step-output alias after the ordered summaries; the wrapper returns a deep copy of the complete result. That detaches the Python record from intermediate arrays and later calls. The TypeScript helper additionally freezes its detached arrays. The default source count is 62 steps and 72 tensors; merges=1 gives 78/94, merges=2 gives 89/110 for ab/ba, and the reachable maximum aa/bb at merges=2 is 92/110. These are manual source inventories, not observed validation output.

The following commands describe the maintained CLI; the examples are not execution results. From the book root, no arguments select the complete default state:

python3 code/python/p13/iv51.py

One JSON argument replaces the whole state. For example, this requests the merged three-slot isolated example; it supplies every field rather than patching defaults:

python3 code/python/p13/iv51.py '{"docA":"ab","docB":"ba","merges":1,"blockSize":3,"isolate":1,"m0":1,"m1":1,"m2":1,"m3":1,"m4":1}'

Alternatively, put that complete JSON object in state.json and use standard input:

python3 code/python/p13/iv51.py - < state.json

- reads one JSON document to the end of standard input. Duplicate object keys, including nested duplicates, and the non-JSON constants NaN/Infinity/−Infinity are rejected. Missing fields are rejected rather than supplied from defaults. Parse failures produce an unavailable JSON record; known numerical faults retain status, code and reason. Unknown implementation errors that escape the derivation propagate as errors instead of becoming a successful record. The old reused IV39 fault boundary remains its original implementation.

The separate assertion mode is:

python3 code/python/p13/iv51.py --self-check

It cannot be combined with a state query. The CLI calls the IV51 source_self_check leaf outside query fault handling; that leaf calls no other declared check leaf. The packing helper has its own separate source_self_check, also calling no other check leaf. Old IV39’s declared check calls the old BPE check only when explicitly invoked. Imports, defaults, JSON queries and stdin queries invoke none of these checks. Assertions and descriptions of syntax/import, parity and rendered interaction checks are not their execution results.

Read the five live corrective checks

The lab above renders the only graded set, defined in exercisesIV51. The separator check distinguishes an EOS marker from an enforced boundary; the reset check uses the six saved IDs and four eligible targets. The live count check reads the current starting-input counts, including a possible zero target count. The live boundary check always uses saved global query 3 and local key 0, independently of the inspection selectors: with S=6/isolation on the cell is forbidden; with S=6/concatenation it is allowed; with S=3 local key 0 belongs to query 3’s own chunk and names global slot 3. The transfer check uses the merged S=3 row-2 cut derived above. Each selected option receives the actual question’s corrective explanation.

Recap and bridge

  • Packing shares physical storage; explicit causal, document and chunk rules determine context.
  • EOS is a real separator/target. PAD is unused storage outside the class vocabulary.
  • Five shifted pairs remain inspectable even when document boundaries, chunk cuts or requests exclude them.
  • Attention permissions and target masks answer different questions; neither computes a loss.

Next, IV-52 — Language-Model Training Steps and Batches adds actual model calculations, token losses, reduction and an optimizer update to a declared training example. This chapter supplies the data bookkeeping that such a calculation must respect.