The neural notebook
← All chapters

IV-61 / Part XV · Modern LLM Architectures

Multi-Query and Grouped-Query Attention

Follow explicit query projections and shared key/value groups, derive every head's causal mixture, and count logical cache bytes under stated storage assumptions.

Review the ideas this chapter uses

Several attention heads can ask different questions about the same sequence while reading the same keys and values. Keeping one set of keys and values for each small group of query heads can reduce the numeric payload retained for later tokens. The query paths still calculate their own matching scores and their own messages. We will follow those paths separately before counting what is shared.

Learning objective: Explain query-head to key/value-head mappings and memory tradeoffs.

The lab uses disclosed, untrained weights and real scalar attention arithmetic. The worksheets below explain its default numbers over exact reals; the saved trace retains the actual binary64 operations and their operands.

Compute it yourself

Multi-Query and Grouped-Query Attention

Start with four query heads sharing two key/value groups. Follow the saved head-to-group map, each head's separate mixture and the original shared cache. Change Hkv to 1 for multi-query attention or to 4 for multi-head attention at Hq=4. You can also vary Hq from 1 to 4. Both menus stay freely editable: invalid pairs report a reason instead of silently changing the other menu.

Legal pairs are 1/1, 2/1, 2/2, 3/1, 3/3, 4/1, 4/2 and 4/4. Open the Q, K or V gain group to edit any of its four continuous gains in [-1,1], including -0. A gain scales BOTH positions after the fixed matrix projection. Inactive gains remain editable and validated. Open key validity to intersect its bits with causality j≤i; setting key0=0 empties the first query's allowed set.

Empty, unfinished, nonfinite or out-of-range drafts, invalid head pairs and fully masked rows withhold computed views and questions. Correct the input or choose Reset example. The 2/4/8-byte menu is an analytical payload assumption only; all actual arithmetic remains binary64. Editing, reset and trace selection clear graded answers; opening a disclosure preserves them.

Hq4
Hkv2
joinedWidth8
keyElements8
Query gains: all four remain editable and validated; heads h >= Hq are inactive
Key gains: all four remain editable and validated; groups g >= Hkv are inactive
Value gains: all four remain editable and validated; groups g >= Hkv are inactive
Key validity: intersect with j <= i; retain all queries
Exact starting inputs for this saved calculation

Hq 4. Hkv 2. joinedWidth 8. keyElements 8. Query head 0: contiguous KV group. Both the key and value lookup use this same group. Every query head retains its own score, probability and output path.

Query head 0: contiguous KV group

group=floor(h/groupWidth); groupWidth=Hq/Hkv

Both the key and value lookup use this same group. Every query head retains its own score, probability and output path.

Saved inputs

h
0
Hq
4
Hkv
2
groupWidth
2

Saved outputs

group
0

Selected saved step grouped_map_0. Query head 0: contiguous KV group. Equation: group=floor(h/groupWidth); groupWidth=Hq/Hkv. Both the key and value lookup use this same group. Every query head retains its own score, probability and output path. Saved inputs: h=0; Hq=4; Hkv=2; groupWidth=2. Saved outputs: group=0.

Keep every query path; share the original keys and values

Saved Hq=4 query heads, Hkv=2 KV groups. Map [0, 0, 1, 1]. Joined shape [1,2,8]. Saved one-layer logical payload: 32 bytes at the saved analytical 2 bytes per scalar.

A query head is one matching-and-mixture path. A KV group supplies one key sequence and one value sequence that its mapped heads share. B=1 is one sequence; Tq=Tk=2 are query/key positions; Din=Dk=Dv=2 are source, matching and value features. Hq and Hkv are different axes. At 1/1 the MHA and MQA endpoint descriptions coincide: one query head, one KV group.

Hand-set forward-only attention toy: B=1,Tq=Tk=2,Din=Dk=Dv=2. No learned parameters, output projection, residual, FFN, tokenizer, generation, training, quantization, measured memory or speedup. Changing Hkv can change outputs and does not losslessly compress arbitrary MHA.

Eight computation stages and eleven saved graph tensors
  1. Basis source and fixed weight banks
  2. Contiguous query-head to KV-group mapping
  3. Project Q, then shared K, then shared V; apply gains last
  4. All head-specific scores
  5. Causal and key-valid stable probabilities
  6. Every weighted value product and ordered sum
  7. Copy every head into the join
  8. One-layer logical cache accounting

The stage list describes operations; the tensor list below separately includes both K and V and the mask. They are not paired one-to-one.

  • grouped_X · B=1 × T=2 × Din=2 · [1,2,2] · 1, 0, 0, 1
  • grouped_HeadToGroup · Hq=4 · [4] · 0, 0, 1, 1
  • grouped_Q · B=1 × Hq=4 × Tq=2 × Dk=2 · [1,4,2,2] · 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, -1, 1, -1
  • grouped_KCache · B=1 × Hkv=2 × Tk=2 × Dk=2 · [1,2,2,2] · 1, 0, 0, 1, 1, 1, 1, -1
  • grouped_VCache · B=1 × Hkv=2 × Tk=2 × Dv=2 · [1,2,2,2] · 1, 0, 0, 1, 2, 0, 0, 2
  • grouped_Scores · B=1 × Hq=4 × Tq=2 × Tk=2 · [1,4,2,2] · 0.7071067811865475, 0, 0.7071067811865475, 0, 0, 0.7071067811865475, 0, 0.7071067811865475, 1.414213562373095, 0, 1.414213562373095, 0, 0, 1.414213562373095, 0, 1.414213562373095
  • grouped_Allowed · B=1 × Hq=4 × Tq=2 × Tk=2 · [1,4,2,2] · 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1
  • grouped_Probabilities · B=1 × Hq=4 × Tq=2 × Tk=2 · [1,4,2,2] · 1, 0, 0.6697615493266569, 0.3302384506733431, 1, 0, 0.3302384506733431, 0.6697615493266569, 1, 0, 0.8044296825069569, 0.19557031749304313, 1, 0, 0.19557031749304313, 0.8044296825069569
  • grouped_HeadOutputs · B=1 × Hq=4 × Tq=2 × Dv=2 · [1,4,2,2] · 1, 0, 0.6697615493266569, 0.3302384506733431, 1, 0, 0.3302384506733431, 0.6697615493266569, 2, 0, 1.6088593650139138, 0.39114063498608626, 2, 0, 0.39114063498608626, 1.6088593650139138
  • grouped_Joined · B=1 × Tq=2 × JoinedFeature=8 · [1,2,8] · 1, 0, 1, 0, 2, 0, 2, 0, 0.6697615493266569, 0.3302384506733431, 0.3302384506733431, 0.6697615493266569, 1.6088593650139138, 0.39114063498608626, 0.39114063498608626, 1.6088593650139138
  • grouped_CacheCounts · CacheField=6 · [6] · 8, 8, 16, 32, 16, 16

The full saved input and all fixed matrices

Raw17 in declared order, including every inactive gain
OffsetFieldCaptured value
0Hq4
1Hkv2
2elementBytes2
3q01
4q11
5q21
6q31
7k01
8k11
9k21
10k31
11v01
12v11
13v21
14v31
15key01
16key11

Every gain remains editable in its control group, including inactive h≥Hq and g≥Hkv. Each scales the result AFTER projecting the same basis X through its fixed matrix. Inactive gains are still validated and captured. These are hand-set matrices, not learned weights; changing Hkv selects different projected group paths.

Saved X rows: [1, 0]; [0, 1]. Row-feature storage uses X[i,f] times W[n,f,d]. Both products and their direct sum execute; the gain multiplies that saved sum afterwards.

All four matrices in each fixed Q, K and V bank
Saved bankHead or group nSource feature fMatrix row over output feature d
WQBank00[1, 0]
WQBank01[1, 0]
WQBank10[0, 1]
WQBank11[0, 1]
WQBank20[1, 1]
WQBank21[1, 1]
WQBank30[1, -1]
WQBank31[1, -1]
WKBank00[1, 0]
WKBank01[0, 1]
WKBank10[1, 1]
WKBank11[1, -1]
WKBank20[1, 0]
WKBank21[-1, 1]
WKBank30[0, 1]
WKBank31[1, 0]
WVBank00[1, 0]
WVBank01[0, 1]
WVBank10[2, 0]
WVBank11[0, 2]
WVBank20[1, 2]
WVBank21[2, -1]
WVBank30[-1, 1]
WVBank31[1, 1]

Actual group mapping and separate head paths

Hq and Hkv each range from one to four with Hq divisible by Hkv. Both K and V use floor(h/(Hq/Hkv)); modulo would change fixed head identities for GQA4/2. Hq=Hkv=1 is the coincident single-head endpoint.

Every query head: shared group, own Q and own output at both positions
Head hSaved group gSaved group widthQ row0Q row1Head output row0Head output row1
002[1, 0][1, 0][1, 0][0.6697615493266569, 0.3302384506733431]
102[0, 1][0, 1][1, 0][0.3302384506733431, 0.6697615493266569]
212[1, 1][1, 1][2, 0][1.6088593650139138, 0.39114063498608626]
312[1, -1][1, -1][2, 0][0.39114063498608626, 1.6088593650139138]
Original shared K/V cache storage: one row per group and key, without Hq expansion
Group gKey jFlat row startSaved K[g,j,:]Saved V[g,j,:]
000[1, 0][1, 0]
012[0, 1][0, 1]
104[1, 1][2, 0]
116[1, -1][0, 2]

Every real projection: two products, direct sum, then gain

One fixed basis source, all four disclosed matrices in each weight bank, then twelve independently editable post-projection gains. Compute active Q heads once, active K groups once, then active V groups once. Inactive gains remain captured, visible and validated.

All active Q/K/V coordinates and saved projection operands/results
KindHead/group nPositionFeature dX rowW columnGainProduct 0Product 1Unscaled direct sumPost-gain value
Q000[1, 0][1, 1]11011
Q001[1, 0][0, 0]10000
Q010[0, 1][1, 1]10111
Q011[0, 1][0, 0]10000
Q100[1, 0][0, 0]10000
Q101[1, 0][1, 1]11011
Q110[0, 1][0, 0]10000
Q111[0, 1][1, 1]10111
Q200[1, 0][1, 1]11011
Q201[1, 0][1, 1]11011
Q210[0, 1][1, 1]10111
Q211[0, 1][1, 1]10111
Q300[1, 0][1, 1]11011
Q301[1, 0][-1, -1]1-1-0-1-1
Q310[0, 1][1, 1]10111
Q311[0, 1][-1, -1]1-0-1-1-1
K000[1, 0][1, 0]11011
K001[1, 0][0, 1]10000
K010[0, 1][1, 0]10000
K011[0, 1][0, 1]10111
K100[1, 0][1, 1]11011
K101[1, 0][1, -1]11-011
K110[0, 1][1, 1]10111
K111[0, 1][1, -1]10-1-1-1
V000[1, 0][1, 0]11011
V001[1, 0][0, 1]10000
V010[0, 1][1, 0]10000
V011[0, 1][0, 1]10111
V100[1, 0][2, 0]12022
V101[1, 0][0, 2]10000
V110[0, 1][2, 0]10000
V111[0, 1][0, 2]10222

Every score cell, mask and stable probability

Compute all raw scores before any row softmax, including forbidden cells. Causality and key validity intersect. One sqrt(Dk=2) supplies every score. Each query-head row keeps its own stable probabilities over original shared K/V storage. Allowed is an int32 decision (1 or 0). A forbidden cell still has its raw score, but no shifted argument or exponential leaf. Its saved term and probability are literal +0. Padding affects keys only; no head or query row is discarded.

Complete h,i,j score grid, including forbidden cells and every stable term
Head hGroup gQuery iKey jScore offsetQ rowK rowProduct 0Product 1DotDivisorScoreAllowedRow maximumSaved shiftExp termDenominatorProbability
00000[1, 0][1, 0]1011.41421356237309510.707106781186547510.70710678118654750111
00011[1, 0][0, 1]0001.4142135623730951000.7071067811865475Absent: forbidden key; no exponential010
00102[1, 0][1, 0]1011.41421356237309510.707106781186547510.7071067811865475011.49306869139523980.6697615493266569
00113[1, 0][0, 1]0001.4142135623730951010.7071067811865475-0.70710678118654750.493068691395239841.49306869139523980.3302384506733431
10004[0, 1][1, 0]0001.41421356237309510100111
10015[0, 1][0, 1]0111.41421356237309510.707106781186547500Absent: forbidden key; no exponential010
10106[0, 1][1, 0]0001.4142135623730951010.7071067811865475-0.70710678118654750.493068691395239841.49306869139523980.3302384506733431
10117[0, 1][0, 1]0111.41421356237309510.707106781186547510.7071067811865475011.49306869139523980.6697615493266569
21008[1, 1][1, 1]1121.41421356237309511.41421356237309511.4142135623730950111
21019[1, 1][1, -1]1-101.4142135623730951001.414213562373095Absent: forbidden key; no exponential010
211010[1, 1][1, 1]1121.41421356237309511.41421356237309511.414213562373095011.24311673443421420.8044296825069569
211111[1, 1][1, -1]1-101.4142135623730951011.414213562373095-1.4142135623730950.243116734434214251.24311673443421420.19557031749304313
310012[1, -1][1, 1]1-101.41421356237309510100111
310113[1, -1][1, -1]1121.41421356237309511.41421356237309500Absent: forbidden key; no exponential010
311014[1, -1][1, 1]1-101.4142135623730951011.414213562373095-1.4142135623730950.243116734434214251.24311673443421420.19557031749304313
311115[1, -1][1, -1]1121.41421356237309511.41421356237309511.414213562373095011.24311673443421420.8044296825069569

All weighted products and running sums

Each head mixes its group's original V rows using its own probability row. Every feature fold starts at +0 and visits BOTH keys, even when P is masked +0. A negative V may produce a saved -0 product. This view copies saved products/partials and does not calculate a new mixture.

Every h,i,j,d weighted operation with its original shared value
Head hGroup gQuery iKey jFeature dStorage offsetProbabilityShared VPrevious sumProductUpdated partial
00000011011
00001110000
00010200101
00011301000
0010040.6697615493266569100.66976154932665690.6697615493266569
0010150.66976154932665690000
0011060.330238450673343100.669761549326656900.6697615493266569
0011170.3302384506733431100.33023845067334310.3302384506733431
10000811011
10001910000
100101000101
100111101000
10100120.3302384506733431100.33023845067334310.3302384506733431
10101130.33023845067334310000
10110140.669761549326656900.330238450673343100.3302384506733431
10111150.6697615493266569100.66976154932665690.6697615493266569
210001612022
210011710000
210101800202
210111902000
21100200.8044296825069569201.60885936501391381.6088593650139138
21101210.80442968250695690000
21110220.1955703174930431301.608859365013913801.6088593650139138
21111230.19557031749304313200.391140634986086260.39114063498608626
310002412022
310012510000
310102600202
310112702000
31100280.19557031749304313200.391140634986086260.39114063498608626
31101290.195570317493043130000
31110300.804429682506956900.3911406349860862600.39114063498608626
31111310.8044296825069569201.60885936501391381.6088593650139138

Join all heads by copying, without averaging

First move [B,Hq,Tq,Dv] to [B,Tq,Hq,Dv], then join the adjacent head/feature axes. The saved source and destination offsets below witness each copy. A plain reshape would mix positions and heads. An output projection back to Din=2 would be a further operation; this toy stops at Joined.

Complete i,h,d head-to-join copy map
Query iHead hFeature dHeadOutputs source offsetJoined destination offsetSaved source wordSaved destination word
0000011
0011100
0104211
0115300
0208422
0219500
03012622
03113700
100280.66976154932665690.6697615493266569
101390.33023845067334310.3302384506733431
1106100.33023845067334310.3302384506733431
1117110.66976154932665690.6697615493266569
12010121.60885936501391381.6088593650139138
12111130.391140634986086260.39114063498608626
13014140.391140634986086260.39114063498608626
13115151.60885936501391381.6088593650139138
Both complete joined output rows, in query-head then value-feature order
Query iSaved joined row
0[1, 0, 1, 0, 2, 0, 2, 0]
1[0.6697615493266569, 0.3302384506733431, 0.3302384506733431, 0.6697615493266569, 1.6088593650139138, 0.39114063498608626, 0.39114063498608626, 1.6088593650139138]

Count logical cache payload with explicit units

K elements=B*Tk*Hkv*Dk; V elements=B*Tk*Hkv*Dv. Add K and V once, then multiply by the assumed bytes per scalar. The following values are saved CacheCounts; this view does not recalculate them from controls.

All six saved counts with their distinct units
Saved fieldValueUnit and meaning
keyElements8K scalars retained
valueElements8V scalars retained
totalElements16K+V scalars retained
logicalBytes32Analytical bytes for one layer
queryElements16Q activation scalars; excluded from KV payload
scoreCells16Dense query/key score cells; excluded from KV payload

KCache and VCache each retain 4*Hkv active binary64 words. Logical payload=(keyElements+valueElements)*elementBytes for one layer. The 2/4/8-byte assumption changes counts only; it performs no cast or quantization. Q, weights, outputs, evidence copies, array overhead, traffic and timing are excluded. All actual scalar calculations remain binary64 at every byte choice. No FP16/FP32 conversion, allocator measurement, latency measurement or quality comparison occurs here. The UI itself retains extra audit copies, so this payload is not its resident memory.

All 28 saved tensors and every cell, including inactive weight banks

Each table groups the last named axis into columns and flattens preceding axes into outer rows. Cells carry their original zero-based flat offset. Shape, axes, dtype, precision and provenance come from the saved record. Round-trip decimal strings preserve -0 explicitly; declared display precision does not round these tables.

grouped_Raw

RawField=17 · shape [17] · float64 · declared display precision 8 · 17 stored cells

Captured raw17 in declared order. Choices use VALUE; all twelve gain words, including inactive gains and -0, use WORD.

grouped_Raw: complete saved storage
Outer row (zero-based)HqHkvelementBytesq0q1q2q3k0k1k2k3v0v1v2v3key0key1
042211111111111111

grouped_X

B=1 × T=2 × Din=2 · shape [1,2,2] · float64 · declared display precision 8 · 4 stored cells

Fixed basis-feature source rows [1,+0],[+0,1]; this same source feeds all projections.

grouped_X: complete saved storage
Outer row (zero-based)Din 0Din 1
010
101

grouped_WQBank

QueryHeadBank=4 × Din=2 × Dk=2 · shape [4,2,2] · float64 · declared display precision 8 · 16 stored cells

All four hand-set query matrices, row-feature orientation, including inactive heads; every structural zero is literal +0.

grouped_WQBank: complete saved storage
Outer row (zero-based)Dk 0Dk 1
010
110
201
301
411
511
61-1
71-1

grouped_WKBank

KVGroupBank=4 × Din=2 × Dk=2 · shape [4,2,2] · float64 · declared display precision 8 · 16 stored cells

All four hand-set key matrices, including inactive groups; active groups are projected once, not once per query head.

grouped_WKBank: complete saved storage
Outer row (zero-based)Dk 0Dk 1
010
101
211
31-1
410
5-11
601
710

grouped_WVBank

KVGroupBank=4 × Din=2 × Dv=2 · shape [4,2,2] · float64 · declared display precision 8 · 16 stored cells

All four hand-set value matrices, including inactive groups; these are weights, not retained KV payload.

grouped_WVBank: complete saved storage
Outer row (zero-based)Dv 0Dv 1
010
101
220
302
412
52-1
6-11
711

grouped_HeadToGroup

Hq=4 · shape [4] · int32 · declared display precision 0 · 4 stored cells

Uniform contiguous mapping floor(h/(Hq/Hkv)); both key and value caches use this index.

grouped_HeadToGroup: complete saved storage
Outer row (zero-based)Hq 0Hq 1Hq 2Hq 3
00011

grouped_QProjection

Hq=4 × Tq=2 × Dk=2 × ProjectionField=4 · shape [4,2,2,4] · float64 · declared display precision 8 · 64 stored cells

Actual product0,product1,unscaled,value for every active query coordinate, in h,i,d order.

grouped_QProjection: complete saved storage
Outer row (zero-based)product0product1unscaledvalue
01011
10000
20111
30000
40000
51011
60000
70111
81011
91011
100111
110111
121011
13-1-0-1-1
140111
15-0-1-1-1

grouped_KProjection

Hkv=2 × Tk=2 × Dk=2 × ProjectionField=4 · shape [2,2,2,4] · float64 · declared display precision 8 · 32 stored cells

Actual product0,product1,unscaled,value for every active key coordinate, in g,j,d order.

grouped_KProjection: complete saved storage
Outer row (zero-based)product0product1unscaledvalue
01011
10000
20000
30111
41011
51-011
60111
70-1-1-1

grouped_VProjection

Hkv=2 × Tk=2 × Dv=2 × ProjectionField=4 · shape [2,2,2,4] · float64 · declared display precision 8 · 32 stored cells

Actual product0,product1,unscaled,value for every active value coordinate, in g,j,d order.

grouped_VProjection: complete saved storage
Outer row (zero-based)product0product1unscaledvalue
01011
10000
20000
30111
42022
50000
60000
70222

grouped_Q

B=1 × Hq=4 × Tq=2 × Dk=2 · shape [1,4,2,2] · float64 · declared display precision 8 · 16 stored cells

Actual projected and post-gain queries; every active query head remains independent of KV sharing.

grouped_Q: complete saved storage
Outer row (zero-based)Dk 0Dk 1
010
110
201
301
411
511
61-1
71-1

grouped_KCache

B=1 × Hkv=2 × Tk=2 × Dk=2 · shape [1,2,2,2] · float64 · declared display precision 8 · 8 stored cells

Original active shared key storage, exactly 4*Hkv words. No Hq-expanded key cache exists.

grouped_KCache: complete saved storage
Outer row (zero-based)Dk 0Dk 1
010
101
211
31-1

grouped_VCache

B=1 × Hkv=2 × Tk=2 × Dv=2 · shape [1,2,2,2] · float64 · declared display precision 8 · 8 stored cells

Original active shared value storage, exactly 4*Hkv words. No Hq-expanded value cache exists.

grouped_VCache: complete saved storage
Outer row (zero-based)Dv 0Dv 1
010
101
220
302

grouped_ScoreEvidence

Hq=4 × Tq=2 × Tk=2 × ScoreField=3 · shape [4,2,2,3] · float64 · declared display precision 8 · 48 stored cells

Actual product0,product1,dot for all score cells, including forbidden cells; direct two-product sum.

grouped_ScoreEvidence: complete saved storage
Outer row (zero-based)product0product1dot
0101
1000
2101
3000
4000
5011
6000
7011
8112
91-10
10112
111-10
121-10
13112
141-10
15112

grouped_Scores

B=1 × Hq=4 × Tq=2 × Tk=2 · shape [1,4,2,2] · float64 · declared display precision 8 · 16 stored cells

Every actual dot divided by the one saved sqrt(Dk) word, in h,i,j order.

grouped_Scores: complete saved storage
Outer row (zero-based)Tk 0Tk 1
00.70710678118654750
10.70710678118654750
200.7071067811865475
300.7071067811865475
41.4142135623730950
51.4142135623730950
601.414213562373095
701.414213562373095

grouped_Allowed

B=1 × Hq=4 × Tq=2 × Tk=2 · shape [1,4,2,2] · int32 · declared display precision 0 · 16 stored cells

Allowed=1 iff the key bit is one and j<=i. Padding affects keys only; no query or head is removed.

grouped_Allowed: complete saved storage
Outer row (zero-based)Tk 0Tk 1
010
111
210
311
410
511
610
711

grouped_RowMaxima

B=1 × Hq=4 × Tq=2 · shape [1,4,2] · float64 · declared display precision 8 · 8 stored cells

Actual unchanged stableSoftmax Math.max over allowed scores, including its +0 preference on zero ties.

grouped_RowMaxima: complete saved storage
Outer row (zero-based)Tq 0Tq 1
00.70710678118654750.7071067811865475
100.7071067811865475
21.4142135623730951.414213562373095
301.414213562373095

grouped_AllowedCoordinates

AllowedCell=12 × IndexField=3 · shape [12,3] · int32 · declared display precision 0 · 36 stored cells

h,i,j of each allowed shifted argument and exp occurrence, in h,i,j order; no forbidden placeholder.

grouped_AllowedCoordinates: complete saved storage
Outer row (zero-based)hij
0000
1010
2011
3100
4110
5111
6200
7210
8211
9300
10310
11311

grouped_Shifted

AllowedCell=12 · shape [12] · float64 · declared display precision 8 · 12 stored cells

Functional exp-argument witnesses from identical immutable score-minus-max operands; no physical interception or masked entry.

grouped_Shifted: complete saved storage
Outer row (zero-based)AllowedCell 0AllowedCell 1AllowedCell 2AllowedCell 3AllowedCell 4AllowedCell 5AllowedCell 6AllowedCell 7AllowedCell 8AllowedCell 9AllowedCell 10AllowedCell 11
000-0.70710678118654750-0.7071067811865475000-1.4142135623730950-1.4142135623730950

grouped_Terms

B=1 × Hq=4 × Tq=2 × Tk=2 · shape [1,4,2,2] · float64 · declared display precision 8 · 16 stored cells

Actual stableSoftmax exp outputs at allowed cells and literal +0 terms at masked cells.

grouped_Terms: complete saved storage
Outer row (zero-based)Tk 0Tk 1
010
110.49306869139523984
210
30.493068691395239841
410
510.24311673443421425
610
70.243116734434214251

grouped_Denominators

B=1 × Hq=4 × Tq=2 · shape [1,4,2] · float64 · declared display precision 8 · 8 stored cells

Actual stableSoftmax reduction (+0+term0)+term1, including each masked +0 addition.

grouped_Denominators: complete saved storage
Outer row (zero-based)Tq 0Tq 1
011.4930686913952398
111.4930686913952398
211.2431167344342142
311.2431167344342142

grouped_Probabilities

B=1 × Hq=4 × Tq=2 × Tk=2 · shape [1,4,2,2] · float64 · declared display precision 8 · 16 stored cells

Actual unchanged term/denominator words; masked probabilities are structural +0, never renormalized in a view.

grouped_Probabilities: complete saved storage
Outer row (zero-based)Tk 0Tk 1
010
10.66976154932665690.3302384506733431
210
30.33023845067334310.6697615493266569
410
50.80442968250695690.19557031749304313
610
70.195570317493043130.8044296825069569

grouped_WeightedProducts

Hq=4 × Tq=2 × Tk=2 × Dv=2 · shape [4,2,2,2] · float64 · declared display precision 8 · 32 stored cells

Actual probability*sharedValue for every h,i,j,d, including masked signed-zero products; B=1 omitted.

grouped_WeightedProducts: complete saved storage
Outer row (zero-based)Dv 0Dv 1
010
100
20.66976154932665690
300.3302384506733431
410
500
60.33023845067334310
700.6697615493266569
820
900
101.60885936501391380
1100.39114063498608626
1220
1300
140.391140634986086260
1501.6088593650139138

grouped_WeightedPartials

Hq=4 × Tq=2 × Tk=2 × Dv=2 · shape [4,2,2,2] · float64 · declared display precision 8 · 32 stored cells

Actual previous+product after every h,i,j,d operation, from separate literal +0 feature accumulators; B=1 omitted.

grouped_WeightedPartials: complete saved storage
Outer row (zero-based)Dv 0Dv 1
010
110
20.66976154932665690
30.66976154932665690.3302384506733431
410
510
60.33023845067334310
70.33023845067334310.6697615493266569
820
920
101.60885936501391380
111.60885936501391380.39114063498608626
1220
1320
140.391140634986086260
150.391140634986086261.6088593650139138

grouped_HeadOutputs

B=1 × Hq=4 × Tq=2 × Dv=2 · shape [1,4,2,2] · float64 · declared display precision 8 · 16 stored cells

Final key1 partials copied per head,query,value-feature; no head averaging.

grouped_HeadOutputs: complete saved storage
Outer row (zero-based)Dv 0Dv 1
010
10.66976154932665690.3302384506733431
210
30.33023845067334310.6697615493266569
420
51.60885936501391380.39114063498608626
620
70.391140634986086261.6088593650139138

grouped_Joined

B=1 × Tq=2 × JoinedFeature=8 · shape [1,2,8] · float64 · declared display precision 8 · 16 stored cells

Indexed copies of all head-output coordinates in token,query-head,value-feature order; no output projection.

grouped_Joined: complete saved storage
Outer row (zero-based)JoinedFeature 0JoinedFeature 1JoinedFeature 2JoinedFeature 3JoinedFeature 4JoinedFeature 5JoinedFeature 6JoinedFeature 7
010102020
10.66976154932665690.33023845067334310.33023845067334310.66976154932665691.60885936501391380.391140634986086260.391140634986086261.6088593650139138

grouped_CacheCounts

CacheField=6 · shape [6] · int32 · declared display precision 0 · 6 stored cells

keyElements,valueElements,totalElements,logicalBytes,queryElements,scoreCells; exact analytical counts, not measured resident memory or traffic.

grouped_CacheCounts: complete saved storage
Outer row (zero-based)keyElementsvalueElementstotalElementslogicalBytesqueryElementsscoreCells
08816321616

grouped_NativeArguments

Native=13 × NativeField=2 · shape [13,2] · float64 · declared display precision 8 · 26 stored cells

Saved native input,output pairs in occurrence order: one sqrt, then allowed exp leaves. Serialization performs no native math.

grouped_NativeArguments: complete saved storage
Outer row (zero-based)inputoutput
021.4142135623730951
101
201
3-0.70710678118654750.49306869139523984
401
5-0.70710678118654750.49306869139523984
601
701
801
9-1.4142135623730950.24311673443421425
1001
11-1.4142135623730950.24311673443421425
1201

grouped_NativeKinds

Native=13 · shape [13] · int32 · declared display precision 0 · 13 stored cells

Native kind codes in occurrence order: sqrt=0,exp=1.

grouped_NativeKinds: complete saved storage
Outer row (zero-based)Native 0Native 1Native 2Native 3Native 4Native 5Native 6Native 7Native 8Native 9Native 10Native 11Native 12
00111111111111

Complete ordered native-leaf ledger

Every actual native occurrence: saved identity, kind, input and output
OccurrenceExact saved IDKindKind codeSaved argumentSaved output
0grouped_sqrtsqrt021.4142135623730951
1grouped_exp_0_0_0exp101
2grouped_exp_0_1_0exp101
3grouped_exp_0_1_1exp1-0.70710678118654750.49306869139523984
4grouped_exp_1_0_0exp101
5grouped_exp_1_1_0exp1-0.70710678118654750.49306869139523984
6grouped_exp_1_1_1exp101
7grouped_exp_2_0_0exp101
8grouped_exp_2_1_0exp101
9grouped_exp_2_1_1exp1-1.4142135623730950.24311673443421425
10grouped_exp_3_0_0exp101
11grouped_exp_3_1_0exp1-1.4142135623730950.24311673443421425
12grouped_exp_3_1_1exp101

One actual sqrt, then allowed stableSoftmax exp outputs in h,i,j order. The shifted arguments repeat the same subtraction of identical immutable operands as the unchanged primitive: functional witnesses, not physical interception. Masked cells have no shifted field or native leaf. No native math occurs in serialization.

Complete saved operation text fallback: all 111 frames in trace order

grouped_map_0: Query head 0: contiguous KV group

group=floor(h/groupWidth); groupWidth=Hq/Hkv

Both the key and value lookup use this same group. Every query head retains its own score, probability and output path.

Saved inputs
h
0
Hq
4
Hkv
2
groupWidth
2
Saved outputs
group
0

grouped_map_1: Query head 1: contiguous KV group

group=floor(h/groupWidth); groupWidth=Hq/Hkv

Both the key and value lookup use this same group. Every query head retains its own score, probability and output path.

Saved inputs
h
1
Hq
4
Hkv
2
groupWidth
2
Saved outputs
group
0

grouped_map_2: Query head 2: contiguous KV group

group=floor(h/groupWidth); groupWidth=Hq/Hkv

Both the key and value lookup use this same group. Every query head retains its own score, probability and output path.

Saved inputs
h
2
Hq
4
Hkv
2
groupWidth
2
Saved outputs
group
1

grouped_map_3: Query head 3: contiguous KV group

group=floor(h/groupWidth); groupWidth=Hq/Hkv

Both the key and value lookup use this same group. Every query head retains its own score, probability and output path.

Saved inputs
h
3
Hq
4
Hkv
2
groupWidth
2
Saved outputs
group
1

grouped_q_0_0_0: Q projection 0, position 0, feature 0

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
0
i
0
d
0
x0
1
x1
0
w0
1
w1
1
gain
1
Saved outputs
product0
1
product1
0
unscaled
1
value
1

grouped_q_0_0_1: Q projection 0, position 0, feature 1

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
0
i
0
d
1
x0
1
x1
0
w0
0
w1
0
gain
1
Saved outputs
product0
0
product1
0
unscaled
0
value
0

grouped_q_0_1_0: Q projection 0, position 1, feature 0

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
0
i
1
d
0
x0
0
x1
1
w0
1
w1
1
gain
1
Saved outputs
product0
0
product1
1
unscaled
1
value
1

grouped_q_0_1_1: Q projection 0, position 1, feature 1

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
0
i
1
d
1
x0
0
x1
1
w0
0
w1
0
gain
1
Saved outputs
product0
0
product1
0
unscaled
0
value
0

grouped_q_1_0_0: Q projection 1, position 0, feature 0

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
1
i
0
d
0
x0
1
x1
0
w0
0
w1
0
gain
1
Saved outputs
product0
0
product1
0
unscaled
0
value
0

grouped_q_1_0_1: Q projection 1, position 0, feature 1

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
1
i
0
d
1
x0
1
x1
0
w0
1
w1
1
gain
1
Saved outputs
product0
1
product1
0
unscaled
1
value
1

grouped_q_1_1_0: Q projection 1, position 1, feature 0

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
1
i
1
d
0
x0
0
x1
1
w0
0
w1
0
gain
1
Saved outputs
product0
0
product1
0
unscaled
0
value
0

grouped_q_1_1_1: Q projection 1, position 1, feature 1

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
1
i
1
d
1
x0
0
x1
1
w0
1
w1
1
gain
1
Saved outputs
product0
0
product1
1
unscaled
1
value
1

grouped_q_2_0_0: Q projection 2, position 0, feature 0

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
2
i
0
d
0
x0
1
x1
0
w0
1
w1
1
gain
1
Saved outputs
product0
1
product1
0
unscaled
1
value
1

grouped_q_2_0_1: Q projection 2, position 0, feature 1

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
2
i
0
d
1
x0
1
x1
0
w0
1
w1
1
gain
1
Saved outputs
product0
1
product1
0
unscaled
1
value
1

grouped_q_2_1_0: Q projection 2, position 1, feature 0

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
2
i
1
d
0
x0
0
x1
1
w0
1
w1
1
gain
1
Saved outputs
product0
0
product1
1
unscaled
1
value
1

grouped_q_2_1_1: Q projection 2, position 1, feature 1

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
2
i
1
d
1
x0
0
x1
1
w0
1
w1
1
gain
1
Saved outputs
product0
0
product1
1
unscaled
1
value
1

grouped_q_3_0_0: Q projection 3, position 0, feature 0

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
3
i
0
d
0
x0
1
x1
0
w0
1
w1
1
gain
1
Saved outputs
product0
1
product1
0
unscaled
1
value
1

grouped_q_3_0_1: Q projection 3, position 0, feature 1

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
3
i
0
d
1
x0
1
x1
0
w0
-1
w1
-1
gain
1
Saved outputs
product0
-1
product1
-0
unscaled
-1
value
-1

grouped_q_3_1_0: Q projection 3, position 1, feature 0

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
3
i
1
d
0
x0
0
x1
1
w0
1
w1
1
gain
1
Saved outputs
product0
0
product1
1
unscaled
1
value
1

grouped_q_3_1_1: Q projection 3, position 1, feature 1

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
3
i
1
d
1
x0
0
x1
1
w0
-1
w1
-1
gain
1
Saved outputs
product0
-0
product1
-1
unscaled
-1
value
-1

grouped_k_0_0_0: K projection 0, position 0, feature 0

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
0
i
0
d
0
x0
1
x1
0
w0
1
w1
0
gain
1
Saved outputs
product0
1
product1
0
unscaled
1
value
1

grouped_k_0_0_1: K projection 0, position 0, feature 1

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
0
i
0
d
1
x0
1
x1
0
w0
0
w1
1
gain
1
Saved outputs
product0
0
product1
0
unscaled
0
value
0

grouped_k_0_1_0: K projection 0, position 1, feature 0

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
0
i
1
d
0
x0
0
x1
1
w0
1
w1
0
gain
1
Saved outputs
product0
0
product1
0
unscaled
0
value
0

grouped_k_0_1_1: K projection 0, position 1, feature 1

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
0
i
1
d
1
x0
0
x1
1
w0
0
w1
1
gain
1
Saved outputs
product0
0
product1
1
unscaled
1
value
1

grouped_k_1_0_0: K projection 1, position 0, feature 0

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
1
i
0
d
0
x0
1
x1
0
w0
1
w1
1
gain
1
Saved outputs
product0
1
product1
0
unscaled
1
value
1

grouped_k_1_0_1: K projection 1, position 0, feature 1

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
1
i
0
d
1
x0
1
x1
0
w0
1
w1
-1
gain
1
Saved outputs
product0
1
product1
-0
unscaled
1
value
1

grouped_k_1_1_0: K projection 1, position 1, feature 0

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
1
i
1
d
0
x0
0
x1
1
w0
1
w1
1
gain
1
Saved outputs
product0
0
product1
1
unscaled
1
value
1

grouped_k_1_1_1: K projection 1, position 1, feature 1

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
1
i
1
d
1
x0
0
x1
1
w0
1
w1
-1
gain
1
Saved outputs
product0
0
product1
-1
unscaled
-1
value
-1

grouped_v_0_0_0: V projection 0, position 0, feature 0

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
0
i
0
d
0
x0
1
x1
0
w0
1
w1
0
gain
1
Saved outputs
product0
1
product1
0
unscaled
1
value
1

grouped_v_0_0_1: V projection 0, position 0, feature 1

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
0
i
0
d
1
x0
1
x1
0
w0
0
w1
1
gain
1
Saved outputs
product0
0
product1
0
unscaled
0
value
0

grouped_v_0_1_0: V projection 0, position 1, feature 0

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
0
i
1
d
0
x0
0
x1
1
w0
1
w1
0
gain
1
Saved outputs
product0
0
product1
0
unscaled
0
value
0

grouped_v_0_1_1: V projection 0, position 1, feature 1

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
0
i
1
d
1
x0
0
x1
1
w0
0
w1
1
gain
1
Saved outputs
product0
0
product1
1
unscaled
1
value
1

grouped_v_1_0_0: V projection 1, position 0, feature 0

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
1
i
0
d
0
x0
1
x1
0
w0
2
w1
0
gain
1
Saved outputs
product0
2
product1
0
unscaled
2
value
2

grouped_v_1_0_1: V projection 1, position 0, feature 1

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
1
i
0
d
1
x0
1
x1
0
w0
0
w1
2
gain
1
Saved outputs
product0
0
product1
0
unscaled
0
value
0

grouped_v_1_1_0: V projection 1, position 1, feature 0

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
1
i
1
d
0
x0
0
x1
1
w0
2
w1
0
gain
1
Saved outputs
product0
0
product1
0
unscaled
0
value
0

grouped_v_1_1_1: V projection 1, position 1, feature 1

product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain

Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.

Saved inputs
n
1
i
1
d
1
x0
0
x1
1
w0
0
w1
2
gain
1
Saved outputs
product0
0
product1
2
unscaled
2
value
2

grouped_sqrt: One shared square root of the key width

divisor=sqrt(Dk)

Dk is two for every head. This one actual native square root supplies every score division; neither query-head nor KV-group count changes its argument.

Saved inputs
Dk
2
Saved outputs
divisor
1.4142135623730951

grouped_score_0_0_0: Head 0, query 0, key 0: score from group 0

product0=q0*k0; product1=q1*k1; dot=product0+product1; score=dot/divisor

Read the original shared key cache by group index. Compute both products, the direct sum and division for every key, including forbidden future or padded keys.

Saved inputs
h
0
g
0
i
0
j
0
q0
1
q1
0
k0
1
k1
0
Dk
2
divisor
1.4142135623730951
Saved outputs
product0
1
product1
0
dot
1
score
0.7071067811865475

grouped_score_0_0_1: Head 0, query 0, key 1: score from group 0

product0=q0*k0; product1=q1*k1; dot=product0+product1; score=dot/divisor

Read the original shared key cache by group index. Compute both products, the direct sum and division for every key, including forbidden future or padded keys.

Saved inputs
h
0
g
0
i
0
j
1
q0
1
q1
0
k0
0
k1
1
Dk
2
divisor
1.4142135623730951
Saved outputs
product0
0
product1
0
dot
0
score
0

grouped_score_0_1_0: Head 0, query 1, key 0: score from group 0

product0=q0*k0; product1=q1*k1; dot=product0+product1; score=dot/divisor

Read the original shared key cache by group index. Compute both products, the direct sum and division for every key, including forbidden future or padded keys.

Saved inputs
h
0
g
0
i
1
j
0
q0
1
q1
0
k0
1
k1
0
Dk
2
divisor
1.4142135623730951
Saved outputs
product0
1
product1
0
dot
1
score
0.7071067811865475

grouped_score_0_1_1: Head 0, query 1, key 1: score from group 0

product0=q0*k0; product1=q1*k1; dot=product0+product1; score=dot/divisor

Read the original shared key cache by group index. Compute both products, the direct sum and division for every key, including forbidden future or padded keys.

Saved inputs
h
0
g
0
i
1
j
1
q0
1
q1
0
k0
0
k1
1
Dk
2
divisor
1.4142135623730951
Saved outputs
product0
0
product1
0
dot
0
score
0

grouped_score_1_0_0: Head 1, query 0, key 0: score from group 0

product0=q0*k0; product1=q1*k1; dot=product0+product1; score=dot/divisor

Read the original shared key cache by group index. Compute both products, the direct sum and division for every key, including forbidden future or padded keys.

Saved inputs
h
1
g
0
i
0
j
0
q0
0
q1
1
k0
1
k1
0
Dk
2
divisor
1.4142135623730951
Saved outputs
product0
0
product1
0
dot
0
score
0

grouped_score_1_0_1: Head 1, query 0, key 1: score from group 0

product0=q0*k0; product1=q1*k1; dot=product0+product1; score=dot/divisor

Read the original shared key cache by group index. Compute both products, the direct sum and division for every key, including forbidden future or padded keys.

Saved inputs
h
1
g
0
i
0
j
1
q0
0
q1
1
k0
0
k1
1
Dk
2
divisor
1.4142135623730951
Saved outputs
product0
0
product1
1
dot
1
score
0.7071067811865475

grouped_score_1_1_0: Head 1, query 1, key 0: score from group 0

product0=q0*k0; product1=q1*k1; dot=product0+product1; score=dot/divisor

Read the original shared key cache by group index. Compute both products, the direct sum and division for every key, including forbidden future or padded keys.

Saved inputs
h
1
g
0
i
1
j
0
q0
0
q1
1
k0
1
k1
0
Dk
2
divisor
1.4142135623730951
Saved outputs
product0
0
product1
0
dot
0
score
0

grouped_score_1_1_1: Head 1, query 1, key 1: score from group 0

product0=q0*k0; product1=q1*k1; dot=product0+product1; score=dot/divisor

Read the original shared key cache by group index. Compute both products, the direct sum and division for every key, including forbidden future or padded keys.

Saved inputs
h
1
g
0
i
1
j
1
q0
0
q1
1
k0
0
k1
1
Dk
2
divisor
1.4142135623730951
Saved outputs
product0
0
product1
1
dot
1
score
0.7071067811865475

grouped_score_2_0_0: Head 2, query 0, key 0: score from group 1

product0=q0*k0; product1=q1*k1; dot=product0+product1; score=dot/divisor

Read the original shared key cache by group index. Compute both products, the direct sum and division for every key, including forbidden future or padded keys.

Saved inputs
h
2
g
1
i
0
j
0
q0
1
q1
1
k0
1
k1
1
Dk
2
divisor
1.4142135623730951
Saved outputs
product0
1
product1
1
dot
2
score
1.414213562373095

grouped_score_2_0_1: Head 2, query 0, key 1: score from group 1

product0=q0*k0; product1=q1*k1; dot=product0+product1; score=dot/divisor

Read the original shared key cache by group index. Compute both products, the direct sum and division for every key, including forbidden future or padded keys.

Saved inputs
h
2
g
1
i
0
j
1
q0
1
q1
1
k0
1
k1
-1
Dk
2
divisor
1.4142135623730951
Saved outputs
product0
1
product1
-1
dot
0
score
0

grouped_score_2_1_0: Head 2, query 1, key 0: score from group 1

product0=q0*k0; product1=q1*k1; dot=product0+product1; score=dot/divisor

Read the original shared key cache by group index. Compute both products, the direct sum and division for every key, including forbidden future or padded keys.

Saved inputs
h
2
g
1
i
1
j
0
q0
1
q1
1
k0
1
k1
1
Dk
2
divisor
1.4142135623730951
Saved outputs
product0
1
product1
1
dot
2
score
1.414213562373095

grouped_score_2_1_1: Head 2, query 1, key 1: score from group 1

product0=q0*k0; product1=q1*k1; dot=product0+product1; score=dot/divisor

Read the original shared key cache by group index. Compute both products, the direct sum and division for every key, including forbidden future or padded keys.

Saved inputs
h
2
g
1
i
1
j
1
q0
1
q1
1
k0
1
k1
-1
Dk
2
divisor
1.4142135623730951
Saved outputs
product0
1
product1
-1
dot
0
score
0

grouped_score_3_0_0: Head 3, query 0, key 0: score from group 1

product0=q0*k0; product1=q1*k1; dot=product0+product1; score=dot/divisor

Read the original shared key cache by group index. Compute both products, the direct sum and division for every key, including forbidden future or padded keys.

Saved inputs
h
3
g
1
i
0
j
0
q0
1
q1
-1
k0
1
k1
1
Dk
2
divisor
1.4142135623730951
Saved outputs
product0
1
product1
-1
dot
0
score
0

grouped_score_3_0_1: Head 3, query 0, key 1: score from group 1

product0=q0*k0; product1=q1*k1; dot=product0+product1; score=dot/divisor

Read the original shared key cache by group index. Compute both products, the direct sum and division for every key, including forbidden future or padded keys.

Saved inputs
h
3
g
1
i
0
j
1
q0
1
q1
-1
k0
1
k1
-1
Dk
2
divisor
1.4142135623730951
Saved outputs
product0
1
product1
1
dot
2
score
1.414213562373095

grouped_score_3_1_0: Head 3, query 1, key 0: score from group 1

product0=q0*k0; product1=q1*k1; dot=product0+product1; score=dot/divisor

Read the original shared key cache by group index. Compute both products, the direct sum and division for every key, including forbidden future or padded keys.

Saved inputs
h
3
g
1
i
1
j
0
q0
1
q1
-1
k0
1
k1
1
Dk
2
divisor
1.4142135623730951
Saved outputs
product0
1
product1
-1
dot
0
score
0

grouped_score_3_1_1: Head 3, query 1, key 1: score from group 1

product0=q0*k0; product1=q1*k1; dot=product0+product1; score=dot/divisor

Read the original shared key cache by group index. Compute both products, the direct sum and division for every key, including forbidden future or padded keys.

Saved inputs
h
3
g
1
i
1
j
1
q0
1
q1
-1
k0
1
k1
-1
Dk
2
divisor
1.4142135623730951
Saved outputs
product0
1
product1
1
dot
2
score
1.414213562373095

grouped_row_0_0: Head 0, query 0: causal stable probabilities

max=Math.max(allowed scores); term[j]=allowed[j]?exp(score[j]-max):+0; denominator=(+0+term0)+term1; probability[j]=term[j]/denominator

The unchanged stableSoftmax selects the allowed maximum, preserving Math.max zero ties, and evaluates only allowed exponentials in key order. Saved shifted fields repeat its immutable subtraction as a functional witness; masked fields and native leaves are absent. Structural masked terms and probabilities are +0.

Saved inputs
h
0
g
0
i
0
score0
0.7071067811865475
score1
0
allowed0
1
allowed1
0
Saved outputs
max
0.7071067811865475
shifted0
0
term0
1
term1
0
denominator
1
probability0
1
probability1
0

grouped_row_0_1: Head 0, query 1: causal stable probabilities

max=Math.max(allowed scores); term[j]=allowed[j]?exp(score[j]-max):+0; denominator=(+0+term0)+term1; probability[j]=term[j]/denominator

The unchanged stableSoftmax selects the allowed maximum, preserving Math.max zero ties, and evaluates only allowed exponentials in key order. Saved shifted fields repeat its immutable subtraction as a functional witness; masked fields and native leaves are absent. Structural masked terms and probabilities are +0.

Saved inputs
h
0
g
0
i
1
score0
0.7071067811865475
score1
0
allowed0
1
allowed1
1
Saved outputs
max
0.7071067811865475
shifted0
0
shifted1
-0.7071067811865475
term0
1
term1
0.49306869139523984
denominator
1.4930686913952398
probability0
0.6697615493266569
probability1
0.3302384506733431

grouped_row_1_0: Head 1, query 0: causal stable probabilities

max=Math.max(allowed scores); term[j]=allowed[j]?exp(score[j]-max):+0; denominator=(+0+term0)+term1; probability[j]=term[j]/denominator

The unchanged stableSoftmax selects the allowed maximum, preserving Math.max zero ties, and evaluates only allowed exponentials in key order. Saved shifted fields repeat its immutable subtraction as a functional witness; masked fields and native leaves are absent. Structural masked terms and probabilities are +0.

Saved inputs
h
1
g
0
i
0
score0
0
score1
0.7071067811865475
allowed0
1
allowed1
0
Saved outputs
max
0
shifted0
0
term0
1
term1
0
denominator
1
probability0
1
probability1
0

grouped_row_1_1: Head 1, query 1: causal stable probabilities

max=Math.max(allowed scores); term[j]=allowed[j]?exp(score[j]-max):+0; denominator=(+0+term0)+term1; probability[j]=term[j]/denominator

The unchanged stableSoftmax selects the allowed maximum, preserving Math.max zero ties, and evaluates only allowed exponentials in key order. Saved shifted fields repeat its immutable subtraction as a functional witness; masked fields and native leaves are absent. Structural masked terms and probabilities are +0.

Saved inputs
h
1
g
0
i
1
score0
0
score1
0.7071067811865475
allowed0
1
allowed1
1
Saved outputs
max
0.7071067811865475
shifted0
-0.7071067811865475
shifted1
0
term0
0.49306869139523984
term1
1
denominator
1.4930686913952398
probability0
0.3302384506733431
probability1
0.6697615493266569

grouped_row_2_0: Head 2, query 0: causal stable probabilities

max=Math.max(allowed scores); term[j]=allowed[j]?exp(score[j]-max):+0; denominator=(+0+term0)+term1; probability[j]=term[j]/denominator

The unchanged stableSoftmax selects the allowed maximum, preserving Math.max zero ties, and evaluates only allowed exponentials in key order. Saved shifted fields repeat its immutable subtraction as a functional witness; masked fields and native leaves are absent. Structural masked terms and probabilities are +0.

Saved inputs
h
2
g
1
i
0
score0
1.414213562373095
score1
0
allowed0
1
allowed1
0
Saved outputs
max
1.414213562373095
shifted0
0
term0
1
term1
0
denominator
1
probability0
1
probability1
0

grouped_row_2_1: Head 2, query 1: causal stable probabilities

max=Math.max(allowed scores); term[j]=allowed[j]?exp(score[j]-max):+0; denominator=(+0+term0)+term1; probability[j]=term[j]/denominator

The unchanged stableSoftmax selects the allowed maximum, preserving Math.max zero ties, and evaluates only allowed exponentials in key order. Saved shifted fields repeat its immutable subtraction as a functional witness; masked fields and native leaves are absent. Structural masked terms and probabilities are +0.

Saved inputs
h
2
g
1
i
1
score0
1.414213562373095
score1
0
allowed0
1
allowed1
1
Saved outputs
max
1.414213562373095
shifted0
0
shifted1
-1.414213562373095
term0
1
term1
0.24311673443421425
denominator
1.2431167344342142
probability0
0.8044296825069569
probability1
0.19557031749304313

grouped_row_3_0: Head 3, query 0: causal stable probabilities

max=Math.max(allowed scores); term[j]=allowed[j]?exp(score[j]-max):+0; denominator=(+0+term0)+term1; probability[j]=term[j]/denominator

The unchanged stableSoftmax selects the allowed maximum, preserving Math.max zero ties, and evaluates only allowed exponentials in key order. Saved shifted fields repeat its immutable subtraction as a functional witness; masked fields and native leaves are absent. Structural masked terms and probabilities are +0.

Saved inputs
h
3
g
1
i
0
score0
0
score1
1.414213562373095
allowed0
1
allowed1
0
Saved outputs
max
0
shifted0
0
term0
1
term1
0
denominator
1
probability0
1
probability1
0

grouped_row_3_1: Head 3, query 1: causal stable probabilities

max=Math.max(allowed scores); term[j]=allowed[j]?exp(score[j]-max):+0; denominator=(+0+term0)+term1; probability[j]=term[j]/denominator

The unchanged stableSoftmax selects the allowed maximum, preserving Math.max zero ties, and evaluates only allowed exponentials in key order. Saved shifted fields repeat its immutable subtraction as a functional witness; masked fields and native leaves are absent. Structural masked terms and probabilities are +0.

Saved inputs
h
3
g
1
i
1
score0
0
score1
1.414213562373095
allowed0
1
allowed1
1
Saved outputs
max
1.414213562373095
shifted0
-1.414213562373095
shifted1
0
term0
0.24311673443421425
term1
1
denominator
1.2431167344342142
probability0
0.19557031749304313
probability1
0.8044296825069569

grouped_weighted_0_0_0_0: Head 0, query 0, key 0, value feature 0

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
0
g
0
i
0
j
0
d
0
probability
1
value
1
previous
0
Saved outputs
product
1
sum
1

grouped_weighted_0_0_0_1: Head 0, query 0, key 0, value feature 1

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
0
g
0
i
0
j
0
d
1
probability
1
value
0
previous
0
Saved outputs
product
0
sum
0

grouped_weighted_0_0_1_0: Head 0, query 0, key 1, value feature 0

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
0
g
0
i
0
j
1
d
0
probability
0
value
0
previous
1
Saved outputs
product
0
sum
1

grouped_weighted_0_0_1_1: Head 0, query 0, key 1, value feature 1

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
0
g
0
i
0
j
1
d
1
probability
0
value
1
previous
0
Saved outputs
product
0
sum
0

grouped_weighted_0_1_0_0: Head 0, query 1, key 0, value feature 0

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
0
g
0
i
1
j
0
d
0
probability
0.6697615493266569
value
1
previous
0
Saved outputs
product
0.6697615493266569
sum
0.6697615493266569

grouped_weighted_0_1_0_1: Head 0, query 1, key 0, value feature 1

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
0
g
0
i
1
j
0
d
1
probability
0.6697615493266569
value
0
previous
0
Saved outputs
product
0
sum
0

grouped_weighted_0_1_1_0: Head 0, query 1, key 1, value feature 0

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
0
g
0
i
1
j
1
d
0
probability
0.3302384506733431
value
0
previous
0.6697615493266569
Saved outputs
product
0
sum
0.6697615493266569

grouped_weighted_0_1_1_1: Head 0, query 1, key 1, value feature 1

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
0
g
0
i
1
j
1
d
1
probability
0.3302384506733431
value
1
previous
0
Saved outputs
product
0.3302384506733431
sum
0.3302384506733431

grouped_weighted_1_0_0_0: Head 1, query 0, key 0, value feature 0

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
1
g
0
i
0
j
0
d
0
probability
1
value
1
previous
0
Saved outputs
product
1
sum
1

grouped_weighted_1_0_0_1: Head 1, query 0, key 0, value feature 1

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
1
g
0
i
0
j
0
d
1
probability
1
value
0
previous
0
Saved outputs
product
0
sum
0

grouped_weighted_1_0_1_0: Head 1, query 0, key 1, value feature 0

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
1
g
0
i
0
j
1
d
0
probability
0
value
0
previous
1
Saved outputs
product
0
sum
1

grouped_weighted_1_0_1_1: Head 1, query 0, key 1, value feature 1

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
1
g
0
i
0
j
1
d
1
probability
0
value
1
previous
0
Saved outputs
product
0
sum
0

grouped_weighted_1_1_0_0: Head 1, query 1, key 0, value feature 0

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
1
g
0
i
1
j
0
d
0
probability
0.3302384506733431
value
1
previous
0
Saved outputs
product
0.3302384506733431
sum
0.3302384506733431

grouped_weighted_1_1_0_1: Head 1, query 1, key 0, value feature 1

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
1
g
0
i
1
j
0
d
1
probability
0.3302384506733431
value
0
previous
0
Saved outputs
product
0
sum
0

grouped_weighted_1_1_1_0: Head 1, query 1, key 1, value feature 0

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
1
g
0
i
1
j
1
d
0
probability
0.6697615493266569
value
0
previous
0.3302384506733431
Saved outputs
product
0
sum
0.3302384506733431

grouped_weighted_1_1_1_1: Head 1, query 1, key 1, value feature 1

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
1
g
0
i
1
j
1
d
1
probability
0.6697615493266569
value
1
previous
0
Saved outputs
product
0.6697615493266569
sum
0.6697615493266569

grouped_weighted_2_0_0_0: Head 2, query 0, key 0, value feature 0

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
2
g
1
i
0
j
0
d
0
probability
1
value
2
previous
0
Saved outputs
product
2
sum
2

grouped_weighted_2_0_0_1: Head 2, query 0, key 0, value feature 1

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
2
g
1
i
0
j
0
d
1
probability
1
value
0
previous
0
Saved outputs
product
0
sum
0

grouped_weighted_2_0_1_0: Head 2, query 0, key 1, value feature 0

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
2
g
1
i
0
j
1
d
0
probability
0
value
0
previous
2
Saved outputs
product
0
sum
2

grouped_weighted_2_0_1_1: Head 2, query 0, key 1, value feature 1

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
2
g
1
i
0
j
1
d
1
probability
0
value
2
previous
0
Saved outputs
product
0
sum
0

grouped_weighted_2_1_0_0: Head 2, query 1, key 0, value feature 0

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
2
g
1
i
1
j
0
d
0
probability
0.8044296825069569
value
2
previous
0
Saved outputs
product
1.6088593650139138
sum
1.6088593650139138

grouped_weighted_2_1_0_1: Head 2, query 1, key 0, value feature 1

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
2
g
1
i
1
j
0
d
1
probability
0.8044296825069569
value
0
previous
0
Saved outputs
product
0
sum
0

grouped_weighted_2_1_1_0: Head 2, query 1, key 1, value feature 0

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
2
g
1
i
1
j
1
d
0
probability
0.19557031749304313
value
0
previous
1.6088593650139138
Saved outputs
product
0
sum
1.6088593650139138

grouped_weighted_2_1_1_1: Head 2, query 1, key 1, value feature 1

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
2
g
1
i
1
j
1
d
1
probability
0.19557031749304313
value
2
previous
0
Saved outputs
product
0.39114063498608626
sum
0.39114063498608626

grouped_weighted_3_0_0_0: Head 3, query 0, key 0, value feature 0

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
3
g
1
i
0
j
0
d
0
probability
1
value
2
previous
0
Saved outputs
product
2
sum
2

grouped_weighted_3_0_0_1: Head 3, query 0, key 0, value feature 1

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
3
g
1
i
0
j
0
d
1
probability
1
value
0
previous
0
Saved outputs
product
0
sum
0

grouped_weighted_3_0_1_0: Head 3, query 0, key 1, value feature 0

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
3
g
1
i
0
j
1
d
0
probability
0
value
0
previous
2
Saved outputs
product
0
sum
2

grouped_weighted_3_0_1_1: Head 3, query 0, key 1, value feature 1

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
3
g
1
i
0
j
1
d
1
probability
0
value
2
previous
0
Saved outputs
product
0
sum
0

grouped_weighted_3_1_0_0: Head 3, query 1, key 0, value feature 0

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
3
g
1
i
1
j
0
d
0
probability
0.19557031749304313
value
2
previous
0
Saved outputs
product
0.39114063498608626
sum
0.39114063498608626

grouped_weighted_3_1_0_1: Head 3, query 1, key 0, value feature 1

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
3
g
1
i
1
j
0
d
1
probability
0.19557031749304313
value
0
previous
0
Saved outputs
product
0
sum
0

grouped_weighted_3_1_1_0: Head 3, query 1, key 1, value feature 0

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
3
g
1
i
1
j
1
d
0
probability
0.8044296825069569
value
0
previous
0.39114063498608626
Saved outputs
product
0
sum
0.39114063498608626

grouped_weighted_3_1_1_1: Head 3, query 1, key 1, value feature 1

product=probability*value; sum=previous+product

Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.

Saved inputs
h
3
g
1
i
1
j
1
d
1
probability
0.8044296825069569
value
2
previous
0
Saved outputs
product
1.6088593650139138
sum
1.6088593650139138

grouped_join_0_0_0: Query 0: copy head 0, feature 0 into the join

Joined[(i*Hq+h)*2+d]=HeadOutputs[(h*2+i)*2+d]

Move the head axis beside its value-feature axis and copy into h*Dv+d. All Hq heads remain; no sum, average, output projection or expanded KV cache is constructed.

Saved inputs
i
0
h
0
d
0
sourceOffset
0
destinationOffset
0
value
1
Saved outputs
value
1

grouped_join_0_0_1: Query 0: copy head 0, feature 1 into the join

Joined[(i*Hq+h)*2+d]=HeadOutputs[(h*2+i)*2+d]

Move the head axis beside its value-feature axis and copy into h*Dv+d. All Hq heads remain; no sum, average, output projection or expanded KV cache is constructed.

Saved inputs
i
0
h
0
d
1
sourceOffset
1
destinationOffset
1
value
0
Saved outputs
value
0

grouped_join_0_1_0: Query 0: copy head 1, feature 0 into the join

Joined[(i*Hq+h)*2+d]=HeadOutputs[(h*2+i)*2+d]

Move the head axis beside its value-feature axis and copy into h*Dv+d. All Hq heads remain; no sum, average, output projection or expanded KV cache is constructed.

Saved inputs
i
0
h
1
d
0
sourceOffset
4
destinationOffset
2
value
1
Saved outputs
value
1

grouped_join_0_1_1: Query 0: copy head 1, feature 1 into the join

Joined[(i*Hq+h)*2+d]=HeadOutputs[(h*2+i)*2+d]

Move the head axis beside its value-feature axis and copy into h*Dv+d. All Hq heads remain; no sum, average, output projection or expanded KV cache is constructed.

Saved inputs
i
0
h
1
d
1
sourceOffset
5
destinationOffset
3
value
0
Saved outputs
value
0

grouped_join_0_2_0: Query 0: copy head 2, feature 0 into the join

Joined[(i*Hq+h)*2+d]=HeadOutputs[(h*2+i)*2+d]

Move the head axis beside its value-feature axis and copy into h*Dv+d. All Hq heads remain; no sum, average, output projection or expanded KV cache is constructed.

Saved inputs
i
0
h
2
d
0
sourceOffset
8
destinationOffset
4
value
2
Saved outputs
value
2

grouped_join_0_2_1: Query 0: copy head 2, feature 1 into the join

Joined[(i*Hq+h)*2+d]=HeadOutputs[(h*2+i)*2+d]

Move the head axis beside its value-feature axis and copy into h*Dv+d. All Hq heads remain; no sum, average, output projection or expanded KV cache is constructed.

Saved inputs
i
0
h
2
d
1
sourceOffset
9
destinationOffset
5
value
0
Saved outputs
value
0

grouped_join_0_3_0: Query 0: copy head 3, feature 0 into the join

Joined[(i*Hq+h)*2+d]=HeadOutputs[(h*2+i)*2+d]

Move the head axis beside its value-feature axis and copy into h*Dv+d. All Hq heads remain; no sum, average, output projection or expanded KV cache is constructed.

Saved inputs
i
0
h
3
d
0
sourceOffset
12
destinationOffset
6
value
2
Saved outputs
value
2

grouped_join_0_3_1: Query 0: copy head 3, feature 1 into the join

Joined[(i*Hq+h)*2+d]=HeadOutputs[(h*2+i)*2+d]

Move the head axis beside its value-feature axis and copy into h*Dv+d. All Hq heads remain; no sum, average, output projection or expanded KV cache is constructed.

Saved inputs
i
0
h
3
d
1
sourceOffset
13
destinationOffset
7
value
0
Saved outputs
value
0

grouped_join_1_0_0: Query 1: copy head 0, feature 0 into the join

Joined[(i*Hq+h)*2+d]=HeadOutputs[(h*2+i)*2+d]

Move the head axis beside its value-feature axis and copy into h*Dv+d. All Hq heads remain; no sum, average, output projection or expanded KV cache is constructed.

Saved inputs
i
1
h
0
d
0
sourceOffset
2
destinationOffset
8
value
0.6697615493266569
Saved outputs
value
0.6697615493266569

grouped_join_1_0_1: Query 1: copy head 0, feature 1 into the join

Joined[(i*Hq+h)*2+d]=HeadOutputs[(h*2+i)*2+d]

Move the head axis beside its value-feature axis and copy into h*Dv+d. All Hq heads remain; no sum, average, output projection or expanded KV cache is constructed.

Saved inputs
i
1
h
0
d
1
sourceOffset
3
destinationOffset
9
value
0.3302384506733431
Saved outputs
value
0.3302384506733431

grouped_join_1_1_0: Query 1: copy head 1, feature 0 into the join

Joined[(i*Hq+h)*2+d]=HeadOutputs[(h*2+i)*2+d]

Move the head axis beside its value-feature axis and copy into h*Dv+d. All Hq heads remain; no sum, average, output projection or expanded KV cache is constructed.

Saved inputs
i
1
h
1
d
0
sourceOffset
6
destinationOffset
10
value
0.3302384506733431
Saved outputs
value
0.3302384506733431

grouped_join_1_1_1: Query 1: copy head 1, feature 1 into the join

Joined[(i*Hq+h)*2+d]=HeadOutputs[(h*2+i)*2+d]

Move the head axis beside its value-feature axis and copy into h*Dv+d. All Hq heads remain; no sum, average, output projection or expanded KV cache is constructed.

Saved inputs
i
1
h
1
d
1
sourceOffset
7
destinationOffset
11
value
0.6697615493266569
Saved outputs
value
0.6697615493266569

grouped_join_1_2_0: Query 1: copy head 2, feature 0 into the join

Joined[(i*Hq+h)*2+d]=HeadOutputs[(h*2+i)*2+d]

Move the head axis beside its value-feature axis and copy into h*Dv+d. All Hq heads remain; no sum, average, output projection or expanded KV cache is constructed.

Saved inputs
i
1
h
2
d
0
sourceOffset
10
destinationOffset
12
value
1.6088593650139138
Saved outputs
value
1.6088593650139138

grouped_join_1_2_1: Query 1: copy head 2, feature 1 into the join

Joined[(i*Hq+h)*2+d]=HeadOutputs[(h*2+i)*2+d]

Move the head axis beside its value-feature axis and copy into h*Dv+d. All Hq heads remain; no sum, average, output projection or expanded KV cache is constructed.

Saved inputs
i
1
h
2
d
1
sourceOffset
11
destinationOffset
13
value
0.39114063498608626
Saved outputs
value
0.39114063498608626

grouped_join_1_3_0: Query 1: copy head 3, feature 0 into the join

Joined[(i*Hq+h)*2+d]=HeadOutputs[(h*2+i)*2+d]

Move the head axis beside its value-feature axis and copy into h*Dv+d. All Hq heads remain; no sum, average, output projection or expanded KV cache is constructed.

Saved inputs
i
1
h
3
d
0
sourceOffset
14
destinationOffset
14
value
0.39114063498608626
Saved outputs
value
0.39114063498608626

grouped_join_1_3_1: Query 1: copy head 3, feature 1 into the join

Joined[(i*Hq+h)*2+d]=HeadOutputs[(h*2+i)*2+d]

Move the head axis beside its value-feature axis and copy into h*Dv+d. All Hq heads remain; no sum, average, output projection or expanded KV cache is constructed.

Saved inputs
i
1
h
3
d
1
sourceOffset
15
destinationOffset
15
value
1.6088593650139138
Saved outputs
value
1.6088593650139138

grouped_cache: Count one layer of logical key and value payload

keyElements=B*Tk*Hkv*Dk; valueElements=B*Tk*Hkv*Dv; totalElements=keyElements+valueElements; logicalBytes=totalElements*elementBytes; queryElements=B*Tq*Hq*Dk; scoreCells=B*Hq*Tq*Tk

Add K and V once before multiplying by the analytical byte assumption. Q activations and score cells are separate counts, excluded from cache payload. Binary64 arithmetic and actual allocation do not change with elementBytes.

Saved inputs
B
1
Tq
2
Tk
2
Hq
4
Hkv
2
Dk
2
Dv
2
elementBytes
2
Saved outputs
keyElements
8
valueElements
8
totalElements
16
logicalBytes
32
queryElements
16
scoreCells
16

finish: Retain every query head and count the original shared cache

output=grouped_Joined; logicalBytes=grouped_CacheCounts[3]

Copy the actual joined width and saved one-layer logical counts after all numerical work. Head sharing changes the original K/V storage, while each query head retains its own output. Native/frame/tensor counts describe this source graph, not measured hardware work.

Saved inputs
Hq
4
Hkv
2
joinedWidth
8
keyElements
8
valueElements
8
totalElements
16
logicalBytes
32
queryElements
16
scoreCells
16
Saved outputs
Hq
4
Hkv
2
joinedWidth
8
keyElements
8
valueElements
8
totalElements
16
logicalBytes
32
queryElements
16
scoreCells
16
sqrtCalls
1
expCalls
12
nativeElementaryCalls
13
frames
111
tensorCount
28
All fourteen primary summaries and every saved policy
Saved dimensions, cache units and source graph counts
Primary output keySaved value
Hq4
Hkv2
joinedWidth8
keyElements8
valueElements8
totalElements16
logicalBytes32
queryElements16
scoreCells16
sqrtCalls1
expCalls12
nativeElementaryCalls13
frames111
tensorCount28

mappingPolicy: Hq and Hkv each range from one to four with Hq divisible by Hkv. Both K and V use floor(h/(Hq/Hkv)); modulo would change fixed head identities for GQA4/2. Hq=Hkv=1 is the coincident single-head endpoint.

projectionPolicy: One fixed basis source, all four disclosed matrices in each weight bank, then twelve independently editable post-projection gains. Compute active Q heads once, active K groups once, then active V groups once. Inactive gains remain captured, visible and validated.

attentionPolicy: Compute all raw scores before any row softmax, including forbidden cells. Causality and key validity intersect. One sqrt(Dk=2) supplies every score. Each query-head row keeps its own stable probabilities over original shared K/V storage.

nativePolicy: One actual sqrt, then allowed stableSoftmax exp outputs in h,i,j order. The shifted arguments repeat the same subtraction of identical immutable operands as the unchanged primitive: functional witnesses, not physical interception. Masked cells have no shifted field or native leaf. No native math occurs in serialization.

zeroPolicy: Every scalar operand, arithmetic result and copy uses binary64 WORD, including -0. Choices, dimensions, indices, decisions and analytical counts use VALUE. Projections and dots add their two products directly. Weighted feature folds start at +0 and retain every masked product and addition.

cachePolicy: KCache and VCache each retain 4*Hkv active binary64 words. Logical payload=(keyElements+valueElements)*elementBytes for one layer. The 2/4/8-byte assumption changes counts only; it performs no cast or quantization. Q, weights, outputs, evidence copies, array overhead, traffic and timing are excluded.

limitsPolicy: Hand-set forward-only attention toy: B=1,Tq=Tk=2,Din=Dk=Dv=2. No learned parameters, output projection, residual, FFN, tokenizer, generation, training, quantization, measured memory or speedup. Changing Hkv can change outputs and does not losslessly compress arbitrary MHA.

tracePolicy: The exact unchanged decoderTrace factory captures detached finite frame operands once, rejects duplicate or empty IDs before operands, and applies its 512-frame cap after operands. No wrapper frame precedes complete raw, prefix and whole-mask preflight. Every frame output is copied to root outputs as frameId_key; finish is last.

summaryPolicy: All fourteen primary summary fields are VALUE dimensions or source counts. Cache summaries copy grouped_CacheCounts; joinedWidth copies the actual Joined shape. Binary64 WORD operands/results remain in tensors, natives, frame fields and aliases, including signed zero. Helper output is the same saved Joined TensorRecord exposed in its tensor list.

validationPolicy: SOURCE IMPLEMENTATION ONLY. All tests, independent executable authority, canonical parity, typecheck, build, browser, accessibility and offline checks are UNRUN under the human FluxGeo hold. Source adoption and validation belong to the owner; this record is not runtime acceptance.

The house inspector below retains all scalar aliases, all text metadata and complete tensor storage from this same whole root. The trace cursor selects an explanation; it does not replace these saved results or change the live question's answer. An edit starts a new calculation and clears grading; trace navigation clears the chosen answer while preserving the same question and answer key.

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.

grouped_Raw

RawField=17 · float64 · precision 8 · Captured raw17 in declared order. Choices use VALUE; all twelve gain words, including inactive gains and -0, use WORD.

Zero-based storage indexStored value
04
12
22
31
41
51
61
71
81
91
101
111
121
131
141
151
161

grouped_X

B=1 × T=2 × Din=2 · float64 · precision 8 · Fixed basis-feature source rows [1,+0],[+0,1]; this same source feeds all projections.

Zero-based storage indexStored value
01
10
20
31

grouped_WQBank

QueryHeadBank=4 × Din=2 × Dk=2 · float64 · precision 8 · All four hand-set query matrices, row-feature orientation, including inactive heads; every structural zero is literal +0.

Zero-based storage indexStored value
01
10
21
30
40
51
60
71
81
91
101
111
121
13-1
141
15-1

grouped_WKBank

KVGroupBank=4 × Din=2 × Dk=2 · float64 · precision 8 · All four hand-set key matrices, including inactive groups; active groups are projected once, not once per query head.

Zero-based storage indexStored value
01
10
20
31
41
51
61
7-1
81
90
10-1
111
120
131
141
150

grouped_WVBank

KVGroupBank=4 × Din=2 × Dv=2 · float64 · precision 8 · All four hand-set value matrices, including inactive groups; these are weights, not retained KV payload.

Zero-based storage indexStored value
01
10
20
31
42
50
60
72
81
92
102
11-1
12-1
131
141
151

grouped_HeadToGroup

Hq=4 · int32 · precision 0 · Uniform contiguous mapping floor(h/(Hq/Hkv)); both key and value caches use this index.

Zero-based storage indexStored value
00
10
21
31

grouped_QProjection

Hq=4 × Tq=2 × Dk=2 × ProjectionField=4 · float64 · precision 8 · Actual product0,product1,unscaled,value for every active query coordinate, in h,i,d order.

Zero-based storage indexStored value
01
10
21
31
40
50
60
70
80
91
101
111
120
130
140
150
160
170
180
190
201
210
221
231
240
250
260
270
280
291
301
311
321
330
341
351
361
370
381
391
400
411
421
431
440
451
461
471
481
490
501
511
52-1
53-0
54-1
55-1
560
571
581
591
60-0
61-1
62-1
63-1

grouped_KProjection

Hkv=2 × Tk=2 × Dk=2 × ProjectionField=4 · float64 · precision 8 · Actual product0,product1,unscaled,value for every active key coordinate, in g,j,d order.

Zero-based storage indexStored value
01
10
21
31
40
50
60
70
80
90
100
110
120
131
141
151
161
170
181
191
201
21-0
221
231
240
251
261
271
280
29-1
30-1
31-1

grouped_VProjection

Hkv=2 × Tk=2 × Dv=2 × ProjectionField=4 · float64 · precision 8 · Actual product0,product1,unscaled,value for every active value coordinate, in g,j,d order.

Zero-based storage indexStored value
01
10
21
31
40
50
60
70
80
90
100
110
120
131
141
151
162
170
182
192
200
210
220
230
240
250
260
270
280
292
302
312

grouped_Q

B=1 × Hq=4 × Tq=2 × Dk=2 · float64 · precision 8 · Actual projected and post-gain queries; every active query head remains independent of KV sharing.

Zero-based storage indexStored value
01
10
21
30
40
51
60
71
81
91
101
111
121
13-1
141
15-1

grouped_KCache

B=1 × Hkv=2 × Tk=2 × Dk=2 · float64 · precision 8 · Original active shared key storage, exactly 4*Hkv words. No Hq-expanded key cache exists.

Zero-based storage indexStored value
01
10
20
31
41
51
61
7-1

grouped_VCache

B=1 × Hkv=2 × Tk=2 × Dv=2 · float64 · precision 8 · Original active shared value storage, exactly 4*Hkv words. No Hq-expanded value cache exists.

Zero-based storage indexStored value
01
10
20
31
42
50
60
72

grouped_ScoreEvidence

Hq=4 × Tq=2 × Tk=2 × ScoreField=3 · float64 · precision 8 · Actual product0,product1,dot for all score cells, including forbidden cells; direct two-product sum.

Zero-based storage indexStored value
01
10
21
30
40
50
61
70
81
90
100
110
120
130
140
150
161
171
180
190
200
210
221
231
241
251
262
271
28-1
290
301
311
322
331
34-1
350
361
37-1
380
391
401
412
421
43-1
440
451
461
472

grouped_Scores

B=1 × Hq=4 × Tq=2 × Tk=2 · float64 · precision 8 · Every actual dot divided by the one saved sqrt(Dk) word, in h,i,j order.

Zero-based storage indexStored value
00.7071067811865475
10
20.7071067811865475
30
40
50.7071067811865475
60
70.7071067811865475
81.414213562373095
90
101.414213562373095
110
120
131.414213562373095
140
151.414213562373095

grouped_Allowed

B=1 × Hq=4 × Tq=2 × Tk=2 · int32 · precision 0 · Allowed=1 iff the key bit is one and j<=i. Padding affects keys only; no query or head is removed.

Zero-based storage indexStored value
01
10
21
31
41
50
61
71
81
90
101
111
121
130
141
151

grouped_RowMaxima

B=1 × Hq=4 × Tq=2 · float64 · precision 8 · Actual unchanged stableSoftmax Math.max over allowed scores, including its +0 preference on zero ties.

Zero-based storage indexStored value
00.7071067811865475
10.7071067811865475
20
30.7071067811865475
41.414213562373095
51.414213562373095
60
71.414213562373095

grouped_AllowedCoordinates

AllowedCell=12 × IndexField=3 · int32 · precision 0 · h,i,j of each allowed shifted argument and exp occurrence, in h,i,j order; no forbidden placeholder.

Zero-based storage indexStored value
00
10
20
30
41
50
60
71
81
91
100
110
121
131
140
151
161
171
182
190
200
212
221
230
242
251
261
273
280
290
303
311
320
333
341
351

grouped_Shifted

AllowedCell=12 · float64 · precision 8 · Functional exp-argument witnesses from identical immutable score-minus-max operands; no physical interception or masked entry.

Zero-based storage indexStored value
00
10
2-0.7071067811865475
30
4-0.7071067811865475
50
60
70
8-1.414213562373095
90
10-1.414213562373095
110

grouped_Terms

B=1 × Hq=4 × Tq=2 × Tk=2 · float64 · precision 8 · Actual stableSoftmax exp outputs at allowed cells and literal +0 terms at masked cells.

Zero-based storage indexStored value
01
10
21
30.49306869139523984
41
50
60.49306869139523984
71
81
90
101
110.24311673443421425
121
130
140.24311673443421425
151

grouped_Denominators

B=1 × Hq=4 × Tq=2 · float64 · precision 8 · Actual stableSoftmax reduction (+0+term0)+term1, including each masked +0 addition.

Zero-based storage indexStored value
01
11.4930686913952398
21
31.4930686913952398
41
51.2431167344342142
61
71.2431167344342142

grouped_Probabilities

B=1 × Hq=4 × Tq=2 × Tk=2 · float64 · precision 8 · Actual unchanged term/denominator words; masked probabilities are structural +0, never renormalized in a view.

Zero-based storage indexStored value
01
10
20.6697615493266569
30.3302384506733431
41
50
60.3302384506733431
70.6697615493266569
81
90
100.8044296825069569
110.19557031749304313
121
130
140.19557031749304313
150.8044296825069569

grouped_WeightedProducts

Hq=4 × Tq=2 × Tk=2 × Dv=2 · float64 · precision 8 · Actual probability*sharedValue for every h,i,j,d, including masked signed-zero products; B=1 omitted.

Zero-based storage indexStored value
01
10
20
30
40.6697615493266569
50
60
70.3302384506733431
81
90
100
110
120.3302384506733431
130
140
150.6697615493266569
162
170
180
190
201.6088593650139138
210
220
230.39114063498608626
242
250
260
270
280.39114063498608626
290
300
311.6088593650139138

grouped_WeightedPartials

Hq=4 × Tq=2 × Tk=2 × Dv=2 · float64 · precision 8 · Actual previous+product after every h,i,j,d operation, from separate literal +0 feature accumulators; B=1 omitted.

Zero-based storage indexStored value
01
10
21
30
40.6697615493266569
50
60.6697615493266569
70.3302384506733431
81
90
101
110
120.3302384506733431
130
140.3302384506733431
150.6697615493266569
162
170
182
190
201.6088593650139138
210
221.6088593650139138
230.39114063498608626
242
250
262
270
280.39114063498608626
290
300.39114063498608626
311.6088593650139138

grouped_HeadOutputs

B=1 × Hq=4 × Tq=2 × Dv=2 · float64 · precision 8 · Final key1 partials copied per head,query,value-feature; no head averaging.

Zero-based storage indexStored value
01
10
20.6697615493266569
30.3302384506733431
41
50
60.3302384506733431
70.6697615493266569
82
90
101.6088593650139138
110.39114063498608626
122
130
140.39114063498608626
151.6088593650139138

grouped_Joined

B=1 × Tq=2 × JoinedFeature=8 · float64 · precision 8 · Indexed copies of all head-output coordinates in token,query-head,value-feature order; no output projection.

Zero-based storage indexStored value
01
10
21
30
42
50
62
70
80.6697615493266569
90.3302384506733431
100.3302384506733431
110.6697615493266569
121.6088593650139138
130.39114063498608626
140.39114063498608626
151.6088593650139138

grouped_CacheCounts

CacheField=6 · int32 · precision 0 · keyElements,valueElements,totalElements,logicalBytes,queryElements,scoreCells; exact analytical counts, not measured resident memory or traffic.

Zero-based storage indexStored value
08
18
216
332
416
516

grouped_NativeArguments

Native=13 × NativeField=2 · float64 · precision 8 · Saved native input,output pairs in occurrence order: one sqrt, then allowed exp leaves. Serialization performs no native math.

Zero-based storage indexStored value
02
11.4142135623730951
20
31
40
51
6-0.7071067811865475
70.49306869139523984
80
91
10-0.7071067811865475
110.49306869139523984
120
131
140
151
160
171
18-1.414213562373095
190.24311673443421425
200
211
22-1.414213562373095
230.24311673443421425
240
251

grouped_NativeKinds

Native=13 · int32 · precision 0 · Native kind codes in occurrence order: sqrt=0,exp=1.

Zero-based storage indexStored value
00
11
21
31
41
51
61
71
81
91
101
111
121

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. Current WHOLE saved root: Hq=4, Hkv=2, elementBytes=2, q0=1, q1=1, q2=1, q3=1, k0=1, k1=1, k2=1, k3=1, v0=1, v1=1, v2=1, v3=1, key0=1, key1=1. Saved head-to-group map=[0, 0, 1, 1]; K=8 scalars, V=8 scalars, total=16 scalars, logical payload=32 bytes under the saved byte assumption. Joined shape=[1,2,8], row0=[1, 0, 1, 0, 2, 0, 2, 0], row1=[0.6697615493266569, 0.3302384506733431, 0.3302384506733431, 0.6697615493266569, 1.6088593650139138, 0.39114063498608626, 0.39114063498608626, 1.6088593650139138]. Which description identifies the saved query paths and K/V sharing? Use this complete root independently of the selected trace step.
2. Fixed shape worksheet: B=1, Tq=Tk=2, Dk=Dv=2; every gain is 1 and both key bits are 1. Which head setting and joined shape are both legal?
3. Fixed GQA worksheet: B=1, Tk=2, Hq=4, Hkv=2, Dk=Dv=2, all gains 1, both keys valid. How many one-layer logical cache bytes at 2 bytes per scalar, then at 4 bytes per scalar?
4. Fixed default GQA4/2 worksheet: all twelve gains start at 1, both keys are valid. Change ONLY q1 to 0 (the post-projection gain for query head 1, at BOTH rows). What happens at query row 1?
5. Fixed default GQA4/2 worksheet: unit gains, both keys valid, fixed head/group labels. Can h mod Hkv replace the contiguous map without changing outputs?

Exactly five corrective questions use either explicit fixed worksheets or the current WHOLE saved root. Focus a table region for keyboard scrolling; menus, numeric inputs, trace controls, disclosures and reset use native controls.

Review IV-29 — Head Concatenation and Output Projection for placing head messages side by side, and IV-50 — KV Cache Memory, Latency and Invalidation for distinguishing logical cache payload from runtime memory. Book II’s II.4 — Dot product, angle, and orthogonality develops dot products and II.10 — Matrix × matrix as composition develops matrix composition; VIII.2 — Rounding and representation error explains rounding. Book III’s III-16 — Multiclass Classification and Softmax Regression connects scores with normalized probabilities, and III-41 — Composition and Learned Representations reviews composing a neural calculation. Our weights below are disclosed, hand-set numbers; nothing is trained here.

Start with one change, then inspect the saved evidence

At reset, read the map [0,0,1,1], the joined shape [1,2,8] and the one-layer logical payload of 32 bytes under the two-byte assumption. In Original shared K/V cache storage, group0 supplies [1,0] and [0,1] as both its keys and values. In Every query head, compare heads0/1: they read that same group but retain different queries and row1 messages. The two joined rows contain every head’s message, in head order.

Change only Shared key/value groups (Hkv) to 1, then to 4, keeping Hq=4. The payload becomes 16, then 64 logical bytes under the same assumption, and the map and messages change according to the worksheets below. Choose Reset example before following any default worksheet. Hq and Hkv are independent menus: selecting 4/3 or 3/2 reports an invalid pair and withholds results and questions until corrected; the lab does not silently change the other menu.

Open Query gains, Key gains or Value gains to reveal all four continuous gain fields in that group. Each accepts numbers from −1 to 1, including −0; a field remains editable and validated when its head or group is inactive. Open Key validity for the two key bits. Blank, unfinished, nonfinite or out-of-range drafts withhold the calculation. Setting key0=0 makes causal row0 undefined. Reset restores all seventeen inputs, the first trace step and unselected exercise answers.

Use Previous step, Next step or Calculation step to inspect one saved operation’s equation and every saved operand. The cursor selects an explanation within the same whole calculation. An input edit starts a new calculation at its first step; edits, reset and trace navigation clear chosen answers. Opening a disclosure preserves them. Menus, numeric fields, buttons, radio questions and disclosures use native keyboard controls. Focus a labelled table region to scroll its wide columns with the keyboard; each table retains row/column headings. The complete operation-text fallback and full tensor inspector provide the same saved evidence without relying on color or animation. Keyboard, layout and screen-reader behavior still require the deferred browser review.

First separate the questions from the shared information

A query is a vector used to compare one position with candidate positions. A key is the vector used in that comparison. A value is the vector contributed to the resulting mixture. A head is a query-specific comparison-and-mixture path. A KV group supplies one sequence of keys and its matching sequence of values to one or more heads. KV abbreviates key/value; it does not mean a group of tokens.

Multi-head attention (MHA) here gives each query head its own KV group. Multi-query attention (MQA) shares one KV group across all query heads. Grouped-query attention (GQA) uses equally sized contiguous groups between those endpoints. Calling projections independent means their parameters and paths are separate; it makes no claim about statistical independence.

Start with four query heads and two KV groups. Heads 0 and 1 read group 0; heads 2 and 3 read group 1. Heads 0 and 1 will produce different probabilities even though they read exactly the same K and V arrays. This is the distinction to keep in view: sharing stored information leaves the queries separate.

A KV cache retains previously projected keys and values for later attention. We will count the payload that these arrays would retain for one layer and two positions. This small forward example does not implement token appending, generation or a cache-reuse transaction.

Name the axes before multiplying

A tensor is an array with named axes; its shape lists their lengths. A scalar is one numeric entry. A feature is one coordinate of a vector. A batch contains sequences, and a token position identifies a row within one sequence. All indices start at zero.

SymbolMeaning and unitThis example
B, bNumber of sequences; sequence indexB=1, b=0
Tq, iQuery positions; query-position indexTq=2, i=0 or 1
Tk, jKey positions; key-position indexTk=2, j=0 or 1
TCommon length when Tq=TkT=2
DinSource features per position2
DkCoordinates per query and key2
DvCoordinates per value and head message2
Hq, hNumber of query heads; query-head indexDefault Hq=4
Hkv, gNumber of KV groups; group indexDefault Hkv=2
d, fProjection coordinate; value coordinate0 or 1
cJoined-feature index0 through 2Hq−1

The source X has shape [B,T,Din]=[1,2,2]. Query tensor Q has [B,Hq,Tq,Dk]; K has [B,Hkv,Tk,Dk]; V has [B,Hkv,Tk,Dv]. Scores, probabilities P and the allowed mask have [B,Hq,Tq,Tk]. Head messages OHeads have [B,Hq,Tq,Dv]; the joined messages J have [B,Tq,Hq*Dv]. Tq and Tk keep different names even though their lengths both equal two. A probability row runs along Tk, never along the group axis.

The hand numbers are dimensionless toy coordinates, not seconds, bytes or learned token embeddings. Counts of features, heads, scalar entries and bytes have different units. The count of bytes will be introduced only after counting K and V entries.

Find every saved tensor, shape and storage field

Open All saved tensors and every cell in the lab for complete storage. Every ID below begins with grouped_. Put H=Hq, K=Hkv, a=H*(2+key1) allowed cells and n=1+a native occurrences; these lengths apply to defined calculations with key0=1. The lowercase a here is a cell count, separate from the uppercase A used later for an exact-real denominator. Shape entries give lengths; the displayed axes identify what each length counts. Flattening preceding axes into table rows preserves their original storage order; the last axis supplies the columns.

Tensor suffixShapeWhat to read
Raw[17]Captured inputs in rawFields order, including inactive gains
X[1,2,2]Batch, position, source feature
WQBank[4,2,2]Query-head bank, source feature, key feature; all four matrices
WKBank[4,2,2]KV-group bank, source feature, key feature; all four matrices
WVBank[4,2,2]KV-group bank, source feature, value feature; all four matrices
HeadToGroup[H]Group index for each query head
QProjection[H,2,2,4]Head, query, key feature, projection field
KProjection[K,2,2,4]Group, key, key feature, projection field
VProjection[K,2,2,4]Group, key, value feature, projection field
Q[1,H,2,2]B,Hq,Tq,Dk: actual post-gain query words
KCache[1,K,2,2]B,Hkv,Tk,Dk: original shared keys
VCache[1,K,2,2]B,Hkv,Tk,Dv: original shared values
ScoreEvidence[H,2,2,3]Head, query, key, product0/product1/dot
Scores[1,H,2,2]B,Hq,Tq,Tk: all scaled scores, including forbidden ones
Allowed[1,H,2,2]B,Hq,Tq,Tk: integer decisions, 1 allowed and 0 forbidden
RowMaxima[1,H,2]B,Hq,Tq: allowed-only maximum
AllowedCoordinates[a,3]Allowed-cell order, h/i/j coordinate field
Shifted[a]Allowed score-minus-maximum witnesses in that order
Terms[1,H,2,2]B,Hq,Tq,Tk: returned exponentials or masked +0
Denominators[1,H,2]B,Hq,Tq: ordered term sum
Probabilities[1,H,2,2]B,Hq,Tq,Tk: actual weights, masked +0
WeightedProducts[H,2,2,2]Hq,Tq,Tk,Dv: every probability times value
WeightedPartials[H,2,2,2]Hq,Tq,Tk,Dv: every updated feature sum
HeadOutputs[1,H,2,2]B,Hq,Tq,Dv: final partial for each head feature
Joined[1,2,2H]B,Tq,JoinedFeature: indexed head-feature copies
CacheCounts[6]K scalars, V scalars, total scalars, logical bytes, Q scalars, score cells
NativeArguments[n,2]Native occurrence, saved input/output field
NativeKinds[n]Native occurrence: sqrt=0, exp=1

The four projection fields are product0, product1, unscaled, value. The rank-four weighted tables omit only the fixed batch axis B=1. All tables expose dtype (numeric representation), display precision, provenance (where the entries came from) and every stored cell. Allowed, HeadToGroup, AllowedCoordinates, CacheCounts and NativeKinds are int32, meaning integer storage metadata; Allowed is not a boolean tensor. Other records are float64. The Raw choice slots at offsets0,1,2,15,16 express dimensions, bytes and key decisions; offsets3…14 retain all twelve gain words. Display precision8 does not round the values used by the model or the full storage tables, which preserve −0 explicitly.

At defaults, manual reading of the source gives 111 frames, 28 tensors with 550 cells, 371 scalar output fields, 20 text entries and 13 native occurrences. These are source inventory counts, not measured DOM counts or hardware instructions. Open All fourteen primary summaries and every saved policy for the saved counts; the house inspector retains every scalar alias and all text arrays too. Eight computation stages and eleven saved graph tensors presents two separate lists: a stage can involve several tensors. Complete saved operation text fallback retains every frame, its equation, explanation, and all ordered inputs and outputs, rather than cutting the trace to its opening steps.

Project the same source, then apply each gain

A projection multiplies a source row by a weight matrix to form a new vector. We use row-feature matrices: each weight matrix has shape [Din,2]. This is the explicit row convention corresponding to the transposed weight orientation of Book II’s column-vector notation.

The SAME basis source supplies Q, K and V:

X[0,:,:]=(1+0+01).X[0,:,:]=\begin{pmatrix}1&+0\\+0&1\end{pmatrix}.

A basis row selects one coordinate direction. It makes the arithmetic easy to inspect, but every product is still part of the calculation. The complete fixed weight banks contain four matrices each, including matrices outside the active head/group counts:

Head or groupWQ: row0; row1WK: row0; row1WV: row0; row1
0(1,+0); (1,+0)(1,+0); (+0,1)(1,+0); (+0,1)
1(+0,1); (+0,1)(1,1); (1,−1)(2,+0); (+0,2)
2(1,1); (1,1)(1,+0); (−1,1)(1,2); (2,−1)
3(1,−1); (1,−1)(+0,1); (1,+0)(−1,1); (1,1)

For ANY one of these matrices W, disclose its rows as (a,b) and (c,d). The two source rows give every coordinate explicitly:

Source rowCoordinate 0: products then direct sumCoordinate 1: products then direct sum
i=01*a + (+0)*c = a1*b + (+0)*d = b
i=1(+0)*a + 1*c = c(+0)*b + 1*d = d

These four equations apply separately to every displayed matrix, with its disclosed a,b,c,d. There is no bias and no initial zero added before the two-product sum. Apply a scalar gain, meaning a multiplier, AFTER that sum: Q uses qh, K uses kg, V uses vg. For example head1’s first query coordinate at either row is (1*0+0*0)*q1 or (0*0+1*0)*q1; its second is (1*1+0*1)*q1 or (0*1+1*1)*q1. Group1’s key at row1 is ((0*1+1*1)*k1,(0*1+1*(-1))*k1)=(k1,-k1) over the reals. Its value there is ((0*2+1*0)*v1,(0*0+1*2)*v1)=(0,2v1).

At unit gains the complete projected bank is therefore:

h or gQh at BOTH rowsKg at key0; key1Vg at key0; key1
0(1,0)(1,0); (0,1)(1,0); (0,1)
1(0,1)(1,1); (1,−1)(2,0); (0,2)
2(1,1)(1,0); (−1,1)(1,2); (2,−1)
3(1,−1)(0,1); (1,0)(−1,1); (1,1)

Only the active Q heads and active K/V groups are projected. Compute Q once per active head, then K once per active group, then V once per active group. At GQA4/2 there are two actual K sequences and two actual V sequences; reading group0 from two heads does not allocate two caches or repeat its projection. The complete weight banks remain disclosed regardless of active dimensions.

The seventeen controls are Hq and Hkv as integers 1 through 4; an analytical storage assumption elementBytes of 2, 4 or 8; twelve gains q0…q3, k0…k3, v0…v3 in [−1,1]; and two key-validity flags key0/key1 equal to 0 or 1. Defaults are 4,2,2, all unit gains, both valid keys. Inactive gains still validate. A gain scales a whole projected matrix; it cannot rotate one query vector or edit just one row.

Assign heads without copying their caches

Let G=Hq/Hkv be the number of query heads per group. This division must be an integer. Select BOTH K and V with

g(h)=⌊h/G⌋.g(h)=\lfloor h/G\rfloor.

The floor symbol means round down to the greatest integer no larger than its argument. At 4/2, G=2 and the mapping is [0,0,1,1].

Hq / HkvHead-to-group mapDescription
1 / 1[0]Single-head case: MHA and MQA endpoints coincide
2 / 1[0,0]MQA
2 / 2[0,1]MHA
3 / 1[0,0,0]MQA
3 / 3[0,1,2]MHA
4 / 1[0,0,0,0]MQA
4 / 2[0,0,1,1]Intermediate GQA
4 / 4[0,1,2,3]MHA

These are all eight valid pairs in the bounded domain. An odd head count is legal: 3/1 and 3/3 work. 4/3 and 3/2 do not divide evenly, so they are invalid inputs rather than requests for uneven groups.

Why the contiguous mapping covers every head exactly once

Integer division writes each head uniquely as h=g*G+u, with 0<=u<G. Thus group g receives precisely g*G through (g+1)*G−1, exactly G consecutive heads. These intervals cover 0 through Hq−1 without overlap. Since h is below Hq=Hkv*G, its g is below Hkv. Both key and value lookups must use that same g; mixing K from one group with V from another changes the calculation.

From a dot product to a causal mixture

A dot product multiplies matching coordinates and adds them. For head2/group1, key0 gives 1*1+1*1=2, while key1 gives 1*1+1*(-1)=0. A score divides each dot by the square root of Dk. The square root of two is the positive number whose square is two; it is reused across all heads. The divisor is not the number of heads or the group width.

Now define s=1/sqrt(2), r=exp(-s) and t=exp(-2s), where exp is the exponential function and exp(0)=1. Hence 0<t<r<1. Also define A=1+r and C=1+t to shorten the tables. These are exact-real symbols; they are not decimal approximations or a recipe for replacing actual scalar operations.

A causal mask permits key j only when j<=i. A padding mask additionally requires keyj=1; padding flags apply to keys and do not delete query rows or heads. At defaults, row0 permits only key0; row1 permits both keys. Stable softmax subtracts the largest ALLOWED score m, exponentiates the allowed differences, and divides each term by their sum Z. A forbidden position gets literal +0 probability; it has no evaluated exponential or shifted argument.

For an allowed key, Ej=exp(scorej-m) and Pj=Ej/Z. Accumulate Z in ascending key order from +0, including the masked zero contribution in the full-width sum. For each value feature f, calculate BOTH key products Pj*V[g,j,f], adding in ascending j from a separate +0 accumulator. This mixture is the head message O. Its coordinates can be negative or sum to something other than one: the probabilities are normalized, the value vectors are not.

Default GQA4/2: row1, every head

The raw score pair contains two direct two-product sums, and both keys are allowed here.

h,gRaw dots: key0; key1Scaled scoresm; allowed shiftsE0,E1; ordered ZP0,P1
0,01*1+0*0=1; 1*0+0*1=0s,0s; 0,−s1,r; (+0+1)+r=A1/A,r/A
1,00*1+1*0=0; 0*0+1*1=10,ss; −s,0r,1; (+0+r)+1=Ar/A,1/A
2,11*1+1*1=2; 1*1+1*(-1)=02s,02s; 0,−2s1,t; (+0+1)+t=C1/C,t/C
3,11*1+(-1)*1=0; 1*1+(-1)*(-1)=20,2s2s; −2s,0t,1; (+0+t)+1=Ct/C,1/C

For clarity each pair below lists feature0 and feature1. R0 is the partial after adding key0’s products to the two +0 accumulators. R1 is the partial after key1, and is the final O.

h,gKey0 products U0R0Key1 products U1R1 = O
0,0((1/A)*1,(1/A)*0)=(1/A,0)(+0+1/A,+0+0)=(1/A,0)((r/A)*0,(r/A)*1)=(0,r/A)(1/A+0,0+r/A)=(1/A,r/A)
1,0((r/A)*1,(r/A)*0)=(r/A,0)(+0+r/A,+0+0)=(r/A,0)((1/A)*0,(1/A)*1)=(0,1/A)(r/A+0,0+1/A)=(r/A,1/A)
2,1((1/C)*2,(1/C)*0)=(2/C,0)(+0+2/C,+0+0)=(2/C,0)((t/C)*0,(t/C)*2)=(0,2t/C)(2/C+0,0+2t/C)=(2/C,2t/C)
3,1((t/C)*2,(t/C)*0)=(2t/C,0)(+0+2t/C,+0+0)=(2t/C,0)((1/C)*0,(1/C)*2)=(0,2/C)(2t/C+0,0+2/C)=(2t/C,2/C)

Heads0/1 share a cache but reverse their probabilities; each of their output vectors has coordinate sum one. Heads2/3 also reverse their probabilities, and each of their output vectors has coordinate sum two because group1’s value vectors have coordinate sum two. These sums describe value coordinates; each probability row still sums to one over the reals.

Expand every source-by-weight product in the three full banks

The entries below are the unscaled two-coordinate projection at source rows0 and1. Multiply EACH resulting coordinate by the gain in the last column, after its displayed direct sum. This makes the basis selection explicit for all twelve matrices rather than silently replacing the projection with a lookup. Only active matrices execute; disclosure of an inactive matrix does not make it part of the cache.

Bank/indexRow0 coordinate0; coordinate1Row1 coordinate0; coordinate1Post gain
WQ01*1+0*1=1; 1*0+0*0=00*1+1*1=1; 0*0+1*0=0q0
WQ11*0+0*0=0; 1*1+0*1=10*0+1*0=0; 0*1+1*1=1q1
WQ21*1+0*1=1; 1*1+0*1=10*1+1*1=1; 0*1+1*1=1q2
WQ31*1+0*1=1; 1*(-1)+0*(-1)=-10*1+1*1=1; 0*(-1)+1*(-1)=-1q3
WK01*1+0*0=1; 1*0+0*1=00*1+1*0=0; 0*0+1*1=1k0
WK11*1+0*1=1; 1*1+0*(-1)=10*1+1*1=1; 0*1+1*(-1)=-1k1
WK21*1+0*(-1)=1; 1*0+0*1=00*1+1*(-1)=-1; 0*0+1*1=1k2
WK31*0+0*1=0; 1*1+0*0=10*0+1*1=1; 0*1+1*0=0k3
WV01*1+0*0=1; 1*0+0*1=00*1+1*0=0; 0*0+1*1=1v0
WV11*2+0*0=2; 1*0+0*2=00*2+1*0=0; 0*0+1*2=2v1
WV21*1+0*2=1; 1*2+0*(-1)=20*1+1*2=2; 0*2+1*(-1)=-1v2
WV31*(-1)+0*1=-1; 1*1+0*1=10*(-1)+1*1=1; 0*1+1*1=1v3

Zeros in this real-algebra table stand for the disclosed +0 source/weight constants; resulting floating-point signs are discussed below. The gain does not move into either product or into the weight bank. At gain1 these give exactly the hand vectors used throughout the worksheets.

Compare the two sharing endpoints, keeping all queries

Changing Hkv selects different active projected groups and changes the mapping. It can change the answer. We therefore calculate complete MQA4/1 and MHA4/4 cases, keeping Hq=4, both valid keys and every gain at one. The definitions s=1/sqrt(2), r=exp(-s), t=exp(-2s), A=1+r, C=1+t remain unchanged.

Complete MQA4/1 row1: one actual KV group, four query paths
h,gRaw dots: key0; key1Scoresm; allowed shiftsE0,E1; ordered ZP0,P1
0,01*1+0*0=1; 1*0+0*1=0s,0s; 0,−s1,r; (+0+1)+r=A1/A,r/A
1,00*1+1*0=0; 0*0+1*1=10,ss; −s,0r,1; (+0+r)+1=Ar/A,1/A
2,01*1+1*0=1; 1*0+1*1=1s,ss; 0,01,1; (+0+1)+1=21/2,1/2
3,01*1+(-1)*0=1; 1*0+(-1)*1=-1s,−ss; 0,−2s1,t; (+0+1)+t=C1/C,t/C
h,gKey0 products U0R0Key1 products U1R1 = O
0,0((1/A)*1,(1/A)*0)=(1/A,0)(+0+1/A,+0+0)=(1/A,0)((r/A)*0,(r/A)*1)=(0,r/A)(1/A+0,0+r/A)=(1/A,r/A)
1,0((r/A)*1,(r/A)*0)=(r/A,0)(+0+r/A,+0+0)=(r/A,0)((1/A)*0,(1/A)*1)=(0,1/A)(r/A+0,0+1/A)=(r/A,1/A)
2,0((1/2)*1,(1/2)*0)=(1/2,0)(+0+1/2,+0+0)=(1/2,0)((1/2)*0,(1/2)*1)=(0,1/2)(1/2+0,0+1/2)=(1/2,1/2)
3,0((1/C)*1,(1/C)*0)=(1/C,0)(+0+1/C,+0+0)=(1/C,0)((t/C)*0,(t/C)*1)=(0,t/C)(1/C+0,0+t/C)=(1/C,t/C)

Head2 is uniform because its two scores tie. This is a property of the supplied data, not a requirement of MQA: head3 shares exactly the same K/V and is nonuniform. All four output heads remain present.

Complete MHA4/4 row1: four separately projected KV groups
h,gRaw dots: key0; key1Scoresm; allowed shiftsE0,E1; ordered ZP0,P1
0,01*1+0*0=1; 1*0+0*1=0s,0s; 0,−s1,r; (+0+1)+r=A1/A,r/A
1,10*1+1*1=1; 0*1+1*(-1)=-1s,−ss; 0,−2s1,t; (+0+1)+t=C1/C,t/C
2,21*1+1*0=1; 1*(-1)+1*1=0s,0s; 0,−s1,r; (+0+1)+r=A1/A,r/A
3,31*0+(-1)*1=-1; 1*1+(-1)*0=1−s,ss; −2s,0t,1; (+0+t)+1=Ct/C,1/C
h,gKey0 products U0R0Key1 products U1R1 = O
0,0((1/A)*1,(1/A)*0)=(1/A,0)(+0+1/A,+0+0)=(1/A,0)((r/A)*0,(r/A)*1)=(0,r/A)(1/A+0,0+r/A)=(1/A,r/A)
1,1((1/C)*2,(1/C)*0)=(2/C,0)(+0+2/C,+0+0)=(2/C,0)((t/C)*0,(t/C)*2)=(0,2t/C)(2/C+0,0+2t/C)=(2/C,2t/C)
2,2((1/A)*1,(1/A)*2)=(1/A,2/A)(+0+1/A,+0+2/A)=(1/A,2/A)((r/A)*2,(r/A)*(-1))=(2r/A,-r/A)(1/A+2r/A,2/A-r/A)=((1+2r)/A,(2-r)/A)
3,3((t/C)*(-1),(t/C)*1)=(-t/C,t/C)(+0-t/C,+0+t/C)=(-t/C,t/C)((1/C)*1,(1/C)*1)=(1/C,1/C)(-t/C+1/C,t/C+1/C)=((1-t)/C,1)

The last second coordinate is (t+1)/C=1 over exact reals. That simplification does not assert that a floating-point program’s ordered sum produces a particular word. Heads0/2 have equal probabilities but different values and different outputs. A probability map alone is insufficient to identify the message.

Row0: causality wins even when the forbidden score is larger

Q is the same at both rows, so the raw dot products below repeat the arithmetic at row1. They still must be calculated at row0, including the forbidden future key1. The allowed maximum uses key0 alone; head1 in GQA is a particularly useful case because key1’s score is larger but forbidden.

All twelve row0 score rows across GQA, MQA and MHA
Modeh,gRaw dots: key0; key1ScoresAllowed maximum m
GQA4/20,01*1+0*0=1; 1*0+0*1=0s,0s
GQA4/21,00*1+1*0=0; 0*0+1*1=10,s0
GQA4/22,11*1+1*1=2; 1*1+1*(-1)=02s,02s
GQA4/23,11*1+(-1)*1=0; 1*1+(-1)*(-1)=20,2s0
MQA4/10,01*1+0*0=1; 1*0+0*1=0s,0s
MQA4/11,00*1+1*0=0; 0*0+1*1=10,s0
MQA4/12,01*1+1*0=1; 1*0+1*1=1s,ss
MQA4/13,01*1+(-1)*0=1; 1*0+(-1)*1=-1s,−ss
MHA4/40,01*1+0*0=1; 1*0+0*1=0s,0s
MHA4/41,10*1+1*1=1; 0*1+1*(-1)=-1s,−ss
MHA4/42,21*1+1*0=1; 1*(-1)+1*1=0s,0s
MHA4/43,31*0+(-1)*1=-1; 1*1+(-1)*0=1−s,s−s

For EACH displayed row the allowed shift is score0-m=0; E0=exp(0)=1; key1’s term is structural +0, not an exponential. The full-width denominator is (+0+1)+(+0)=1. Therefore P0=1/1=1 and P1=+0. There is no shifted argument or exponential leaf for key1. In particular the last row uses m=−s even though the forbidden score is +s.

Modeh,gU0: both productsR0: separate +0 sumsU1: both masked productsR1 = O
GQA4/20,0(1*1,1*0)=(1,0)(+0+1,+0+0)=(1,0)(0*0,0*1)=(0,0)(1+0,0+0)=(1,0)
GQA4/21,0(1*1,1*0)=(1,0)(+0+1,+0+0)=(1,0)(0*0,0*1)=(0,0)(1+0,0+0)=(1,0)
GQA4/22,1(1*2,1*0)=(2,0)(+0+2,+0+0)=(2,0)(0*0,0*2)=(0,0)(2+0,0+0)=(2,0)
GQA4/23,1(1*2,1*0)=(2,0)(+0+2,+0+0)=(2,0)(0*0,0*2)=(0,0)(2+0,0+0)=(2,0)
MQA4/10,0(1*1,1*0)=(1,0)(+0+1,+0+0)=(1,0)(0*0,0*1)=(0,0)(1+0,0+0)=(1,0)
MQA4/11,0(1*1,1*0)=(1,0)(+0+1,+0+0)=(1,0)(0*0,0*1)=(0,0)(1+0,0+0)=(1,0)
MQA4/12,0(1*1,1*0)=(1,0)(+0+1,+0+0)=(1,0)(0*0,0*1)=(0,0)(1+0,0+0)=(1,0)
MQA4/13,0(1*1,1*0)=(1,0)(+0+1,+0+0)=(1,0)(0*0,0*1)=(0,0)(1+0,0+0)=(1,0)
MHA4/40,0(1*1,1*0)=(1,0)(+0+1,+0+0)=(1,0)(0*0,0*1)=(0,0)(1+0,0+0)=(1,0)
MHA4/41,1(1*2,1*0)=(2,0)(+0+2,+0+0)=(2,0)(0*0,0*2)=(0,0)(2+0,0+0)=(2,0)
MHA4/42,2(1*1,1*2)=(1,2)(+0+1,+0+2)=(1,2)(0*2,0*(-1))=(0,0)(1+0,2+0)=(1,2)
MHA4/43,3(1*(-1),1*1)=(-1,1)(+0-1,+0+1)=(-1,1)(0*1,0*1)=(0,0)(-1+0,1+0)=(-1,1)

All shown products and additions are required work even when masked. These are real-number equalities: for instance binary64 (+0)*(-1) is −0, although its real contribution is zero. The implementation must retain such actual signed-zero products, not rewrite this table’s algebra as a shortcut.

Join every head message, preserving its identity

Concatenation, also called joining, places feature coordinates beside one another. For each query i, copy head0’s two features, then head1’s, and so on. The rule is c=h*Dv+f and

J[b,i,c]=OHeads[b,h,i,f].J[b,i,c]=OHeads[b,h,i,f].

No addition, averaging or output projection occurs. A group index never replaces h here. First move the axes from [B,Hq,Tq,Dv] to [B,Tq,Hq,Dv], then combine the adjacent head and feature axes. Simply reshaping the original flat list would mix positions and heads.

ModeJoined row0Joined row1
GQA4/2(1,0,1,0,2,0,2,0)(1/A,r/A,r/A,1/A,2/C,2t/C,2t/C,2/C)
MQA4/1(1,0,1,0,1,0,1,0)(1/A,r/A,r/A,1/A,1/2,1/2,1/C,t/C)
MHA4/4(1,0,2,0,1,2,-1,1)(1/A,r/A,2/C,2t/C,(1+2r)/A,(2-r)/A,(1-t)/C,1)

All three tensors have shape [1,2,8]: changing Hkv does not remove query-head outputs. At Hq3 the joined width is six, including MQA3/1. A full transformer would need an additional output matrix of shape [2Hq,Dout] to map these features to a chosen output width Dout. No such matrix, residual addition or feed-forward layer is computed here; eight joined coordinates cannot simply be added to the two-feature source.

Invert the join and locate every stored coordinate

Given any joined coordinate c, integer division uniquely recovers h=floor(c/Dv) and f=c mod Dv; mod means the nonnegative remainder. This inverse proves every head feature appears exactly once. For Hq4,Dv2 the joined indices0…7 recover (h,f)=(0,0),(0,1),(1,0),(1,1),(2,0),(2,1),(3,0),(3,1).

With B=1,Tq=Tk=2, the zero-based flat offsets are Q/O=(h*2+i)*2+d, K/V=(g*2+j)*2+d, score/P=(h*2+i)*2+j, and J=(i*Hq+h)*2+d. Here d means the matching within-vector feature (use f for values). Weighted products and running partials, omitting the fixed batch axis, have shape [Hq,Tq,Tk,Dv] and offset ((h*2+i)*2+j)*2+f.

For example head1,query0,feature0 lives at source O offset4 and destination J offset2 for Hq4. Their values coincide because this is an indexed copy; no sum can explain that relocation. K/V offsets use g rather than h, so two heads in one group read the same original entries rather than expanded per-head storage.

A mapping that looks balanced can still be wrong

At GQA4/2 the formula h mod Hkv would give [0,1,0,1] rather than [0,0,1,1]. Each group still receives two heads, but the identities have changed. Hold the query bank and output-head labels fixed and inspect head1:

Correctly floor(1/2)=0. Row1 uses dots (0*1+1*0,0*0+1*1)=(0,1), scores (0,s), allowed maximum s, shifts (−s,0), terms (r,1), Z=(+0+r)+1=A, P=(r/A,1/A). The value products are (r/A,0) and (0,1/A); the two partials give O=(r/A,1/A).

The modulo replacement gives group1. Row1 dots become (0*1+1*1,0*1+1*(-1))=(1,-1), scores (s,−s), maximum s, shifts (0,−2s), terms (1,t), Z=(+0+1)+t=C, P=(1/C,t/C). The value products are (2/C,0) and (0,2t/C), so O=(2/C,2t/C). Correct coordinates sum to one; wrong coordinates sum to two. Also the correct first coordinate is below one and the wrong one above one, since r,t lie strictly between zero and one.

Already at row0 both P rows are (1,0) yet correct O=(1,0) and wrong O=(2,0). At the MQA and MHA endpoints the two mappings coincide, so inspecting only endpoints misses the error. An interleaved convention can describe another architecture with consistently relabelled weights; it does not describe this fixed contiguous architecture.

Count the retained K and V entries once

A logical payload counts just the retained numeric entries under a declared representation assumption. A byte contains eight bits; a bit is a binary digit. Let e denote the assumed bytes per scalar, equal to elementBytes. For one layer:

NK=B Tk Hkv Dk,NV=B Tk Hkv Dv,N_K=B\,Tk\,Hkv\,Dk,\qquad N_V=B\,Tk\,Hkv\,Dv, NKV=NK+NV=B Tk Hkv (Dk+Dv),bytes=NKV e.N_{KV}=N_K+N_V=B\,Tk\,Hkv\,(Dk+Dv),\qquad \mathrm{bytes}=N_{KV}\,e.

NK and NV count scalars; multiplying by e bytes/scalar gives bytes. With B1,Tk2,Dk=Dv2, K has4Hkv entries and V another4Hkv, giving8Hkv entries. Add K and V ONCE before multiplying. An extra factor of two after Dk+Dv counts both payloads twice.

HkvK scalarsV scalarsTotal scalarse=2 bytes/scalare=4 bytes/scalare=8 bytes/scalar
144816 bytes32 bytes64 bytes
2881632 bytes64 bytes128 bytes
312122448 bytes96 bytes192 bytes
416163264 bytes128 bytes256 bytes

Hkv3 is available only at Hq3 in this bounded domain. At fixed Hq4 and the same e, GQA4/2 has half the logical KV payload of MHA4/4 and MQA4/1 one quarter. At Hq3, MQA3/1 has one third the payload of MHA3/3. With Hkv fixed, changing Hq changes query/output shapes without changing this payload. All of these are count ratios, with no measured memory or speed result.

The actual scalar arithmetic and cache values remain binary64, a 64-bit floating-point representation, for every e choice. Selecting e=2 or4 is an analytical storage assumption. It does not cast values, round them into a smaller format, quantize them or allocate a packed buffer. Quantization deliberately maps numbers into a restricted representation; that operation belongs to a separate lesson. Displayed rounding likewise never feeds subsequent arithmetic.

Q contains BTqHq*Dk=4Hq activation scalars and is excluded from the KV cache. Also exclude the weight banks, scores, probabilities, value products, running partials, head/joined outputs, saved audit copies, object headers, alignment, allocator reservations and temporary workspaces. An allocator is the runtime’s memory manager. Teaching evidence occupies space beyond the model payload, so process memory cannot be inferred from this table. Additional layers would contribute their own payloads.

Sharing K/V leaves a score path per query head: the full two-row score tensor contains BHqTq*Tk=4Hq cells. At Hq4 with both valid keys, twelve are allowed and four future-key cells are forbidden, but all sixteen raw scores are calculated. K/V storage scales with Hkv; these score cells scale with Hq. Neither a payload ratio nor a scalar-cell count establishes latency, bandwidth, throughput or kernel efficiency. Latency is elapsed time for a request; throughput is work completed per unit time. Neither was measured here.

What a gain or key flag can change

At the default GQA4/2 setting, q1=0 makes ONLY head1’s row1 scores tie at zero over the reals. With both keys valid, its exponentials are (1,1), Z=2, P=(1/2,1/2), and the unchanged group0 values give O=(1/2,1/2). Its row0 still has P=(1,0) because only one key is allowed. Both query rows are scaled; this is not a one-row vector rotation. Head0’s Q and every K/V entry remain unchanged.

Setting k0=0 instead makes row1 scores tie for BOTH heads mapped to group0. Setting v0=0 leaves probabilities unchanged but makes those heads’ value mixtures zero over the reals. None of these gain edits changes logical cache dimensions. Distinct query heads may happen to contain equal vectors without merging their identities.

Setting key1=0 makes every head at both rows select its group’s first value with P=(1,0). Key1’s raw scores and all masked value products still exist. The two-position cache tensors and their logical payload counts retain their declared shapes; a validity flag does not compact or remove a row. Setting key0=0 makes query0 have no eligible key, even if key1=1, since future keys cannot repair causality.

Reject an empty row before doing partial work

Preflight means deciding whether the complete requested calculation is defined before starting its trace or numerical work. Eligibility is keyj=1 AND j<=i. A row with no eligible key returns Unavailable(FULLY_MASKED_ROW). It must not create a uniform row, an all-zero output, a NaN (not-a-number), or a secretly unmasked key. Check all heads and queries before any projection, square root, exponential or appended trace frame, so failure leaves an existing collector unchanged.

The input boundary captures exactly the seventeen declared data fields. It examines all field descriptors before reading their values: a descriptor says whether an object’s field is ordinary stored data rather than a getter that could execute code. It requires ordinary or null-prototype objects with their own data fields; it does not coerce strings or run accessors. Capture all fields, require ALL values finite before any domain decision, validate domains in declared order, then validate head divisibility, the trace-name prefix, and finally the whole allowed mask. A prefix is the text prepended to saved trace identities; its exact accepted spelling belongs to the adopted implementation.

This order matters even if a field is inactive: q3 outside Hq3 or k3/v3 outside Hkv3 cannot hide an invalid gain. Invalid head pairs are withheld rather than rounded, clamped or partially calculated. No result is supplied from a previous successful state. The fixed disclosed source and matrices must also be used faithfully; no invalid V entry could be hidden by a zero probability. Finite intermediates and the declared operation order remain part of the numerical contract. The helper prefix starts with an ASCII letter and contains only ASCII letters, digits or underscores; the chapter uses the literal grouped. The chapter’s unavailable record contains its status, typed code and reason, with no partial computed views.

Why numerical zeros and native evidence need special care

The worksheets describe exact REAL numbers. Binary64 additionally distinguishes +0 and −0. They are equal as reals, but their sign bits can matter when an operand is copied, serialized or used by a later operation. Structural masked probabilities are literal +0; products formed using them can be −0. Do not rewrite an actual product’s sign or replace masked multiplications/additions with skipped work.

For example q0=−0 multiplies the projected coordinates (1,+0) to (-0,-0). Against group0’s key0 (1,+0), the two dot products are (-0,-0) and their DIRECT sum is −0. Adding an initial +0 before those products would erase that distinction. This is why the signed design uses two products followed by their direct addition for projections AND dots. It still starts each value-feature accumulator at +0, as explicitly shown in the tables. Moving a gain into the weights or reassociating arithmetic would describe a different sequence of rounded operations.

At q2=−0 in GQA4/2, head2’s row1 scores are (-0,+0). The signed softmax convention takes the tied maximum as +0; the allowed shifted arguments remain (-0,+0) and exponentials are +1. A gain of zero is legal, whereas a zero head count is not. A uniform allowed row is valid; a fully masked row is not. An allowed exponential that rounds to zero in another problem would be numerical underflow, not proof of a mask. No small positive epsilon is added to forbidden probabilities.

A native operation here is the platform’s square root or exponential evaluation. The signed evidence contract calls for one actual sqrt(2), reused everywhere, followed by exponentials for allowed positions in ascending head/query/key order. There are Hq*(2+key1) exponential leaves for any valid mask here, so the default has one square-root leaf plus twelve exponentials, regardless of Hkv. A leaf is one such operation’s recorded identity, input and returned output. Forbidden shifted arguments and exponential leaves are absent, while forbidden raw dots and all value-product/addition work remain present.

A functional witness reconstructs an exponential’s input from the same immutable saved score and maximum and records the actual returned term. It does not physically intercept a call inside a platform function. A copy binding checks that later operands and published copies use the same admitted value, including signed-zero bits where required. The saved returned exponential, rather than a second fresh exponential call in a display, must feed subsequent computation.

The disclosed bounds give query/key coordinate magnitudes at most one and value magnitudes at most two. Thus each dot’s magnitude is at most two. The separate independent oracle’s contract admits sqrt(2) within four adjacent positive binary64 steps while remaining greater than one, giving score magnitudes at most two and allowed shifts in [−4,0]. These sit inside its generic exponential domain [−256,0]. An adjacent step means moving to the next representable binary64 value; it is not a decimal tolerance or a measured machine error. That independent admission budget is at most four such steps, with exp(0) fixed to +1. Native identity, operation kind and exact input word must match before any budget is considered; every downstream rounded operation and copy then needs exact binding within that record. This admission belongs to oracle/p15/iv61_exact.py, independently of Python’s ordinary native math in the canonical reference.

WORD comparison means retaining the exact binary64 bits, including the sign of zero; VALUE comparison means exact equality of a dimension, index, decision or analytical count. Every float64 tensor cell is WORD except Raw’s five choice slots. In particular, fixed bank zeros and masked Terms/Probabilities are +0 WORD: replacing one with −0 is not an acceptable copy. All int32 cells use VALUE. In the native ledger even the fixed sqrt input2 is WORD, while its frame’s dimension Dk=2 is VALUE. A computed integer-looking scalar remains WORD. A display showing the same real number is not enough to establish these copy rules.

These are signed proof requirements, not executed evidence. They do not establish whole-platform transcendental word parity, a hardware attestation or real execution timings. RN, when used in later proof notes, means rounding an exact operation to the nearest binary64 value under the specified tie convention. No derivative, loss or parameter update is computed, so a gradient check is not applicable to this forward/cache-count scope.

Sharing is a restriction, not a lossless conversion promise

Starting with a particular grouped model, one could write an MHA-shaped description in which each head’s K and V are copies of its selected group. With the same Q and mask, each dot, probability and value sum would then agree over exact reals. Materializing those repeated tensors would waste the physical sharing we are trying to describe; this lesson retains actual group-indexed K/V storage instead.

The converse does not hold for arbitrary MHA. Literal grouping would require BOTH K and V to coincide within each proposed group. Averaging unequal key/value sequences does not satisfy that condition. An accidental matching output for a particular query is also insufficient to prove model equivalence. Our distinct fixed groups deliberately make the outputs change when Hkv changes. No model-quality guarantee, learned adaptation or lossless compression claim follows.

Changing projections, mapping or head configuration also changes what a coherent cache means. The previous cache cannot silently be relabelled as the new architecture’s valid cache. IV-50 — KV Cache Memory, Latency and Invalidation explains the separate reuse-validity problem; this chapter performs no append or reuse acceptance experiment.

Use the five questions with their stated inputs

The lab above contains the single set of five graded questions. The first reads the current WHOLE saved root: all seventeen captured inputs, its complete head-to-group map, K/V counts and bytes, joined shape and both full joined rows. Moving the trace cursor leaves this question’s evidence and answer key unchanged, though it clears a chosen radio answer. At 1/1 its description is explicitly the coincident single-head endpoint; with multiple queries it distinguishes MQA, intermediate GQA and MHA. Equal or zero numerical vectors do not change those architectural identities.

The other four questions state fixed worksheet premises. The legal-shape question fixes B=1,Tq=Tk=2,Dk=Dv=2, unit gains and both valid keys. The cache question fixes GQA4/2 with those unit gains and valid keys, then asks about two and four analytical bytes per scalar. The gain question starts at default GQA4/2 with all twelve gains1 and both valid keys, then changes only q1 to zero at BOTH rows. The counterexample fixes default4/2, unit gains, both valid keys and unchanged head/group labels before proposing modulo. Current edits do not replace those written premises. Select any option to receive reasoning that addresses all alternatives; there is no additional grader hidden in these worksheets.

Read the complete canonical source in dependency order

These three panels import the full repository files directly with ?raw. Their dependency closure is the new iv61.py entry, new grouped_reference.py helper and unchanged decoder_reference.py support. The canonical files also use the Python standard library and NumPy; NumPy supplies explicitly indexed binary64 storage, while scalar products, additions, divisions and native calls are written out. No program is executed by displaying its source.

Read the shared support first for NumericalFault, finite-number capture, freezing, prefix checks, the trace collector and indexed storage. Its full file also contains the earlier decoder’s task and checks. The new grouped helper uses the generic pieces; it does not call that older decoder’s state, block, attention or task calculation as IV61 mathematics or proof. The unequal head/group projection, contiguous lookup, softmax, contraction and join are the new helper’s own scalar graph.

1. Readonly IV59 generic support — complete file

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.

"""Independent IV59 scalar FIRST, with owner-adopted public bindings.

All execution and checks are UNRUN. Saved scalar captures drive serialization.
NumPy is used only for explicitly indexed result storage, never contractions.
"""
import math
import re
from types import MappingProxyType

import numpy as np


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


class _FrozenDict(dict):
    def _readonly(self, *args, **kwargs):
        raise TypeError("Frozen trace record.")
    __setitem__ = __delitem__ = clear = pop = popitem = setdefault = update = __ior__ = _readonly


class _FrozenList(list):
    def _readonly(self, *args, **kwargs):
        raise TypeError("Frozen trace array.")
    __setitem__ = __delitem__ = append = clear = extend = insert = pop = remove = reverse = sort = __iadd__ = __imul__ = _readonly


def _freeze(value):
    if type(value) in (dict, _FrozenDict):
        return _FrozenDict({key: _freeze(child) for key, child in value.items()})
    if type(value) in (list, tuple, _FrozenList):
        return _FrozenList(_freeze(child) for child in value)
    if value is None or type(value) in (str, bool, int, float):
        if type(value) is float and not math.isfinite(value):
            raise TypeError("Trace values must be finite, plain JSON data.")
        return value
    raise TypeError("Copy typed arrays to plain arrays before tracing.")



DEFAULT_IV59 = _freeze(dict(
    token0=97, token1=97, positionScale=0.5,
    q1=1.0, k1=1.0, v1=1.0, o1=0.5, f1=0.5,
    q2=1.0, k2=0.5, v2=1.0, o2=0.25, f2=0.25,
    biasA=0.0, biasB=0.0, biasEOS=0.0))
_FIELDS = tuple(DEFAULT_IV59)
_GAIN_FIELDS = ("q", "k", "v", "o", "f")
_IDS = (97, 98, 512)


def _finite(value, name):
    if not math.isfinite(value):
        raise NumericalFault("NONFINITE", name + " must be finite.")
    return value


def _capture_record(value, fields, label):
    # Exact built-ins exclude custom reflection/getitem/accessor side effects.
    if type(value) not in (dict, _FrozenDict):
        raise NumericalFault("INVALID_INPUT", label + " must be a plain object.")
    keys = tuple(value)
    if len(keys) != len(fields) or any(type(key) is not str for key in keys) or set(keys) != set(fields):
        raise NumericalFault("INVALID_INPUT", label + " must have exactly " + ", ".join(fields) + " as own fields.")
    captured = {key: value[key] for key in fields}
    for key in fields:
        item = captured[key]
        if type(item) not in (int, float) or (type(item) is float and not math.isfinite(item)):
            raise NumericalFault("NONFINITE", label + "." + key + " must be an actual finite number.")
    return captured


def decoder_state(value):
    """Capture raw16 once; check every number before any domain or conversion."""
    captured = _capture_record(value, _FIELDS, "state")
    for key in _FIELDS:
        item = captured[key]
        if key in ("token0", "token1"):
            if item not in _IDS or (type(item) is float and not item.is_integer()):
                raise NumericalFault("INVALID_INPUT", key + " must be an integer token ID in {97,98,512}.")
        else:
            lower, upper = ((0, 1) if key == "positionScale" else
                            (-2, 2) if key.startswith("bias") else (-1, 1))
            if not lower <= item <= upper:
                raise NumericalFault("INVALID_INPUT", f"{key} must be between {lower} and {upper}.")
    return _freeze({key: int(captured[key]) if key in ("token0", "token1") else float(captured[key])
                    for key in _FIELDS})


def _block_inputs(features, gains, prefix):
    if type(features) not in (list, _FrozenList):
        raise NumericalFault("INVALID_INPUT", "features must be an ordinary dense array.")
    if len(features) not in (2, 4, 6):
        raise NumericalFault("INVALID_INPUT", "features must contain 2, 4 or 6 words for B=1,T=1..3,D=2.")
    captured = list(features)
    for i, item in enumerate(captured):
        if type(item) not in (int, float) or (type(item) is float and not math.isfinite(item)):
            raise NumericalFault("NONFINITE", f"features[{i}] must be an actual finite number.")
    for i, item in enumerate(captured):
        if not -16 <= item <= 16:
            raise NumericalFault("INVALID_INPUT", f"features[{i}] must be between -16 and 16.")
    captured_gains = _capture_record(gains, _GAIN_FIELDS, "gains")
    for key in _GAIN_FIELDS:
        if not -1 <= captured_gains[key] <= 1:
            raise NumericalFault("INVALID_INPUT", f"gains.{key} must be between -1 and 1.")
    _prefix(prefix)
    return [float(item) for item in captured], {key: float(captured_gains[key]) for key in _GAIN_FIELDS}


def _prefix(prefix):
    if type(prefix) is not str or re.fullmatch(r"[A-Za-z][A-Za-z0-9_]*", prefix) is None:
        raise NumericalFault("INVALID_INPUT", "prefix must start with an ASCII letter and contain only ASCII letters, digits or underscores.")


class _MechanismTrace:
    """Private captures; labels and schema are NOT the public adopted inventory."""
    def __init__(self):
        self.steps = []
        self.native = []
        self._ids = set()

    def add(self, identifier, inputs, outputs):
        if type(identifier) is not str or not identifier or identifier in self._ids:
            raise NumericalFault("INVALID_INPUT", "Trace IDs must be nonempty and unique.")
        before, after = dict(inputs), dict(outputs)
        for record in (before, after):
            for key, value in record.items():
                if type(key) is not str or type(value) not in (int, float):
                    raise NumericalFault("INVALID_INPUT", "Capture scalar data only.")
                _finite(value, identifier + "/" + key)
        if len(self.steps) >= 512:
            raise NumericalFault("UNSUPPORTED_SIZE", "At most 512 operations are supported.")
        self._ids.add(identifier)
        self.steps.append((identifier, MappingProxyType(before), MappingProxyType(after)))

    def leaf(self, identifier, kind, argument):
        _finite(argument, identifier + " argument")
        lower, upper = (0.25, 4096.0) if kind == "sqrt" else (-256.0, 0.0)
        if not lower <= argument <= upper:
            raise NumericalFault("INVALID_INPUT", "Native argument outside authored scope.")
        if any(record["id"] == identifier for record in self.native):
            raise NumericalFault("INVALID_INPUT", "Native capture ID must be unique.")
        output = _finite(math.sqrt(argument) if kind == "sqrt" else math.exp(argument), identifier)
        if output <= 0:
            raise NumericalFault("NONFINITE", "Native result must be positive.")
        self.native.append(MappingProxyType(dict(id=identifier, kind=kind, input=argument, output=output)))
        return output


def decoder_trace():
    """Create the adopted collector, with no implicit self-check."""
    return _PublicTrace()


def _norm(features, trace, prefix):
    result = []
    for t in range(len(features) // 2):
        x0, x1 = features[2 * t:2 * t + 2]
        total = _finite(x0 + x1, "feature sum")
        mean = _finite(total / 2.0, "feature mean")
        centered0, centered1 = _finite(x0 - mean, "centered0"), _finite(x1 - mean, "centered1")
        square0, square1 = _finite(centered0 * centered0, "square0"), _finite(centered1 * centered1, "square1")
        square_sum = _finite(square0 + square1, "square sum")
        variance = _finite(square_sum / 2.0, "population variance")
        argument = _finite(variance + 0.25, "variance plus epsilon")
        denominator = trace.leaf(f"{prefix}_{t}_sqrt", "sqrt", argument)
        trace.add(f"{prefix}_{t}_statistics", dict(x0=x0, x1=x1, epsilon=0.25),
                  dict(sum=total, mean=mean, centered0=centered0, centered1=centered1,
                       square0=square0, square1=square1, squareSum=square_sum,
                       variance=variance, variancePlusEpsilon=argument, denominator=denominator))
        for d, source in enumerate((centered0, centered1)):
            normalized = _finite(source / denominator, "normalized")
            scaled = _finite(1.0 * normalized, "gamma times normalized")
            value = _finite(scaled + 0.0, "plus beta")
            result.append(value)
            trace.add(f"{prefix}_{t}_feature_{d}", dict(source=source, denominator=denominator, gamma=1.0, beta=0.0),
                      dict(normalized=normalized, scaled=scaled, value=value))
    return result


def _two_products(features, weights, trace, prefix, bias=None, cols=2):
    result = []
    for t in range(len(features) // 2):
        x0, x1 = features[2 * t:2 * t + 2]
        for d in range(cols):
            w0, w1 = weights[d], weights[cols + d]
            product0, product1 = _finite(x0 * w0, "product0"), _finite(x1 * w1, "product1")
            total = _finite(product0 + product1, "two product sum")
            outputs = dict(product0=product0, product1=product1, sum=total)
            inputs = dict(x0=x0, x1=x1, w0=w0, w1=w1)
            value = total
            if bias is not None:
                inputs["bias"] = bias[d]
                value = _finite(total + bias[d], "bias last")
            outputs["value"] = value
            trace.add(f"{prefix}_{t}_{d}", inputs, outputs)
            result.append(value)
    return result


def _softmax(logits, allowed, trace, prefix, positive_zero=True):
    candidates = [value for value, keep in zip(logits, allowed) if keep]
    maximum = candidates[0]
    for value in candidates[1:]:
        # Match Math.max's +0 preference; the shifted native argument keeps sign.
        if value > maximum or (positive_zero and value == 0.0 and maximum == 0.0 and math.copysign(1.0, value) > 0.0):
            maximum = value
    terms = []
    shifted = {}
    denominator = 0.0
    running = []
    for j, (value, keep) in enumerate(zip(logits, allowed)):
        term = 0.0
        if keep:
            argument = _finite(value - maximum, "allowed shifted logit")
            shifted[f"shifted{j}"] = argument
            term = trace.leaf(f"{prefix}_exp_{j}", "exp", argument)
        terms.append(term)
    for term in terms:
        denominator = _finite(denominator + term, "softmax ordered denominator")
        running.append(denominator)
    probabilities = [_finite(term / denominator, "probability") for term in terms]
    inputs = {f"logit{j}": value for j, value in enumerate(logits)}
    inputs.update({f"allowed{j}": int(keep) for j, keep in enumerate(allowed)})
    outputs = dict(max=maximum, denominator=denominator, **shifted)
    outputs.update({f"term{j}": term for j, term in enumerate(terms)})
    outputs.update({f"p{j}": probability for j, probability in enumerate(probabilities)})
    outputs.update({f"running{j}": value for j, value in enumerate(running)})
    trace.add(prefix, inputs, outputs)
    return probabilities


def _accumulate_rows(features, width, weights, cols, trace, prefix, bias=None):
    result = []
    for t in range(len(features) // width):
        for d in range(cols):
            running = 0.0
            inputs, outputs = {}, {}
            for k in range(width):
                value, weight = features[t * width + k], weights[k * cols + d]
                inputs[f"x{k}"], inputs[f"w{k}"] = value, weight
                product = _finite(value * weight, "ordered product")
                running = _finite(running + product, "ordered running sum")
                outputs[f"product{k}"], outputs[f"running{k}"] = product, running
            value = running
            if bias is not None:
                inputs["bias"] = bias[d]
                value = _finite(running + bias[d], "output bias last")
            outputs["value"] = value
            trace.add(f"{prefix}_{t}_{d}", inputs, outputs)
            result.append(value)
    return result


def _residual(left, right, trace, prefix):
    result = []
    for i in range(len(left)):
        value = _finite(left[i] + right[i], "residual")
        trace.add(f"{prefix}_{i}", dict(left=left[i], right=right[i]), dict(value=value))
        result.append(value)
    return result


def _storage(values, rows, cols):
    """No numerical NumPy operation: store already computed Python scalars."""
    stored = np.empty((1, rows, cols), dtype=np.float64)
    for t in range(rows):
        for d in range(cols):
            stored[0, t, d] = values[t * cols + d]
    return stored


def _decoder_block_mechanics(features, gains, trace, prefix):
    """Original independent scalar graph; public metadata is a copy projection."""
    count = len(features) // 2
    norm1 = _norm(features, trace, prefix + "_ln1")
    matrices = {key: [gains[key], 0.0, 0.0, gains[key]] for key in ("q", "k", "v", "o")}
    q = _two_products(norm1, matrices["q"], trace, prefix + "_Q")
    k = _two_products(norm1, matrices["k"], trace, prefix + "_K")
    v = _two_products(norm1, matrices["v"], trace, prefix + "_V")
    # H=1 split is still an actual copy with an explicit coordinate capture.
    heads = []
    for label, source in (("Q", q), ("K", k), ("V", v)):
        copied = []
        for i, value in enumerate(source):
            copied.append(value)
            trace.add(f"{prefix}_{label}_split_{i}", dict(source=value), dict(value=value))
        heads.append(copied)
    q, k, v = heads
    divisor = trace.leaf(prefix + "_attention_sqrt", "sqrt", 2.0)
    raw, scores, logits, allowed = [], [], [], []
    for i in range(count):
        for j in range(count):
            product0 = _finite(q[2 * i] * k[2 * j], "score product0")
            product1 = _finite(q[2 * i + 1] * k[2 * j + 1], "score product1")
            dot = _finite(product0 + product1, "raw score")
            score = _finite(dot / divisor, "scaled score")
            raw.append(dot)
            scores.append(score)
            trace.add(f"{prefix}_score_{i}_{j}", dict(q0=q[2*i], q1=q[2*i+1], k0=k[2*j], k1=k[2*j+1], divisor=divisor),
                      dict(product0=product0, product1=product1, raw=dot, score=score))
    probabilities = []
    for i in range(count):
        row, mask = [], []
        for j in range(count):
            row.append(_finite(scores[i * count + j] + 0.0, "score plus zero common shift"))
            mask.append(j <= i)
        logits.extend(row)
        allowed.extend(mask)
        probabilities.extend(_softmax(row, mask, trace, f"{prefix}_attention_row_{i}"))
    mixed = []
    for i in range(count):
        for d in range(2):
            running = 0.0
            inputs, outputs = {}, {}
            for j in range(count):
                probability, value = probabilities[i * count + j], v[2 * j + d]
                inputs[f"p{j}"], inputs[f"v{j}"] = probability, value
                product = _finite(probability * value, "including forbidden zero product")
                running = _finite(running + product, "attention running sum")
                outputs[f"product{j}"], outputs[f"running{j}"] = product, running
            outputs["value"] = running
            trace.add(f"{prefix}_mix_{i}_{d}", inputs, outputs)
            mixed.append(running)
    joined = []
    for i, value in enumerate(mixed):
        joined.append(value)
        trace.add(f"{prefix}_join_{i}", dict(source=value), dict(value=value))
    attention = _accumulate_rows(joined, 2, matrices["o"], 2, trace, prefix + "_WO")
    residual1 = _residual(features, attention, trace, prefix + "_residual1")
    norm2 = _norm(residual1, trace, prefix + "_ln2")
    w1, w2 = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0], [gains["f"], 0.0, 0.0, gains["f"], 0.0, 0.0]
    preactivation = _two_products(norm2, w1, trace, prefix + "_ffn_hidden", [0.0, 0.0, 0.0], 3)
    hidden = []
    for i, value in enumerate(preactivation):
        activation = value if value > 0.0 else 0.0
        hidden.append(activation)
        trace.add(f"{prefix}_relu_{i}", dict(preactivation=value), dict(activation=activation))
    ffn = _accumulate_rows(hidden, 3, w2, 2, trace, prefix + "_ffn_output", [0.0, 0.0])
    output = _residual(residual1, ffn, trace, prefix + "_residual2")
    return dict(input=list(features), norm1=norm1, matrices=matrices, Q=q, K=k, V=v,
                raw=raw, scores=scores, logits=logits, allowed=allowed, probabilities=probabilities,
                mixed=mixed, joined=joined, attention=attention, residual1=residual1,
                norm2=norm2, W1=w1, W2=w2, b1=[0.0]*3, b2=[0.0]*2,
                preactivation=preactivation, hidden=hidden, ffn=ffn, output=output,
                storage=_storage(output, count, 2))


def _evaluate_decoder_mechanics(state, trace, prefix):
    features, embedding, positions = [], [], []
    table = {97: (1.0, 0.0), 98: (0.0, 1.0), 512: (0.0, 0.0)}
    for t in range(2):
        token = state[f"token{t}"]
        for d in range(2):
            looked_up = table[token][d]
            position = state["positionScale"] if (t, d) == (1, 1) else 0.0
            value = _finite(looked_up + position, "embedding plus position")
            embedding.append(looked_up)
            positions.append(position)
            features.append(value)
            trace.add(f"{prefix}_position_{t}_{d}", dict(token=token, embedding=looked_up, position=position), dict(value=value))
    block1 = _decoder_block_mechanics(features, {key: state[key + "1"] for key in _GAIN_FIELDS}, trace, prefix + "_block1")
    block2 = _decoder_block_mechanics(block1["output"], {key: state[key + "2"] for key in _GAIN_FIELDS}, trace, prefix + "_block2")
    readout = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0]
    bias = [state["biasA"], state["biasB"], state["biasEOS"]]
    logits = _two_products(block2["output"], readout, trace, prefix + "_readout", bias, 3)
    probabilities, winners = [], []
    for t in range(2):
        row = logits[3*t:3*t+3]
        distribution = _softmax(row, [True, True, True], trace, f"{prefix}_class_row_{t}", positive_zero=False)
        probabilities.extend(distribution)
        best = 0
        for index in range(1, 3):
            if row[index] > row[best]:
                best = index
        winner = dict(index=best, token=_IDS[best], probability=distribution[best])
        winners.append(winner)
        trace.add(f"{prefix}_winner_{t}", {f"logit{j}": row[j] for j in range(3)}, winner)
    return dict(embedding=embedding, positions=positions, features=features, block1=block1, block2=block2,
                U=readout, bias=bias, logits=logits, probabilities=probabilities,
                winners=winners, next=winners[-1].copy(), storage=_storage(logits, 2, 3))


def check_mechanism():
    """Explicit bounded FIRST checks only; these do NOT admit public records."""
    if not __debug__:
        raise RuntimeError("Explicit mechanism self-check refuses optimized Python (-O).")
    import struct

    def words(values):
        return [struct.pack(">d", value) for value in values]

    default = decoder_state(dict(DEFAULT_IV59))
    trace = _MechanismTrace()
    result = _evaluate_decoder_mechanics(default, trace, "default")
    assert result["features"] == [1.0, 0.0, 1.0, 0.5]
    assert words(result["block2"]["input"]) == words(result["block1"]["output"])
    assert words(result["block1"]["storage"][0].flat) == words(result["block1"]["output"])
    assert result["block1"]["input"] != result["block2"]["input"]
    assert [winner["token"] for winner in result["winners"]] == [97, 97]
    assert result["next"] == result["winners"][-1] and result["next"] is not result["winners"][-1]
    assert result["block1"]["W1"] == [1.0, 0.0, 0.0, 0.0, 1.0, 0.0]
    assert result["block1"]["W2"] == [0.5, 0.0, 0.0, 0.5, 0.0, 0.0]
    assert result["block2"]["W2"] == [0.25, 0.0, 0.0, 0.25, 0.0, 0.0]
    for block in (result["block1"], result["block2"]):
        assert block["allowed"] == [True, False, True, True]
        assert words(block["probabilities"][:2]) == words([1.0, 0.0])
        assert len(block["raw"]) == 4 and len(block["preactivation"]) == 6
        assert words(block["preactivation"][2::3]) == words([0.0, 0.0])
        assert words(block["hidden"][2::3]) == words([0.0, 0.0])
    frames = {identifier: (inputs, outputs) for identifier, inputs, outputs in trace.steps}
    first = frames["default_block1_ln1_0_statistics"][1]
    assert first["sum"] == 1.0 and first["mean"] == 0.5
    assert first["centered0"] == 0.5 and first["centered1"] == -0.5
    assert first["variancePlusEpsilon"] == 0.5
    second = frames["default_block1_ln1_1_statistics"][1]
    assert second["sum"] == 1.5 and second["mean"] == 0.75
    assert second["centered0"] == 0.25 and second["centered1"] == -0.25
    assert second["variancePlusEpsilon"] == 0.3125
    assert frames["default_block1_mix_0_0"][1]["product1"] == 0.0
    native_ids = [leaf["id"] for leaf in trace.native]
    assert len(set(native_ids)) == len(native_ids)
    for leaf in trace.native:
        if leaf["kind"] == "sqrt":
            assert 0.25 <= leaf["input"] <= 4096.0
            expected = math.sqrt(leaf["input"])
        else:
            assert -256.0 <= leaf["input"] <= 0.0
            expected = math.exp(leaf["input"])
        assert words([leaf["output"]]) == words([expected])
    for layer in (1, 2):
        leaf = next(item for item in trace.native if item["id"] == f"default_block{layer}_attention_sqrt")
        for i in range(2):
            for j in range(2):
                copied = frames[f"default_block{layer}_score_{i}_{j}"][0]["divisor"]
                assert words([copied]) == words([leaf["output"]])

    zero = dict(default, o1=0.0, f1=0.0, o2=0.0, f2=0.0)
    zero_trace = _MechanismTrace()
    identity = _evaluate_decoder_mechanics(zero, zero_trace, "zero")
    for key in ("block1", "block2"):
        assert words(identity[key]["output"]) == words([1.0, 0.0, 1.0, 0.5])
        assert len(identity[key]["hidden"]) == 6
    assert words(identity["logits"]) == words([1.0, 0.0, 0.0, 1.0, 0.5, 0.0])
    for t, arguments in enumerate(((0.0, -1.0, -1.0), (0.0, -0.5, -1.0))):
        terms = [math.exp(argument) for argument in arguments]
        denominator = ((0.0 + terms[0]) + terms[1]) + terms[2]
        expected = [term / denominator for term in terms]
        assert words(identity["probabilities"][3*t:3*t+3]) == words(expected)
    assert len(zero_trace.native) == len(trace.native)
    assert len(zero_trace.steps) == len(trace.steps)

    # A changed future token cannot change any first-row result in either block.
    future_trace = _MechanismTrace()
    future = _evaluate_decoder_mechanics(dict(default, token1=98), future_trace, "future")
    assert words(future["logits"][:3]) == words(result["logits"][:3])
    assert words(future["block2"]["output"][:2]) == words(result["block2"]["output"][:2])
    tied = _evaluate_decoder_mechanics(dict(zero, token0=512, token1=512, positionScale=0.0), _MechanismTrace(), "tie")
    assert words(tied["logits"]) == words([0.0] * 6)
    assert [winner["index"] for winner in tied["winners"]] == [0, 0]
    assert [winner["token"] for winner in tied["winners"]] == [97, 97]
    for length in (2, 4, 6):
        features = [16.0, -16.0] * (length // 2)
        gains = dict(q=-1.0, k=1.0, v=-1.0, o=0.0, f=0.0)
        captured, checked_gains = _block_inputs(features, gains, "bounded")
        block = _decoder_block_mechanics(captured, checked_gains, _MechanismTrace(), "bounded")
        assert words(block["output"]) == words(features)
        assert len(block["hidden"]) == (length // 2) * 3
    captured, gains = _block_inputs([-0.0, 0.0], dict(q=-0.0, k=1, v=1, o=0, f=0), "signed")
    assert words([captured[0], gains["q"]]) == words([-0.0, -0.0])
    detached = _MechanismTrace()
    before, after = dict(x=-0.0), dict(y=1.0)
    detached.add("capture", before, after)
    before["x"], after["y"] = 8.0, 9.0
    assert words([detached.steps[0][1]["x"]]) == words([-0.0])
    assert detached.steps[0][2]["y"] == 1.0

    signed_trace = _MechanismTrace()
    _softmax([-0.0, 0.0, -1.0], [True, True, True], signed_trace, "signed_max")
    assert words([signed_trace.steps[0][2]["max"]]) == words([0.0])
    assert words([signed_trace.native[0]["input"]]) == words([-0.0])
    assert words([signed_trace.native[1]["input"]]) == words([0.0])


# Public binding projects the independent FIRST captures; it never recomputes floats.

def _numeric(value, label):
    if type(value) is int:
        # Compare before conversion: huge Python integers must not raise OverflowError.
        if not -1.7976931348623157e308 <= value <= 1.7976931348623157e308:
            raise NumericalFault("NONFINITE", label + " must be an actual finite number.")
        return value if -9007199254740991 <= value <= 9007199254740991 else float(value)
    if type(value) is not float or not math.isfinite(value):
        raise NumericalFault("NONFINITE", label + " must be an actual finite number.")
    return value


def _trace_entries(value):
    """Capture trusted items once, then use JavaScript's canonical-index order."""
    if type(value) in (list, str):
        entries = [(str(index), item) for index, item in enumerate(value)]
    elif type(value) in (int, float, bool):
        entries = []
    else:
        entries = list(value.items())  # Preserve trusted observers and their exception identity.
    indices, rest = [], []
    for key, item in entries:
        if type(key) is not str:
            raise TypeError("Trusted trace operand keys must be strings.")
        index = (bool(key) and len(key) <= 10 and all(c in "0123456789" for c in key)
                 and (key == "0" or key[0] != "0") and int(key) < 4294967295)
        (indices if index else rest).append((key, item))
    return sorted(indices, key=lambda pair: int(pair[0])) + rest


class _PublicTrace:
    """Frozen observer container, mutable collector, immutable saved frames."""
    __slots__ = ("outputs", "steps", "_ids")

    def __init__(self):
        object.__setattr__(self, "outputs", {})
        object.__setattr__(self, "steps", [])
        object.__setattr__(self, "_ids", set())

    def __setattr__(self, name, value):
        raise TypeError("Frozen trace observer.")

    def __delattr__(self, name):
        raise TypeError("Frozen trace observer.")

    def add(self, identifier, label, equation, explanation, inputs, outputs):
        if type(identifier) is not str or not identifier or identifier in self._ids:
            raise NumericalFault("INVALID_INPUT", "Trace IDs must be nonempty and unique.")
        before = {key: _numeric(value, identifier + ".inputs." + key) for key, value in _trace_entries(inputs)}
        after = {key: _numeric(value, identifier + ".outputs." + key) for key, value in _trace_entries(outputs)}
        if len(self.steps) >= 512:
            raise NumericalFault("UNSUPPORTED_SIZE", "At most 512 operations are supported.")
        frame = _freeze(dict(id=identifier, label=label, equation=equation, explanation=explanation,
                             inputs=before, outputs=after))
        self.steps.append(frame)
        self._ids.add(identifier)
        for key, value in after.items():
            alias = identifier + "_" + key
            # The actual ordinary JS object ignores numeric assignments to its inherited setter.
            if alias != "__proto__":
                self.outputs[alias] = value


_STAT_FIELDS = ("sum", "mean", "centered0", "centered1", "square0", "square1", "squareSum",
                "variance", "variancePlusEpsilon", "denominator")


def _tensor(identifier, shape, axes, values, provenance, dtype="float64"):
    return dict(id=identifier, shape=list(shape), axes=list(axes), dtype=dtype, values=list(values),
                provenance=provenance, precision=0 if dtype == "int32" else 8)


def _native_tensors(prefix, natives):
    return [
        _tensor(prefix + "_NativeArguments", [len(natives), 2], ["Native", "NativeField"],
                [value for leaf in natives for value in (leaf["input"], leaf["output"])],
                "Ordered actual native input,output words; IDs and kinds are recorded in texts.nativeIds and texts.nativeKinds. No native evaluation occurs while serializing."),
        _tensor(prefix + "_NativeKinds", [len(natives)], ["Native"],
                [0 if leaf["kind"] == "sqrt" else 1 for leaf in natives],
                "Native kind codes in native occurrence order: sqrt=0, exp=1.", "int32"),
    ]


def _native_texts(natives):
    return dict(nativeIds=[leaf["id"] for leaf in natives], nativeKinds=[leaf["kind"] for leaf in natives],
                nativeFields=["input", "output"])


def _norm_binding(mechanism, captures, trace, prefix, stage):
    T = len(mechanism["input"]) // 2
    private = prefix + ("_ln1" if stage == 1 else "_ln2")
    public = prefix + f"_n{stage}"
    statistics, centered, normalized = [], [], []
    for t in range(T):
        before, after = captures[f"{private}_{t}_statistics"]
        trace.add(f"{public}_0_{t}_statistics", f"0_{t}: feature-only mean and population variance",
                  "sum=x0+x1; mean=sum/2; centered=x-mean; squareSum=centered0²+centered1²; variance=squareSum/2; denominator=sqrt(variance+epsilon)",
                  "Only these two features contribute. Epsilon is inside the square root; no batch or token statistics are mixed.",
                  dict(before), dict(after))
        statistics.extend(after[key] for key in _STAT_FIELDS)
        centered.extend((after["centered0"], after["centered1"]))
        for d in range(2):
            before, after = captures[f"{private}_{t}_feature_{d}"]
            trace.add(f"{public}_0_{t}_feature_{d}", f"0_{t}: affine feature {d}",
                      "normalized=source/denominator; scaled=gamma*normalized; value=scaled+beta",
                      "The source is the saved centered feature. Gamma and beta may change output mean and variance.",
                      dict(d=d, **before), dict(after))
            normalized.append(after["normalized"])
    shape, axes = [1, T, 2], ["B", "T", "D"]
    return [
        _tensor(public + "_Gamma", [2], ["D"], [1.0, 1.0], "Shared literal feature scales [1,1]."),
        _tensor(public + "_Beta", [2], ["D"], [0.0, 0.0], "Shared literal feature offsets [+0,+0]."),
        _tensor(public + "_Statistics", [1, T, 10], ["B", "T", "NormStatistic"], statistics,
                "Actual sum,mean,centered0,centered1,square0,square1,squareSum,variance,variancePlusEpsilon,denominator in token order."),
        _tensor(public + "_Centered", shape, axes, centered, "Actual saved input feature minus feature mean, before division."),
        _tensor(public + "_Normalized", shape, axes, normalized, "Actual centered/denominator words before gamma multiplication and beta addition."),
        _tensor(public + "_Output", shape, axes, mechanism[f"norm{stage}"], "Actual per-position feature LayerNorm affine output; gamma=[1,1], beta=[0,0], epsilon=1/4."),
    ]


def _block_natives(captured, prefix, T):
    names = {f"{prefix}_ln1_{t}_sqrt": f"{prefix}_n1_0_{t}_sqrt" for t in range(T)}
    names[prefix + "_attention_sqrt"] = prefix + "_attn_sqrt"
    for i in range(T):
        for j in range(i + 1):
            names[f"{prefix}_attention_row_{i}_exp_{j}"] = f"{prefix}_attn_exp_0_0_{i}_{j}"
    names.update({f"{prefix}_ln2_{t}_sqrt": f"{prefix}_n2_0_{t}_sqrt" for t in range(T)})
    return [dict(id=names[leaf["id"]], kind=leaf["kind"], input=leaf["input"], output=leaf["output"])
            for leaf in captured]


def _residual_binding(mechanism, captures, trace, prefix, stage, left_id, right_id):
    T = len(mechanism["input"]) // 2
    identifier = prefix + ("_R1" if stage == 1 else "_Output")
    for t in range(T):
        for d in range(2):
            before, after = captures[f"{prefix}_residual{stage}_{2*t+d}"]
            trace.add(f"{prefix}_r{stage}_0_{t}_{d}", f"{identifier}[0,{t},{d}]: skip plus branch", "value=skip+branch",
                      "The unchanged same-shape primitive performs this actual feature addition. Both residuals are always on; no broadcasting or zero-gain bypass occurs.",
                      dict(b=0, t=t, d=d, skip=before["left"], branch=before["right"]), dict(after))
    return _tensor(identifier, [1, T, 2], ["B", "T", "D"],
                   mechanism["residual1" if stage == 1 else "output"],
                   f"Exact named-shape addition of {left_id} and {right_id}; no broadcasting.")


def _bind_block(features, gains, mechanism, captured, trace, prefix):
    T = len(features) // 2
    captures = {identifier: (before, after) for identifier, before, after in captured.steps}
    natives = _block_natives(captured.native, prefix, T)
    tensors = [
        _tensor(prefix + "_Features", [1, T, 2], ["B", "T", "D"], features,
                "Actual captured per-position block features; repeated token IDs do not merge positions."),
        _tensor(prefix + "_Gains", [5], ["Gain"], [gains[key] for key in _GAIN_FIELDS],
                "Actual q,k,v,o,f gain words; diagonal slots copy these words and off-diagonal slots are literal +0."),
    ]
    tensors.extend(_norm_binding(mechanism, captures, trace, prefix, 1))
    a = prefix + "_attn"
    setup = dict(B=1, T=T, H=1, Dk=2, Dv=2)
    for name in ("x000", "x001", "x010", "x011", "x020", "x021", "x100", "x101", "x110", "x111", "x120", "x121"):
        setup[name] = 0.0
    for kind in ("q", "k", "v"):
        for name in ("000", "001", "010", "011", "100", "101", "110", "111"):
            setup["w" + kind + name] = gains[kind] if name in ("000", "101") else 0.0
    setup.update(mode=1, valid0=1, valid1=1, valid2=1, shift=0.0)
    for name in ("000", "001", "010", "011", "100", "101", "110", "111"):
        setup["wo" + name] = gains["o"] if name in ("000", "011") else 0.0
    for t in range(T):
        for d in range(2):
            setup[f"x0{t}{d}"] = mechanism["norm1"][2*t+d]
    trace.add(a + "_setup", "Validate every scalar slot, then select active dimensions",
              "D=2; X[B,T,2]; WQ,WK[2,H*Dk]; WV[2,H*Dv]",
              "All inactive fields remain finite and bounded. Parameter names identify input d, head h and feature f, so changing width never relabels a head’s weights.",
              setup, dict(B=1, T=T, D=2, H=1, Dk=2, Dv=2))
    for kind in ("Q", "K", "V"):
        for t in range(T):
            for f in range(2):
                before, after = captures[f"{prefix}_{kind}_{t}_{f}"]
                trace.add(f"{a}_project_{kind}_0_{t}_0_{f}", f"{kind}[0,{t},head 0,feature {f}]: both input contributions",
                          "product0=x0*w0; product1=x1*w1; value=product0+product1",
                          "One token row times the packed column h*F+f, keeping both input-feature rows. Weights are hand-set; no bias, activation or learning is hidden.",
                          dict(b=0, t=t, h=0, f=f, **before),
                          dict(product0=after["product0"], product1=after["product1"], value=after["value"]))
    for kind in ("Q", "K", "V"):
        trace.add(f"{a}_reshape_{kind}", f"{kind}: reshape the packed feature axis",
                  "[B,T,H*F] → [B,T,H,F]; feature=h*F+f",
                  "Reshaping preserves every flat value and its order. H counts attention heads; F counts features within each head. No projection feature is dropped.",
                  dict(B=1, T=T, H=1, F=2, features=2, elements=2*T), dict(elements=2*T))
        for t in range(T):
            for f in range(2):
                before, after = captures[f"{prefix}_{kind}_split_{2*t+f}"]
                trace.add(f"{a}_permute_{kind}_0_0_{t}_{f}", f"{kind}: copy [0,{t},0,{f}] to [0,0,{t},{f}]",
                          "axes [0,2,1,3]; destination[b,h,t,f]=source[b,t,h,f]",
                          "Moving the head axis is a declared permutation, separate from reshape. The recorded offsets are actual row-major flat indices; this indexed value is copied unchanged.",
                          dict(b=0, h=0, t=t, f=f, feature=f, sourceOffset=2*t+f, destinationOffset=2*t+f, sourceValue=before["source"]), dict(after))
    for i in range(T):
        for j in range(T):
            before, after = captures[f"{prefix}_score_{i}_{j}"]
            trace.add(f"{a}_score_0_0_{i}_{j}", f"Batch 0, head 0: query {i} against key {j}",
                      "product0=q0*k0; product1=q1*k1; raw=product0+product1; score=raw/sqrt(Dk)",
                      "Matching features are multiplied inside this batch and head only. Dk, not H or T or Dv, supplies the scaling width. Signed scores are not probabilities.",
                      dict(b=0, h=0, i=i, j=j, Dk=2, divisor=before["divisor"], q0=before["q0"], k0=before["k0"], q1=before["q1"], k1=before["k1"]), dict(after))
    for i in range(T):
        before, after = captures[f"{prefix}_attention_row_{i}"]
        inputs = dict(b=0, h=0, i=i, mode=1, shift=0.0)
        inputs.update({f"score{j}": mechanism["scores"][i*T+j] for j in range(T)})
        inputs.update({f"allowed{j}": before[f"allowed{j}"] for j in range(T)})
        outputs = dict(max=after["max"], denominator=after["denominator"])
        outputs.update({f"shifted{j}": after[f"shifted{j}"] for j in range(i+1)})
        outputs.update({f"term{j}": after[f"term{j}"] for j in range(T)})
        outputs.update({f"p{j}": after[f"p{j}"] for j in range(T)})
        trace.add(f"{a}_row_0_0_{i}", f"Batch 0, head 0, query {i}: key-axis stable softmax",
                  "logit_j=score_j+shift; max=max(allowed logits); term_j=allowed_j?exp(logit_j-max):0; denominator=sum_j term_j; p_j=term_j/denominator",
                  "Each head has its own probabilities. Key validity is shared across batches and heads; queries remain. Forbidden terms are exactly zero, without an infinity sentinel or invented shifted value. Allowed terms can underflow; a large common shift can change low bits.", inputs, outputs)
    for i in range(T):
        for f in range(2):
            before, after = captures[f"{prefix}_mix_{i}_{f}"]
            outputs = {f"product{j}": after[f"product{j}"] for j in range(T)}
            outputs.update({f"running{j}": after[f"running{j}"] for j in range(T)})
            outputs["value"] = after["value"]
            trace.add(f"{a}_head_mix_0_0_{i}_{f}", f"OHeads[0,0,{i},{f}]: this head’s weighted values",
                      "product_j=p_j*v_j; running starts at 0; running_j=previous+product_j; value=last running sum",
                      "Use the real probability row and values in the same head and batch. Compute each product, then immediately accumulate in ascending key order, including actual zero times V for forbidden keys. No averaging across heads or extra division.",
                      dict(b=0, h=0, i=i, f=f, **before), outputs)
    for t in range(T):
        for f in range(2):
            before, after = captures[f"{prefix}_join_{2*t+f}"]
            trace.add(f"{a}_concat_0_{t}_0_{f}", f"Join head 0, feature {f} into C[0,{t},{f}]", "C[b,t,h*Dv+f]=OHeads[b,h,t,f]",
                      "Copy one actual head output unchanged. Concatenate in head order then within-head feature order; never average heads or mix batches.",
                      dict(b=0, t=t, h=0, f=f, concatFeature=f, sourceOffset=2*t+f, destinationOffset=2*t+f, sourceValue=before["source"]), dict(after))
    for t in range(T):
        for d in range(2):
            before, after = captures[f"{prefix}_WO_{t}_{d}"]
            inputs = dict(b=0, t=t, d=d, c0=before["x0"], w0=before["w0"], c1=before["x1"], w1=before["w1"])
            outputs = {key: after[key] for key in ("product0", "product1", "running0", "running1", "value")}
            trace.add(f"{a}_output_0_{t}_{d}", f"Y[0,{t},{d}]: explicit output projection",
                      "product_c=C_c*WO[c,d]; running starts at 0; running_c=previous+product_c; Y=last running sum",
                      "WO rows preserve named head/feature identity when Dv changes. Every joined feature contributes one recorded product and running sum. Y may be signed; no output softmax, bias, residual, dropout or normalization is added.", inputs, outputs)
    tensors.extend(_attention_tensors(mechanism, a, T))
    tensors.append(_residual_binding(mechanism, captures, trace, prefix, 1, prefix + "_Features", a + "_Y"))
    tensors.extend(_norm_binding(mechanism, captures, trace, prefix, 2))
    tensors.extend(_ffn_binding(mechanism, captures, trace, prefix, T))
    output = _residual_binding(mechanism, captures, trace, prefix, 2, prefix + "_R1", prefix + "_ffn_F")
    tensors.extend([output, *_native_tensors(prefix, natives)])
    texts = dict(**_native_texts(natives), gainFields=list(_GAIN_FIELDS), normStatisticFields=list(_STAT_FIELDS),
        featurePolicy="One batch, one to three positions, two features per position. Block output keeps B,T,D axes and feeds the next block directly; it is never a token lookup.",
        kernelPolicy="Unchanged p07 featureNorm, p06 projectHeads/attendHeads/joinHeads, p07 feedForward and sameShapeAdd perform all scalar arithmetic. All inactive attention state slots are explicit +0 except validity=1; active dimensions are B1,H1,Dk2,Dv2,mode1,shift+0. Every matrix coordinate and all three FFN hidden coordinates are computed at every gain.",
        nativePolicy="Occurrence order is LN1 sqrt by token, one sqrt(Dk), allowed attention exp by query/key, then LN2 sqrt by token. LN arguments/outputs and attention divisor/terms copy actual primitive records. Old stableSoftmax trace shifted values repeat the same subtraction of immutable logit and max operands as its exp arguments: functional reconstruction, not a physical instruction trace. Masked cells have no exp occurrence. No native math occurs in serialization.",
        zeroPolicy="Feature words, gain words, arithmetic results and every copy retain binary64 WORD, including allowed -0. Diagonal weights copy gains; every off-diagonal or inactive weight is literal +0. Dimensions, indices, mask decisions and native kind codes use VALUE.",
        limitsPolicy="Forward-only authored toy. No differentiated loss, training, optimizer, dropout, sampling, KV cache, physical timing or production-model claim. Public input features are bounded [-16,16], gains [-1,1]; epsilon=1/4, gamma=[1,1], beta=[0,0], width-three ReLU FFN.")
    return _freeze(dict(features=features, gains=gains, output=output, natives=natives, tensors=tensors, texts=texts))


def _attention_tensors(m, prefix, T):
    shape, axes = [1, T, 2], ["B", "T", "D"]
    result = [_tensor(prefix + "_X", shape, axes, m["norm1"], "Active token rows; D=2 input features always retained.")]
    for kind, feature, provenance in (
        ("Q", "QueryFeature", "Query columns packed by h*Dk+f from wq{d}{h}{f}."),
        ("K", "KeyFeature", "Key columns packed by h*Dk+f from wk{d}{h}{f}."),
        ("V", "ValueFeature", "Value columns packed by h*Dv+f from wv{d}{h}{f}.")):
        result.append(_tensor(prefix + "_W" + kind, [2, 2], ["D", feature], m["matrices"][kind.lower()], provenance))
    for kind, feature, provenance in (
        ("Q", "QueryFeature", "XWQ; each packed coordinate has two products and one sum."),
        ("K", "KeyFeature", "XWK; each packed coordinate has two products and one sum."),
        ("V", "ValueFeature", "XWV; values are projected separately from queries and keys.")):
        result.append(_tensor(prefix + "_" + kind + "Concat", shape, ["B", "T", feature], m[kind], provenance))
    for kind in ("Q", "K", "V"):
        width = "Dv" if kind == "V" else "Dk"
        result.extend([
            _tensor(prefix + "_" + kind + "Split", [1, T, 1, 2], ["B", "T", "H", width], m[kind],
                    kind + "Concat reshaped without changing flat order; feature=h*F+f."),
            _tensor(prefix + "_" + kind + "Heads", [1, 1, T, 2], ["B", "H", "T", width], m[kind],
                    kind + "Split permuted by axes [0,2,1,3]; every copied source/destination offset is traced."),
        ])
    shape, axes = [1, 1, T, T], ["B", "H", "Query", "Key"]
    for key, provenance, dtype in (
        ("raw", "Separate QHeads KHeads transpose products within every batch and head.", "float64"),
        ("scores", "raw/sqrt(Dk); the two-product order matches IV25 for H1,Dk2.", "float64"),
        ("allowed", "Causal and/or valid-key mask; shared validity across B and H; every query retained.", "bool"),
        ("logits", "Finite score+shift, including forbidden cells; mask applied separately.", "float64"),
        ("probabilities", "Stable allowed-key softmax for each B/H/query independently; forbidden probabilities exactly zero.", "float64")):
        result.append(_tensor(prefix + "_" + key, shape, axes, m[key], provenance, dtype))
    result.extend([
        _tensor(prefix + "_OHeads", [1, 1, T, 2], ["B", "H", "Query", "Dv"], m["mixed"], "Actual per-head P times VHeads; every product and running sum is traced."),
        _tensor(prefix + "_C", [1, T, 2], ["B", "T", "JoinedValue"], m["joined"], "OHeads permuted to token-major order then joined by c=h*Dv+f; values unchanged."),
        _tensor(prefix + "_WO", [2, 2], ["JoinedValue", "D"], m["matrices"]["o"], "wo{h}{f}{d} packed in h,f,d order, preserving parameter identity."),
        _tensor(prefix + "_Y", [1, T, 2], ["B", "T", "D"], m["attention"], "Y=C WO, summing products in ascending joined-feature order from zero; no normalization."),
    ])
    return result


def _ffn_binding(m, captures, trace, prefix, T):
    f = prefix + "_ffn"
    for t in range(T):
        for hidden in range(3):
            before, after = captures[f"{prefix}_ffn_hidden_{t}_{hidden}"]
            trace.add(f"{f}_hidden_0_{t}_{hidden}", f"Hidden affine [0,{t},{hidden}]",
                      "product0=x0*w0; product1=x1*w1; sum=product0+product1; preactivation=sum+bias",
                      "The same W1 and b1 apply separately to each token. Add bias after the two input products; no token sum occurs.",
                      dict(b=0, t=t, m=hidden, **before),
                      dict(product0=after["product0"], product1=after["product1"], sum=after["sum"], preactivation=after["value"]))
    for t in range(T):
        for hidden in range(3):
            before, after = captures[f"{prefix}_relu_{3*t+hidden}"]
            trace.add(f"{f}_relu_0_{t}_{hidden}", f"ReLU [0,{t},{hidden}]", "activation=max(0,preactivation)",
                      "ReLU means rectified linear unit: keep a positive value and replace a nonpositive value with zero, including zero itself.",
                      dict(b=0, t=t, m=hidden, **before), dict(after))
    for t in range(T):
        for d in range(2):
            before, after = captures[f"{prefix}_ffn_output_{t}_{d}"]
            inputs = dict(b=0, t=t, d=d)
            for hidden in range(3):
                inputs[f"h{hidden}"] = before[f"x{hidden}"]
                inputs[f"w{hidden}"] = before[f"w{hidden}"]
            inputs["bias"] = before["bias"]
            outputs = {f"product{hidden}": after[f"product{hidden}"] for hidden in range(3)}
            outputs.update({f"running{hidden}": after[f"running{hidden}"] for hidden in range(3)})
            outputs.update(sum=after["running2"], value=after["value"])
            trace.add(f"{f}_output_0_{t}_{d}", f"FFN output [0,{t},{d}]",
                      "product_m=h_m*w_m; running starts at 0; running_m=previous+product_m; sum=running2; value=sum+bias",
                      "Multiply then immediately accumulate hidden features in ascending order 0,1,2. Add b2 last. Output may be signed; there is no softmax or residual inside the FFN.", inputs, outputs)
    return [
        _tensor(f + "_W1", [2, 3], ["D", "HiddenFeature"], m["W1"], "Shared input-to-hidden weights, f1{d}{m}; M=3 hidden features."),
        _tensor(f + "_b1", [3], ["HiddenFeature"], m["b1"], "Shared hidden bias, added after the two products."),
        _tensor(f + "_Z", [1, T, 3], ["B", "T", "HiddenFeature"], m["preactivation"], "Hidden preactivations X W1+b1; no batch or token mixing."),
        _tensor(f + "_Hidden", [1, T, 3], ["B", "T", "HiddenFeature"], m["hidden"], "ReLU(Z)=max(0,Z), before the second affine layer."),
        _tensor(f + "_W2", [3, 2], ["HiddenFeature", "D"], m["W2"], "Shared hidden-to-output weights, f2{m}{d}."),
        _tensor(f + "_b2", [2], ["D"], m["b2"], "Shared output bias, added after all three running sums."),
        _tensor(f + "_F", [1, T, 2], ["B", "T", "D"], m["ffn"], "ReLU(X W1+b1) W2+b2, independently per token with shared parameters."),
    ]


def decoder_block(features, gains, trace, prefix):
    """Adopted helper, scalar FIRST plus complete metadata/copy projection."""
    features, gains = _block_inputs(features, gains, prefix)
    captured = _MechanismTrace()
    mechanism = _decoder_block_mechanics(features, gains, captured, prefix)
    return _bind_block(features, gains, mechanism, captured, trace, prefix)


def _head_binding(mechanism, captures, captured_natives, trace, prefix):
    logits, probabilities = mechanism["logits"], mechanism["probabilities"]
    maxima, shifted, terms, denominators, readout = [], [], [], [], []
    for t in range(2):
        for c in range(3):
            before, after = captures[f"{prefix}_readout_{t}_{c}"]
            trace.add(f"{prefix}_readout_{t}_{c}", f"Readout at position {t}, class {c}",
                      "product0=x0*u0; product1=x1*u1; sum=product0+product1; logit=sum+bias",
                      "Both final block features contribute through actual products for every class, including zero weights. Add that class bias last. U is hand-set, not trained.",
                      dict(t=t, c=c, x0=before["x0"], x1=before["x1"], u0=before["w0"], u1=before["w1"], bias=before["bias"]),
                      dict(product0=after["product0"], product1=after["product1"], sum=after["sum"], logit=after["value"]))
            readout.extend((after["product0"], after["product1"], after["sum"], after["value"]))
    for t in range(2):
        before, after = captures[f"{prefix}_class_row_{t}"]
        maximum = after["max"]
        maxima.append(maximum)
        trace.add(f"{prefix}_classMax_{t}", f"Stable class maximum at position {t}",
                  "max=logit0; scan class1,class2; replace only on strict greater",
                  "The maximum is selected from the actual saved logits. Class order is a,b,EOS with ascending IDs 97,98,512.",
                  {f"logit{c}": logits[3*t+c] for c in range(3)}, dict(max=maximum))
        for c in range(3):
            argument, term = after[f"shifted{c}"], after[f"term{c}"]
            shifted.append(argument)
            terms.append(term)
            trace.add(f"{prefix}_classExp_{t}_{c}", f"Stable class exponential at position {t}, class {c}",
                      "shifted=logit-max; term=exp(shifted)",
                      "Save the exact argument and output at this native exp call. The argument is nonpositive; there is no logarithm or hidden loss.",
                      dict(logit=logits[3*t+c], max=maximum), dict(shifted=argument, term=term))
        for c in range(3):
            previous = 0.0 if c == 0 else after[f"running{c-1}"]
            trace.add(f"{prefix}_classSum_{t}_{c}", f"Ordered class denominator at position {t}, class {c}", "sum=previous+term",
                      "Start from literal +0 and immediately add terms in class order 0,1,2. Keep this actual running sum; do not simplify equal terms.",
                      dict(previous=previous, term=after[f"term{c}"]), dict(sum=after[f"running{c}"]))
        denominators.append(after["denominator"])
        for c in range(3):
            trace.add(f"{prefix}_classProbability_{t}_{c}", f"Class probability at position {t}, class {c}", "probability=term/denominator",
                      "Divide the saved class term by the final saved ordered denominator. Display rounding is never an operand.",
                      dict(term=after[f"term{c}"], denominator=after["denominator"]), dict(probability=probabilities[3*t+c]))
        winner = mechanism["winners"][t]
        inputs = {f"logit{c}": logits[3*t+c] for c in range(3)}
        inputs.update({f"probability{c}": probabilities[3*t+c] for c in range(3)})
        trace.add(f"{prefix}_argmax_{t}", f"Greedy recommendation from position {t}",
                  "index=first maximum logit; tokenId=IDS[index]; probability=probabilities[index]",
                  "Strict-greater scanning retains the smallest actual token ID on an exact logit tie. This row recommends the next token after this observed prefix; it does not append it.",
                  inputs, dict(index=winner["index"], tokenId=winner["token"], probability=winner["probability"]))
    natives = []
    for leaf in captured_natives:
        # Only readout leaves are supplied; each name is a direct occurrence copy.
        suffix = leaf["id"].removeprefix(prefix + "_class_row_")
        t, c = suffix.split("_exp_")
        natives.append(dict(id=f"{prefix}_readout_exp_{t}_{c}", kind=leaf["kind"], input=leaf["input"], output=leaf["output"]))
    return dict(readout=readout, maxima=maxima, shifted=shifted, terms=terms, denominators=denominators, natives=natives)


def evaluate_decoder(value, trace, prefix):
    """All actual scalar values are captured before metadata projection."""
    state = decoder_state(value)
    _prefix(prefix)
    captured = _MechanismTrace()
    mechanism = _evaluate_decoder_mechanics(state, captured, prefix)
    captures = {identifier: (before, after) for identifier, before, after in captured.steps}
    for t in range(2):
        token_id = state[f"token{t}"]
        row = _IDS.index(token_id)
        for d in range(2):
            before, after = captures[f"{prefix}_position_{t}_{d}"]
            trace.add(f"{prefix}_embedding_{t}_{d}", f"Observed position {t}, feature {d}: lookup then add position", "feature=embedding+position",
                      "Look up this observed token ID in the authored E table and add the displayed absolute-position coordinate. An observed EOS has its explicit zero row; no token is generated or silently stopped.",
                      dict(t=t, d=d, tokenId=token_id, row=row, embedding=before["embedding"], position=before["position"]), dict(feature=after["value"]))
    blocks = []
    for layer in (1, 2):
        block_prefix = prefix + f"_block{layer}"
        block_capture = _MechanismTrace()
        block_capture.steps = [frame for frame in captured.steps if frame[0].startswith(block_prefix + "_")]
        block_capture.native = [leaf for leaf in captured.native if leaf["id"].startswith(block_prefix + "_")]
        m = mechanism[f"block{layer}"]
        gains = {key: state[key + str(layer)] for key in _GAIN_FIELDS}
        blocks.append(_bind_block(m["input"], gains, m, block_capture, trace, block_prefix))
    block1, block2 = blocks
    head = _head_binding(mechanism, captures, [leaf for leaf in captured.native if leaf["id"].startswith(prefix + "_class_row_")], trace, prefix)
    natives = [*block1["natives"], *block2["natives"], *head["natives"]]
    indices = [winner["index"] for winner in mechanism["winners"]]
    ids = [winner["token"] for winner in mechanism["winners"]]
    selected = [winner["probability"] for winner in mechanism["winners"]]
    tensors = _evaluation_tensors(state, mechanism, block1, block2, head, natives, prefix, indices, ids, selected)
    texts = _evaluation_texts(natives)
    return _freeze(dict(state=state, features=mechanism["features"], block1=block1, block2=block2,
                        logits=mechanism["logits"], probabilities=mechanism["probabilities"], argmaxIndices=indices,
                        argmaxIds=ids, selectedProbabilities=selected, nextTokenId=ids[1], nextTokenProbability=selected[1],
                        natives=natives, tensors=tensors, texts=texts))


def _evaluation_tensors(state, m, block1, block2, head, natives, p, indices, ids, selected):
    return [
        _tensor(p + "_Raw", [16], ["RawField"], [state[key] for key in _FIELDS], "Captured raw16 in declared field order; token0/token1 cells are integer VALUE, all other cells binary64 WORD."),
        _tensor(p + "_TokenIds", [1, 2], ["B", "T"], [state["token0"], state["token1"]], "Both observed input token IDs; EOS is an ordinary explicit lookup row here.", "int32"),
        _tensor(p + "_VocabularyIds", [3], ["Vocab"], _IDS, "Class order and strict-tie ID order: a=97,b=98,EOS=512.", "int32"),
        _tensor(p + "_E", [3, 2], ["Vocab", "D"], [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], "Authored embedding rows [1,0],[0,1],[0,0] for a,b,EOS."),
        _tensor(p + "_Positions", [1, 2, 2], ["B", "T", "D"], m["positions"], "Literal P0=[+0,+0], P1=[+0,positionScale]; disclosed absolute position addition."),
        _tensor(p + "_Embeddings", [1, 2, 2], ["B", "T", "D"], m["embedding"], "Actual E lookup copies before position addition."),
        _tensor(p + "_Features", [1, 2, 2], ["B", "T", "D"], m["features"], "Actual lookup plus position sums; first block input, retained on its residual skip."),
        *block1["tensors"], *block2["tensors"],
        _tensor(p + "_U", [2, 3], ["D", "Vocab"], m["U"], "Authored feature-last readout rows [1,0,0],[0,1,0]."),
        _tensor(p + "_Bias", [3], ["Vocab"], m["bias"], "Actual biasA,biasB,biasEOS words, added after both feature products."),
        _tensor(p + "_Readout", [1, 2, 3, 4], ["B", "T", "Vocab", "ReadoutField"], head["readout"], "Actual product0,product1,sum,logit per position and class."),
        _tensor(p + "_Logits", [1, 2, 3], ["B", "T", "Vocab"], m["logits"], "Actual final readout logits before stable class softmax."),
        _tensor(p + "_ClassMaxima", [1, 2], ["B", "T"], head["maxima"], "Actual selected maximum logit per observed position."),
        _tensor(p + "_ClassShifted", [1, 2, 3], ["B", "T", "Vocab"], head["shifted"], "Actual direct exp arguments, each saved once as logit minus row maximum."),
        _tensor(p + "_ClassTerms", [1, 2, 3], ["B", "T", "Vocab"], head["terms"], "Actual native exp outputs; no log native exists in this family."),
        _tensor(p + "_ClassDenominators", [1, 2], ["B", "T"], head["denominators"], "Final ordered +0 then term0,term1,term2 running sums."),
        _tensor(p + "_Probabilities", [1, 2, 3], ["B", "T", "Vocab"], m["probabilities"], "Actual term/final denominator probabilities at every observed position."),
        _tensor(p + "_ArgmaxIndices", [1, 2], ["B", "T"], indices, "Smallest class index on exact actual-logit ties.", "int32"),
        _tensor(p + "_ArgmaxIds", [1, 2], ["B", "T"], ids, "Actual selected token IDs in observed-position order.", "int32"),
        _tensor(p + "_SelectedProbabilities", [1, 2], ["B", "T"], selected, "Unchanged copies of the actual selected class probabilities."),
        *_native_tensors(p, natives),
    ]


def _evaluation_texts(natives):
    return dict(**_native_texts(natives), rawFields=list(_FIELDS), vocabularyLabels=["a", "b", "EOS"],
        gainFields=list(_GAIN_FIELDS), normStatisticFields=list(_STAT_FIELDS), readoutFields=["product0", "product1", "sum", "logit"],
        inputPolicy="Exact own-data raw16 on a plain/null-prototype object: all descriptors, then all actual finite numbers, then domains in raw order, then ASCII prefix. Tokens are integer members {97,98,512}; positionScale [0,1]; ten gains [-1,1]; three biases [-2,2]. No coercion, clamping, partial defaults or skipped inactive computation.",
        architecturePolicy="B1,T2,D2,H1,Dk2,Dv2. Look up both observed IDs, add absolute positions, compute two distinct pre-norm causal blocks on actual per-position features, then compute all three readout logits and class probabilities at both positions. Block2 consumes block1 output words, never token IDs or re-embedded values.",
        headPolicy="U rows [1,0,0],[0,1,0]; each logit uses two products, sum, bias last. Stable class softmax saves exp arguments/outputs, ordered +0 term sum and divisions. Greedy strict-greater scan over ascending IDs keeps the smallest token ID on exact logit ties. Only the last observed row supplies nextTokenId and nextTokenProbability; no token is appended.",
        nativePolicy="Both complete block-native ledgers precede output-head exp occurrences in token/class order. LN sqrt and attention sqrt(Dk) save actual outputs. Old attention shifted arguments repeat the identical immutable-operand subtraction used internally by stableSoftmax: functional word reconstruction, not a physical instruction trace. Output-head exp arguments are captured directly. No log, sin, cos or native call during serialization.",
        numericPolicy="Separate finite binary64 scalar operations retain primitive order without contraction or reassociation. Every numeric operand/result/copy uses WORD including admitted -0, except explicit token IDs, indices, dimensions, mask decisions, kind codes and counts use VALUE. Display precision8 is presentation only. Root Raw token cells are VALUE and its other fourteen cells are WORD.",
        nativeAdmissionPolicy="Declared future independent policy: positive finite sqrt outputs with argument [1/4,4096] and exp outputs with argument [-256,0], at most four ordered binary64 word steps from an independently isolated RN-even reference. Admit each complete TS/canonical record separately, then require exact scalar/copy words inside it. This is neither bit-exact libm parity nor validation evidence.",
        limitsPolicy="Authored forward-only toy with hand-set embeddings, gains, norms, FFN and readout. Two blocks are neither two generated tokens nor two optimizer steps. An observed EOS is an input embedding; generated-EOS stopping is not implemented. No loss, gradient, training, sampling, cache, latency, production intelligence or physical-trace claim. Runtime validation remains deferred under the FluxGeo hold.",
        provenance="Owner-chosen IV59 toy within the human full-book source authorization; these concrete model choices are not attributed to the human or the dossier. No external model or dataset.")


def _check_native_copies(natives, tensors, texts, frames, prefix):
    if not __debug__:
        raise RuntimeError("Explicit native-copy self-check refuses optimized Python (-O).")
    import struct

    def word(value):
        return struct.pack(">d", value)

    table = {record["id"]: record for record in tensors}
    arguments = table[prefix + "_NativeArguments"]["values"]
    kinds = table[prefix + "_NativeKinds"]["values"]
    assert texts["nativeFields"] == ["input", "output"]
    assert texts["nativeIds"] == [leaf["id"] for leaf in natives]
    assert texts["nativeKinds"] == [leaf["kind"] for leaf in natives]
    assert len(arguments) == 2 * len(natives) and len(kinds) == len(natives)
    for n, leaf in enumerate(natives):
        assert tuple(leaf) == ("id", "kind", "input", "output")
        assert word(arguments[2*n]) == word(leaf["input"])
        assert word(arguments[2*n+1]) == word(leaf["output"])
        assert kinds[n] == (0 if leaf["kind"] == "sqrt" else 1)
        identifier = leaf["id"]
        if leaf["kind"] == "sqrt" and "_attn_sqrt" not in identifier:
            statistics_id = identifier.removesuffix("_sqrt") + "_statistics"
            frame = frames[statistics_id]
            assert word(leaf["input"]) == word(frame["outputs"]["variancePlusEpsilon"])
            assert word(leaf["output"]) == word(frame["outputs"]["denominator"])
            norm_prefix, t = identifier.removesuffix("_sqrt").rsplit("_0_", 1)
            row = table[norm_prefix + "_Statistics"]["values"][10*int(t):10*int(t)+10]
            assert word(row[8]) == word(leaf["input"]) and word(row[9]) == word(leaf["output"])
            for d in range(2):
                copied = frames[f"{norm_prefix}_0_{t}_feature_{d}"]["inputs"]["denominator"]
                assert word(copied) == word(leaf["output"])
        elif leaf["kind"] == "sqrt":
            attention = identifier.removesuffix("_sqrt")
            assert leaf["input"] == 2.0
            for key, frame in frames.items():
                if key.startswith(attention + "_score_"):
                    assert word(frame["inputs"]["Dk"]) == word(leaf["input"])
                    assert word(frame["inputs"]["divisor"]) == word(leaf["output"])
        elif "_readout_exp_" in identifier:
            evaluation, coordinates = identifier.split("_readout_exp_")
            t, c = (int(index) for index in coordinates.split("_"))
            frame = frames[f"{evaluation}_classExp_{t}_{c}"]
            assert word(frame["outputs"]["shifted"]) == word(leaf["input"])
            assert word(frame["outputs"]["term"]) == word(leaf["output"])
            assert word(table[evaluation + "_ClassShifted"]["values"][3*t+c]) == word(leaf["input"])
            assert word(table[evaluation + "_ClassTerms"]["values"][3*t+c]) == word(leaf["output"])
            assert word(frames[f"{evaluation}_classSum_{t}_{c}"]["inputs"]["term"]) == word(leaf["output"])
            assert word(frames[f"{evaluation}_classProbability_{t}_{c}"]["inputs"]["term"]) == word(leaf["output"])
        else:
            attention, coordinates = identifier.split("_exp_0_0_")
            i, j = (int(index) for index in coordinates.split("_"))
            frame = frames[f"{attention}_row_0_0_{i}"]
            assert frame["inputs"][f"allowed{j}"] == 1
            assert word(frame["outputs"][f"shifted{j}"]) == word(leaf["input"])
            assert word(frame["outputs"][f"term{j}"]) == word(leaf["output"])


def check_public():
    """Explicit complete helper/native/copy checks; not an independent oracle."""
    if not __debug__:
        raise RuntimeError("Explicit public-helper self-check refuses optimized Python (-O).")
    import struct

    def words(values):
        return [struct.pack(">d", value) for value in values]

    ordered = decoder_trace()
    operands = {"2": -0.0, "1": 1.0, "01": 2.0, "4294967295": 3.0, "4294967294": 4.0}
    ordered.add("order", "", "", "", operands, operands)
    expected_keys = ["1", "2", "4294967294", "01", "4294967295"]
    assert list(ordered.steps[0]["inputs"]) == list(ordered.steps[0]["outputs"]) == expected_keys
    assert list(ordered.outputs) == ["order_" + key for key in expected_keys]
    assert words([ordered.steps[0]["inputs"]["2"]]) == words([-0.0])
    reused = decoder_trace()
    reused.add("frozen", "", "", "", ordered.steps[0]["inputs"], ordered.steps[0]["outputs"])
    assert list(reused.steps[0]["inputs"]) == expected_keys
    assert words(reused.steps[0]["inputs"].values()) == words(ordered.steps[0]["inputs"].values())
    proto = decoder_trace()
    proto.add("__proto", "", "", "", {}, {"_": 1.0})
    assert proto.outputs == {} and proto.steps[0]["outputs"] == {"_": 1.0}
    proto.add("ordinary", "", "", "", {}, {"__proto__": 2.0})
    assert proto.outputs == {"ordinary___proto__": 2.0}
    large = decoder_trace()
    large.add("large", "", "", "", {"x": 2**53 + 1, "y": 10**300}, {"z": -0.0})
    assert words(large.steps[0]["inputs"].values()) == words([9007199254740992.0, 1e300])
    for huge in (10**400, -(10**400)):
        for side in ("inputs", "outputs"):
            try:
                large.add("bad", "", "", "", {"x": huge} if side == "inputs" else {}, {"x": huge} if side == "outputs" else {})
            except NumericalFault as error:
                assert error.code == "NONFINITE" and str(error) == "bad." + side + ".x must be an actual finite number."
            else:
                raise AssertionError("Huge trace integer must fail before conversion.")
    assert len(large.steps) == 1

    gains = dict(q=-0.0, k=0.5, v=-1.0, o=0.0, f=0.0)
    for T, frame_count, alias_count, native_count in ((1, 42, 127, 4), (2, 82, 266, 8), (3, 124, 426, 13)):
        features = [16.0, -16.0] * T
        trace = decoder_trace()
        block = decoder_block(features, gains, trace, "bounded")
        assert tuple(block) == ("features", "gains", "output", "natives", "tensors", "texts")
        assert len(trace.steps) == frame_count and len(trace.outputs) == alias_count
        assert len(block["tensors"]) == 47 and len(block["natives"]) == native_count
        assert len(block["texts"]) == 10 and tuple(block["gains"]) == _GAIN_FIELDS
        assert block["output"]["id"] == "bounded_Output"
        assert block["output"] == block["tensors"][44]
        assert words(block["output"]["values"]) == words(features)
        assert words(block["features"]) == words(features)
        features[0] = 3.0
        assert block["features"][0] == 16.0
        table = {record["id"]: record for record in block["tensors"]}
        frames = {frame["id"]: frame for frame in trace.steps}
        assert len(table) == 47 and len(frames) == frame_count
        assert tuple(block["texts"]) == ("nativeIds", "nativeKinds", "nativeFields", "gainFields", "normStatisticFields",
                                         "featurePolicy", "kernelPolicy", "nativePolicy", "zeroPolicy", "limitsPolicy")
        for record in block["tensors"]:
            assert tuple(record) == ("id", "shape", "axes", "dtype", "values", "provenance", "precision")
            assert len(record["shape"]) == len(record["axes"])
            assert record["precision"] == (0 if record["dtype"] == "int32" else 8)
        mask = table["bounded_attn_allowed"]
        assert mask["dtype"] == "bool" and mask["precision"] == 8
        assert mask["values"] == [j <= i for i in range(T) for j in range(T)]
        assert all(type(value) is bool for value in mask["values"])
        assert words(table["bounded_attn_WQ"]["values"]) == words([-0.0, 0.0, 0.0, -0.0])
        for stage in (1, 2):
            p = f"bounded_n{stage}"
            for t in range(T):
                statistics = frames[f"{p}_0_{t}_statistics"]["outputs"]
                assert words(table[p + "_Statistics"]["values"][10*t:10*t+10]) == words(statistics.values())
                for d in range(2):
                    frame = frames[f"{p}_0_{t}_feature_{d}"]
                    assert words([frame["inputs"]["source"]]) == words([table[p + "_Centered"]["values"][2*t+d]])
                    assert words([frame["outputs"]["normalized"]]) == words([table[p + "_Normalized"]["values"][2*t+d]])
                    assert words([frame["outputs"]["value"]]) == words([table[p + "_Output"]["values"][2*t+d]])
        for i in range(T):
            row = frames[f"bounded_attn_row_0_0_{i}"]["outputs"]
            for j in range(T):
                probability = table["bounded_attn_probabilities"]["values"][i*T+j]
                assert words([probability]) == words([row[f"p{j}"]])
                if j > i:
                    assert f"shifted{j}" not in row
                    assert words([probability, row[f"term{j}"]]) == words([0.0, 0.0])
            for d in range(2):
                mixed = frames[f"bounded_attn_head_mix_0_0_{i}_{d}"]["outputs"]["value"]
                assert words([mixed]) == words([table["bounded_attn_OHeads"]["values"][2*i+d]])
                assert words([mixed]) == words([table["bounded_attn_C"]["values"][2*i+d]])
                for suffix, source in (("r1", "R1"), ("r2", "Output")):
                    assert words([frames[f"bounded_{suffix}_0_{i}_{d}"]["outputs"]["value"]]) == words([table["bounded_" + source]["values"][2*i+d]])
            for hidden in range(3):
                index = 3*i+hidden
                assert words([frames[f"bounded_ffn_hidden_0_{i}_{hidden}"]["outputs"]["preactivation"]]) == words([table["bounded_ffn_Z"]["values"][index]])
                assert words([frames[f"bounded_ffn_relu_0_{i}_{hidden}"]["outputs"]["activation"]]) == words([table["bounded_ffn_Hidden"]["values"][index]])
        for frame in trace.steps:
            assert tuple(frame) == ("id", "label", "equation", "explanation", "inputs", "outputs")
            for key, value in frame["outputs"].items():
                assert words([value]) == words([trace.outputs[frame["id"] + "_" + key]])
        _check_native_copies(block["natives"], block["tensors"], block["texts"], frames, "bounded")
        try:
            block["output"]["values"][0] = 0.0
        except TypeError:
            pass
        else:
            raise AssertionError("Saved tensor must be immutable.")

    trace = decoder_trace()
    evaluated = evaluate_decoder(DEFAULT_IV59, trace, "observed")
    assert tuple(evaluated) == ("state", "features", "block1", "block2", "logits", "probabilities", "argmaxIndices", "argmaxIds",
                                "selectedProbabilities", "nextTokenId", "nextTokenProbability", "natives", "tensors", "texts")
    assert len(trace.steps) == 196 and len(trace.outputs) == 592
    assert len(evaluated["tensors"]) == 115 and len(evaluated["texts"]) == 16
    assert sum(len(record["values"]) for record in evaluated["tensors"]) == 640
    assert words(evaluated["block2"]["features"]) == words(evaluated["block1"]["output"]["values"])
    assert evaluated["argmaxIds"] == [97, 97]
    assert evaluated["nextTokenId"] == evaluated["argmaxIds"][1]
    assert words([evaluated["nextTokenProbability"]]) == words([evaluated["selectedProbabilities"][1]])
    frames = {frame["id"]: frame for frame in trace.steps}
    _check_native_copies(evaluated["natives"], evaluated["tensors"], evaluated["texts"], frames, "observed")
    assert [frame["id"] for frame in trace.steps if "_readout_" in frame["id"]] == [f"observed_readout_{t}_{c}" for t in range(2) for c in range(3)]
    assert next(i for i, frame in enumerate(trace.steps) if "_classMax_" in frame["id"]) > next(i for i, frame in enumerate(trace.steps) if frame["id"] == "observed_readout_1_2")

    # A fabricated logit row isolates strict-FIRST head max, even if unreachable by a particular preset.
    for first, second in ((-0.0, 0.0), (0.0, -0.0)):
        capture = _MechanismTrace()
        _softmax([first, second, -1.0], [True]*3, capture, "head", positive_zero=False)
        assert words([capture.steps[0][2]["max"]]) == words([first])
    # Serialization must consume captures even when native evaluation is disabled.
    source = [1.0, 0.0, 1.0, 0.5]
    capture = _MechanismTrace()
    mechanism = _decoder_block_mechanics(source, gains, capture, "serialized")
    saved_sqrt, saved_exp = math.sqrt, math.exp
    def forbidden(argument):
        raise AssertionError("Native evaluation during serialization.")
    try:
        math.sqrt = math.exp = forbidden
        projected = _bind_block(source, gains, mechanism, capture, decoder_trace(), "serialized")
        assert len(projected["tensors"]) == 47
    finally:
        math.sqrt, math.exp = saved_sqrt, saved_exp

2. Grouped-attention helper — complete file

In _scalar_graph, follow _capture_state, whole-mask preflight, Q then shared K then shared V projections, one square root, every score, allowed softmax rows, all weighted products/partials and the final indexed join. _store_heads stores already calculated words. _serialize copies saved operands and results into the public frames, tensors and texts; it performs no new floating-point attention calculation or native call. group_state(value) captures state, group_trace() is the exact generic collector alias, and evaluate_grouped(value, trace, prefix) supplies the complete helper record and trace.

The Python helper completes its independent scalar/native capture AND indexed storage before replaying public trace.add callbacks. Its private observer replay likewise consumes finished immutable captures. The TypeScript model appends frames during its calculation. Consequently, a Python callback failure occurs after the graph was captured, rather than at the same arithmetic instant as a TypeScript observer failure. Both reject bad raw state, prefix and an empty allowed row before numerical work or any observer append. Callback timing is an explicit limit on what a trace comparison can establish.

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.

"""IV61 independent scalar graph with the owner-adopted public binding.

Source only: every check is UNRUN. Independent FIRST preceded producer reads.
Observer callbacks replay immutable captures AFTER the entire scalar graph.
"""
import importlib.util
import math
from pathlib import Path
import sys
from types import MappingProxyType, ModuleType


def _load_support():
    """Load only the adjacent generic support, with exact cache identity."""
    path = Path(__file__).resolve().with_name("decoder_reference.py")
    name = "_book_iv_p15_grouped_decoder_support"
    if name in sys.modules:
        cached = sys.modules[name]
        if (type(cached) is not ModuleType or
                Path(getattr(cached, "__file__", "")).resolve() != path or
                getattr(getattr(cached, "__spec__", None), "origin", None) != str(path)):
            raise ImportError("IV61 generic support cache has an unexpected file identity.")
        return cached
    spec = importlib.util.spec_from_file_location(name, path)
    if spec is None or spec.loader is None:
        raise ImportError("Cannot load adjacent decoder_reference.py.")
    module = importlib.util.module_from_spec(spec)
    sys.modules[name] = module
    global _owned_support
    _owned_support = module
    try:
        spec.loader.exec_module(module)
        if (sys.modules.get(name) is not module or
                Path(getattr(module, "__file__", "")).resolve() != path or
                getattr(getattr(module, "__spec__", None), "origin", None) != str(path)):
            raise ImportError("IV61 generic support cache identity changed while loading.")
    except BaseException:
        if sys.modules.get(name) is module:
            sys.modules.pop(name)
        raise
    return module


_support = _load_support()
NumericalFault = _support.NumericalFault
_freeze = _support._freeze
_finite = _support._finite
_prefix = _support._prefix
_numeric = _support._numeric
# Exact factory alias, not a wrapper and never a decoder task invocation.
group_trace = _support.decoder_trace
_FIELDS = ("Hq", "Hkv", "elementBytes", "q0", "q1", "q2", "q3",
           "k0", "k1", "k2", "k3", "v0", "v1", "v2", "v3", "key0", "key1")
_CHOICES = ("Hq", "Hkv", "elementBytes", "key0", "key1")
_DEFAULT_RAW = _freeze(dict(zip(_FIELDS, (4, 2, 2, 1.0, 1.0, 1.0, 1.0,
                                           1.0, 1.0, 1.0, 1.0,
                                           1.0, 1.0, 1.0, 1.0, 1, 1))))
_X = (1.0, 0.0, 0.0, 1.0)
_WQ = ((1.0, 0.0, 1.0, 0.0), (0.0, 1.0, 0.0, 1.0),
       (1.0, 1.0, 1.0, 1.0), (1.0, -1.0, 1.0, -1.0))
_WK = ((1.0, 0.0, 0.0, 1.0), (1.0, 1.0, 1.0, -1.0),
       (1.0, 0.0, -1.0, 1.0), (0.0, 1.0, 1.0, 0.0))
_WV = ((1.0, 0.0, 0.0, 1.0), (2.0, 0.0, 0.0, 2.0),
       (1.0, 2.0, 2.0, -1.0), (-1.0, 1.0, 1.0, 1.0))



def _capture_state(value):
    """Private raw17 capture: all fields, all finite, domains in order, pairing."""
    if type(value) not in (dict, _support._FrozenDict):
        raise NumericalFault("INVALID_INPUT", "state must be a plain object.")
    keys = tuple(value)
    if (len(keys) != len(_FIELDS) or any(type(key) is not str for key in keys)
            or set(keys) != set(_FIELDS)):
        raise NumericalFault("INVALID_INPUT", "state must have exactly " + ", ".join(_FIELDS) + " as own fields.")
    captured = {key: value[key] for key in _FIELDS}
    for key in _FIELDS:
        _numeric(captured[key], "state." + key)
    for key in _FIELDS:
        item = captured[key]
        if key in ("Hq", "Hkv"):
            valid = 1 <= item <= 4 and int(item) == item
            reason = key + " must be an integer from 1 to 4."
        elif key == "elementBytes":
            valid = item in (2, 4, 8)
            reason = "elementBytes must be exactly 2, 4 or 8."
        elif key in ("key0", "key1"):
            valid = item in (0, 1)
            reason = key + " must be an integer from 0 to 1."
        else:
            valid = -1 <= item <= 1
            reason = key + " must be between -1 and 1."
        if not valid:
            raise NumericalFault("INVALID_INPUT", reason)
    if captured["Hkv"] > captured["Hq"] or captured["Hq"] % captured["Hkv"] != 0:
        raise NumericalFault("INVALID_INPUT", "Hq must be divisible by Hkv, with Hkv no greater than Hq.")
    return _freeze({key: float(captured[key]) for key in _FIELDS})


class _Capture:
    """Private scalar captures, deliberately independent of public frame metadata."""
    def __init__(self):
        self.steps = []
        self.natives = []
        self.ids = set()

    def add(self, identifier, inputs, outputs):
        if identifier in self.ids:
            raise NumericalFault("INVALID_INPUT", "Duplicate private capture ID.")
        for record in (inputs, outputs):
            for key, value in record.items():
                _finite(value, identifier + "/" + key)
        self.ids.add(identifier)
        self.steps.append(_freeze(dict(id=identifier, inputs=inputs, outputs=outputs)))

    def leaf(self, identifier, kind, argument):
        _finite(argument, identifier)
        if kind == "sqrt":
            if argument != 2.0:
                raise NumericalFault("INVALID_INPUT", "IV61 sqrt argument must be two.")
            result = _finite(math.sqrt(argument), identifier)
        elif kind == "exp" and -4.0 <= argument <= 0.0:
            result = _finite(math.exp(argument), identifier)
        else:
            raise NumericalFault("INVALID_INPUT", "IV61 native argument is outside the signed scope.")
        if result <= 0.0 or any(item["id"] == identifier for item in self.natives):
            raise NumericalFault("INVALID_INPUT", "Invalid or duplicate IV61 native leaf.")
        self.natives.append(_freeze(dict(id=identifier, kind=kind, input=argument, output=result)))
        return result


def _project(bank, gains, count, capture, prefix):
    result = []
    for head in range(count):
        for i in range(2):
            for d in range(2):
                x0, x1 = _X[2*i], _X[2*i+1]
                w0, w1 = bank[head][d], bank[head][2+d]
                p0 = _finite(x0 * w0, "projection product0")
                p1 = _finite(x1 * w1, "projection product1")
                unscaled = _finite(p0 + p1, "direct projection sum")
                scaled = _finite(unscaled * gains[head], "post-projection gain")
                capture.add(f"{prefix}_{head}_{i}_{d}",
                            dict(x0=x0, x1=x1, w0=w0, w1=w1, gain=gains[head]),
                            dict(product0=p0, product1=p1, unscaled=unscaled, scaled=scaled))
                result.append(scaled)
    return result


def _store_heads(values, count):
    """Indexed float64 storage only; no NumPy numerical contraction or reduction."""
    stored = _support.np.empty((1, count, 2, 2), dtype=_support.np.float64)
    for h in range(count):
        for i in range(2):
            for d in range(2):
                stored[0, h, i, d] = values[(h*2+i)*2+d]
    stored.flags.writeable = False
    return stored


def _scalar_graph(value, prefix):
    """Independent ordered graph; no trusted observer is invoked during arithmetic."""
    state = _capture_state(value)
    _prefix(prefix)
    Hq, Hkv = int(state["Hq"]), int(state["Hkv"])
    allowed = []
    for h in range(Hq):
        for i in range(2):
            row = [state[f"key{j}"] == 1 and j <= i for j in range(2)]
            if not any(row):
                raise NumericalFault("FULLY_MASKED_ROW", "This query has no allowed keys; no probability distribution exists.")
            allowed.extend(row)
    capture = _Capture()
    width = Hq // Hkv
    groups = [h // width for h in range(Hq)]
    q = _project(_WQ, [state[f"q{h}"] for h in range(4)], Hq, capture, prefix + "_Q")
    k = _project(_WK, [state[f"k{g}"] for g in range(4)], Hkv, capture, prefix + "_K")
    v = _project(_WV, [state[f"v{g}"] for g in range(4)], Hkv, capture, prefix + "_V")
    divisor = capture.leaf(prefix + "_sqrt", "sqrt", 2.0)
    capture.add(prefix + "_scale", dict(Dk=2.0), dict(divisor=divisor))
    raw, scores = [], []
    for h in range(Hq):
        g = groups[h]
        for i in range(2):
            for j in range(2):
                q0, q1 = q[(h*2+i)*2:(h*2+i)*2+2]
                k0, k1 = k[(g*2+j)*2:(g*2+j)*2+2]
                p0 = _finite(q0 * k0, "score product0")
                p1 = _finite(q1 * k1, "score product1")
                dot = _finite(p0 + p1, "direct score sum")
                score = _finite(dot / divisor, "scaled score")
                capture.add(f"{prefix}_score_{h}_{i}_{j}",
                            dict(group=g, q0=q0, q1=q1, k0=k0, k1=k1, divisor=divisor),
                            dict(product0=p0, product1=p1, raw=dot, score=score))
                raw.append(dot)
                scores.append(score)
    probabilities, softmax = [], []
    for h in range(Hq):
        for i in range(2):
            offset = (h*2+i)*2
            row, mask = scores[offset:offset+2], allowed[offset:offset+2]
            maximum = next(row[j] for j in range(2) if mask[j])
            for j in range(2):
                if mask[j] and (row[j] > maximum or
                        (row[j] == maximum == 0.0 and math.copysign(1.0, row[j]) > 0.0)):
                    maximum = row[j]
            terms, shifts, running = [], {}, []
            for j in range(2):
                term = 0.0
                if mask[j]:
                    argument = _finite(row[j] - maximum, "allowed shift")
                    shifts[f"shifted{j}"] = argument
                    term = capture.leaf(f"{prefix}_exp_{h}_{i}_{j}", "exp", argument)
                terms.append(term)
            denominator = 0.0
            for term in terms:
                denominator = _finite(denominator + term, "ordered denominator")
                running.append(denominator)
            if denominator <= 0.0:
                raise NumericalFault("NONFINITE", "Softmax denominator must be positive.")
            p = [_finite(terms[j] / denominator, "probability") if mask[j] else 0.0 for j in range(2)]
            outputs = dict(max=maximum, **shifts, term0=terms[0], term1=terms[1],
                           running0=running[0], running1=running[1], denominator=denominator,
                           p0=p[0], p1=p[1])
            capture.add(f"{prefix}_softmax_{h}_{i}",
                        dict(score0=row[0], score1=row[1], allowed0=int(mask[0]), allowed1=int(mask[1])), outputs)
            softmax.append(_freeze(outputs))
            probabilities.extend(p)
    products, partials, output = [], [], []
    for h in range(Hq):
        g = groups[h]
        for i in range(2):
            running = [0.0, 0.0]
            for j in range(2):
                for d in range(2):
                    probability = probabilities[(h*2+i)*2+j]
                    value = v[(g*2+j)*2+d]
                    before = running[d]
                    product = _finite(probability * value, "including masked product")
                    running[d] = _finite(before + product, "ordered weighted sum")
                    capture.add(f"{prefix}_weighted_{h}_{i}_{j}_{d}",
                                dict(group=g, probability=probability, value=value, before=before),
                                dict(product=product, running=running[d]))
                    products.append(product)
                    partials.append(running[d])
            output.extend(running)
    joined = []
    for i in range(2):
        for h in range(Hq):
            for d in range(2):
                source = (h*2+i)*2+d
                target = (i*Hq+h)*2+d
                word = output[source]
                joined.append(word)
                capture.add(f"{prefix}_join_{i}_{h}_{d}", dict(sourceOffset=source, targetOffset=target, source=word), dict(value=word))
    key_elements = 1 * 2 * Hkv * 2
    value_elements = 1 * 2 * Hkv * 2
    total_elements = key_elements + value_elements
    cache_bytes = total_elements * state["elementBytes"]
    counts = dict(keyElements=key_elements, valueElements=value_elements,
                  totalElements=total_elements, cacheBytes=cache_bytes, queryElements=1*2*Hq*2)
    capture.add(prefix + "_cache", dict(B=1, T=2, Hkv=Hkv, Dk=2, Dv=2, elementBytes=state["elementBytes"]), counts)
    evidence = _freeze(dict(state=state, X=_X, WQBank=_WQ, WKBank=_WK, WVBank=_WV,
                           groupWidth=width, groups=groups, Q=q, K=k, V=v,
                           divisor=divisor, raw=raw, scores=scores, allowed=allowed,
                           softmax=softmax, probabilities=probabilities,
                           products=products, partials=partials, output=output, joined=joined,
                           counts=counts, captures=capture.steps, natives=capture.natives))
    storage = MappingProxyType(dict(Q=_store_heads(q, Hq), K=_store_heads(k, Hkv),
                                    V=_store_heads(v, Hkv), output=_store_heads(output, Hq),
                                    joined=_support._storage(joined, 2, 2*Hq)))
    storage["joined"].flags.writeable = False
    return MappingProxyType(dict(evidence=evidence, storage=storage))


def _notify(graph, observer):
    """Post-capture callback timing differs from a live producer; copy saved operands only."""
    for frame in graph["evidence"]["captures"]:
        observer(frame["id"], dict(frame["inputs"]), dict(frame["outputs"]))


def group_state(value):
    return _capture_state(value)


def evaluate_grouped(value, trace, prefix):
    return _serialize(_scalar_graph(value, prefix), trace, prefix)


def check_mechanism():
    """Explicit independent mechanism checks; never public admission or implicit work."""
    if not __debug__:
        raise RuntimeError("Explicit IV61 mechanism check refuses optimized Python (-O).")
    import struct
    def words(values):
        if not __debug__:
            raise RuntimeError("Explicit IV61 word-check helper refuses optimized Python (-O).")
        return [struct.pack(">d", value) for value in values]
    for Hq, Hkv, mapping in ((1,1,[0]), (2,1,[0,0]), (2,2,[0,1]),
                             (3,1,[0,0,0]), (3,3,[0,1,2]), (4,1,[0,0,0,0]),
                             (4,2,[0,0,1,1]), (4,4,[0,1,2,3])):
        graph = _scalar_graph(dict(_DEFAULT_RAW, Hq=Hq, Hkv=Hkv), "check")
        e = graph["evidence"]
        assert e["groups"] == mapping
        assert len(e["K"]) == len(e["V"]) == 4*Hkv
        assert len(e["natives"]) == 1+3*Hq
        assert e["counts"]["cacheBytes"] == 16*Hkv
        assert len(e["joined"]) == 4*Hq
        assert words(graph["storage"]["joined"][0].flat) == words(e["joined"])
        for i in range(2):
            for h in range(Hq):
                for d in range(2):
                    assert words([e["joined"][(i*Hq+h)*2+d]]) == words([e["output"][(h*2+i)*2+d]])
    default = _scalar_graph(dict(_DEFAULT_RAW), "default")["evidence"]
    assert default["joined"][:8] == [1.0,0.0,1.0,0.0,2.0,0.0,2.0,0.0]
    assert default["probabilities"][:2] == [1.0,0.0]
    assert default["joined"][10] < 1.0
    mha = _scalar_graph(dict(_DEFAULT_RAW, Hkv=4), "mha")["evidence"]
    assert mha["joined"][:8] == [1.0,0.0,2.0,0.0,1.0,2.0,-1.0,1.0]
    assert mha["joined"][10] > 1.0
    negative = _scalar_graph(dict(_DEFAULT_RAW, q0=-0.0, q2=-0.0), "negative")["evidence"]
    assert words(negative["Q"][:4]) == words([-0.0]*4)
    assert words(negative["raw"][:4]) == words([-0.0]*4)
    assert words([negative["softmax"][5]["shifted0"], negative["softmax"][5]["shifted1"]]) == words([-0.0,0.0])
    padded = _scalar_graph(dict(_DEFAULT_RAW, key1=0), "padded")["evidence"]
    assert len(padded["natives"]) == 9
    assert len(padded["products"]) == 32
    assert all(padded["probabilities"][j] == 0.0 for j in range(1,16,2))
    changed_bytes = _scalar_graph(dict(_DEFAULT_RAW, elementBytes=8), "bytes")["evidence"]
    for key in ("Q", "K", "V", "probabilities", "output", "joined"):
        assert words(default[key]) == words(changed_bytes[key])
    assert changed_bytes["counts"]["cacheBytes"] == 128


def check_public():
    """Explicit adopted serializer invariants; no producer baseline is synthesized."""
    if not __debug__:
        raise RuntimeError("Explicit IV61 public check refuses optimized Python (-O).")
    _check_public_binding()


def check_captures():
    """Explicit storage/callback isolation checks on the independent private graph."""
    if not __debug__:
        raise RuntimeError("Explicit IV61 capture check refuses optimized Python (-O).")
    import struct
    graph = _scalar_graph(dict(_DEFAULT_RAW), "capture")
    evidence = graph["evidence"]
    for key in ("Q", "K", "V", "output", "joined"):
        assert [struct.pack(">d", x) for x in graph["storage"][key].flat] == [struct.pack(">d", x) for x in evidence[key]]
        assert not graph["storage"][key].flags.writeable
    seen = []
    def observe(identifier, inputs, outputs):
        if not __debug__:
            raise RuntimeError("Explicit IV61 observer check hook refuses optimized Python (-O).")
        seen.append(identifier)
        inputs.clear()
        outputs.clear()
    _notify(graph, observe)
    assert seen == [frame["id"] for frame in evidence["captures"]]
    assert evidence["captures"][0]["inputs"] and evidence["captures"][0]["outputs"]
    sentinel = RuntimeError("observer sentinel")
    def fail(identifier, inputs, outputs):
        if not __debug__:
            raise RuntimeError("Explicit IV61 failure hook refuses optimized Python (-O).")
        raise sentinel
    try:
        _notify(graph, fail)
    except RuntimeError as fault:
        assert fault is sentinel
    else:
        raise AssertionError("Observer exception was hidden.")
    collector = group_trace()
    collector.add("existing", "Existing", "x=x", "Prior immutable frame.", dict(x=-0.0), dict(x=-0.0))
    old_steps = tuple(collector.steps)
    old_outputs = dict(collector.outputs)
    for value, prefix, expected in (
            (dict(_DEFAULT_RAW, Hq=3, Hkv=2, key0=0), "!", "INVALID_INPUT"),
            (dict(_DEFAULT_RAW, key0=0), "!", "INVALID_INPUT"),
            (dict(_DEFAULT_RAW, key0=0), "masked", "FULLY_MASKED_ROW")):
        try:
            _notify(_scalar_graph(value, prefix), observe)
        except NumericalFault as fault:
            assert fault.code == expected
        else:
            raise AssertionError("Invalid input reached capture replay.")
        assert tuple(collector.steps) == old_steps and collector.outputs == old_outputs
    assert len(seen) == len(evidence["captures"])
    for frame in evidence["captures"]:
        if "_softmax_" in frame["id"] and frame["inputs"]["allowed1"] == 0:
            assert "shifted1" not in frame["outputs"]
    assert group_trace is _support.decoder_trace


# Adopted metadata below projects FIRST captures; no floating/native arithmetic.
DEFAULT_IV61 = _DEFAULT_RAW
_CACHE_FIELDS = ("keyElements", "valueElements", "totalElements", "logicalBytes", "queryElements", "scoreCells")
_SUMMARY_FIELDS = ("Hq", "Hkv", "joinedWidth") + _CACHE_FIELDS + ("sqrtCalls", "expCalls", "nativeElementaryCalls", "frames", "tensorCount")


def _tensor(identifier, shape, axes, values, provenance, dtype="float64"):
    return dict(id=identifier, shape=list(shape), axes=list(axes), dtype=dtype,
                values=list(values), provenance=provenance, precision=0 if dtype == "int32" else 8)


def _serialize(graph, trace, prefix):
    """Replay public callbacks AFTER complete scalar/native capture and indexed storage."""
    e = graph["evidence"]
    s = e["state"]
    H, K = int(s["Hq"]), int(s["Hkv"])
    captures = {frame["id"]: frame for frame in e["captures"]}
    projection = {kind: [] for kind in ("q", "k", "v")}
    score_evidence, maxima, coordinates, shifted, terms, denominators = [], [], [], [], [], []
    for h in range(H):
        trace.add(f"{prefix}_map_{h}", f"Query head {h}: contiguous KV group", "group=floor(h/groupWidth); groupWidth=Hq/Hkv",
                  "Both the key and value lookup use this same group. Every query head retains its own score, probability and output path.",
                  dict(h=h, Hq=s["Hq"], Hkv=s["Hkv"], groupWidth=e["groupWidth"]), dict(group=e["groups"][h]))
    for kind, count in (("q", H), ("k", K), ("v", K)):
        for n in range(count):
            for i in range(2):
                for d in range(2):
                    frame = captures[f"{prefix}_{kind.upper()}_{n}_{i}_{d}"]
                    before, after = frame["inputs"], frame["outputs"]
                    output = dict(product0=after["product0"], product1=after["product1"], unscaled=after["unscaled"], value=after["scaled"])
                    projection[kind].extend(output.values())
                    trace.add(f"{prefix}_{kind}_{n}_{i}_{d}", f"{kind.upper()} projection {n}, position {i}, feature {d}",
                              "product0=x0*w0; product1=x1*w1; unscaled=product0+product1; value=unscaled*gain",
                              "Project the same basis source through this disclosed matrix, then apply its gain. Both products and their direct sum execute even for zero entries; gain is never moved into the weights.",
                              dict(n=n, i=i, d=d, **before), output)
    trace.add(prefix + "_sqrt", "One shared square root of the key width", "divisor=sqrt(Dk)",
              "Dk is two for every head. This one actual native square root supplies every score division; neither query-head nor KV-group count changes its argument.",
              dict(Dk=2), dict(divisor=e["divisor"]))
    for h in range(H):
        g = e["groups"][h]
        for i in range(2):
            for j in range(2):
                frame = captures[f"{prefix}_score_{h}_{i}_{j}"]
                b, a = frame["inputs"], frame["outputs"]
                score_evidence.extend((a["product0"], a["product1"], a["raw"]))
                trace.add(frame["id"], f"Head {h}, query {i}, key {j}: score from group {g}",
                          "product0=q0*k0; product1=q1*k1; dot=product0+product1; score=dot/divisor",
                          "Read the original shared key cache by group index. Compute both products, the direct sum and division for every key, including forbidden future or padded keys.",
                          dict(h=h, g=g, i=i, j=j, q0=b["q0"], q1=b["q1"], k0=b["k0"], k1=b["k1"], Dk=2, divisor=b["divisor"]),
                          dict(product0=a["product0"], product1=a["product1"], dot=a["raw"], score=a["score"]))
    for h in range(H):
        for i in range(2):
            frame = captures[f"{prefix}_softmax_{h}_{i}"]
            b, a = frame["inputs"], frame["outputs"]
            output = dict(max=a["max"])
            for j in range(2):
                key = f"shifted{j}"
                if key in a:
                    shifted.append(a[key])
                    coordinates.extend((h, i, j))
                    output[key] = a[key]
            output.update(term0=a["term0"], term1=a["term1"], denominator=a["denominator"], probability0=a["p0"], probability1=a["p1"])
            maxima.append(a["max"])
            terms.extend((a["term0"], a["term1"]))
            denominators.append(a["denominator"])
            trace.add(f"{prefix}_row_{h}_{i}", f"Head {h}, query {i}: causal stable probabilities",
                      "max=Math.max(allowed scores); term[j]=allowed[j]?exp(score[j]-max):+0; denominator=(+0+term0)+term1; probability[j]=term[j]/denominator",
                      "The unchanged stableSoftmax selects the allowed maximum, preserving Math.max zero ties, and evaluates only allowed exponentials in key order. Saved shifted fields repeat its immutable subtraction as a functional witness; masked fields and native leaves are absent. Structural masked terms and probabilities are +0.",
                      dict(h=h, g=e["groups"][h], i=i, **b), output)
    for h in range(H):
        for i in range(2):
            for j in range(2):
                for d in range(2):
                    frame = captures[f"{prefix}_weighted_{h}_{i}_{j}_{d}"]
                    b, a = frame["inputs"], frame["outputs"]
                    trace.add(frame["id"], f"Head {h}, query {i}, key {j}, value feature {d}", "product=probability*value; sum=previous+product",
                              "Each feature accumulator starts at literal +0. Every key product and addition executes, including masked probability times a negative value and its possible -0 product.",
                              dict(h=h, g=b["group"], i=i, j=j, d=d, probability=b["probability"], value=b["value"], previous=b["before"]),
                              dict(product=a["product"], sum=a["running"]))
    for i in range(2):
        for h in range(H):
            for d in range(2):
                frame = captures[f"{prefix}_join_{i}_{h}_{d}"]
                b, a = frame["inputs"], frame["outputs"]
                trace.add(frame["id"], f"Query {i}: copy head {h}, feature {d} into the join", "Joined[(i*Hq+h)*2+d]=HeadOutputs[(h*2+i)*2+d]",
                          "Move the head axis beside its value-feature axis and copy into h*Dv+d. All Hq heads remain; no sum, average, output projection or expanded KV cache is constructed.",
                          dict(i=i, h=h, d=d, sourceOffset=b["sourceOffset"], destinationOffset=b["targetOffset"], value=b["source"]), dict(value=a["value"]))
    counts = dict(keyElements=e["counts"]["keyElements"], valueElements=e["counts"]["valueElements"], totalElements=e["counts"]["totalElements"],
                  logicalBytes=e["counts"]["cacheBytes"], queryElements=e["counts"]["queryElements"], scoreCells=len(e["scores"]))
    trace.add(prefix + "_cache", "Count one layer of logical key and value payload",
              "keyElements=B*Tk*Hkv*Dk; valueElements=B*Tk*Hkv*Dv; totalElements=keyElements+valueElements; logicalBytes=totalElements*elementBytes; queryElements=B*Tq*Hq*Dk; scoreCells=B*Hq*Tq*Tk",
              "Add K and V once before multiplying by the analytical byte assumption. Q activations and score cells are separate counts, excluded from cache payload. Binary64 arithmetic and actual allocation do not change with elementBytes.",
              dict(B=1, Tq=2, Tk=2, Hq=s["Hq"], Hkv=s["Hkv"], Dk=2, Dv=2, elementBytes=s["elementBytes"]), dict(counts))
    shape, axes = [1, H, 2, 2], ["B", "Hq", "Tq", "Tk"]
    natives = e["natives"]
    tensors = [
        _tensor(prefix + "_Raw", [17], ["RawField"], [s[key] for key in _FIELDS], "Captured raw17 in declared order. Choices use VALUE; all twelve gain words, including inactive gains and -0, use WORD."),
        _tensor(prefix + "_X", [1,2,2], ["B","T","Din"], e["X"], "Fixed basis-feature source rows [1,+0],[+0,1]; this same source feeds all projections."),
        _tensor(prefix + "_WQBank", [4,2,2], ["QueryHeadBank","Din","Dk"], [x for row in e["WQBank"] for x in row], "All four hand-set query matrices, row-feature orientation, including inactive heads; every structural zero is literal +0."),
        _tensor(prefix + "_WKBank", [4,2,2], ["KVGroupBank","Din","Dk"], [x for row in e["WKBank"] for x in row], "All four hand-set key matrices, including inactive groups; active groups are projected once, not once per query head."),
        _tensor(prefix + "_WVBank", [4,2,2], ["KVGroupBank","Din","Dv"], [x for row in e["WVBank"] for x in row], "All four hand-set value matrices, including inactive groups; these are weights, not retained KV payload."),
        _tensor(prefix + "_HeadToGroup", [H], ["Hq"], e["groups"], "Uniform contiguous mapping floor(h/(Hq/Hkv)); both key and value caches use this index.", "int32"),
        _tensor(prefix + "_QProjection", [H,2,2,4], ["Hq","Tq","Dk","ProjectionField"], projection["q"], "Actual product0,product1,unscaled,value for every active query coordinate, in h,i,d order."),
        _tensor(prefix + "_KProjection", [K,2,2,4], ["Hkv","Tk","Dk","ProjectionField"], projection["k"], "Actual product0,product1,unscaled,value for every active key coordinate, in g,j,d order."),
        _tensor(prefix + "_VProjection", [K,2,2,4], ["Hkv","Tk","Dv","ProjectionField"], projection["v"], "Actual product0,product1,unscaled,value for every active value coordinate, in g,j,d order."),
        _tensor(prefix + "_Q", [1,H,2,2], ["B","Hq","Tq","Dk"], e["Q"], "Actual projected and post-gain queries; every active query head remains independent of KV sharing."),
        _tensor(prefix + "_KCache", [1,K,2,2], ["B","Hkv","Tk","Dk"], e["K"], "Original active shared key storage, exactly 4*Hkv words. No Hq-expanded key cache exists."),
        _tensor(prefix + "_VCache", [1,K,2,2], ["B","Hkv","Tk","Dv"], e["V"], "Original active shared value storage, exactly 4*Hkv words. No Hq-expanded value cache exists."),
        _tensor(prefix + "_ScoreEvidence", [H,2,2,3], ["Hq","Tq","Tk","ScoreField"], score_evidence, "Actual product0,product1,dot for all score cells, including forbidden cells; direct two-product sum."),
        _tensor(prefix + "_Scores", shape, axes, e["scores"], "Every actual dot divided by the one saved sqrt(Dk) word, in h,i,j order."),
        _tensor(prefix + "_Allowed", shape, axes, [int(x) for x in e["allowed"]], "Allowed=1 iff the key bit is one and j<=i. Padding affects keys only; no query or head is removed.", "int32"),
        _tensor(prefix + "_RowMaxima", [1,H,2], ["B","Hq","Tq"], maxima, "Actual unchanged stableSoftmax Math.max over allowed scores, including its +0 preference on zero ties."),
        _tensor(prefix + "_AllowedCoordinates", [len(shifted),3], ["AllowedCell","IndexField"], coordinates, "h,i,j of each allowed shifted argument and exp occurrence, in h,i,j order; no forbidden placeholder.", "int32"),
        _tensor(prefix + "_Shifted", [len(shifted)], ["AllowedCell"], shifted, "Functional exp-argument witnesses from identical immutable score-minus-max operands; no physical interception or masked entry."),
        _tensor(prefix + "_Terms", shape, axes, terms, "Actual stableSoftmax exp outputs at allowed cells and literal +0 terms at masked cells."),
        _tensor(prefix + "_Denominators", [1,H,2], ["B","Hq","Tq"], denominators, "Actual stableSoftmax reduction (+0+term0)+term1, including each masked +0 addition."),
        _tensor(prefix + "_Probabilities", shape, axes, e["probabilities"], "Actual unchanged term/denominator words; masked probabilities are structural +0, never renormalized in a view."),
        _tensor(prefix + "_WeightedProducts", [H,2,2,2], ["Hq","Tq","Tk","Dv"], e["products"], "Actual probability*sharedValue for every h,i,j,d, including masked signed-zero products; B=1 omitted."),
        _tensor(prefix + "_WeightedPartials", [H,2,2,2], ["Hq","Tq","Tk","Dv"], e["partials"], "Actual previous+product after every h,i,j,d operation, from separate literal +0 feature accumulators; B=1 omitted."),
        _tensor(prefix + "_HeadOutputs", [1,H,2,2], ["B","Hq","Tq","Dv"], e["output"], "Final key1 partials copied per head,query,value-feature; no head averaging."),
        _tensor(prefix + "_Joined", [1,2,2*H], ["B","Tq","JoinedFeature"], e["joined"], "Indexed copies of all head-output coordinates in token,query-head,value-feature order; no output projection."),
        _tensor(prefix + "_CacheCounts", [6], ["CacheField"], counts.values(), "keyElements,valueElements,totalElements,logicalBytes,queryElements,scoreCells; exact analytical counts, not measured resident memory or traffic.", "int32"),
        _tensor(prefix + "_NativeArguments", [len(natives),2], ["Native","NativeField"], [x for leaf in natives for x in (leaf["input"], leaf["output"])], "Saved native input,output pairs in occurrence order: one sqrt, then allowed exp leaves. Serialization performs no native math."),
        _tensor(prefix + "_NativeKinds", [len(natives)], ["Native"], [0 if leaf["kind"] == "sqrt" else 1 for leaf in natives], "Native kind codes in occurrence order: sqrt=0,exp=1.", "int32"),
    ]
    texts = dict(
        rawFields=list(_FIELDS), projectionFields=["product0","product1","unscaled","value"], scoreFields=["product0","product1","dot"],
        allowedCoordinateFields=["h","i","j"], cacheFields=list(_CACHE_FIELDS), nativeIds=[leaf["id"] for leaf in natives], nativeKinds=[leaf["kind"] for leaf in natives], nativeFields=["input","output"],
        mappingPolicy="Hq and Hkv each range from one to four with Hq divisible by Hkv. Both K and V use floor(h/(Hq/Hkv)); modulo would change fixed head identities for GQA4/2. Hq=Hkv=1 is the coincident single-head endpoint.",
        projectionPolicy="One fixed basis source, all four disclosed matrices in each weight bank, then twelve independently editable post-projection gains. Compute active Q heads once, active K groups once, then active V groups once. Inactive gains remain captured, visible and validated.",
        attentionPolicy="Compute all raw scores before any row softmax, including forbidden cells. Causality and key validity intersect. One sqrt(Dk=2) supplies every score. Each query-head row keeps its own stable probabilities over original shared K/V storage.",
        nativePolicy="One actual sqrt, then allowed stableSoftmax exp outputs in h,i,j order. The shifted arguments repeat the same subtraction of identical immutable operands as the unchanged primitive: functional witnesses, not physical interception. Masked cells have no shifted field or native leaf. No native math occurs in serialization.",
        zeroPolicy="Every scalar operand, arithmetic result and copy uses binary64 WORD, including -0. Choices, dimensions, indices, decisions and analytical counts use VALUE. Projections and dots add their two products directly. Weighted feature folds start at +0 and retain every masked product and addition.",
        cachePolicy="KCache and VCache each retain 4*Hkv active binary64 words. Logical payload=(keyElements+valueElements)*elementBytes for one layer. The 2/4/8-byte assumption changes counts only; it performs no cast or quantization. Q, weights, outputs, evidence copies, array overhead, traffic and timing are excluded.",
        limitsPolicy="Hand-set forward-only attention toy: B=1,Tq=Tk=2,Din=Dk=Dv=2. No learned parameters, output projection, residual, FFN, tokenizer, generation, training, quantization, measured memory or speedup. Changing Hkv can change outputs and does not losslessly compress arbitrary MHA.")
    saved = _freeze(dict(state=s, natives=natives, tensors=tensors, texts=texts))
    # Preserve the adopted helper output/tensor identity after recursive freezing.
    return _support._FrozenDict(state=saved["state"], output=saved["tensors"][24], natives=saved["natives"], tensors=saved["tensors"], texts=saved["texts"])


def _check_public_binding():
    """Explicit source invariants; no supplied producer baseline is invented here."""
    if not __debug__:
        raise RuntimeError("Explicit IV61 binding check refuses optimized Python (-O).")
    for H, K in ((1,1),(2,1),(2,2),(3,1),(3,3),(4,1),(4,2),(4,4)):
        for key1 in (0,1):
            for element_bytes in (2,4,8):
                trace = group_trace()
                result = evaluate_grouped(dict(DEFAULT_IV61, Hq=H, Hkv=K, key1=key1, elementBytes=element_bytes, q3=-0.0), trace, "pub")
                assert tuple(result) == ("state", "output", "natives", "tensors", "texts")
                assert result["output"] is result["tensors"][24]
                assert len(result["tensors"]) == 28 and len(result["texts"]) == 15
                assert len(trace.steps) == 23*H+8*K+2
                assert len(trace.outputs) == (67+key1)*H+32*K+7
                assert sum(len(t["values"]) for t in result["tensors"]) == 78+77*H+40*K+7*H*(2+key1)
                assert result["tensors"][25]["values"][3] == 8*K*element_bytes
                assert result["tensors"][10]["shape"] == result["tensors"][11]["shape"] == [1,K,2,2]
                assert tuple(trace.steps[-1]["inputs"]) == ("B","Tq","Tk","Hq","Hkv","Dk","Dv","elementBytes")
                assert _word(result["tensors"][0]["values"][6]) == _word(-0.0)
                for n, frame in enumerate(trace.steps):
                    assert tuple(frame) == ("id","label","equation","explanation","inputs","outputs")
                    for field, value in frame["outputs"].items():
                        assert _word(trace.outputs[frame["id"] + "_" + field]) == _word(value)
                for t in result["tensors"]:
                    assert tuple(t) == ("id","shape","axes","dtype","values","provenance","precision")
                _check_copies(result, trace, "pub")
                for n, leaf in enumerate(result["natives"]):
                    assert tuple(leaf) == ("id","kind","input","output")
                    assert _word(leaf["input"]) == _word(result["tensors"][26]["values"][2*n])
                    assert _word(leaf["output"]) == _word(result["tensors"][26]["values"][2*n+1])
                for h in range(H):
                    for i in range(2):
                        for j in range(2):
                            offset = (h*2+i)*2+j
                            if not result["tensors"][14]["values"][offset]:
                                assert _word(result["tensors"][18]["values"][offset]) == _word(0.0)
                                assert _word(result["tensors"][20]["values"][offset]) == _word(0.0)
                try:
                    result["output"]["values"][0] = 9.0
                except TypeError:
                    pass
                else:
                    raise AssertionError("Public tensor is mutable.")
    # Callback sees the completely finished independent graph, even on its first frame.
    from unittest.mock import patch
    graph = _scalar_graph(dict(DEFAULT_IV61), "observer")
    seen = []
    class Observer:
        def add(self, identifier, label, equation, explanation, inputs, outputs):
            if not __debug__:
                raise RuntimeError("Explicit IV61 public observer hook refuses optimized Python (-O).")
            seen.append(identifier)
            inputs.clear()
            outputs.clear()
            assert len(graph["evidence"]["natives"]) == 13
    with patch.object(sys.modules[__name__], "_scalar_graph", return_value=graph):
        evaluate_grouped(dict(DEFAULT_IV61), Observer(), "observer")
    assert seen[0] == "observer_map_0" and seen[-1] == "observer_cache"


def _word(value):
    """Explicit check-only word helper; never called by imports or normal queries."""
    if not __debug__:
        raise RuntimeError("Explicit IV61 word-check helper refuses optimized Python (-O).")
    import struct
    return struct.pack(">d", float(_numeric(value, "check operand")))


def _check_copies(result, trace, prefix):
    """Explicit saved-copy checks only; native captures are not accuracy references."""
    if not __debug__:
        raise RuntimeError("Explicit IV61 copy check refuses optimized Python (-O).")
    tensors = result["tensors"]
    frames = {frame["id"]: frame for frame in trace.steps}
    leaves = {leaf["id"]: leaf for leaf in result["natives"]}
    H = int(result["state"]["Hq"])
    divisor = leaves[prefix+"_sqrt"]["output"]
    assert _word(frames[prefix+"_sqrt"]["outputs"]["divisor"]) == _word(divisor)
    allowed_ordinal = 0
    for h in range(H):
        g = tensors[5]["values"][h]
        for i in range(2):
            row = frames[f"{prefix}_row_{h}_{i}"]
            assert _word(row["outputs"]["max"]) == _word(tensors[15]["values"][h*2+i])
            assert _word(row["outputs"]["denominator"]) == _word(tensors[19]["values"][h*2+i])
            for j in range(2):
                score_offset = (h*2+i)*2+j
                score = frames[f"{prefix}_score_{h}_{i}_{j}"]
                assert _word(score["inputs"]["divisor"]) == _word(divisor)
                assert _word(score["outputs"]["score"]) == _word(tensors[13]["values"][score_offset])
                assert _word(row["inputs"][f"score{j}"]) == _word(tensors[13]["values"][score_offset])
                assert _word(row["outputs"][f"term{j}"]) == _word(tensors[18]["values"][score_offset])
                assert _word(row["outputs"][f"probability{j}"]) == _word(tensors[20]["values"][score_offset])
                leaf_id = f"{prefix}_exp_{h}_{i}_{j}"
                if tensors[14]["values"][score_offset]:
                    leaf = leaves[leaf_id]
                    assert _word(row["outputs"][f"shifted{j}"]) == _word(leaf["input"])
                    assert _word(tensors[17]["values"][allowed_ordinal]) == _word(leaf["input"])
                    assert tensors[16]["values"][3*allowed_ordinal:3*allowed_ordinal+3] == [h,i,j]
                    assert _word(row["outputs"][f"term{j}"]) == _word(leaf["output"])
                    allowed_ordinal += 1
                else:
                    assert leaf_id not in leaves and f"shifted{j}" not in row["outputs"]
                for d in range(2):
                    weighted = frames[f"{prefix}_weighted_{h}_{i}_{j}_{d}"]
                    offset = score_offset*2+d
                    assert weighted["inputs"]["g"] == g
                    assert _word(weighted["inputs"]["probability"]) == _word(tensors[20]["values"][score_offset])
                    assert _word(weighted["inputs"]["value"]) == _word(tensors[11]["values"][(g*2+j)*2+d])
                    assert _word(weighted["outputs"]["product"]) == _word(tensors[21]["values"][offset])
                    assert _word(weighted["outputs"]["sum"]) == _word(tensors[22]["values"][offset])
                    previous = 0.0 if j == 0 else tensors[22]["values"][offset-2]
                    assert _word(weighted["inputs"]["previous"]) == _word(previous)
            for d in range(2):
                source, target = (h*2+i)*2+d, (i*H+h)*2+d
                word = tensors[23]["values"][source]
                join = frames[f"{prefix}_join_{i}_{h}_{d}"]
                assert _word(word) == _word(tensors[22]["values"][((h*2+i)*2+1)*2+d])
                assert join["inputs"]["sourceOffset"] == source and join["inputs"]["destinationOffset"] == target
                assert _word(join["inputs"]["value"]) == _word(word)
                assert _word(join["outputs"]["value"]) == _word(word)
                assert _word(tensors[24]["values"][target]) == _word(word)
    assert allowed_ordinal == len(tensors[17]["values"])

3. IV61 chapter entry and ordinary CLI — complete file

derive_iv61(value) accepts one complete raw state, observes that original state once, calls the grouped helper and appends the final summary. It does not merge missing defaults into a supplied state. DEFAULT_IV61 supplies the disclosed reset state. run() takes zero Python arguments and reads its ordinary command-line mode from argv: a full JSON state, stdin selected by -, or the explicit local --self-check mode. Imports and ordinary calculations do not silently invoke self-checks; explicit local checks refuse optimized Python (-O), while ordinary input guards remain active.

Canonical native captures record that program’s actual sqrt/exp returns and their copies. Local scalar, storage and serializer checks are not independent transcendental authority. The separate oracle owns complete supplied-record verification, helper-selector reports and independently rounded native admission; Python’s math results are not its RN proof. The panels are source evidence; displaying them alone does not establish numerical correctness, canonical parity, accessible interaction or offline behavior.

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.

"""IV61 canonical entry and strict JSON CLI.

Source only; ALL checks UNRUN. Closure: this file, grouped_reference.py and
readonly decoder_reference.py. Normal imports and queries run zero checks.
"""
import importlib.util
import json
import math
from pathlib import Path
import sys
from types import ModuleType


def _trusted(module, path):
    return (type(module) is ModuleType and
            Path(getattr(module, "__file__", "")).resolve() == path and
            getattr(getattr(module, "__spec__", None), "origin", None) == str(path))


def _load_reference():
    path = Path(__file__).resolve().with_name("grouped_reference.py")
    support_path = path.with_name("decoder_reference.py")
    name, support_name = "_book_iv_p15_grouped_reference", "_book_iv_p15_grouped_decoder_support"
    if name in sys.modules:
        cached = sys.modules[name]
        if not _trusted(cached, path):
            raise ImportError("IV61 reference cache has an unexpected file identity.")
        support = sys.modules.get(support_name)
        if not _trusted(support, support_path) or getattr(cached, "_support", None) is not support:
            raise ImportError("IV61 reference and support cache identities disagree.")
        return cached
    spec = importlib.util.spec_from_file_location(name, path)
    if spec is None or spec.loader is None:
        raise ImportError("Cannot load adjacent grouped_reference.py.")
    had_support = support_name in sys.modules
    module = importlib.util.module_from_spec(spec)
    sys.modules[name] = module
    try:
        spec.loader.exec_module(module)
        if sys.modules.get(name) is not module or not _trusted(module, path):
            raise ImportError("IV61 reference cache identity changed while loading.")
        support = sys.modules.get(support_name)
        if not _trusted(support, support_path) or getattr(module, "_support", None) is not support:
            raise ImportError("IV61 reference and support cache identities disagree.")
    except BaseException:
        if sys.modules.get(name) is module:
            sys.modules.pop(name)
        owned = getattr(module, "_owned_support", None)
        if (not had_support and _trusted(owned, support_path) and
                sys.modules.get(support_name) is owned):
            sys.modules.pop(support_name)
        raise
    return module


_reference = _load_reference()
NumericalFault = _reference.NumericalFault
group_state = _reference.group_state
group_trace = _reference.group_trace
evaluate_grouped = _reference.evaluate_grouped
DEFAULT_IV61 = _reference.DEFAULT_IV61
_KNOWN_CODES = ("INVALID_INPUT", "SHAPE_MISMATCH", "NONFINITE", "UNSUPPORTED_SIZE", "FULLY_MASKED_ROW", "UNAVAILABLE")


def _known(fault):
    return type(fault) is NumericalFault and fault.code in _KNOWN_CODES


def _finish(evaluated, trace):
    state, tensors, natives = evaluated["state"], evaluated["tensors"], evaluated["natives"]
    counts = tensors[25]["values"]
    summary = dict(Hq=state["Hq"], Hkv=state["Hkv"], joinedWidth=evaluated["output"]["shape"][2],
                   **dict(zip(_reference._CACHE_FIELDS, counts)), sqrtCalls=1, expCalls=len(natives)-1,
                   nativeElementaryCalls=len(natives), frames=len(trace.steps)+1, tensorCount=len(tensors))
    trace.add("finish", "Retain every query head and count the original shared cache", "output=grouped_Joined; logicalBytes=grouped_CacheCounts[3]",
              "Copy the actual joined width and saved one-layer logical counts after all numerical work. Head sharing changes the original K/V storage, while each query head retains its own output. Native/frame/tensor counts describe this source graph, not measured hardware work.",
              {key: summary[key] for key in _reference._SUMMARY_FIELDS[:9]}, summary)
    texts = dict(evaluated["texts"])
    texts.update(
        graphStages=["Basis source and fixed weight banks", "Contiguous query-head to KV-group mapping", "Project Q, then shared K, then shared V; apply gains last", "All head-specific scores", "Causal and key-valid stable probabilities", "Every weighted value product and ordered sum", "Copy every head into the join", "One-layer logical cache accounting"],
        graphTensorIds=["grouped_X", "grouped_HeadToGroup", "grouped_Q", "grouped_KCache", "grouped_VCache", "grouped_Scores", "grouped_Allowed", "grouped_Probabilities", "grouped_HeadOutputs", "grouped_Joined", "grouped_CacheCounts"],
        tracePolicy="The exact unchanged decoderTrace factory captures detached finite frame operands once, rejects duplicate or empty IDs before operands, and applies its 512-frame cap after operands. No wrapper frame precedes complete raw, prefix and whole-mask preflight. Every frame output is copied to root outputs as frameId_key; finish is last.",
        summaryPolicy="All fourteen primary summary fields are VALUE dimensions or source counts. Cache summaries copy grouped_CacheCounts; joinedWidth copies the actual Joined shape. Binary64 WORD operands/results remain in tensors, natives, frame fields and aliases, including signed zero. Helper output is the same saved Joined TensorRecord exposed in its tensor list.",
        validationPolicy="SOURCE IMPLEMENTATION ONLY. All tests, independent executable authority, canonical parity, typecheck, build, browser, accessibility and offline checks are UNRUN under the human FluxGeo hold. Source adoption and validation belong to the owner; this record is not runtime acceptance.")
    outputs = dict(summary)
    for frame in trace.steps:
        for key, value in frame["outputs"].items():
            alias = frame["id"] + "_" + key
            if alias in outputs:
                raise RuntimeError("IV61 output aliases must be unique.")
            outputs[alias] = value
    return _reference._freeze(dict(status="defined", outputs=outputs, steps=trace.steps, tensors=tensors, texts=texts))


def derive_iv61(value):
    """Exactly one original raw-state observation; no preliminary duplicate capture."""
    try:
        trace = group_trace()
        return _finish(evaluate_grouped(value, trace, "grouped"), trace)
    except NumericalFault as fault:
        if not _known(fault):
            raise
        return _reference._freeze(dict(status="unavailable", code=fault.code, reason=fault.reason))


class _ParseFault(ValueError):
    pass


def _pairs(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise _ParseFault("Duplicate JSON field: " + key)
        result[key] = value
    return result


def _constant(value):
    raise _ParseFault("Nonfinite JSON constant: " + value)


def _integer(source):
    if source == "-0":
        return -0.0
    if len(source.lstrip("-")) > 309:
        raise _ParseFault("JSON integer exceeds the bounded numeric domain.")
    return int(source)


def _number(source):
    value = float(source)
    if not math.isfinite(value):
        raise _ParseFault("JSON number must be finite.")
    return value


def strict_json(source):
    try:
        return json.loads(source, object_pairs_hook=_pairs, parse_constant=_constant, parse_int=_integer, parse_float=_number)
    except json.JSONDecodeError as fault:
        raise _ParseFault(str(fault)) from fault


def _trace_view(trace):
    return _reference._freeze(dict(outputs=trace.outputs, steps=trace.steps))


def check_boundaries():
    """Parser, finite/domain order, inactive gains, exact faults and preflight isolation."""
    if not __debug__:
        raise RuntimeError("Explicit IV61 boundary check refuses optimized Python (-O).")
    assert _reference._word(strict_json("-0")) == _reference._word(-0.0)
    assert _reference._word(strict_json("-0.0")) == _reference._word(-0.0)
    assert len(str(strict_json("1"*309))) == 309
    for source in ('{"q0":1,"q0":2}', '{"a":{"x":1,"x":2}}', "NaN", "Infinity", "-Infinity", "1e999", "1"*310):
        try:
            strict_json(source)
        except _ParseFault:
            pass
        else:
            raise AssertionError("Malformed JSON was accepted.")
    for value, expected_code, expected_reason in (
            ({}, "INVALID_INPUT", "state must have exactly " + ", ".join(_reference._FIELDS) + " as own fields."),
            (dict(DEFAULT_IV61, Hq=0, v3=float("nan")), "NONFINITE", "state.v3 must be an actual finite number."),
            (dict(DEFAULT_IV61, Hq=3, Hkv=2), "INVALID_INPUT", "Hq must be divisible by Hkv, with Hkv no greater than Hq."),
            (dict(DEFAULT_IV61, Hq=1, Hkv=1, q3=2), "INVALID_INPUT", "q3 must be between -1 and 1."),
            (dict(DEFAULT_IV61, key0=True), "NONFINITE", "state.key0 must be an actual finite number."),
            (dict(DEFAULT_IV61, k3=10**310), "NONFINITE", "state.k3 must be an actual finite number.")):
        result = derive_iv61(value)
        assert tuple(result) == ("status", "code", "reason")
        assert result == dict(status="unavailable", code=expected_code, reason=expected_reason)
    trace = group_trace()
    trace.add("prior", "Prior", "x=x", "Saved before a rejected evaluation.", dict(x=-0.0), dict(x=-0.0))
    before = _trace_view(trace)
    for value, prefix, code in ((dict(DEFAULT_IV61, Hq=3, Hkv=2, key0=0), "!", "INVALID_INPUT"),
                                (dict(DEFAULT_IV61, key0=0), "!", "INVALID_INPUT"),
                                (dict(DEFAULT_IV61, key0=0), "masked", "FULLY_MASKED_ROW")):
        try:
            evaluate_grouped(value, trace, prefix)
        except NumericalFault as fault:
            assert fault.code == code
        else:
            raise AssertionError("Invalid preflight was accepted.")
        assert _trace_view(trace) == before
    assert group_state(dict(DEFAULT_IV61, key0=-0.0))["key0"] == 0
    assert _reference._word(group_state(dict(DEFAULT_IV61, key0=-0.0))["key0"]) == _reference._word(-0.0)


def check_loading():
    """Ownership-scoped own/dependency rollback; never delete a replacement incumbent."""
    if not __debug__:
        raise RuntimeError("Explicit IV61 loading check refuses optimized Python (-O).")
    from importlib.machinery import ModuleSpec
    from unittest.mock import patch
    name, support_name = "_book_iv_p15_grouped_reference", "_book_iv_p15_grouped_decoder_support"
    path = Path(__file__).resolve().with_name("grouped_reference.py")
    support_path = path.with_name("decoder_reference.py")
    original = {key: sys.modules[key] for key in (name, support_name) if key in sys.modules}
    old_owned = getattr(_reference, "_owned_support", None)
    had_owned = hasattr(_reference, "_owned_support")
    sentinel = RuntimeError("loader sentinel")
    replacement = ModuleType("unexpected replacement")
    owned = ModuleType(support_name)
    owned.__file__ = str(support_path)
    owned.__spec__ = ModuleSpec(support_name, None, origin=str(support_path))
    class LoadHook:
        def __init__(self, target, replace_own, replace_dependency):
            if not __debug__:
                raise RuntimeError("Explicit IV61 load-hook constructor refuses optimized Python (-O).")
            self.target, self.replace_own, self.replace_dependency = target, replace_own, replace_dependency
        def create_module(self, spec):
            if not __debug__:
                raise RuntimeError("Explicit IV61 loader creation hook refuses optimized Python (-O).")
            return None
        def exec_module(self, module):
            if not __debug__:
                raise RuntimeError("Explicit IV61 loader execution hook refuses optimized Python (-O).")
            if self.target == name:
                if support_name not in sys.modules:
                    module._owned_support = owned
                    sys.modules[support_name] = owned
                if self.replace_dependency:
                    sys.modules[support_name] = replacement
            if self.replace_own:
                sys.modules[self.target] = replacement
            raise sentinel
    try:
        for key, loader in ((name, _load_reference), (support_name, _reference._load_support)):
            for incumbent in (None, replacement):
                sys.modules[key] = incumbent
                try:
                    loader()
                except ImportError:
                    assert sys.modules[key] is incumbent
                else:
                    raise AssertionError("Unexpected cache incumbent was accepted.")
        for target, loader, location in ((name, _load_reference, path), (support_name, _reference._load_support, support_path)):
            for replace_own in (False, True):
                for replace_dependency in (False, True):
                    for dependency_mode in ("absent", "trusted", "none"):
                        sys.modules.pop(name, None)
                        sys.modules.pop(support_name, None)
                        if target == name and dependency_mode != "absent":
                            sys.modules[support_name] = _reference._support if dependency_mode == "trusted" else None
                        spec = ModuleSpec(target, LoadHook(target, replace_own, replace_dependency), origin=str(location))
                        with patch.object(importlib.util, "spec_from_file_location", return_value=spec):
                            try:
                                loader()
                            except RuntimeError as fault:
                                assert fault is sentinel
                            else:
                                raise AssertionError("Unknown loader failure was hidden.")
                        if replace_own:
                            assert sys.modules[target] is replacement
                        else:
                            assert target not in sys.modules
                        if target == name:
                            if replace_dependency:
                                assert sys.modules[support_name] is replacement
                            elif dependency_mode == "trusted":
                                assert sys.modules[support_name] is _reference._support
                            elif dependency_mode == "none":
                                assert support_name in sys.modules and sys.modules[support_name] is None
                            else:
                                assert support_name not in sys.modules
    finally:
        for key in (name, support_name):
            sys.modules.pop(key, None)
        sys.modules.update(original)
        if had_owned:
            _reference._owned_support = old_owned
        elif hasattr(_reference, "_owned_support"):
            del _reference._owned_support
    assert _load_reference() is _reference
    assert _reference._load_support() is _reference._support
    assert group_trace is _reference._support.decoder_trace
    assert {Path(__file__).resolve(), Path(_reference.__file__).resolve(), Path(_reference._support.__file__).resolve()} == {
        path.with_name("iv61.py"), path, support_path}


def check_unknown():
    """Unknown code/subclass/programmer faults preserve exact identity on every public path."""
    if not __debug__:
        raise RuntimeError("Explicit IV61 unknown check refuses optimized Python (-O).")
    from unittest.mock import patch
    class UnknownNumericalFault(NumericalFault):
        pass
    for sentinel in (RuntimeError("unknown sentinel"), NumericalFault("UNKNOWN", "unknown code"), UnknownNumericalFault("INVALID_INPUT", "unknown class")):
        with patch.object(_reference, "_capture_state", side_effect=sentinel):
            for public in (derive_iv61, group_state):
                try:
                    public(dict(DEFAULT_IV61))
                except BaseException as fault:
                    assert fault is sentinel
                else:
                    raise AssertionError("Unknown exception identity was lost.")
            try:
                evaluate_grouped(dict(DEFAULT_IV61), group_trace(), "unknown")
            except BaseException as fault:
                assert fault is sentinel
            else:
                raise AssertionError("Helper swallowed unknown exception.")


def check_root():
    """Canonical public invariants; independent D alone owns admission."""
    if not __debug__:
        raise RuntimeError("Explicit IV61 root check refuses optimized Python (-O).")
    from unittest.mock import patch
    original = _reference._capture_state
    seen = []
    def capture(value):
        if not __debug__:
            raise RuntimeError("Explicit IV61 once-capture hook refuses optimized Python (-O).")
        seen.append(value)
        return original(value)
    state = dict(DEFAULT_IV61, q0=-0.0, q2=-0.0)
    with patch.object(_reference, "_capture_state", side_effect=capture):
        record = derive_iv61(state)
    assert seen == [state] and seen[0] is state
    assert tuple(record) == ("status", "outputs", "steps", "tensors", "texts")
    assert tuple(record["outputs"])[:14] == _reference._SUMMARY_FIELDS
    assert len(record["steps"]) == 111 and len(record["outputs"]) == 371
    assert len(record["tensors"]) == 28 and len(record["texts"]) == 20
    assert record["steps"][-1]["id"] == "finish"
    assert tuple(record["steps"][-1]["outputs"]) == _reference._SUMMARY_FIELDS
    assert record["outputs"]["frames"] == len(record["steps"])
    for frame in record["steps"]:
        for key, value in frame["outputs"].items():
            assert _reference._word(record["outputs"][frame["id"]+"_"+key]) == _reference._word(value)
    for source, arguments in ((0, ()), (1, (dict(DEFAULT_IV61), dict(DEFAULT_IV61)))):
        try:
            derive_iv61(*arguments)
        except TypeError:
            pass
        else:
            raise AssertionError("derive_iv61 must have one argument.")


def source_self_check():
    """Explicit aggregate; no query/import path invokes this or a child implicitly."""
    if not __debug__:
        raise RuntimeError("Explicit IV61 aggregate check refuses optimized Python (-O).")
    _reference.check_mechanism()
    _reference.check_captures()
    _reference.check_public()
    check_boundaries()
    check_loading()
    check_unknown()
    check_root()
    check_cli()
    check_trace_protocol()
    check_probes()




def run():
    """Zero Python arguments: default/noargs, full JSON replacement, stdin or explicit checks."""
    args = sys.argv[1:]
    if args == ["--self-check"]:
        source_self_check()
        return 0
    if len(args) > 1 or (args and args[0].startswith("--")):
        print("Usage: iv61.py [JSON|-|--self-check]", file=sys.stderr)
        return 2
    if not args:
        value = dict(DEFAULT_IV61)
    else:
        try:
            value = strict_json(sys.stdin.read() if args[0] == "-" else args[0])
        except _ParseFault as fault:
            if type(fault) is not _ParseFault:
                raise
            print(json.dumps(dict(status="unavailable", code="INVALID_INPUT", reason=str(fault)), allow_nan=False))
            return 0
    print(json.dumps(derive_iv61(value), allow_nan=False))
    return 0


def check_cli():
    """Direct real CLI default/replacement/stdin/known faults; unsupported modes are misuse."""
    if not __debug__:
        raise RuntimeError("Explicit IV61 CLI check refuses optimized Python (-O).")
    from contextlib import redirect_stdout, redirect_stderr
    from io import StringIO
    from unittest.mock import patch
    for args, stdin, status in ((["--unknown"], "", 2), (["{}", "{}"], "", 2),
            (["--verify"], "", 2), (["--verify", "{}"], "", 2),
            (["{}"], "", 0), (["-"], "{}", 0), (["NaN"], "", 0),
            (['{"Hq":1,"Hq":2}'], "", 0)):
        output, errors = StringIO(), StringIO()
        with patch.object(sys, "argv", ["iv61.py"] + args), patch.object(sys, "stdin", StringIO(stdin)):
            with redirect_stdout(output), redirect_stderr(errors):
                assert run() == status
        if status == 2:
            assert not output.getvalue() and errors.getvalue().startswith("Usage:")
        else:
            result = strict_json(output.getvalue())
            assert tuple(result) == ("status", "code", "reason")
            assert result["status"] == "unavailable" and result["code"] == "INVALID_INPUT"
            assert not errors.getvalue()
    for args, stdin in (([], ""), ([json.dumps(dict(DEFAULT_IV61))], ""), (["-"], json.dumps(dict(DEFAULT_IV61)))):
        output = StringIO()
        with patch.object(sys, "argv", ["iv61.py"]+args), patch.object(sys, "stdin", StringIO(stdin)), redirect_stdout(output):
            assert run() == 0
        result = strict_json(output.getvalue())
        assert tuple(result) == ("status","outputs","steps","tensors","texts")
        assert result["status"] == "defined" and result["outputs"]["frames"] == 111
    sentinel = RuntimeError("CLI unknown sentinel")
    with patch.object(sys, "argv", ["iv61.py"]), patch.object(_reference, "_capture_state", side_effect=sentinel):
        try:
            run()
        except RuntimeError as fault:
            assert fault is sentinel
        else:
            raise AssertionError("CLI hid an unknown query exception.")
    try:
        run([])
    except TypeError:
        pass
    else:
        raise AssertionError("run must have zero Python arguments.")


def check_trace_protocol():
    """Direct generic collector copies, canonical indices, once capture and typed failures."""
    if not __debug__:
        raise RuntimeError("Explicit IV61 trace protocol check refuses optimized Python (-O).")
    trace = group_trace()
    trace.add("_", "Alias", "x=x", "__proto__ assignment is omitted.", {}, {"proto__":1.0})
    assert "__proto__" not in trace.outputs
    trace.add("a", "First", "x=x", "First alias.", {"2":2, "0":-0.0, "01":1}, {"b_c":-0.0})
    trace.add("a_b", "Second", "x=x", "Overwrite same alias.", {}, {"c":1.0})
    assert tuple(trace.steps[1]["inputs"]) == ("0", "2", "01")
    assert trace.outputs["a_b_c"] == 1.0
    before = _trace_view(trace)
    try:
        trace.add("a", "Duplicate", "x=x", "Reject before nonfinite operands.", {"x":True}, {})
    except NumericalFault as fault:
        assert fault.code == "INVALID_INPUT" and fault.reason == "Trace IDs must be nonempty and unique."
    else:
        raise AssertionError("Duplicate trace ID was accepted.")
    assert _trace_view(trace) == before
    class Items:
        def __init__(self):
            if not __debug__:
                raise RuntimeError("Explicit IV61 items constructor refuses optimized Python (-O).")
            self.calls = 0
        def items(self):
            if not __debug__:
                raise RuntimeError("Explicit IV61 items capture hook refuses optimized Python (-O).")
            self.calls += 1
            return [("x", -0.0)]
    values = Items()
    trace.add("once", "Once", "x=x", "Read trusted items once.", values, {})
    assert values.calls == 1 and _reference._word(trace.steps[-1]["inputs"]["x"]) == _reference._word(-0.0)


def check_probes():
    """Real canonical declarations/aliases and failure inside the first real aggregate check."""
    if not __debug__:
        raise RuntimeError("Explicit IV61 source probes refuse optimized Python (-O).")
    from unittest.mock import patch
    for function, arity in ((group_state,1), (group_trace,0), (evaluate_grouped,3), (derive_iv61,1), (run,0),
                            (_reference._scalar_graph,2), (_reference._Capture.__init__,1)):
        assert function.__code__.co_argcount == arity
    assert group_state is _reference.group_state and evaluate_grouped is _reference.evaluate_grouped
    assert DEFAULT_IV61 is _reference.DEFAULT_IV61
    assert group_trace is _reference._support.decoder_trace
    assert Path(group_state.__code__.co_filename).resolve() == Path(_reference.__file__).resolve()
    assert Path(derive_iv61.__code__.co_filename).resolve() == Path(__file__).resolve()
    sentinel = RuntimeError("inside-real-first-check")
    first_code = _reference.check_mechanism.__code__
    with patch.object(_reference, "_scalar_graph", side_effect=sentinel):
        for entry in (_reference.check_mechanism, source_self_check):
            try:
                entry()
            except RuntimeError as fault:
                assert fault is sentinel
            else:
                raise AssertionError("Real first-check error did not escape.")
        with patch.object(sys, "argv", ["iv61.py", "--self-check"]):
            try:
                run()
            except RuntimeError as fault:
                assert fault is sentinel
            else:
                raise AssertionError("CLI hid real first-check failure.")
    assert _reference.check_mechanism.__code__ is first_code


if __name__ == "__main__":
    raise SystemExit(run())

Carry the distinction forward

Keep four takeaways: queries retain their own paths; an explicit map selects one original K/V group for each path; joining preserves every query-head feature; and logical payload adds K and V once under an explicit byte assumption. The next curriculum topic, Mixture-of-Experts Routing, asks which feed-forward experts process a token.

Reading the exact worksheets alongside the saved scalar trace

The symbols s,r,t,A,C shorten exact-real reasoning. The scalar calculation divides each saved direct dot by the one saved sqrt(2) result; multiplying by a rounded reciprocal instead would change its operation sequence. It calculates allowed shifts by subtracting the saved allowed maximum and uses the actual returned exponential at each allowed key. It does not substitute a positive exponential and reciprocal, compute t by squaring an earlier exponential, or insert the closed-form worksheet ratios in place of those operations. Products, denominators, value partials and indexed copies consume their actual saved operands.