IV-62 / Part XV · Modern LLM Architectures
Mixture-of-Experts Routing
Follow all router products, selected gates, real three-hidden-unit expert networks, and the consequences of partial or full capacity drops.
Review the ideas this chapter uses
A feed-forward network applies the same small network to every token. A mixture of experts, or MoE, keeps several networks and routes each token to a few of them. We will follow three two-number token vectors from router multiplication through the chosen networks to their combined output. The weights are hand-set: “expert” names a network’s role, not evidence that it has learned a skill.
Learning objective: Compute router scores, top-k dispatch and gated expert outputs.
The lab computes the actual router and every admitted expert from your current inputs. The worksheets below derive its starting numbers over exact reals; the saved trace retains the binary64 operations, returned exponential values and intermediate copies. The models and checks are authored source; runtime validation remains deferred.
Route a small batch through real experts
A router gives each token row three scores and selects one or two expert networks. Each admitted expert really computes a three-feature hidden layer and a two-feature output; the saved gates weight those results.
In the starting worksheet, expert0 and expert1 each fill two slots before token2 arrives. Token2 therefore has two dropped assignments and a defined zero branch output. Change capacity to3 to admit it, or set r2=-1 to explore a partial drop. These statements describe that fixed starting worksheet.
Open the feature/gain/bias groups to edit all fifteen floating operands, including -0 and unused experts. The two menus choose topK and capacity. Invalid or fractional menu values withhold results and grading; correct the draft or choose Reset example. Editing, reset and trace selection clear graded answers; opening a disclosure preserves them.
Six input features: original tokens 0, 1 and 2
Router gains: multiply the completed two-product sum
Router biases: add after the gain
Expert output gains: apply after the complete real MLP, including when gain is zero
Exact starting inputs for this saved calculation
topK 2. capacity 2. tokens 3. experts 3. Router at token 0, expert 0. Compute both feature products, add them directly, multiply this expert router gain, then add its bias last. Zero coefficients and capacity zero do not skip work.
Router at token 0, expert 0
product0=x0*w0; product1=x1*w1; sum=product0+product1; scaled=sum*gain; logit=scaled+bias
Compute both feature products, add them directly, multiply this expert router gain, then add its bias last. Zero coefficients and capacity zero do not skip work.
Saved inputs
- t
- 0
- expert
- 0
- x0
- 1
- x1
- 0
- w0
- 1
- w1
- 0
- gain
- 1
- bias
- 0
Saved outputs
- product0
- 1
- product1
- 0
- sum
- 1
- scaled
- 1
- logit
- 1
Selected saved step moe_router_0_0. Router at token 0, expert 0. Equation: product0=x0*w0; product1=x1*w1; sum=product0+product1; scaled=sum*gain; logit=scaled+bias. Compute both feature products, add them directly, multiply this expert router gain, then add its bias last. Zero coefficients and capacity zero do not skip work. Saved inputs: t=0; expert=0; x0=1; x1=0; w0=1; w1=0; gain=1; bias=0. Saved outputs: product0=1; product1=0; sum=1; scaled=1; logit=1.
One router, real experts, three original token rows
6 selected assignments; 4 admitted, 2 dropped; 1 fully lost tokens and 0 partially dropped tokens. A token is one row with two features. An assignment is one token sent to one selected expert; it is the unit capacity counts.
Untrained fixed toy; forward only. No attention, residual, load-balancing loss, gradients, training, sampling, model API, measured speed or quality claim. Capacity counts assignments, not features; discarded signed messages can remove cancellation. All runtime validation remains deferred.
| Original token | X row | Logits over all3 experts | Full P over all3 experts | Selected IDs in rank order | Pre-drop gates | Admitted flags | Expert slots (-1=dropped) | Kept/lost gate mass | Fully lost / partial flags | Y row |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | [1, 0] | [1, 0, -1] | [0.6652409557748218, 0.24472847105479764, 0.09003057317038046] | [0, 1] | [0.7310585786300048, 0.26894142136999516] | [1, 1] | [0, 0] | 1 / 0 | 0 / 0 | [1.327646446575012, 0.5965878679450072] |
| 1 | [0, 1] | [0, 1, -1] | [0.24472847105479764, 0.6652409557748218, 0.09003057317038046] | [1, 0] | [0.7310585786300048, 0.26894142136999516] | [1, 1] | [1, 1] | 1 / 0 | 0 / 0 | [0, 1.7310585786300048] |
| 2 | [1, 1] | [1, 1, -2] | [0.4878555511603684, 0.4878555511603684, 0.024288897679263205] | [0, 1] | [0.5, 0.5] | [0, 0] | [-1, -1] | 0 / 1 | 1 / 0 | [0, 0] |
Reset expert loads each evaluation; visit token then rank. Admit if that expert load is below capacity, allocate its old count as slot and increment only on admission. No reroute, fallback, implicit residual or post-drop redistribution. Fully lost means no admitted assignment, not merely a zero vector.
Eight saved computation stages
- Fixed router and full meaningful M3 expert banks
- All nine router logits
- Full stable three-expert probabilities
- Computed-logit ranking and pre-drop selected gates
- Token/rank first-come per-expert capacity
- Only admitted actual M3 expert invocations
- Expert post-output gains
- Original-token feature/rank gated combine and explicit drop messages
moe_Xmoe_RouterWeightsmoe_Logitsmoe_Probabilitiesmoe_Rankingmoe_SelectedExpertsmoe_Gatesmoe_Admittedmoe_Slotsmoe_Loadsmoe_KeptMassmoe_LostMassmoe_GatedContributionsmoe_Ymoe_Counts
Raw inputs and fixed banks remain visible even when capacity is zero
| Offset | Field | Saved value |
|---|---|---|
| 0 | topK | 2 |
| 1 | capacity | 2 |
| 2 | x00 | 1 |
| 3 | x01 | 0 |
| 4 | x10 | 0 |
| 5 | x11 | 1 |
| 6 | x20 | 1 |
| 7 | x21 | 1 |
| 8 | r0 | 1 |
| 9 | r1 | 1 |
| 10 | r2 | 1 |
| 11 | b0 | 0 |
| 12 | b1 | 0 |
| 13 | b2 | 0 |
| 14 | e0 | 1 |
| 15 | e1 | 1 |
| 16 | e2 | 1 |
Raw X has shape [B=1,T=3,D=2]. The router weight matrix [D=2,Expert=3] transforms each two-feature row into three scores. Each expert expands to three hidden features, then returns two output features. Fixed banks include every expert, but a fixed matrix being visible does not mean its MLP ran.
Only admitted assignments compute an expert MLP
Only accepted invocations have Context, Input, detached namespaced unchanged W1,b1,Z,Hidden,W2,b2,F tensors and PostGain. Prefix records original token/rank/expert/slot; unchanged FFN frames use local b=0,t=0. No unselected or dropped hidden/output tensor is fabricated.
| Invocation prefix | Original token/rank/expert/slot | Source offset / local batch / local token | Copied input | Three hidden coordinates | F before output gain | PostGain |
|---|---|---|---|---|---|---|
| moe_t0_r0_e0_s0 | [0, 0, 0, 0] | [0, 0, 0] | [1, 0] | [1, 0, 1] | [2, 1] | [2, 1] |
| moe_t0_r1_e1_s0 | [0, 1, 1, 0] | [0, 0, 0] | [1, 0] | [1, 0, 1] | [-0.5, -0.5] | [-0.5, -0.5] |
| moe_t1_r0_e1_s1 | [1, 0, 1, 1] | [2, 0, 0] | [0, 1] | [0, 1, 0] | [0, 2] | [0, 2] |
| moe_t1_r1_e0_s1 | [1, 1, 0, 1] | [2, 0, 0] | [0, 1] | [0, 1, 0] | [0, 1] | [0, 1] |
Complete every admitted M3 affine/ReLU/affine before multiplying expert post-output gain. For each original token and feature start +0 and fold selected ranks: admitted gate times saved postgain output, dropped literal +0 message, then addition. Keep and lost gate masses are separate +0 rank folds.
Nine saved exp occurrences, including functional argument witnesses
Exactly nine actual stableSoftmax exp calls in token/expert order at every valid capacity, including zero; no sqrt/log. Returned max/terms/denominator/probabilities are actual helper values. Argument witnesses repeat identical immutable-operand subtractions; no physical interception and no native call during projection or serialization.
Future independent admission binds each native ID/kind/WORD input before positive finite output and CAP4 distance from independent RN-even exp, argument [-256,0]; exp(0) must be exact +1. Actual router shifts lie in [-12,0]. This declared policy is not executed evidence or a libm WORD-parity claim.
| Occurrence | ID | Kind | Saved argument | Actual return |
|---|---|---|---|---|
| 0 | moe_exp_0_0 | exp | 0 | 1 |
| 1 | moe_exp_0_1 | exp | -1 | 0.36787944117144233 |
| 2 | moe_exp_0_2 | exp | -2 | 0.1353352832366127 |
| 3 | moe_exp_1_0 | exp | -1 | 0.36787944117144233 |
| 4 | moe_exp_1_1 | exp | 0 | 1 |
| 5 | moe_exp_1_2 | exp | -2 | 0.1353352832366127 |
| 6 | moe_exp_2_0 | exp | 0 | 1 |
| 7 | moe_exp_2_1 | exp | 0 | 1 |
| 8 | moe_exp_2_2 | exp | -3 | 0.049787068367863944 |
Every actual saved tensor, in original record order (76 tensors)
Every floating operand, intermediate and copy retains binary64 WORD including -0. Only raw topK/capacity and explicit dimensions, IDs, indices, decisions, slots, loads and source counts use VALUE. Structural drop contributions and accumulator initializers are literal +0. ReLU uses unchanged Math.max(+0,z).
These tables show the stored words without display rounding. Indices only locate copies; the view does not calculate router scores, gates, expert outputs or sums.
moe_Raw
RawField=17 · shape [17] · float64 · declared display precision 8
Captured raw17 in rawFields order; topK/capacity are VALUE, all other raw cells WORD including -0.
| Outer storage row (zero-based) | RawField 0 | RawField 1 | RawField 2 | RawField 3 | RawField 4 | RawField 5 | RawField 6 | RawField 7 | RawField 8 | RawField 9 | RawField 10 | RawField 11 | RawField 12 | RawField 13 | RawField 14 | RawField 15 | RawField 16 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 2 | 2 | 1 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 1 | 1 | 1 |
moe_X
B=1 × T=3 × D=2 · shape [1,3,2] · float64 · declared display precision 8
Six actual raw input feature words in original token order; no lookup or token reordering.
| Outer storage row (zero-based) | D 0 | D 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 1 |
| 2 | 1 | 1 |
moe_RouterWeights
D=2 × Expert=3 · shape [2,3] · float64 · declared display precision 8
Fixed row-feature router matrix [[1,+0,-1],[+0,1,-1]]; gains are applied after both products and their direct sum.
| Outer storage row (zero-based) | Expert 0 | Expert 1 | Expert 2 |
|---|---|---|---|
| 0 | 1 | 0 | -1 |
| 1 | 0 | 1 | -1 |
moe_RouterGains
Expert=3 · shape [3] · float64 · declared display precision 8
Actual r0,r1,r2 postprojection gain words.
| Outer storage row (zero-based) | Expert 0 | Expert 1 | Expert 2 |
|---|---|---|---|
| 0 | 1 | 1 | 1 |
moe_RouterBiases
Expert=3 · shape [3] · float64 · declared display precision 8
Actual b0,b1,b2 words, added after router gain.
| Outer storage row (zero-based) | Expert 0 | Expert 1 | Expert 2 |
|---|---|---|---|
| 0 | 0 | 0 | 0 |
moe_ExpertGains
Expert=3 · shape [3] · float64 · declared display precision 8
Actual e0,e1,e2 post-output gain words, including unused experts.
| Outer storage row (zero-based) | Expert 0 | Expert 1 | Expert 2 |
|---|---|---|---|
| 0 | 1 | 1 | 1 |
moe_ExpertW1
Expert=3 × D=2 × HiddenFeature=3 · shape [3,2,3] · float64 · declared display precision 8
All three fixed meaningful M3 expert W1 banks in row-feature storage, including unselected experts.
| Outer storage row (zero-based) | HiddenFeature 0 | HiddenFeature 1 | HiddenFeature 2 |
|---|---|---|---|
| 0 | 1 | 0 | 1 |
| 1 | 0 | 1 | -1 |
| 2 | 1 | 0 | 1 |
| 3 | 0 | 1 | -1 |
| 4 | 1 | -1 | 1 |
| 5 | 1 | 1 | 0 |
moe_ExpertB1
Expert=3 × HiddenFeature=3 · shape [3,3] · float64 · declared display precision 8
All three fixed hidden bias banks; every coordinate is literal +0 and is added last.
| Outer storage row (zero-based) | HiddenFeature 0 | HiddenFeature 1 | HiddenFeature 2 |
|---|---|---|---|
| 0 | 0 | 0 | 0 |
| 1 | 0 | 0 | 0 |
| 2 | 0 | 0 | 0 |
moe_ExpertW2
Expert=3 × HiddenFeature=3 × D=2 · shape [3,3,2] · float64 · declared display precision 8
All three fixed output banks; all three hidden products and ordered running sums remain real work.
| Outer storage row (zero-based) | D 0 | D 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 1 |
| 2 | 1 | 1 |
| 3 | -1 | 0 |
| 4 | 0 | 2 |
| 5 | 0.5 | -0.5 |
| 6 | 0.5 | 0.5 |
| 7 | 1 | -1 |
| 8 | 0 | 1 |
moe_ExpertB2
Expert=3 × D=2 · shape [3,2] · float64 · declared display precision 8
All three fixed output bias banks, literal +0 added after three products and running sums.
| Outer storage row (zero-based) | D 0 | D 1 |
|---|---|---|
| 0 | 0 | 0 |
| 1 | 0 | 0 |
| 2 | 0 | 0 |
moe_RouterStages
B=1 × T=3 × Expert=3 × RouterField=5 · shape [1,3,3,5] · float64 · declared display precision 8
Actual product0,product1,sum,scaled,logit in token/expert order.
| Outer storage row (zero-based) | RouterField 0 | RouterField 1 | RouterField 2 | RouterField 3 | RouterField 4 |
|---|---|---|---|---|---|
| 0 | 1 | 0 | 1 | 1 | 1 |
| 1 | 0 | 0 | 0 | 0 | 0 |
| 2 | -1 | -0 | -1 | -1 | -1 |
| 3 | 0 | 0 | 0 | 0 | 0 |
| 4 | 0 | 1 | 1 | 1 | 1 |
| 5 | -0 | -1 | -1 | -1 | -1 |
| 6 | 1 | 0 | 1 | 1 | 1 |
| 7 | 0 | 1 | 1 | 1 | 1 |
| 8 | -1 | -1 | -2 | -2 | -2 |
moe_Logits
B=1 × T=3 × Expert=3 · shape [1,3,3] · float64 · declared display precision 8
Actual computed finite router logits; these words alone determine expert ranking.
| Outer storage row (zero-based) | Expert 0 | Expert 1 | Expert 2 |
|---|---|---|---|
| 0 | 1 | 0 | -1 |
| 1 | 0 | 1 | -1 |
| 2 | 1 | 1 | -2 |
moe_Maxima
T=3 · shape [3] · float64 · declared display precision 8
Actual Math.max-selected full-row maxima, including its +0 preference.
| Outer storage row (zero-based) | T 0 | T 1 | T 2 |
|---|---|---|---|
| 0 | 1 | 1 | 1 |
moe_Shifted
B=1 × T=3 × Expert=3 · shape [1,3,3] · float64 · declared display precision 8
Functional native-argument witnesses: the identical immutable logit-minus-max subtraction used by unchanged stableSoftmax, without another exp.
| Outer storage row (zero-based) | Expert 0 | Expert 1 | Expert 2 |
|---|---|---|---|
| 0 | 0 | -1 | -2 |
| 1 | -1 | 0 | -2 |
| 2 | 0 | 0 | -3 |
moe_Terms
B=1 × T=3 × Expert=3 · shape [1,3,3] · float64 · declared display precision 8
All nine actual native exp outputs, including capacity zero.
| Outer storage row (zero-based) | Expert 0 | Expert 1 | Expert 2 |
|---|---|---|---|
| 0 | 1 | 0.36787944117144233 | 0.1353352832366127 |
| 1 | 0.36787944117144233 | 1 | 0.1353352832366127 |
| 2 | 1 | 1 | 0.049787068367863944 |
moe_Denominators
T=3 · shape [3] · float64 · declared display precision 8
Actual stableSoftmax denominators from +0 then term0,term1,term2 in expert order.
| Outer storage row (zero-based) | T 0 | T 1 | T 2 |
|---|---|---|---|
| 0 | 1.5032147244080551 | 1.5032147244080551 | 2.049787068367864 |
moe_Probabilities
B=1 × T=3 × Expert=3 · shape [1,3,3] · float64 · declared display precision 8
Full three-expert probabilities before top-k selection or capacity.
| Outer storage row (zero-based) | Expert 0 | Expert 1 | Expert 2 |
|---|---|---|---|
| 0 | 0.6652409557748218 | 0.24472847105479764 | 0.09003057317038046 |
| 1 | 0.24472847105479764 | 0.6652409557748218 | 0.09003057317038046 |
| 2 | 0.4878555511603684 | 0.4878555511603684 | 0.024288897679263205 |
moe_Ranking
T=3 × Rank=3 · shape [3,3] · int32 · declared display precision 0
All expert IDs sorted by descending actual computed logits and exact lower-ID ties.
| Outer storage row (zero-based) | Rank 0 | Rank 1 | Rank 2 |
|---|---|---|---|
| 0 | 0 | 1 | 2 |
| 1 | 1 | 0 | 2 |
| 2 | 0 | 1 | 2 |
moe_SelectedExperts
T=3 × Rank=2 · shape [3,2] · int32 · declared display precision 0
First topK distinct expert IDs from each full computed-logit ranking.
| Outer storage row (zero-based) | Rank 0 | Rank 1 |
|---|---|---|
| 0 | 0 | 1 |
| 1 | 1 | 0 |
| 2 | 0 | 1 |
moe_SelectedProbabilities
T=3 × Rank=2 · shape [3,2] · float64 · declared display precision 8
Unchanged selected full-softmax probability words in token/rank order.
| Outer storage row (zero-based) | Rank 0 | Rank 1 |
|---|---|---|
| 0 | 0.6652409557748218 | 0.24472847105479764 |
| 1 | 0.6652409557748218 | 0.24472847105479764 |
| 2 | 0.4878555511603684 | 0.4878555511603684 |
moe_SelectedSums
T=3 · shape [3] · float64 · declared display precision 8
Completed +0 rank folds over selected full probabilities, before admission.
| Outer storage row (zero-based) | T 0 | T 1 | T 2 |
|---|---|---|---|
| 0 | 0.9099694268296195 | 0.9099694268296195 | 0.9757111023207368 |
moe_Gates
T=3 × Rank=2 · shape [3,2] · float64 · declared display precision 8
Actual selected probability divided by selected sum before capacity; never renormalized after drops.
| Outer storage row (zero-based) | Rank 0 | Rank 1 |
|---|---|---|
| 0 | 0.7310585786300048 | 0.26894142136999516 |
| 1 | 0.7310585786300048 | 0.26894142136999516 |
| 2 | 0.5 | 0.5 |
moe_Admitted
T=3 × Rank=2 · shape [3,2] · int32 · declared display precision 0
1 if this token/rank assignment was admitted, 0 if capacity dropped it; not an expert-output value.
| Outer storage row (zero-based) | Rank 0 | Rank 1 |
|---|---|---|
| 0 | 1 | 1 |
| 1 | 1 | 1 |
| 2 | 0 | 0 |
moe_Slots
T=3 × Rank=2 · shape [3,2] · int32 · declared display precision 0
Per-expert zero-based admitted slot; -1 means dropped and allocates no slot.
| Outer storage row (zero-based) | Rank 0 | Rank 1 |
|---|---|---|
| 0 | 0 | 0 |
| 1 | 1 | 1 |
| 2 | -1 | -1 |
moe_t0_r0_e0_s0_Context
ContextField=7 · shape [7] · int32 · declared display precision 0
Original token,rank,expert,slot,sourceOffset,localB,localT in that order; local B/T indices are 0, not original token IDs.
| Outer storage row (zero-based) | ContextField 0 | ContextField 1 | ContextField 2 | ContextField 3 | ContextField 4 | ContextField 5 | ContextField 6 |
|---|---|---|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
moe_t0_r0_e0_s0_Input
B=1 × T=1 × D=2 · shape [1,1,2] · float64 · declared display precision 8
Exact original token feature words copied to local B=1,T=1,D=2; context records the original token, rank, expert and admitted slot.
| Outer storage row (zero-based) | D 0 | D 1 |
|---|---|---|
| 0 | 1 | 0 |
moe_t0_r0_e0_s0_ffn_W1
D=2 × HiddenFeature=3 · shape [2,3] · float64 · declared display precision 8
Shared input-to-hidden weights, f1{d}{m}; M=3 hidden features.
| Outer storage row (zero-based) | HiddenFeature 0 | HiddenFeature 1 | HiddenFeature 2 |
|---|---|---|---|
| 0 | 1 | 0 | 1 |
| 1 | 0 | 1 | -1 |
moe_t0_r0_e0_s0_ffn_b1
HiddenFeature=3 · shape [3] · float64 · declared display precision 8
Shared hidden bias, added after the two products.
| Outer storage row (zero-based) | HiddenFeature 0 | HiddenFeature 1 | HiddenFeature 2 |
|---|---|---|---|
| 0 | 0 | 0 | 0 |
moe_t0_r0_e0_s0_ffn_Z
B=1 × T=1 × HiddenFeature=3 · shape [1,1,3] · float64 · declared display precision 8
Hidden preactivations X W1+b1; no batch or token mixing.
| Outer storage row (zero-based) | HiddenFeature 0 | HiddenFeature 1 | HiddenFeature 2 |
|---|---|---|---|
| 0 | 1 | 0 | 1 |
moe_t0_r0_e0_s0_ffn_Hidden
B=1 × T=1 × HiddenFeature=3 · shape [1,1,3] · float64 · declared display precision 8
ReLU(Z)=max(0,Z), before the second affine layer.
| Outer storage row (zero-based) | HiddenFeature 0 | HiddenFeature 1 | HiddenFeature 2 |
|---|---|---|---|
| 0 | 1 | 0 | 1 |
moe_t0_r0_e0_s0_ffn_W2
HiddenFeature=3 × D=2 · shape [3,2] · float64 · declared display precision 8
Shared hidden-to-output weights, f2{m}{d}.
| Outer storage row (zero-based) | D 0 | D 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 1 |
| 2 | 1 | 1 |
moe_t0_r0_e0_s0_ffn_b2
D=2 · shape [2] · float64 · declared display precision 8
Shared output bias, added after all three running sums.
| Outer storage row (zero-based) | D 0 | D 1 |
|---|---|---|
| 0 | 0 | 0 |
moe_t0_r0_e0_s0_ffn_F
B=1 × T=1 × D=2 · shape [1,1,2] · float64 · declared display precision 8
ReLU(X W1+b1) W2+b2, independently per token with shared parameters.
| Outer storage row (zero-based) | D 0 | D 1 |
|---|---|---|
| 0 | 2 | 1 |
moe_t0_r0_e0_s0_PostGain
B=1 × T=1 × D=2 · shape [1,1,2] · float64 · declared display precision 8
Actual completed expert F words multiplied by the selected expert post-output gain; no gain moved into weights or before ReLU.
| Outer storage row (zero-based) | D 0 | D 1 |
|---|---|---|
| 0 | 2 | 1 |
moe_t0_r1_e1_s0_Context
ContextField=7 · shape [7] · int32 · declared display precision 0
Original token,rank,expert,slot,sourceOffset,localB,localT in that order; local B/T indices are 0, not original token IDs.
| Outer storage row (zero-based) | ContextField 0 | ContextField 1 | ContextField 2 | ContextField 3 | ContextField 4 | ContextField 5 | ContextField 6 |
|---|---|---|---|---|---|---|---|
| 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 |
moe_t0_r1_e1_s0_Input
B=1 × T=1 × D=2 · shape [1,1,2] · float64 · declared display precision 8
Exact original token feature words copied to local B=1,T=1,D=2; context records the original token, rank, expert and admitted slot.
| Outer storage row (zero-based) | D 0 | D 1 |
|---|---|---|
| 0 | 1 | 0 |
moe_t0_r1_e1_s0_ffn_W1
D=2 × HiddenFeature=3 · shape [2,3] · float64 · declared display precision 8
Shared input-to-hidden weights, f1{d}{m}; M=3 hidden features.
| Outer storage row (zero-based) | HiddenFeature 0 | HiddenFeature 1 | HiddenFeature 2 |
|---|---|---|---|
| 0 | 1 | 0 | 1 |
| 1 | 0 | 1 | -1 |
moe_t0_r1_e1_s0_ffn_b1
HiddenFeature=3 · shape [3] · float64 · declared display precision 8
Shared hidden bias, added after the two products.
| Outer storage row (zero-based) | HiddenFeature 0 | HiddenFeature 1 | HiddenFeature 2 |
|---|---|---|---|
| 0 | 0 | 0 | 0 |
moe_t0_r1_e1_s0_ffn_Z
B=1 × T=1 × HiddenFeature=3 · shape [1,1,3] · float64 · declared display precision 8
Hidden preactivations X W1+b1; no batch or token mixing.
| Outer storage row (zero-based) | HiddenFeature 0 | HiddenFeature 1 | HiddenFeature 2 |
|---|---|---|---|
| 0 | 1 | 0 | 1 |
moe_t0_r1_e1_s0_ffn_Hidden
B=1 × T=1 × HiddenFeature=3 · shape [1,1,3] · float64 · declared display precision 8
ReLU(Z)=max(0,Z), before the second affine layer.
| Outer storage row (zero-based) | HiddenFeature 0 | HiddenFeature 1 | HiddenFeature 2 |
|---|---|---|---|
| 0 | 1 | 0 | 1 |
moe_t0_r1_e1_s0_ffn_W2
HiddenFeature=3 × D=2 · shape [3,2] · float64 · declared display precision 8
Shared hidden-to-output weights, f2{m}{d}.
| Outer storage row (zero-based) | D 0 | D 1 |
|---|---|---|
| 0 | -1 | 0 |
| 1 | 0 | 2 |
| 2 | 0.5 | -0.5 |
moe_t0_r1_e1_s0_ffn_b2
D=2 · shape [2] · float64 · declared display precision 8
Shared output bias, added after all three running sums.
| Outer storage row (zero-based) | D 0 | D 1 |
|---|---|---|
| 0 | 0 | 0 |
moe_t0_r1_e1_s0_ffn_F
B=1 × T=1 × D=2 · shape [1,1,2] · float64 · declared display precision 8
ReLU(X W1+b1) W2+b2, independently per token with shared parameters.
| Outer storage row (zero-based) | D 0 | D 1 |
|---|---|---|
| 0 | -0.5 | -0.5 |
moe_t0_r1_e1_s0_PostGain
B=1 × T=1 × D=2 · shape [1,1,2] · float64 · declared display precision 8
Actual completed expert F words multiplied by the selected expert post-output gain; no gain moved into weights or before ReLU.
| Outer storage row (zero-based) | D 0 | D 1 |
|---|---|---|
| 0 | -0.5 | -0.5 |
moe_t1_r0_e1_s1_Context
ContextField=7 · shape [7] · int32 · declared display precision 0
Original token,rank,expert,slot,sourceOffset,localB,localT in that order; local B/T indices are 0, not original token IDs.
| Outer storage row (zero-based) | ContextField 0 | ContextField 1 | ContextField 2 | ContextField 3 | ContextField 4 | ContextField 5 | ContextField 6 |
|---|---|---|---|---|---|---|---|
| 0 | 1 | 0 | 1 | 1 | 2 | 0 | 0 |
moe_t1_r0_e1_s1_Input
B=1 × T=1 × D=2 · shape [1,1,2] · float64 · declared display precision 8
Exact original token feature words copied to local B=1,T=1,D=2; context records the original token, rank, expert and admitted slot.
| Outer storage row (zero-based) | D 0 | D 1 |
|---|---|---|
| 0 | 0 | 1 |
moe_t1_r0_e1_s1_ffn_W1
D=2 × HiddenFeature=3 · shape [2,3] · float64 · declared display precision 8
Shared input-to-hidden weights, f1{d}{m}; M=3 hidden features.
| Outer storage row (zero-based) | HiddenFeature 0 | HiddenFeature 1 | HiddenFeature 2 |
|---|---|---|---|
| 0 | 1 | 0 | 1 |
| 1 | 0 | 1 | -1 |
moe_t1_r0_e1_s1_ffn_b1
HiddenFeature=3 · shape [3] · float64 · declared display precision 8
Shared hidden bias, added after the two products.
| Outer storage row (zero-based) | HiddenFeature 0 | HiddenFeature 1 | HiddenFeature 2 |
|---|---|---|---|
| 0 | 0 | 0 | 0 |
moe_t1_r0_e1_s1_ffn_Z
B=1 × T=1 × HiddenFeature=3 · shape [1,1,3] · float64 · declared display precision 8
Hidden preactivations X W1+b1; no batch or token mixing.
| Outer storage row (zero-based) | HiddenFeature 0 | HiddenFeature 1 | HiddenFeature 2 |
|---|---|---|---|
| 0 | 0 | 1 | -1 |
moe_t1_r0_e1_s1_ffn_Hidden
B=1 × T=1 × HiddenFeature=3 · shape [1,1,3] · float64 · declared display precision 8
ReLU(Z)=max(0,Z), before the second affine layer.
| Outer storage row (zero-based) | HiddenFeature 0 | HiddenFeature 1 | HiddenFeature 2 |
|---|---|---|---|
| 0 | 0 | 1 | 0 |
moe_t1_r0_e1_s1_ffn_W2
HiddenFeature=3 × D=2 · shape [3,2] · float64 · declared display precision 8
Shared hidden-to-output weights, f2{m}{d}.
| Outer storage row (zero-based) | D 0 | D 1 |
|---|---|---|
| 0 | -1 | 0 |
| 1 | 0 | 2 |
| 2 | 0.5 | -0.5 |
moe_t1_r0_e1_s1_ffn_b2
D=2 · shape [2] · float64 · declared display precision 8
Shared output bias, added after all three running sums.
| Outer storage row (zero-based) | D 0 | D 1 |
|---|---|---|
| 0 | 0 | 0 |
moe_t1_r0_e1_s1_ffn_F
B=1 × T=1 × D=2 · shape [1,1,2] · float64 · declared display precision 8
ReLU(X W1+b1) W2+b2, independently per token with shared parameters.
| Outer storage row (zero-based) | D 0 | D 1 |
|---|---|---|
| 0 | 0 | 2 |
moe_t1_r0_e1_s1_PostGain
B=1 × T=1 × D=2 · shape [1,1,2] · float64 · declared display precision 8
Actual completed expert F words multiplied by the selected expert post-output gain; no gain moved into weights or before ReLU.
| Outer storage row (zero-based) | D 0 | D 1 |
|---|---|---|
| 0 | 0 | 2 |
moe_t1_r1_e0_s1_Context
ContextField=7 · shape [7] · int32 · declared display precision 0
Original token,rank,expert,slot,sourceOffset,localB,localT in that order; local B/T indices are 0, not original token IDs.
| Outer storage row (zero-based) | ContextField 0 | ContextField 1 | ContextField 2 | ContextField 3 | ContextField 4 | ContextField 5 | ContextField 6 |
|---|---|---|---|---|---|---|---|
| 0 | 1 | 1 | 0 | 1 | 2 | 0 | 0 |
moe_t1_r1_e0_s1_Input
B=1 × T=1 × D=2 · shape [1,1,2] · float64 · declared display precision 8
Exact original token feature words copied to local B=1,T=1,D=2; context records the original token, rank, expert and admitted slot.
| Outer storage row (zero-based) | D 0 | D 1 |
|---|---|---|
| 0 | 0 | 1 |
moe_t1_r1_e0_s1_ffn_W1
D=2 × HiddenFeature=3 · shape [2,3] · float64 · declared display precision 8
Shared input-to-hidden weights, f1{d}{m}; M=3 hidden features.
| Outer storage row (zero-based) | HiddenFeature 0 | HiddenFeature 1 | HiddenFeature 2 |
|---|---|---|---|
| 0 | 1 | 0 | 1 |
| 1 | 0 | 1 | -1 |
moe_t1_r1_e0_s1_ffn_b1
HiddenFeature=3 · shape [3] · float64 · declared display precision 8
Shared hidden bias, added after the two products.
| Outer storage row (zero-based) | HiddenFeature 0 | HiddenFeature 1 | HiddenFeature 2 |
|---|---|---|---|
| 0 | 0 | 0 | 0 |
moe_t1_r1_e0_s1_ffn_Z
B=1 × T=1 × HiddenFeature=3 · shape [1,1,3] · float64 · declared display precision 8
Hidden preactivations X W1+b1; no batch or token mixing.
| Outer storage row (zero-based) | HiddenFeature 0 | HiddenFeature 1 | HiddenFeature 2 |
|---|---|---|---|
| 0 | 0 | 1 | -1 |
moe_t1_r1_e0_s1_ffn_Hidden
B=1 × T=1 × HiddenFeature=3 · shape [1,1,3] · float64 · declared display precision 8
ReLU(Z)=max(0,Z), before the second affine layer.
| Outer storage row (zero-based) | HiddenFeature 0 | HiddenFeature 1 | HiddenFeature 2 |
|---|---|---|---|
| 0 | 0 | 1 | 0 |
moe_t1_r1_e0_s1_ffn_W2
HiddenFeature=3 × D=2 · shape [3,2] · float64 · declared display precision 8
Shared hidden-to-output weights, f2{m}{d}.
| Outer storage row (zero-based) | D 0 | D 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 1 |
| 2 | 1 | 1 |
moe_t1_r1_e0_s1_ffn_b2
D=2 · shape [2] · float64 · declared display precision 8
Shared output bias, added after all three running sums.
| Outer storage row (zero-based) | D 0 | D 1 |
|---|---|---|
| 0 | 0 | 0 |
moe_t1_r1_e0_s1_ffn_F
B=1 × T=1 × D=2 · shape [1,1,2] · float64 · declared display precision 8
ReLU(X W1+b1) W2+b2, independently per token with shared parameters.
| Outer storage row (zero-based) | D 0 | D 1 |
|---|---|---|
| 0 | 0 | 1 |
moe_t1_r1_e0_s1_PostGain
B=1 × T=1 × D=2 · shape [1,1,2] · float64 · declared display precision 8
Actual completed expert F words multiplied by the selected expert post-output gain; no gain moved into weights or before ReLU.
| Outer storage row (zero-based) | D 0 | D 1 |
|---|---|---|
| 0 | 0 | 1 |
moe_Loads
Expert=3 · shape [3] · int32 · declared display precision 0
Final per-expert admitted assignment counts, reset for every evaluation.
| Outer storage row (zero-based) | Expert 0 | Expert 1 | Expert 2 |
|---|---|---|---|
| 0 | 2 | 2 | 0 |
moe_TokenAccepted
T=3 · shape [3] · int32 · declared display precision 0
Number of admitted assignments for each original token.
| Outer storage row (zero-based) | T 0 | T 1 | T 2 |
|---|---|---|---|
| 0 | 2 | 2 | 0 |
moe_TokenDropped
T=3 · shape [3] · int32 · declared display precision 0
Number of dropped selected assignments for each original token.
| Outer storage row (zero-based) | T 0 | T 1 | T 2 |
|---|---|---|---|
| 0 | 0 | 0 | 2 |
moe_FullyLost
T=3 · shape [3] · int32 · declared display precision 0
1 exactly when no assignment was admitted for this token; zero output alone does not establish loss.
| Outer storage row (zero-based) | T 0 | T 1 | T 2 |
|---|---|---|---|
| 0 | 0 | 0 | 1 |
moe_PartiallyDropped
T=3 · shape [3] · int32 · declared display precision 0
1 exactly when some but not all selected assignments were dropped.
| Outer storage row (zero-based) | T 0 | T 1 | T 2 |
|---|---|---|---|
| 0 | 0 | 0 | 0 |
moe_KeptMass
T=3 · shape [3] · float64 · declared display precision 8
Independent +0 rank fold of admitted pre-drop gates; not computed as one minus lost mass.
| Outer storage row (zero-based) | T 0 | T 1 | T 2 |
|---|---|---|---|
| 0 | 1 | 1 | 0 |
moe_LostMass
T=3 · shape [3] · float64 · declared display precision 8
Independent +0 rank fold of dropped pre-drop gates; not a quality, norm or probability of failure.
| Outer storage row (zero-based) | T 0 | T 1 | T 2 |
|---|---|---|---|
| 0 | 0 | 0 | 1 |
moe_GatedContributions
B=1 × T=3 × Rank=2 × D=2 · shape [1,3,2,2] · float64 · declared display precision 8
Admitted gate times saved postgain output; dropped cells are literal +0 policy messages, not computed expert outputs.
| Outer storage row (zero-based) | D 0 | D 1 |
|---|---|---|
| 0 | 1.4621171572600096 | 0.7310585786300048 |
| 1 | -0.13447071068499758 | -0.13447071068499758 |
| 2 | 0 | 1.4621171572600096 |
| 3 | 0 | 0.26894142136999516 |
| 4 | 0 | 0 |
| 5 | 0 | 0 |
moe_Y
B=1 × T=3 × D=2 · shape [1,3,2] · float64 · declared display precision 8
Actual per-original-token branch output, +0 then rank-ordered admitted gated messages and explicit dropped-policy +0 additions. No residual or fallback.
| Outer storage row (zero-based) | D 0 | D 1 |
|---|---|---|
| 0 | 1.327646446575012 | 0.5965878679450072 |
| 1 | 0 | 1.7310585786300048 |
| 2 | 0 | 0 |
moe_Counts
CountField=5 · shape [5] · int32 · declared display precision 0
Selected assignments,accepted assignments,dropped assignments,fully lost tokens,partially dropped tokens in that order.
| Outer storage row (zero-based) | CountField 0 | CountField 1 | CountField 2 | CountField 3 | CountField 4 |
|---|---|---|---|---|---|
| 0 | 6 | 4 | 2 | 1 | 0 |
moe_NativeArguments
Native=9 × NativeField=2 · shape [9,2] · float64 · declared display precision 8
Actual exp argument functional witnesses and actual exp outputs in token/expert occurrence order; no native call during serialization.
| Outer storage row (zero-based) | NativeField 0 | NativeField 1 |
|---|---|---|
| 0 | 0 | 1 |
| 1 | -1 | 0.36787944117144233 |
| 2 | -2 | 0.1353352832366127 |
| 3 | -1 | 0.36787944117144233 |
| 4 | 0 | 1 |
| 5 | -2 | 0.1353352832366127 |
| 6 | 0 | 1 |
| 7 | 0 | 1 |
| 8 | -3 | 0.049787068367863944 |
moe_NativeKinds
Native=9 · shape [9] · int32 · declared display precision 0
Native kind code exp=1 for all nine occurrences; no sqrt occurs.
| Outer storage row (zero-based) | Native 0 | Native 1 | Native 2 | Native 3 | Native 4 | Native 5 | Native 6 | Native 7 | Native 8 |
|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
Every saved operation, including all expert products and both combine branches (90 frames)
Exact unchanged decoderTrace factory alias: detached finite frame operands captured once; empty/duplicate IDs rejected before operands; 512-frame cap after operands. No frame precedes full raw/domain/prefix preflight. All numerical frames precede finish. Every frame output is copied to root outputs as frameId_key.
Router at token 0, expert 0
moe_router_0_0
product0=x0*w0; product1=x1*w1; sum=product0+product1; scaled=sum*gain; logit=scaled+bias
Compute both feature products, add them directly, multiply this expert router gain, then add its bias last. Zero coefficients and capacity zero do not skip work.
Saved inputs
- t
- 0
- expert
- 0
- x0
- 1
- x1
- 0
- w0
- 1
- w1
- 0
- gain
- 1
- bias
- 0
Saved outputs
- product0
- 1
- product1
- 0
- sum
- 1
- scaled
- 1
- logit
- 1
Router at token 0, expert 1
moe_router_0_1
product0=x0*w0; product1=x1*w1; sum=product0+product1; scaled=sum*gain; logit=scaled+bias
Compute both feature products, add them directly, multiply this expert router gain, then add its bias last. Zero coefficients and capacity zero do not skip work.
Saved inputs
- t
- 0
- expert
- 1
- x0
- 1
- x1
- 0
- w0
- 0
- w1
- 1
- gain
- 1
- bias
- 0
Saved outputs
- product0
- 0
- product1
- 0
- sum
- 0
- scaled
- 0
- logit
- 0
Router at token 0, expert 2
moe_router_0_2
product0=x0*w0; product1=x1*w1; sum=product0+product1; scaled=sum*gain; logit=scaled+bias
Compute both feature products, add them directly, multiply this expert router gain, then add its bias last. Zero coefficients and capacity zero do not skip work.
Saved inputs
- t
- 0
- expert
- 2
- x0
- 1
- x1
- 0
- w0
- -1
- w1
- -1
- gain
- 1
- bias
- 0
Saved outputs
- product0
- -1
- product1
- -0
- sum
- -1
- scaled
- -1
- logit
- -1
Router at token 1, expert 0
moe_router_1_0
product0=x0*w0; product1=x1*w1; sum=product0+product1; scaled=sum*gain; logit=scaled+bias
Compute both feature products, add them directly, multiply this expert router gain, then add its bias last. Zero coefficients and capacity zero do not skip work.
Saved inputs
- t
- 1
- expert
- 0
- x0
- 0
- x1
- 1
- w0
- 1
- w1
- 0
- gain
- 1
- bias
- 0
Saved outputs
- product0
- 0
- product1
- 0
- sum
- 0
- scaled
- 0
- logit
- 0
Router at token 1, expert 1
moe_router_1_1
product0=x0*w0; product1=x1*w1; sum=product0+product1; scaled=sum*gain; logit=scaled+bias
Compute both feature products, add them directly, multiply this expert router gain, then add its bias last. Zero coefficients and capacity zero do not skip work.
Saved inputs
- t
- 1
- expert
- 1
- x0
- 0
- x1
- 1
- w0
- 0
- w1
- 1
- gain
- 1
- bias
- 0
Saved outputs
- product0
- 0
- product1
- 1
- sum
- 1
- scaled
- 1
- logit
- 1
Router at token 1, expert 2
moe_router_1_2
product0=x0*w0; product1=x1*w1; sum=product0+product1; scaled=sum*gain; logit=scaled+bias
Compute both feature products, add them directly, multiply this expert router gain, then add its bias last. Zero coefficients and capacity zero do not skip work.
Saved inputs
- t
- 1
- expert
- 2
- x0
- 0
- x1
- 1
- w0
- -1
- w1
- -1
- gain
- 1
- bias
- 0
Saved outputs
- product0
- -0
- product1
- -1
- sum
- -1
- scaled
- -1
- logit
- -1
Router at token 2, expert 0
moe_router_2_0
product0=x0*w0; product1=x1*w1; sum=product0+product1; scaled=sum*gain; logit=scaled+bias
Compute both feature products, add them directly, multiply this expert router gain, then add its bias last. Zero coefficients and capacity zero do not skip work.
Saved inputs
- t
- 2
- expert
- 0
- x0
- 1
- x1
- 1
- w0
- 1
- w1
- 0
- gain
- 1
- bias
- 0
Saved outputs
- product0
- 1
- product1
- 0
- sum
- 1
- scaled
- 1
- logit
- 1
Router at token 2, expert 1
moe_router_2_1
product0=x0*w0; product1=x1*w1; sum=product0+product1; scaled=sum*gain; logit=scaled+bias
Compute both feature products, add them directly, multiply this expert router gain, then add its bias last. Zero coefficients and capacity zero do not skip work.
Saved inputs
- t
- 2
- expert
- 1
- x0
- 1
- x1
- 1
- w0
- 0
- w1
- 1
- gain
- 1
- bias
- 0
Saved outputs
- product0
- 0
- product1
- 1
- sum
- 1
- scaled
- 1
- logit
- 1
Router at token 2, expert 2
moe_router_2_2
product0=x0*w0; product1=x1*w1; sum=product0+product1; scaled=sum*gain; logit=scaled+bias
Compute both feature products, add them directly, multiply this expert router gain, then add its bias last. Zero coefficients and capacity zero do not skip work.
Saved inputs
- t
- 2
- expert
- 2
- x0
- 1
- x1
- 1
- w0
- -1
- w1
- -1
- gain
- 1
- bias
- 0
Saved outputs
- product0
- -1
- product1
- -1
- sum
- -2
- scaled
- -2
- logit
- -2
Full three-expert stable softmax at token 0
moe_softmax_0
max=Math.max(logits); term_e=exp(logit_e-max); denominator=((+0+term0)+term1)+term2; probability_e=term_e/denominator
The unchanged stableSoftmax computes all three native exponentials before top-k or capacity. Saved shifts reconstruct its arguments from identical immutable operands; this is a functional witness, not physical interception.
Saved inputs
- t
- 0
- logit0
- 1
- logit1
- 0
- logit2
- -1
Saved outputs
- max
- 1
- shifted0
- 0
- term0
- 1
- shifted1
- -1
- term1
- 0.36787944117144233
- shifted2
- -2
- term2
- 0.1353352832366127
- denominator
- 1.5032147244080551
- probability0
- 0.6652409557748218
- probability1
- 0.24472847105479764
- probability2
- 0.09003057317038046
Rank actual computed logits at token 0
moe_rank_0
descending computed logit; exact ties ascending expert ID
Compare saved finite logits directly with greater/less. Rounded probabilities and display decimals never choose an expert.
Saved inputs
- t
- 0
- logit0
- 1
- logit1
- 0
- logit2
- -1
Saved outputs
- expert0
- 0
- expert1
- 1
- expert2
- 2
Selected-probability fold at token 0, rank 0
moe_selectedSum_0_0
sum=previous+probability
Start from literal +0 and add selected full-softmax probabilities in rank order before any admission decision.
Saved inputs
- t
- 0
- rank
- 0
- expert
- 0
- previous
- 0
- probability
- 0.6652409557748218
Saved outputs
- sum
- 0.6652409557748218
Selected-probability fold at token 0, rank 1
moe_selectedSum_0_1
sum=previous+probability
Start from literal +0 and add selected full-softmax probabilities in rank order before any admission decision.
Saved inputs
- t
- 0
- rank
- 1
- expert
- 1
- previous
- 0.6652409557748218
- probability
- 0.24472847105479764
Saved outputs
- sum
- 0.9099694268296195
Pre-drop gate at token 0, rank 0
moe_gate_0_0
gate=probability/selectedSum
Divide the saved selected probability by the completed selected-probability sum. Do not replace this operation with a selected-only softmax or renormalize after drops.
Saved inputs
- t
- 0
- rank
- 0
- expert
- 0
- probability
- 0.6652409557748218
- selectedSum
- 0.9099694268296195
Saved outputs
- gate
- 0.7310585786300048
Pre-drop gate at token 0, rank 1
moe_gate_0_1
gate=probability/selectedSum
Divide the saved selected probability by the completed selected-probability sum. Do not replace this operation with a selected-only softmax or renormalize after drops.
Saved inputs
- t
- 0
- rank
- 1
- expert
- 1
- probability
- 0.24472847105479764
- selectedSum
- 0.9099694268296195
Saved outputs
- gate
- 0.26894142136999516
Full three-expert stable softmax at token 1
moe_softmax_1
max=Math.max(logits); term_e=exp(logit_e-max); denominator=((+0+term0)+term1)+term2; probability_e=term_e/denominator
The unchanged stableSoftmax computes all three native exponentials before top-k or capacity. Saved shifts reconstruct its arguments from identical immutable operands; this is a functional witness, not physical interception.
Saved inputs
- t
- 1
- logit0
- 0
- logit1
- 1
- logit2
- -1
Saved outputs
- max
- 1
- shifted0
- -1
- term0
- 0.36787944117144233
- shifted1
- 0
- term1
- 1
- shifted2
- -2
- term2
- 0.1353352832366127
- denominator
- 1.5032147244080551
- probability0
- 0.24472847105479764
- probability1
- 0.6652409557748218
- probability2
- 0.09003057317038046
Rank actual computed logits at token 1
moe_rank_1
descending computed logit; exact ties ascending expert ID
Compare saved finite logits directly with greater/less. Rounded probabilities and display decimals never choose an expert.
Saved inputs
- t
- 1
- logit0
- 0
- logit1
- 1
- logit2
- -1
Saved outputs
- expert0
- 1
- expert1
- 0
- expert2
- 2
Selected-probability fold at token 1, rank 0
moe_selectedSum_1_0
sum=previous+probability
Start from literal +0 and add selected full-softmax probabilities in rank order before any admission decision.
Saved inputs
- t
- 1
- rank
- 0
- expert
- 1
- previous
- 0
- probability
- 0.6652409557748218
Saved outputs
- sum
- 0.6652409557748218
Selected-probability fold at token 1, rank 1
moe_selectedSum_1_1
sum=previous+probability
Start from literal +0 and add selected full-softmax probabilities in rank order before any admission decision.
Saved inputs
- t
- 1
- rank
- 1
- expert
- 0
- previous
- 0.6652409557748218
- probability
- 0.24472847105479764
Saved outputs
- sum
- 0.9099694268296195
Pre-drop gate at token 1, rank 0
moe_gate_1_0
gate=probability/selectedSum
Divide the saved selected probability by the completed selected-probability sum. Do not replace this operation with a selected-only softmax or renormalize after drops.
Saved inputs
- t
- 1
- rank
- 0
- expert
- 1
- probability
- 0.6652409557748218
- selectedSum
- 0.9099694268296195
Saved outputs
- gate
- 0.7310585786300048
Pre-drop gate at token 1, rank 1
moe_gate_1_1
gate=probability/selectedSum
Divide the saved selected probability by the completed selected-probability sum. Do not replace this operation with a selected-only softmax or renormalize after drops.
Saved inputs
- t
- 1
- rank
- 1
- expert
- 0
- probability
- 0.24472847105479764
- selectedSum
- 0.9099694268296195
Saved outputs
- gate
- 0.26894142136999516
Full three-expert stable softmax at token 2
moe_softmax_2
max=Math.max(logits); term_e=exp(logit_e-max); denominator=((+0+term0)+term1)+term2; probability_e=term_e/denominator
The unchanged stableSoftmax computes all three native exponentials before top-k or capacity. Saved shifts reconstruct its arguments from identical immutable operands; this is a functional witness, not physical interception.
Saved inputs
- t
- 2
- logit0
- 1
- logit1
- 1
- logit2
- -2
Saved outputs
- max
- 1
- shifted0
- 0
- term0
- 1
- shifted1
- 0
- term1
- 1
- shifted2
- -3
- term2
- 0.049787068367863944
- denominator
- 2.049787068367864
- probability0
- 0.4878555511603684
- probability1
- 0.4878555511603684
- probability2
- 0.024288897679263205
Rank actual computed logits at token 2
moe_rank_2
descending computed logit; exact ties ascending expert ID
Compare saved finite logits directly with greater/less. Rounded probabilities and display decimals never choose an expert.
Saved inputs
- t
- 2
- logit0
- 1
- logit1
- 1
- logit2
- -2
Saved outputs
- expert0
- 0
- expert1
- 1
- expert2
- 2
Selected-probability fold at token 2, rank 0
moe_selectedSum_2_0
sum=previous+probability
Start from literal +0 and add selected full-softmax probabilities in rank order before any admission decision.
Saved inputs
- t
- 2
- rank
- 0
- expert
- 0
- previous
- 0
- probability
- 0.4878555511603684
Saved outputs
- sum
- 0.4878555511603684
Selected-probability fold at token 2, rank 1
moe_selectedSum_2_1
sum=previous+probability
Start from literal +0 and add selected full-softmax probabilities in rank order before any admission decision.
Saved inputs
- t
- 2
- rank
- 1
- expert
- 1
- previous
- 0.4878555511603684
- probability
- 0.4878555511603684
Saved outputs
- sum
- 0.9757111023207368
Pre-drop gate at token 2, rank 0
moe_gate_2_0
gate=probability/selectedSum
Divide the saved selected probability by the completed selected-probability sum. Do not replace this operation with a selected-only softmax or renormalize after drops.
Saved inputs
- t
- 2
- rank
- 0
- expert
- 0
- probability
- 0.4878555511603684
- selectedSum
- 0.9757111023207368
Saved outputs
- gate
- 0.5
Pre-drop gate at token 2, rank 1
moe_gate_2_1
gate=probability/selectedSum
Divide the saved selected probability by the completed selected-probability sum. Do not replace this operation with a selected-only softmax or renormalize after drops.
Saved inputs
- t
- 2
- rank
- 1
- expert
- 1
- probability
- 0.4878555511603684
- selectedSum
- 0.9757111023207368
Saved outputs
- gate
- 0.5
Admission at token 0, rank 0, expert 0
moe_dispatch_0_0
admitted=countBefore<capacity; slot=admitted?countBefore:-1; increment only admitted expert; fold kept or lost gate separately
Visit tokens then ranks. Capacity counts assignments per expert; rejection does not increment load, reroute, add a residual or redistribute a gate.
Saved inputs
- t
- 0
- rank
- 0
- expert
- 0
- capacity
- 2
- countBefore
- 0
- gate
- 0.7310585786300048
- keptBefore
- 0
- lostBefore
- 0
Saved outputs
- admitted
- 1
- slot
- 0
- countAfter
- 1
- keptMass
- 0.7310585786300048
- lostMass
- 0
Dispatch original token 0, rank 0 to expert 0, slot 0
moe_t0_r0_e0_s0_context
localX[0,0,0]=X[sourceOffset]; localX[0,0,1]=X[sourceOffset+1]
Original token/rank/expert/slot identify this invocation. The unchanged feedForward uses a separate local batch 0 and local token 0; its local t is never the original token index.
Saved inputs
- originalToken
- 0
- rank
- 0
- expert
- 0
- slot
- 0
- sourceOffset
- 0
- localB
- 0
- localT
- 0
- x0
- 1
- x1
- 0
Saved outputs
- localX0
- 1
- localX1
- 0
Hidden affine [0,0,0]
moe_t0_r0_e0_s0_ffn_hidden_0_0_0
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.
Saved inputs
- b
- 0
- t
- 0
- m
- 0
- x0
- 1
- x1
- 0
- w0
- 1
- w1
- 0
- bias
- 0
Saved outputs
- product0
- 1
- product1
- 0
- sum
- 1
- preactivation
- 1
Hidden affine [0,0,1]
moe_t0_r0_e0_s0_ffn_hidden_0_0_1
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.
Saved inputs
- b
- 0
- t
- 0
- m
- 1
- x0
- 1
- x1
- 0
- w0
- 0
- w1
- 1
- bias
- 0
Saved outputs
- product0
- 0
- product1
- 0
- sum
- 0
- preactivation
- 0
Hidden affine [0,0,2]
moe_t0_r0_e0_s0_ffn_hidden_0_0_2
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.
Saved inputs
- b
- 0
- t
- 0
- m
- 2
- x0
- 1
- x1
- 0
- w0
- 1
- w1
- -1
- bias
- 0
Saved outputs
- product0
- 1
- product1
- -0
- sum
- 1
- preactivation
- 1
ReLU [0,0,0]
moe_t0_r0_e0_s0_ffn_relu_0_0_0
activation=max(0,preactivation)
ReLU means rectified linear unit: keep a positive value and replace a nonpositive value with zero, including zero itself.
Saved inputs
- b
- 0
- t
- 0
- m
- 0
- preactivation
- 1
Saved outputs
- activation
- 1
ReLU [0,0,1]
moe_t0_r0_e0_s0_ffn_relu_0_0_1
activation=max(0,preactivation)
ReLU means rectified linear unit: keep a positive value and replace a nonpositive value with zero, including zero itself.
Saved inputs
- b
- 0
- t
- 0
- m
- 1
- preactivation
- 0
Saved outputs
- activation
- 0
ReLU [0,0,2]
moe_t0_r0_e0_s0_ffn_relu_0_0_2
activation=max(0,preactivation)
ReLU means rectified linear unit: keep a positive value and replace a nonpositive value with zero, including zero itself.
Saved inputs
- b
- 0
- t
- 0
- m
- 2
- preactivation
- 1
Saved outputs
- activation
- 1
FFN output [0,0,0]
moe_t0_r0_e0_s0_ffn_output_0_0_0
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.
Saved inputs
- b
- 0
- t
- 0
- d
- 0
- h0
- 1
- w0
- 1
- h1
- 0
- w1
- 0
- h2
- 1
- w2
- 1
- bias
- 0
Saved outputs
- product0
- 1
- product1
- 0
- product2
- 1
- running0
- 1
- running1
- 1
- running2
- 2
- sum
- 2
- value
- 2
FFN output [0,0,1]
moe_t0_r0_e0_s0_ffn_output_0_0_1
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.
Saved inputs
- b
- 0
- t
- 0
- d
- 1
- h0
- 1
- w0
- 0
- h1
- 0
- w1
- 1
- h2
- 1
- w2
- 1
- bias
- 0
Saved outputs
- product0
- 0
- product1
- 0
- product2
- 1
- running0
- 0
- running1
- 0
- running2
- 1
- sum
- 1
- value
- 1
Post-output expert gain at original token 0, rank 0, feature 0
moe_t0_r0_e0_s0_gain_0
scaled=value*gain
Multiply the actual completed M3 expert output by its gain after all hidden/output products, ReLUs and biases. A zero gain still follows a full admitted expert invocation.
Saved inputs
- t
- 0
- rank
- 0
- expert
- 0
- slot
- 0
- d
- 0
- value
- 2
- gain
- 1
Saved outputs
- scaled
- 2
Post-output expert gain at original token 0, rank 0, feature 1
moe_t0_r0_e0_s0_gain_1
scaled=value*gain
Multiply the actual completed M3 expert output by its gain after all hidden/output products, ReLUs and biases. A zero gain still follows a full admitted expert invocation.
Saved inputs
- t
- 0
- rank
- 0
- expert
- 0
- slot
- 0
- d
- 1
- value
- 1
- gain
- 1
Saved outputs
- scaled
- 1
Admission at token 0, rank 1, expert 1
moe_dispatch_0_1
admitted=countBefore<capacity; slot=admitted?countBefore:-1; increment only admitted expert; fold kept or lost gate separately
Visit tokens then ranks. Capacity counts assignments per expert; rejection does not increment load, reroute, add a residual or redistribute a gate.
Saved inputs
- t
- 0
- rank
- 1
- expert
- 1
- capacity
- 2
- countBefore
- 0
- gate
- 0.26894142136999516
- keptBefore
- 0.7310585786300048
- lostBefore
- 0
Saved outputs
- admitted
- 1
- slot
- 0
- countAfter
- 1
- keptMass
- 1
- lostMass
- 0
Dispatch original token 0, rank 1 to expert 1, slot 0
moe_t0_r1_e1_s0_context
localX[0,0,0]=X[sourceOffset]; localX[0,0,1]=X[sourceOffset+1]
Original token/rank/expert/slot identify this invocation. The unchanged feedForward uses a separate local batch 0 and local token 0; its local t is never the original token index.
Saved inputs
- originalToken
- 0
- rank
- 1
- expert
- 1
- slot
- 0
- sourceOffset
- 0
- localB
- 0
- localT
- 0
- x0
- 1
- x1
- 0
Saved outputs
- localX0
- 1
- localX1
- 0
Hidden affine [0,0,0]
moe_t0_r1_e1_s0_ffn_hidden_0_0_0
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.
Saved inputs
- b
- 0
- t
- 0
- m
- 0
- x0
- 1
- x1
- 0
- w0
- 1
- w1
- 0
- bias
- 0
Saved outputs
- product0
- 1
- product1
- 0
- sum
- 1
- preactivation
- 1
Hidden affine [0,0,1]
moe_t0_r1_e1_s0_ffn_hidden_0_0_1
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.
Saved inputs
- b
- 0
- t
- 0
- m
- 1
- x0
- 1
- x1
- 0
- w0
- 0
- w1
- 1
- bias
- 0
Saved outputs
- product0
- 0
- product1
- 0
- sum
- 0
- preactivation
- 0
Hidden affine [0,0,2]
moe_t0_r1_e1_s0_ffn_hidden_0_0_2
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.
Saved inputs
- b
- 0
- t
- 0
- m
- 2
- x0
- 1
- x1
- 0
- w0
- 1
- w1
- -1
- bias
- 0
Saved outputs
- product0
- 1
- product1
- -0
- sum
- 1
- preactivation
- 1
ReLU [0,0,0]
moe_t0_r1_e1_s0_ffn_relu_0_0_0
activation=max(0,preactivation)
ReLU means rectified linear unit: keep a positive value and replace a nonpositive value with zero, including zero itself.
Saved inputs
- b
- 0
- t
- 0
- m
- 0
- preactivation
- 1
Saved outputs
- activation
- 1
ReLU [0,0,1]
moe_t0_r1_e1_s0_ffn_relu_0_0_1
activation=max(0,preactivation)
ReLU means rectified linear unit: keep a positive value and replace a nonpositive value with zero, including zero itself.
Saved inputs
- b
- 0
- t
- 0
- m
- 1
- preactivation
- 0
Saved outputs
- activation
- 0
ReLU [0,0,2]
moe_t0_r1_e1_s0_ffn_relu_0_0_2
activation=max(0,preactivation)
ReLU means rectified linear unit: keep a positive value and replace a nonpositive value with zero, including zero itself.
Saved inputs
- b
- 0
- t
- 0
- m
- 2
- preactivation
- 1
Saved outputs
- activation
- 1
FFN output [0,0,0]
moe_t0_r1_e1_s0_ffn_output_0_0_0
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.
Saved inputs
- b
- 0
- t
- 0
- d
- 0
- h0
- 1
- w0
- -1
- h1
- 0
- w1
- 0
- h2
- 1
- w2
- 0.5
- bias
- 0
Saved outputs
- product0
- -1
- product1
- 0
- product2
- 0.5
- running0
- -1
- running1
- -1
- running2
- -0.5
- sum
- -0.5
- value
- -0.5
FFN output [0,0,1]
moe_t0_r1_e1_s0_ffn_output_0_0_1
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.
Saved inputs
- b
- 0
- t
- 0
- d
- 1
- h0
- 1
- w0
- 0
- h1
- 0
- w1
- 2
- h2
- 1
- w2
- -0.5
- bias
- 0
Saved outputs
- product0
- 0
- product1
- 0
- product2
- -0.5
- running0
- 0
- running1
- 0
- running2
- -0.5
- sum
- -0.5
- value
- -0.5
Post-output expert gain at original token 0, rank 1, feature 0
moe_t0_r1_e1_s0_gain_0
scaled=value*gain
Multiply the actual completed M3 expert output by its gain after all hidden/output products, ReLUs and biases. A zero gain still follows a full admitted expert invocation.
Saved inputs
- t
- 0
- rank
- 1
- expert
- 1
- slot
- 0
- d
- 0
- value
- -0.5
- gain
- 1
Saved outputs
- scaled
- -0.5
Post-output expert gain at original token 0, rank 1, feature 1
moe_t0_r1_e1_s0_gain_1
scaled=value*gain
Multiply the actual completed M3 expert output by its gain after all hidden/output products, ReLUs and biases. A zero gain still follows a full admitted expert invocation.
Saved inputs
- t
- 0
- rank
- 1
- expert
- 1
- slot
- 0
- d
- 1
- value
- -0.5
- gain
- 1
Saved outputs
- scaled
- -0.5
Admission at token 1, rank 0, expert 1
moe_dispatch_1_0
admitted=countBefore<capacity; slot=admitted?countBefore:-1; increment only admitted expert; fold kept or lost gate separately
Visit tokens then ranks. Capacity counts assignments per expert; rejection does not increment load, reroute, add a residual or redistribute a gate.
Saved inputs
- t
- 1
- rank
- 0
- expert
- 1
- capacity
- 2
- countBefore
- 1
- gate
- 0.7310585786300048
- keptBefore
- 0
- lostBefore
- 0
Saved outputs
- admitted
- 1
- slot
- 1
- countAfter
- 2
- keptMass
- 0.7310585786300048
- lostMass
- 0
Dispatch original token 1, rank 0 to expert 1, slot 1
moe_t1_r0_e1_s1_context
localX[0,0,0]=X[sourceOffset]; localX[0,0,1]=X[sourceOffset+1]
Original token/rank/expert/slot identify this invocation. The unchanged feedForward uses a separate local batch 0 and local token 0; its local t is never the original token index.
Saved inputs
- originalToken
- 1
- rank
- 0
- expert
- 1
- slot
- 1
- sourceOffset
- 2
- localB
- 0
- localT
- 0
- x0
- 0
- x1
- 1
Saved outputs
- localX0
- 0
- localX1
- 1
Hidden affine [0,0,0]
moe_t1_r0_e1_s1_ffn_hidden_0_0_0
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.
Saved inputs
- b
- 0
- t
- 0
- m
- 0
- x0
- 0
- x1
- 1
- w0
- 1
- w1
- 0
- bias
- 0
Saved outputs
- product0
- 0
- product1
- 0
- sum
- 0
- preactivation
- 0
Hidden affine [0,0,1]
moe_t1_r0_e1_s1_ffn_hidden_0_0_1
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.
Saved inputs
- b
- 0
- t
- 0
- m
- 1
- x0
- 0
- x1
- 1
- w0
- 0
- w1
- 1
- bias
- 0
Saved outputs
- product0
- 0
- product1
- 1
- sum
- 1
- preactivation
- 1
Hidden affine [0,0,2]
moe_t1_r0_e1_s1_ffn_hidden_0_0_2
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.
Saved inputs
- b
- 0
- t
- 0
- m
- 2
- x0
- 0
- x1
- 1
- w0
- 1
- w1
- -1
- bias
- 0
Saved outputs
- product0
- 0
- product1
- -1
- sum
- -1
- preactivation
- -1
ReLU [0,0,0]
moe_t1_r0_e1_s1_ffn_relu_0_0_0
activation=max(0,preactivation)
ReLU means rectified linear unit: keep a positive value and replace a nonpositive value with zero, including zero itself.
Saved inputs
- b
- 0
- t
- 0
- m
- 0
- preactivation
- 0
Saved outputs
- activation
- 0
ReLU [0,0,1]
moe_t1_r0_e1_s1_ffn_relu_0_0_1
activation=max(0,preactivation)
ReLU means rectified linear unit: keep a positive value and replace a nonpositive value with zero, including zero itself.
Saved inputs
- b
- 0
- t
- 0
- m
- 1
- preactivation
- 1
Saved outputs
- activation
- 1
ReLU [0,0,2]
moe_t1_r0_e1_s1_ffn_relu_0_0_2
activation=max(0,preactivation)
ReLU means rectified linear unit: keep a positive value and replace a nonpositive value with zero, including zero itself.
Saved inputs
- b
- 0
- t
- 0
- m
- 2
- preactivation
- -1
Saved outputs
- activation
- 0
FFN output [0,0,0]
moe_t1_r0_e1_s1_ffn_output_0_0_0
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.
Saved inputs
- b
- 0
- t
- 0
- d
- 0
- h0
- 0
- w0
- -1
- h1
- 1
- w1
- 0
- h2
- 0
- w2
- 0.5
- bias
- 0
Saved outputs
- product0
- -0
- product1
- 0
- product2
- 0
- running0
- 0
- running1
- 0
- running2
- 0
- sum
- 0
- value
- 0
FFN output [0,0,1]
moe_t1_r0_e1_s1_ffn_output_0_0_1
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.
Saved inputs
- b
- 0
- t
- 0
- d
- 1
- h0
- 0
- w0
- 0
- h1
- 1
- w1
- 2
- h2
- 0
- w2
- -0.5
- bias
- 0
Saved outputs
- product0
- 0
- product1
- 2
- product2
- -0
- running0
- 0
- running1
- 2
- running2
- 2
- sum
- 2
- value
- 2
Post-output expert gain at original token 1, rank 0, feature 0
moe_t1_r0_e1_s1_gain_0
scaled=value*gain
Multiply the actual completed M3 expert output by its gain after all hidden/output products, ReLUs and biases. A zero gain still follows a full admitted expert invocation.
Saved inputs
- t
- 1
- rank
- 0
- expert
- 1
- slot
- 1
- d
- 0
- value
- 0
- gain
- 1
Saved outputs
- scaled
- 0
Post-output expert gain at original token 1, rank 0, feature 1
moe_t1_r0_e1_s1_gain_1
scaled=value*gain
Multiply the actual completed M3 expert output by its gain after all hidden/output products, ReLUs and biases. A zero gain still follows a full admitted expert invocation.
Saved inputs
- t
- 1
- rank
- 0
- expert
- 1
- slot
- 1
- d
- 1
- value
- 2
- gain
- 1
Saved outputs
- scaled
- 2
Admission at token 1, rank 1, expert 0
moe_dispatch_1_1
admitted=countBefore<capacity; slot=admitted?countBefore:-1; increment only admitted expert; fold kept or lost gate separately
Visit tokens then ranks. Capacity counts assignments per expert; rejection does not increment load, reroute, add a residual or redistribute a gate.
Saved inputs
- t
- 1
- rank
- 1
- expert
- 0
- capacity
- 2
- countBefore
- 1
- gate
- 0.26894142136999516
- keptBefore
- 0.7310585786300048
- lostBefore
- 0
Saved outputs
- admitted
- 1
- slot
- 1
- countAfter
- 2
- keptMass
- 1
- lostMass
- 0
Dispatch original token 1, rank 1 to expert 0, slot 1
moe_t1_r1_e0_s1_context
localX[0,0,0]=X[sourceOffset]; localX[0,0,1]=X[sourceOffset+1]
Original token/rank/expert/slot identify this invocation. The unchanged feedForward uses a separate local batch 0 and local token 0; its local t is never the original token index.
Saved inputs
- originalToken
- 1
- rank
- 1
- expert
- 0
- slot
- 1
- sourceOffset
- 2
- localB
- 0
- localT
- 0
- x0
- 0
- x1
- 1
Saved outputs
- localX0
- 0
- localX1
- 1
Hidden affine [0,0,0]
moe_t1_r1_e0_s1_ffn_hidden_0_0_0
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.
Saved inputs
- b
- 0
- t
- 0
- m
- 0
- x0
- 0
- x1
- 1
- w0
- 1
- w1
- 0
- bias
- 0
Saved outputs
- product0
- 0
- product1
- 0
- sum
- 0
- preactivation
- 0
Hidden affine [0,0,1]
moe_t1_r1_e0_s1_ffn_hidden_0_0_1
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.
Saved inputs
- b
- 0
- t
- 0
- m
- 1
- x0
- 0
- x1
- 1
- w0
- 0
- w1
- 1
- bias
- 0
Saved outputs
- product0
- 0
- product1
- 1
- sum
- 1
- preactivation
- 1
Hidden affine [0,0,2]
moe_t1_r1_e0_s1_ffn_hidden_0_0_2
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.
Saved inputs
- b
- 0
- t
- 0
- m
- 2
- x0
- 0
- x1
- 1
- w0
- 1
- w1
- -1
- bias
- 0
Saved outputs
- product0
- 0
- product1
- -1
- sum
- -1
- preactivation
- -1
ReLU [0,0,0]
moe_t1_r1_e0_s1_ffn_relu_0_0_0
activation=max(0,preactivation)
ReLU means rectified linear unit: keep a positive value and replace a nonpositive value with zero, including zero itself.
Saved inputs
- b
- 0
- t
- 0
- m
- 0
- preactivation
- 0
Saved outputs
- activation
- 0
ReLU [0,0,1]
moe_t1_r1_e0_s1_ffn_relu_0_0_1
activation=max(0,preactivation)
ReLU means rectified linear unit: keep a positive value and replace a nonpositive value with zero, including zero itself.
Saved inputs
- b
- 0
- t
- 0
- m
- 1
- preactivation
- 1
Saved outputs
- activation
- 1
ReLU [0,0,2]
moe_t1_r1_e0_s1_ffn_relu_0_0_2
activation=max(0,preactivation)
ReLU means rectified linear unit: keep a positive value and replace a nonpositive value with zero, including zero itself.
Saved inputs
- b
- 0
- t
- 0
- m
- 2
- preactivation
- -1
Saved outputs
- activation
- 0
FFN output [0,0,0]
moe_t1_r1_e0_s1_ffn_output_0_0_0
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.
Saved inputs
- b
- 0
- t
- 0
- d
- 0
- h0
- 0
- w0
- 1
- h1
- 1
- w1
- 0
- h2
- 0
- w2
- 1
- bias
- 0
Saved outputs
- product0
- 0
- product1
- 0
- product2
- 0
- running0
- 0
- running1
- 0
- running2
- 0
- sum
- 0
- value
- 0
FFN output [0,0,1]
moe_t1_r1_e0_s1_ffn_output_0_0_1
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.
Saved inputs
- b
- 0
- t
- 0
- d
- 1
- h0
- 0
- w0
- 0
- h1
- 1
- w1
- 1
- h2
- 0
- w2
- 1
- bias
- 0
Saved outputs
- product0
- 0
- product1
- 1
- product2
- 0
- running0
- 0
- running1
- 1
- running2
- 1
- sum
- 1
- value
- 1
Post-output expert gain at original token 1, rank 1, feature 0
moe_t1_r1_e0_s1_gain_0
scaled=value*gain
Multiply the actual completed M3 expert output by its gain after all hidden/output products, ReLUs and biases. A zero gain still follows a full admitted expert invocation.
Saved inputs
- t
- 1
- rank
- 1
- expert
- 0
- slot
- 1
- d
- 0
- value
- 0
- gain
- 1
Saved outputs
- scaled
- 0
Post-output expert gain at original token 1, rank 1, feature 1
moe_t1_r1_e0_s1_gain_1
scaled=value*gain
Multiply the actual completed M3 expert output by its gain after all hidden/output products, ReLUs and biases. A zero gain still follows a full admitted expert invocation.
Saved inputs
- t
- 1
- rank
- 1
- expert
- 0
- slot
- 1
- d
- 1
- value
- 1
- gain
- 1
Saved outputs
- scaled
- 1
Admission at token 2, rank 0, expert 0
moe_dispatch_2_0
admitted=countBefore<capacity; slot=admitted?countBefore:-1; increment only admitted expert; fold kept or lost gate separately
Visit tokens then ranks. Capacity counts assignments per expert; rejection does not increment load, reroute, add a residual or redistribute a gate.
Saved inputs
- t
- 2
- rank
- 0
- expert
- 0
- capacity
- 2
- countBefore
- 2
- gate
- 0.5
- keptBefore
- 0
- lostBefore
- 0
Saved outputs
- admitted
- 0
- slot
- -1
- countAfter
- 2
- keptMass
- 0
- lostMass
- 0.5
Admission at token 2, rank 1, expert 1
moe_dispatch_2_1
admitted=countBefore<capacity; slot=admitted?countBefore:-1; increment only admitted expert; fold kept or lost gate separately
Visit tokens then ranks. Capacity counts assignments per expert; rejection does not increment load, reroute, add a residual or redistribute a gate.
Saved inputs
- t
- 2
- rank
- 1
- expert
- 1
- capacity
- 2
- countBefore
- 2
- gate
- 0.5
- keptBefore
- 0
- lostBefore
- 0.5
Saved outputs
- admitted
- 0
- slot
- -1
- countAfter
- 2
- keptMass
- 0
- lostMass
- 1
Combine token 0, feature 0, rank 0
moe_combine_0_0_0
contribution=gate*expertOutput; value=previous+contribution
Use the original pre-drop gate and the saved postgain output of this admitted invocation. Start each output coordinate at +0 and fold ranks in order.
Saved inputs
- t
- 0
- rank
- 0
- expert
- 0
- d
- 0
- admitted
- 1
- gate
- 0.7310585786300048
- expertOutput
- 2
- previous
- 0
Saved outputs
- contribution
- 1.4621171572600096
- value
- 1.4621171572600096
Combine token 0, feature 0, rank 1
moe_combine_0_0_1
contribution=gate*expertOutput; value=previous+contribution
Use the original pre-drop gate and the saved postgain output of this admitted invocation. Start each output coordinate at +0 and fold ranks in order.
Saved inputs
- t
- 0
- rank
- 1
- expert
- 1
- d
- 0
- admitted
- 1
- gate
- 0.26894142136999516
- expertOutput
- -0.5
- previous
- 1.4621171572600096
Saved outputs
- contribution
- -0.13447071068499758
- value
- 1.327646446575012
Combine token 0, feature 1, rank 0
moe_combine_0_1_0
contribution=gate*expertOutput; value=previous+contribution
Use the original pre-drop gate and the saved postgain output of this admitted invocation. Start each output coordinate at +0 and fold ranks in order.
Saved inputs
- t
- 0
- rank
- 0
- expert
- 0
- d
- 1
- admitted
- 1
- gate
- 0.7310585786300048
- expertOutput
- 1
- previous
- 0
Saved outputs
- contribution
- 0.7310585786300048
- value
- 0.7310585786300048
Combine token 0, feature 1, rank 1
moe_combine_0_1_1
contribution=gate*expertOutput; value=previous+contribution
Use the original pre-drop gate and the saved postgain output of this admitted invocation. Start each output coordinate at +0 and fold ranks in order.
Saved inputs
- t
- 0
- rank
- 1
- expert
- 1
- d
- 1
- admitted
- 1
- gate
- 0.26894142136999516
- expertOutput
- -0.5
- previous
- 0.7310585786300048
Saved outputs
- contribution
- -0.13447071068499758
- value
- 0.5965878679450072
Combine token 1, feature 0, rank 0
moe_combine_1_0_0
contribution=gate*expertOutput; value=previous+contribution
Use the original pre-drop gate and the saved postgain output of this admitted invocation. Start each output coordinate at +0 and fold ranks in order.
Saved inputs
- t
- 1
- rank
- 0
- expert
- 1
- d
- 0
- admitted
- 1
- gate
- 0.7310585786300048
- expertOutput
- 0
- previous
- 0
Saved outputs
- contribution
- 0
- value
- 0
Combine token 1, feature 0, rank 1
moe_combine_1_0_1
contribution=gate*expertOutput; value=previous+contribution
Use the original pre-drop gate and the saved postgain output of this admitted invocation. Start each output coordinate at +0 and fold ranks in order.
Saved inputs
- t
- 1
- rank
- 1
- expert
- 0
- d
- 0
- admitted
- 1
- gate
- 0.26894142136999516
- expertOutput
- 0
- previous
- 0
Saved outputs
- contribution
- 0
- value
- 0
Combine token 1, feature 1, rank 0
moe_combine_1_1_0
contribution=gate*expertOutput; value=previous+contribution
Use the original pre-drop gate and the saved postgain output of this admitted invocation. Start each output coordinate at +0 and fold ranks in order.
Saved inputs
- t
- 1
- rank
- 0
- expert
- 1
- d
- 1
- admitted
- 1
- gate
- 0.7310585786300048
- expertOutput
- 2
- previous
- 0
Saved outputs
- contribution
- 1.4621171572600096
- value
- 1.4621171572600096
Combine token 1, feature 1, rank 1
moe_combine_1_1_1
contribution=gate*expertOutput; value=previous+contribution
Use the original pre-drop gate and the saved postgain output of this admitted invocation. Start each output coordinate at +0 and fold ranks in order.
Saved inputs
- t
- 1
- rank
- 1
- expert
- 0
- d
- 1
- admitted
- 1
- gate
- 0.26894142136999516
- expertOutput
- 1
- previous
- 1.4621171572600096
Saved outputs
- contribution
- 0.26894142136999516
- value
- 1.7310585786300048
Dropped contribution at token 2, feature 0, rank 0
moe_combine_2_0_0
contribution=+0 (drop policy); value=previous+contribution
This literal +0 is a dropped message policy, not a computed expert output. No MLP or multiplication by an unevaluated expert result occurs.
Saved inputs
- t
- 2
- rank
- 0
- expert
- 0
- d
- 0
- admitted
- 0
- previous
- 0
Saved outputs
- contribution
- 0
- value
- 0
Dropped contribution at token 2, feature 0, rank 1
moe_combine_2_0_1
contribution=+0 (drop policy); value=previous+contribution
This literal +0 is a dropped message policy, not a computed expert output. No MLP or multiplication by an unevaluated expert result occurs.
Saved inputs
- t
- 2
- rank
- 1
- expert
- 1
- d
- 0
- admitted
- 0
- previous
- 0
Saved outputs
- contribution
- 0
- value
- 0
Dropped contribution at token 2, feature 1, rank 0
moe_combine_2_1_0
contribution=+0 (drop policy); value=previous+contribution
This literal +0 is a dropped message policy, not a computed expert output. No MLP or multiplication by an unevaluated expert result occurs.
Saved inputs
- t
- 2
- rank
- 0
- expert
- 0
- d
- 1
- admitted
- 0
- previous
- 0
Saved outputs
- contribution
- 0
- value
- 0
Dropped contribution at token 2, feature 1, rank 1
moe_combine_2_1_1
contribution=+0 (drop policy); value=previous+contribution
This literal +0 is a dropped message policy, not a computed expert output. No MLP or multiplication by an unevaluated expert result occurs.
Saved inputs
- t
- 2
- rank
- 1
- expert
- 1
- d
- 1
- admitted
- 0
- previous
- 0
Saved outputs
- contribution
- 0
- value
- 0
Retain every original token and disclose routing losses
finish
output=moe_Y; counts=moe_Counts; no post-drop redistribution
Copy the saved dispatch counts after all router, admitted expert and combine work. A fully lost token has no admitted assignment; a zero output can also be real expert cancellation. Source graph counts are not measured hardware performance.
Saved inputs
- topK
- 2
- capacity
- 2
- tokens
- 3
- experts
- 3
- hiddenWidth
- 3
- selectedAssignments
- 6
- acceptedAssignments
- 4
- droppedAssignments
- 2
- fullyLostTokens
- 1
- partiallyDroppedTokens
- 0
Saved outputs
- topK
- 2
- capacity
- 2
- tokens
- 3
- experts
- 3
- hiddenWidth
- 3
- selectedAssignments
- 6
- acceptedAssignments
- 4
- droppedAssignments
- 2
- fullyLostTokens
- 1
- partiallyDroppedTokens
- 0
- expCalls
- 9
- sqrtCalls
- 0
- nativeElementaryCalls
- 9
- frames
- 90
- tensorCount
- 76
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.
moe_Raw
RawField=17 · float64 · precision 8 · Captured raw17 in rawFields order; topK/capacity are VALUE, all other raw cells WORD including -0.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2 |
| 1 | 2 |
| 2 | 1 |
| 3 | 0 |
| 4 | 0 |
| 5 | 1 |
| 6 | 1 |
| 7 | 1 |
| 8 | 1 |
| 9 | 1 |
| 10 | 1 |
| 11 | 0 |
| 12 | 0 |
| 13 | 0 |
| 14 | 1 |
| 15 | 1 |
| 16 | 1 |
moe_X
B=1 × T=3 × D=2 · float64 · precision 8 · Six actual raw input feature words in original token order; no lookup or token reordering.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
moe_RouterWeights
D=2 × Expert=3 · float64 · precision 8 · Fixed row-feature router matrix [[1,+0,-1],[+0,1,-1]]; gains are applied after both products and their direct sum.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | -1 |
| 3 | 0 |
| 4 | 1 |
| 5 | -1 |
moe_RouterGains
Expert=3 · float64 · precision 8 · Actual r0,r1,r2 postprojection gain words.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 1 |
moe_RouterBiases
Expert=3 · float64 · precision 8 · Actual b0,b1,b2 words, added after router gain.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
moe_ExpertGains
Expert=3 · float64 · precision 8 · Actual e0,e1,e2 post-output gain words, including unused experts.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 1 |
moe_ExpertW1
Expert=3 × D=2 × HiddenFeature=3 · float64 · precision 8 · All three fixed meaningful M3 expert W1 banks in row-feature storage, including unselected experts.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 1 |
| 3 | 0 |
| 4 | 1 |
| 5 | -1 |
| 6 | 1 |
| 7 | 0 |
| 8 | 1 |
| 9 | 0 |
| 10 | 1 |
| 11 | -1 |
| 12 | 1 |
| 13 | -1 |
| 14 | 1 |
| 15 | 1 |
| 16 | 1 |
| 17 | 0 |
moe_ExpertB1
Expert=3 × HiddenFeature=3 · float64 · precision 8 · All three fixed hidden bias banks; every coordinate is literal +0 and is added last.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
| 6 | 0 |
| 7 | 0 |
| 8 | 0 |
moe_ExpertW2
Expert=3 × HiddenFeature=3 × D=2 · float64 · precision 8 · All three fixed output banks; all three hidden products and ordered running sums remain real work.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
| 6 | -1 |
| 7 | 0 |
| 8 | 0 |
| 9 | 2 |
| 10 | 0.5 |
| 11 | -0.5 |
| 12 | 0.5 |
| 13 | 0.5 |
| 14 | 1 |
| 15 | -1 |
| 16 | 0 |
| 17 | 1 |
moe_ExpertB2
Expert=3 × D=2 · float64 · precision 8 · All three fixed output bias banks, literal +0 added after three products and running sums.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
moe_RouterStages
B=1 × T=3 × Expert=3 × RouterField=5 · float64 · precision 8 · Actual product0,product1,sum,scaled,logit in token/expert order.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 1 |
| 3 | 1 |
| 4 | 1 |
| 5 | 0 |
| 6 | 0 |
| 7 | 0 |
| 8 | 0 |
| 9 | 0 |
| 10 | -1 |
| 11 | -0 |
| 12 | -1 |
| 13 | -1 |
| 14 | -1 |
| 15 | 0 |
| 16 | 0 |
| 17 | 0 |
| 18 | 0 |
| 19 | 0 |
| 20 | 0 |
| 21 | 1 |
| 22 | 1 |
| 23 | 1 |
| 24 | 1 |
| 25 | -0 |
| 26 | -1 |
| 27 | -1 |
| 28 | -1 |
| 29 | -1 |
| 30 | 1 |
| 31 | 0 |
| 32 | 1 |
| 33 | 1 |
| 34 | 1 |
| 35 | 0 |
| 36 | 1 |
| 37 | 1 |
| 38 | 1 |
| 39 | 1 |
| 40 | -1 |
| 41 | -1 |
| 42 | -2 |
| 43 | -2 |
| 44 | -2 |
moe_Logits
B=1 × T=3 × Expert=3 · float64 · precision 8 · Actual computed finite router logits; these words alone determine expert ranking.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | -1 |
| 3 | 0 |
| 4 | 1 |
| 5 | -1 |
| 6 | 1 |
| 7 | 1 |
| 8 | -2 |
moe_Maxima
T=3 · float64 · precision 8 · Actual Math.max-selected full-row maxima, including its +0 preference.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 1 |
moe_Shifted
B=1 × T=3 × Expert=3 · float64 · precision 8 · Functional native-argument witnesses: the identical immutable logit-minus-max subtraction used by unchanged stableSoftmax, without another exp.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | -1 |
| 2 | -2 |
| 3 | -1 |
| 4 | 0 |
| 5 | -2 |
| 6 | 0 |
| 7 | 0 |
| 8 | -3 |
moe_Terms
B=1 × T=3 × Expert=3 · float64 · precision 8 · All nine actual native exp outputs, including capacity zero.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0.36787944117144233 |
| 2 | 0.1353352832366127 |
| 3 | 0.36787944117144233 |
| 4 | 1 |
| 5 | 0.1353352832366127 |
| 6 | 1 |
| 7 | 1 |
| 8 | 0.049787068367863944 |
moe_Denominators
T=3 · float64 · precision 8 · Actual stableSoftmax denominators from +0 then term0,term1,term2 in expert order.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1.5032147244080551 |
| 1 | 1.5032147244080551 |
| 2 | 2.049787068367864 |
moe_Probabilities
B=1 × T=3 × Expert=3 · float64 · precision 8 · Full three-expert probabilities before top-k selection or capacity.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.6652409557748218 |
| 1 | 0.24472847105479764 |
| 2 | 0.09003057317038046 |
| 3 | 0.24472847105479764 |
| 4 | 0.6652409557748218 |
| 5 | 0.09003057317038046 |
| 6 | 0.4878555511603684 |
| 7 | 0.4878555511603684 |
| 8 | 0.024288897679263205 |
moe_Ranking
T=3 × Rank=3 · int32 · precision 0 · All expert IDs sorted by descending actual computed logits and exact lower-ID ties.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 2 |
| 3 | 1 |
| 4 | 0 |
| 5 | 2 |
| 6 | 0 |
| 7 | 1 |
| 8 | 2 |
moe_SelectedExperts
T=3 × Rank=2 · int32 · precision 0 · First topK distinct expert IDs from each full computed-logit ranking.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 1 |
| 3 | 0 |
| 4 | 0 |
| 5 | 1 |
moe_SelectedProbabilities
T=3 × Rank=2 · float64 · precision 8 · Unchanged selected full-softmax probability words in token/rank order.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.6652409557748218 |
| 1 | 0.24472847105479764 |
| 2 | 0.6652409557748218 |
| 3 | 0.24472847105479764 |
| 4 | 0.4878555511603684 |
| 5 | 0.4878555511603684 |
moe_SelectedSums
T=3 · float64 · precision 8 · Completed +0 rank folds over selected full probabilities, before admission.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.9099694268296195 |
| 1 | 0.9099694268296195 |
| 2 | 0.9757111023207368 |
moe_Gates
T=3 × Rank=2 · float64 · precision 8 · Actual selected probability divided by selected sum before capacity; never renormalized after drops.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.7310585786300048 |
| 1 | 0.26894142136999516 |
| 2 | 0.7310585786300048 |
| 3 | 0.26894142136999516 |
| 4 | 0.5 |
| 5 | 0.5 |
moe_Admitted
T=3 × Rank=2 · int32 · precision 0 · 1 if this token/rank assignment was admitted, 0 if capacity dropped it; not an expert-output value.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 0 |
| 5 | 0 |
moe_Slots
T=3 × Rank=2 · int32 · precision 0 · Per-expert zero-based admitted slot; -1 means dropped and allocates no slot.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 1 |
| 3 | 1 |
| 4 | -1 |
| 5 | -1 |
moe_t0_r0_e0_s0_Context
ContextField=7 · int32 · precision 0 · Original token,rank,expert,slot,sourceOffset,localB,localT in that order; local B/T indices are 0, not original token IDs.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
| 6 | 0 |
moe_t0_r0_e0_s0_Input
B=1 × T=1 × D=2 · float64 · precision 8 · Exact original token feature words copied to local B=1,T=1,D=2; context records the original token, rank, expert and admitted slot.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
moe_t0_r0_e0_s0_ffn_W1
D=2 × HiddenFeature=3 · float64 · precision 8 · Shared input-to-hidden weights, f1{d}{m}; M=3 hidden features.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 1 |
| 3 | 0 |
| 4 | 1 |
| 5 | -1 |
moe_t0_r0_e0_s0_ffn_b1
HiddenFeature=3 · float64 · precision 8 · Shared hidden bias, added after the two products.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
moe_t0_r0_e0_s0_ffn_Z
B=1 × T=1 × HiddenFeature=3 · float64 · precision 8 · Hidden preactivations X W1+b1; no batch or token mixing.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 1 |
moe_t0_r0_e0_s0_ffn_Hidden
B=1 × T=1 × HiddenFeature=3 · float64 · precision 8 · ReLU(Z)=max(0,Z), before the second affine layer.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 1 |
moe_t0_r0_e0_s0_ffn_W2
HiddenFeature=3 × D=2 · float64 · precision 8 · Shared hidden-to-output weights, f2{m}{d}.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
moe_t0_r0_e0_s0_ffn_b2
D=2 · float64 · precision 8 · Shared output bias, added after all three running sums.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
moe_t0_r0_e0_s0_ffn_F
B=1 × T=1 × D=2 · float64 · precision 8 · ReLU(X W1+b1) W2+b2, independently per token with shared parameters.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2 |
| 1 | 1 |
moe_t0_r0_e0_s0_PostGain
B=1 × T=1 × D=2 · float64 · precision 8 · Actual completed expert F words multiplied by the selected expert post-output gain; no gain moved into weights or before ReLU.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2 |
| 1 | 1 |
moe_t0_r1_e1_s0_Context
ContextField=7 · int32 · precision 0 · Original token,rank,expert,slot,sourceOffset,localB,localT in that order; local B/T indices are 0, not original token IDs.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 1 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
| 6 | 0 |
moe_t0_r1_e1_s0_Input
B=1 × T=1 × D=2 · float64 · precision 8 · Exact original token feature words copied to local B=1,T=1,D=2; context records the original token, rank, expert and admitted slot.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
moe_t0_r1_e1_s0_ffn_W1
D=2 × HiddenFeature=3 · float64 · precision 8 · Shared input-to-hidden weights, f1{d}{m}; M=3 hidden features.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 1 |
| 3 | 0 |
| 4 | 1 |
| 5 | -1 |
moe_t0_r1_e1_s0_ffn_b1
HiddenFeature=3 · float64 · precision 8 · Shared hidden bias, added after the two products.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
moe_t0_r1_e1_s0_ffn_Z
B=1 × T=1 × HiddenFeature=3 · float64 · precision 8 · Hidden preactivations X W1+b1; no batch or token mixing.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 1 |
moe_t0_r1_e1_s0_ffn_Hidden
B=1 × T=1 × HiddenFeature=3 · float64 · precision 8 · ReLU(Z)=max(0,Z), before the second affine layer.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 1 |
moe_t0_r1_e1_s0_ffn_W2
HiddenFeature=3 × D=2 · float64 · precision 8 · Shared hidden-to-output weights, f2{m}{d}.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 2 |
| 4 | 0.5 |
| 5 | -0.5 |
moe_t0_r1_e1_s0_ffn_b2
D=2 · float64 · precision 8 · Shared output bias, added after all three running sums.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
moe_t0_r1_e1_s0_ffn_F
B=1 × T=1 × D=2 · float64 · precision 8 · ReLU(X W1+b1) W2+b2, independently per token with shared parameters.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.5 |
| 1 | -0.5 |
moe_t0_r1_e1_s0_PostGain
B=1 × T=1 × D=2 · float64 · precision 8 · Actual completed expert F words multiplied by the selected expert post-output gain; no gain moved into weights or before ReLU.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.5 |
| 1 | -0.5 |
moe_t1_r0_e1_s1_Context
ContextField=7 · int32 · precision 0 · Original token,rank,expert,slot,sourceOffset,localB,localT in that order; local B/T indices are 0, not original token IDs.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 0 |
| 6 | 0 |
moe_t1_r0_e1_s1_Input
B=1 × T=1 × D=2 · float64 · precision 8 · Exact original token feature words copied to local B=1,T=1,D=2; context records the original token, rank, expert and admitted slot.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
moe_t1_r0_e1_s1_ffn_W1
D=2 × HiddenFeature=3 · float64 · precision 8 · Shared input-to-hidden weights, f1{d}{m}; M=3 hidden features.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 1 |
| 3 | 0 |
| 4 | 1 |
| 5 | -1 |
moe_t1_r0_e1_s1_ffn_b1
HiddenFeature=3 · float64 · precision 8 · Shared hidden bias, added after the two products.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
moe_t1_r0_e1_s1_ffn_Z
B=1 × T=1 × HiddenFeature=3 · float64 · precision 8 · Hidden preactivations X W1+b1; no batch or token mixing.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | -1 |
moe_t1_r0_e1_s1_ffn_Hidden
B=1 × T=1 × HiddenFeature=3 · float64 · precision 8 · ReLU(Z)=max(0,Z), before the second affine layer.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 0 |
moe_t1_r0_e1_s1_ffn_W2
HiddenFeature=3 × D=2 · float64 · precision 8 · Shared hidden-to-output weights, f2{m}{d}.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 2 |
| 4 | 0.5 |
| 5 | -0.5 |
moe_t1_r0_e1_s1_ffn_b2
D=2 · float64 · precision 8 · Shared output bias, added after all three running sums.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
moe_t1_r0_e1_s1_ffn_F
B=1 × T=1 × D=2 · float64 · precision 8 · ReLU(X W1+b1) W2+b2, independently per token with shared parameters.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 2 |
moe_t1_r0_e1_s1_PostGain
B=1 × T=1 × D=2 · float64 · precision 8 · Actual completed expert F words multiplied by the selected expert post-output gain; no gain moved into weights or before ReLU.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 2 |
moe_t1_r1_e0_s1_Context
ContextField=7 · int32 · precision 0 · Original token,rank,expert,slot,sourceOffset,localB,localT in that order; local B/T indices are 0, not original token IDs.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 0 |
| 3 | 1 |
| 4 | 2 |
| 5 | 0 |
| 6 | 0 |
moe_t1_r1_e0_s1_Input
B=1 × T=1 × D=2 · float64 · precision 8 · Exact original token feature words copied to local B=1,T=1,D=2; context records the original token, rank, expert and admitted slot.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
moe_t1_r1_e0_s1_ffn_W1
D=2 × HiddenFeature=3 · float64 · precision 8 · Shared input-to-hidden weights, f1{d}{m}; M=3 hidden features.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 1 |
| 3 | 0 |
| 4 | 1 |
| 5 | -1 |
moe_t1_r1_e0_s1_ffn_b1
HiddenFeature=3 · float64 · precision 8 · Shared hidden bias, added after the two products.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
moe_t1_r1_e0_s1_ffn_Z
B=1 × T=1 × HiddenFeature=3 · float64 · precision 8 · Hidden preactivations X W1+b1; no batch or token mixing.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | -1 |
moe_t1_r1_e0_s1_ffn_Hidden
B=1 × T=1 × HiddenFeature=3 · float64 · precision 8 · ReLU(Z)=max(0,Z), before the second affine layer.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 0 |
moe_t1_r1_e0_s1_ffn_W2
HiddenFeature=3 × D=2 · float64 · precision 8 · Shared hidden-to-output weights, f2{m}{d}.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
moe_t1_r1_e0_s1_ffn_b2
D=2 · float64 · precision 8 · Shared output bias, added after all three running sums.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
moe_t1_r1_e0_s1_ffn_F
B=1 × T=1 × D=2 · float64 · precision 8 · ReLU(X W1+b1) W2+b2, independently per token with shared parameters.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
moe_t1_r1_e0_s1_PostGain
B=1 × T=1 × D=2 · float64 · precision 8 · Actual completed expert F words multiplied by the selected expert post-output gain; no gain moved into weights or before ReLU.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
moe_Loads
Expert=3 · int32 · precision 0 · Final per-expert admitted assignment counts, reset for every evaluation.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2 |
| 1 | 2 |
| 2 | 0 |
moe_TokenAccepted
T=3 · int32 · precision 0 · Number of admitted assignments for each original token.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2 |
| 1 | 2 |
| 2 | 0 |
moe_TokenDropped
T=3 · int32 · precision 0 · Number of dropped selected assignments for each original token.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 2 |
moe_FullyLost
T=3 · int32 · precision 0 · 1 exactly when no assignment was admitted for this token; zero output alone does not establish loss.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 1 |
moe_PartiallyDropped
T=3 · int32 · precision 0 · 1 exactly when some but not all selected assignments were dropped.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
moe_KeptMass
T=3 · float64 · precision 8 · Independent +0 rank fold of admitted pre-drop gates; not computed as one minus lost mass.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 0 |
moe_LostMass
T=3 · float64 · precision 8 · Independent +0 rank fold of dropped pre-drop gates; not a quality, norm or probability of failure.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 1 |
moe_GatedContributions
B=1 × T=3 × Rank=2 × D=2 · float64 · precision 8 · Admitted gate times saved postgain output; dropped cells are literal +0 policy messages, not computed expert outputs.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1.4621171572600096 |
| 1 | 0.7310585786300048 |
| 2 | -0.13447071068499758 |
| 3 | -0.13447071068499758 |
| 4 | 0 |
| 5 | 1.4621171572600096 |
| 6 | 0 |
| 7 | 0.26894142136999516 |
| 8 | 0 |
| 9 | 0 |
| 10 | 0 |
| 11 | 0 |
moe_Y
B=1 × T=3 × D=2 · float64 · precision 8 · Actual per-original-token branch output, +0 then rank-ordered admitted gated messages and explicit dropped-policy +0 additions. No residual or fallback.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1.327646446575012 |
| 1 | 0.5965878679450072 |
| 2 | 0 |
| 3 | 1.7310585786300048 |
| 4 | 0 |
| 5 | 0 |
moe_Counts
CountField=5 · int32 · precision 0 · Selected assignments,accepted assignments,dropped assignments,fully lost tokens,partially dropped tokens in that order.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 6 |
| 1 | 4 |
| 2 | 2 |
| 3 | 1 |
| 4 | 0 |
moe_NativeArguments
Native=9 × NativeField=2 · float64 · precision 8 · Actual exp argument functional witnesses and actual exp outputs in token/expert occurrence order; no native call during serialization.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | -1 |
| 3 | 0.36787944117144233 |
| 4 | -2 |
| 5 | 0.1353352832366127 |
| 6 | -1 |
| 7 | 0.36787944117144233 |
| 8 | 0 |
| 9 | 1 |
| 10 | -2 |
| 11 | 0.1353352832366127 |
| 12 | 0 |
| 13 | 1 |
| 14 | 0 |
| 15 | 1 |
| 16 | -3 |
| 17 | 0.049787068367863944 |
moe_NativeKinds
Native=9 · int32 · precision 0 · Native kind code exp=1 for all nine occurrences; no sqrt occurs.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
| 6 | 1 |
| 7 | 1 |
| 8 | 1 |
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.
Exactly five corrective questions use explicit fixed worksheets or this current WHOLE saved root. Native controls, focused scrollable tables and the complete operation fallback support keyboard/touch exploration. All runtime, browser and accessibility checks remain deferred.
Begin with one capacity change
At Reset example, read the three rows in Every original token. The default selects experts (0,1), (1,0), and (0,1). In Admitted flags, the last two assignments are zero, and the corresponding slots are -1. The saved counts show four admissions, two drops and one fully lost token. Its row remains in Y as the explicit zero branch output; the input row is still present.
Change Admitted assignments per expert (capacity) to3. The final token now has two real expert calls, and Y2 becomes [0,3/2]: its first feature cancels, although neither assignment was lost. Reset, open Router gains, and change only r2 to -1. The final token now keeps its expert0 route after expert2 fills: its two output coordinates equal that surviving original gate, rather than being redistributed to one. The full hand derivation appears below.
All seventeen inputs are editable. The two menus choose topK and capacity; the feature, router-gain, router-bias and expert-output-gain groups reveal the fifteen continuous numerical operands. Those fields accept finite fractional values within their stated ranges, including -0. Even an unused expert gain is validated. A blank, nonfinite or out-of-range draft withholds output tables and grading until corrected; reset restores the entire starting state.
Use Calculation step, Previous step and Next step to inspect a saved operation, including its equation, explanation and every operand. The cursor changes which step is explained; it does not create a different numerical result. Edits, reset and trace changes clear chosen exercise answers, while opening a disclosure preserves them. Every actual saved tensor includes all fixed banks and the true per-invocation storage. Every saved operation is a text fallback for all products and combine branches. The nine-occurrence native ledger distinguishes functional argument witnesses from a physical instruction trace. Focus a labelled table region to scroll wide storage tables with the keyboard. Browser, layout and accessibility behavior still await the deferred checks.
Review IV-33 — A Complete Transformer Block for the position-wise feed-forward network. Book II’s II.4 — Dot product, angle, and orthogonality develops dot products, II.10 — Matrix × matrix as composition explains matrix composition, and VIII.2 — Rounding and representation error explains numerical rounding. Book III’s III-16 — Multiclass Classification and Softmax Regression connects scores with softmax, and III-41 — Composition and Learned Representations develops composition of neural calculations. Those earlier calculations provide the ingredients; here the new step is deciding which networks receive which tokens.
What is being routed?
A token here is an already embedded input position represented by two features, its numerical coordinates. It is not a vocabulary ID or a generated word. A batch groups inputs processed together. A tensor is an array with named axes. Input X has shape [B=1,T=3,D=2]: one batch, three token positions, two features per token. Its default rows are t0=(1,0), t1=(0,1), and t2=(1,1). Output Y keeps shape [1,3,2], including a row whose routes were all dropped.
There are E=3 experts, numbered 0, 1, and 2. Each is a real MLP, a multilayer perceptron: an affine layer, a ReLU, and another affine layer. Affine means multiply and then add a bias. A bias is a parameter added after the products. ReLU, rectified linear unit, keeps a positive number and replaces a negative number with zero; at zero its output is zero. Every expert has M=3 hidden coordinates. “Hidden” means intermediate, and we will show all of them.
The router produces a logit, an unrestricted preference score, for each expert. Softmax converts the three scores into positive normalized weights. Top-k selects k distinct expert IDs, with k equal to 1 or 2. A token paired with a selected expert is an assignment: top-2 makes two assignments per token, each carrying the entire two-coordinate vector. A gate multiplies an expert’s output. It is not a hidden activation or a probability of the next word.
Dispatch visits assignments and decides whether to admit them. Capacity C is the maximum number of admitted assignments per expert in this batch. A slot is an admitted assignment’s zero-based position inside that expert. Overflow drops an assignment when its expert is full. A partially dropped token retains at least one admitted route and loses another; a fully lost token has no admitted route. The word “lost” refers to this isolated branch: the original input row is still present.
The pipeline has separate jobs: scores express preferences; softmax and selected normalization form gates; admission decides which assignments exist; admitted MLPs compute feature vectors; combine adds gated vectors. A spare slot in an unselected expert does not create permission to reroute.
The complete bounded input and its units
The seventeen raw fields are topK, capacity, x00, x01, x10, x11, x20, x21, r0, r1, r2, b0, b1, b2, e0, e1, e2, in that order. topK is k and capacity is C. xij is coordinate j of original token i. The three r fields scale router projections; the three b fields are router biases; the three e fields scale completed expert outputs. An expert ID is an integer identity, whereas e0 is a numerical gain for expert 0.
| Fields | Default | Domain | Meaning / units |
|---|---|---|---|
| topK | 2 | integer 1 or 2 | assignments selected per token |
| capacity | 2 | integer 0 through 3 | admitted assignments per expert per batch |
| x00,x01,x10,x11,x20,x21 | 1,0,0,1,1,1 | each in [-2,2] | dimensionless feature coordinates |
| r0,r1,r2 | 1,1,1 | each in [-1,1] | dimensionless router postprojection gains |
| b0,b1,b2 | 0,0,0 | each in [-2,2] | additive score offsets, in logit units |
| e0,e1,e2 | 1,1,1 | each in [-1,1] | dimensionless expert post-output gains |
All numbers must be finite. These toy features have no physical unit such as seconds or bytes. Gates and their sums are dimensionless; loads count assignments. A kept gate mass of one half is not half a token or a measured quality score.
The input boundary examines all own data-field descriptors before reading their values. A descriptor distinguishes stored data from a getter that could execute code. Only a complete ordinary or null-prototype data record with exactly these fields is accepted. All seventeen values must be finite before domain decisions are made in the listed order; trace-prefix validation follows. There is no coercion of strings, clamping, or merging a partial supplied state with defaults. Even at C=0, unused e2 or a coordinate of a later dropped token must be valid. Invalid input withholds the result rather than showing an old success.
Shapes explain why the products are legal
For one mathematical column token v=(x,y), v has shape [2,1]. The router column matrix is the transpose of the stored row-feature W_R, so W_R transpose has shape [3,2] and maps v to three scores. Expert input matrices in column form have shape [3,2]; their output matrices have shape [2,3]. A transpose interchanges a matrix’s row and column axes. It changes storage orientation without changing the intended linear map when used consistently.
In feature-last row storage, use these shapes:
| Quantity | Shape and axes | Interpretation |
|---|---|---|
| X and Y | [1,3,2], B,T,D | original input and combined output |
| W_R | [2,3], D,Expert | router matrix |
| full score/softmax rows | [1,3,3], B,T,Expert | all three experts for each token |
| selected assignment metadata | [3,k], T,Rank | expert ID, decision, slot or drop marker |
| each expert W1 | [2,3], D,HiddenFeature | two inputs to three hidden coordinates |
| each expert hidden bias | [3], HiddenFeature | added to that expert’s hidden row |
| each expert W2 | [3,2], HiddenFeature,D | three hidden values to two output values |
| each expert output bias | [2], D | added last to its output row |
| admitted call input | [1,1,2], B,T,D (T is local) | one original token sent to one expert |
| admitted call hidden and output | [1,1,3] and [1,1,2] | actual per-call intermediate and result |
In these stored axis names B means batch, T token position, D the two feature coordinates, and HiddenFeature the three intermediate coordinates. An admitted call has its own local T axis; its separate context identifies the original token. The full fixed banks add an outer Expert axis: W1 [3,2,3], hidden biases [3,3], W2 [3,3,2], output biases [3,2]. These shapes describe the actual saved banks; the inspector names them ExpertW1, ExpertB1, ExpertW2 and ExpertB2 under the moe prefix. Bias addition broadcasts the [3] or [2] bias to the single call’s hidden or output row. No implicit transpose or broadcast across expert identities is intended.
An admitted call uses local token index 0 even when it came from original t2. Its context must retain original token, selected rank, expert, slot, and source offset. The final Y assembles messages in original token order; it does not concatenate expert queues. A dropped or unselected call has no hidden/output tensor. An empty queue is metadata, not a tensor with an empty axis.
All nine router logits
The fixed row-feature router bank is W_R=[[1,0,-1],[0,1,-1]]. For original token t and expert j, compute two products p0=X[t,0]*W_R[0,j] and p1=X[t,1]*W_R[1,j]. Add them directly to get u=p0+p1, multiply by rj, and add bj last: score=(u*rj)+bj. Do not move rj into the matrix coefficients. Even zero products remain part of the stated operation sequence.
With the default gains and biases:
| Token | Expert 0 | Expert 1 | Expert 2 |
|---|---|---|---|
| t0=(1,0) | p=(1*1,0*0)=(1,0); u=1+0=1; 1*1+0=1 | p=(1*0,0*1)=(0,0); u=0+0=0; 0*1+0=0 | p=(1*(-1),0*(-1))=(-1,0); u=-1+0=-1; -1*1+0=-1 |
| t1=(0,1) | p=(0*1,1*0)=(0,0); u=0+0=0; 0*1+0=0 | p=(0*0,1*1)=(0,1); u=0+1=1; 1*1+0=1 | p=(0*(-1),1*(-1))=(0,-1); u=0-1=-1; -1*1+0=-1 |
| t2=(1,1) | p=(1*1,1*0)=(1,0); u=1+0=1; 1*1+0=1 | p=(1*0,1*1)=(0,1); u=0+1=1; 1*1+0=1 | p=(1*(-1),1*(-1))=(-1,-1); u=-1-1=-2; -2*1+0=-2 |
The third base score is -x-y. It is not -x. All tables in this lesson use the disclosed three-hidden-unit expert family and this router.
Full softmax first, selected gates second
Let m be a row’s largest computed score, a_j=score_j-m its shift, and u_j=exp(a_j) its exponential term. Here exp is the real exponential function, with exp(0)=1. Stable softmax subtracts m so every shift is nonpositive. Subtracting the same number from all scores preserves real softmax probabilities because the common exponential factor cancels.
Start the full denominator at +0 and add terms in expert-ID order: Z=((+0+u0)+u1)+u2. Full probability Pj=uj/Z includes all three experts, even an expert that will not be selected. For the exact-real worksheet define q=exp(-1), d=1+q, Z0=1+q+exp(-2), Z1=q+1+exp(-2), and Z2=2+exp(-3). Subscripts on Z identify tokens.
| Token | Maximum; shifts | Exponential terms; ordered denominator | Full P in expert order | Full expert ranking |
|---|---|---|---|---|
| t0 | 1; (0,-1,-2) | (1,q,exp(-2)); ((0+1)+q)+exp(-2)=Z0 | (1/Z0,q/Z0,exp(-2)/Z0) | (0,1,2) |
| t1 | 1; (-1,0,-2) | (q,1,exp(-2)); ((0+q)+1)+exp(-2)=Z1 | (q/Z1,1/Z1,exp(-2)/Z1) | (1,0,2) |
| t2 | 1; (0,0,-3) | (1,1,exp(-3)); ((0+1)+1)+exp(-3)=Z2 | (1/Z2,1/Z2,exp(-3)/Z2) | (0,1,2) |
Rank the actual finite logits descending, using lower expert ID only for exact computed-score ties. Selected rank 0 means first choice, not expert 0. At t1, rank 0 is expert 1. At t2, expert 0 wins the exact tie with expert 1.
For k=2, add the saved selected full probabilities in rank order, starting at +0, to obtain S. Then each gate g=Pselected/S. Thus t0 has S=(0+1/Z0)+q/Z0=d/Z0; t1 has S=(0+1/Z1)+q/Z1=d/Z1; t2 has S=(0+1/Z2)+1/Z2=2/Z2. Over exact reals the selected gate pairs are (1/d,q/d), (1/d,q/d), and (1/2,1/2). For k=1, S equals the one selected positive P and g=P/P=1. Using the winner’s full P as its gate would be a different policy.
These cancellations explain the numbers; they do not replace the native sequence. Binary64 is the finite floating-point format used by the source implementation. It uses saved returned exponential terms, full probabilities, the ordered selected sum, and gate divisions. It does not compute exp(-2) by squaring a rounded exp(-1), or substitute the simplified real gate ratios. Display rounding never feeds arithmetic, and a rounded gate sum need not equal one exactly.
Why sorting rounded probabilities is a trap
A monotone real softmax preserves score order, but finite returned probabilities can coincide after rounding. Set router gains to zero, b0=0, b1=epsilon, and b2=-1, where epsilon is the smallest positive binary64 number. The computed logits distinguish expert 1 from expert 0. Their shifted exponentials and probabilities can round equal. Sorting those equal-looking P values and choosing the lower ID could incorrectly choose expert 0 for top-1. The specified comparator selects expert 1 from the unequal logits. A displayed tie is not an exact score tie; no tolerance or extra epsilon is added to the comparator.
Admission spends per-expert capacity
Reset all expert admitted counts to zero on each recomputation. Visit original tokens t0,t1,t2, and within each visit selected ranks 0 then 1. If the target expert’s count is less than C, its current count becomes the slot, then that count increments. A rejection leaves the count unchanged. This is first-come token/rank order, not a global priority sort by gate size.
At default k=2,C=2:
| Visit | Token,rank,expert | Target count before | Decision / slot | Counts after (E0,E1,E2) |
|---|---|---|---|---|
| 0 | t0,0,0 | 0 | admit / 0 | (1,0,0) |
| 1 | t0,1,1 | 0 | admit / 0 | (1,1,0) |
| 2 | t1,0,1 | 1 | admit / 1 | (1,2,0) |
| 3 | t1,1,0 | 1 | admit / 1 | (2,2,0) |
| 4 | t2,0,0 | 2 | drop / no slot | (2,2,0) |
| 5 | t2,1,1 | 2 | drop / no slot | (2,2,0) |
There are six selected assignments, four admitted, two dropped, and one fully lost token. Loads (2,2,0) count assignments, not hidden units. Expert 2’s unused capacity does not rescue t2. Metadata can use the declared integer drop marker -1; that marker is not a real slot or a feature value.
Selected gates are fixed before capacity. Keep a sum of admitted gates and a separate sum of dropped gates, each starting at +0 in rank order. Over reals they sum to one per token. Do not compute lost mass as 1 minus kept mass, clip a rounded residual, or renormalize surviving gates. Default kept masses are (1,1,0) and lost masses (0,0,1) over the reals. Unselected full-P mass is not dropped selected-gate mass.
The full fixed expert banks
For expert j, W1_j maps the two features to three hidden coordinates; W2_j maps those three values back to two output features. Let beta_j be its hidden bias and gamma_j its output bias, distinguishing them from router biases b0,b1,b2. Every beta is (0,0,0) and every gamma is (0,0). All listed matrix zeros are literal +0 in the fixed bank.
| Expert | W1, rows InputFeature and columns Hidden | W2, rows Hidden and columns OutputFeature | beta; gamma |
|---|---|---|---|
| E0 | [[1,0,1],[0,1,-1]] | [[1,0],[0,1],[1,1]] | (0,0,0); (0,0) |
| E1 | [[1,0,1],[0,1,-1]] | [[-1,0],[0,2],[1/2,-1/2]] | (0,0,0); (0,0) |
| E2 | [[1,-1,1],[1,1,0]] | [[1/2,1/2],[1,-1],[0,1]] | (0,0,0); (0,0) |
For hidden coordinate m=0,1,2, form p0=x*W1[0,m], p1=y*W1[1,m], their direct sum p0+p1, then z_m=(p0+p1)+beta_m. Apply h_m=max(+0,z_m). For output feature f=0,1, form all three products h0*W2[0,f], h1*W2[1,f], h2*W2[2,f]. Start a running sum at +0, add those products in hidden-coordinate order, then add gamma_f last. Call this completed output F_j. There is no second ReLU after F_j, so a negative output is legal.
Only after both affine layers and ReLU compute the expert postgain vector V_j=(F_j[0]*e_j,F_j[1]*e_j). Moving this gain inside ReLU would change the network, particularly when the gain is negative. A zero gain still follows a fully evaluated admitted MLP; it does not remove a route or refund a slot.
Every hidden product, direct sum, bias, and ReLU for all three tokens
These are exact-real hand worksheets, including counterfactual pairs. In the default C=2 run, E0 and E1 on t0/t1 are admitted; E0/E1 on t2 are selected but dropped and therefore not computed. Every E2 pair is unselected and not computed in that default. At C=3, the E0/E1 t2 rows become real admitted work. In the later r2=-1,C=2 case, E2 t0/t1 become real admitted work, while E2 t2 is dropped. The tables do not claim that a sparse run evaluates all nine pairs.
E0 and E1 have the same input-to-hidden bank, so this table spells out their shared arithmetic once for each token. Each occurrence is independently evaluated when that expert is admitted.
| Token | Hidden 0: products, direct sum, bias, ReLU | Hidden 1: products, direct sum, bias, ReLU | Hidden 2: products, direct sum, bias, ReLU |
|---|---|---|---|
| t0=(1,0) | (1*1,0*0)=(1,0); 1+0=1; z0=1+0=1; h0=max(0,1)=1 | (1*0,0*1)=(0,0); 0+0=0; z1=0+0=0; h1=max(0,0)=0 | (1*1,0*(-1))=(1,0); 1+0=1; z2=1+0=1; h2=max(0,1)=1 |
| t1=(0,1) | (0*1,1*0)=(0,0); 0+0=0; z0=0+0=0; h0=max(0,0)=0 | (0*0,1*1)=(0,1); 0+1=1; z1=1+0=1; h1=max(0,1)=1 | (0*1,1*(-1))=(0,-1); 0-1=-1; z2=-1+0=-1; h2=max(0,-1)=0 |
| t2=(1,1) | (1*1,1*0)=(1,0); 1+0=1; z0=1+0=1; h0=max(0,1)=1 | (1*0,1*1)=(0,1); 0+1=1; z1=1+0=1; h1=max(0,1)=1 | (1*1,1*(-1))=(1,-1); 1-1=0; z2=0+0=0; h2=max(0,0)=0 |
The hidden vectors are (1,0,1), (0,1,0), and (1,1,0). The third coordinate is meaningful: for t0 it contributes to both E0 outputs and both E1 outputs. It is not padding introduced to fit a helper.
| Token | Hidden 0 | Hidden 1 | Hidden 2 |
|---|---|---|---|
| t0=(1,0) | (1*1,0*1)=(1,0); 1+0=1; z0=1+0=1; h0=max(0,1)=1 | (1*(-1),0*1)=(-1,0); -1+0=-1; z1=-1+0=-1; h1=max(0,-1)=0 | (1*1,0*0)=(1,0); 1+0=1; z2=1+0=1; h2=max(0,1)=1 |
| t1=(0,1) | (0*1,1*1)=(0,1); 0+1=1; z0=1+0=1; h0=max(0,1)=1 | (0*(-1),1*1)=(0,1); 0+1=1; z1=1+0=1; h1=max(0,1)=1 | (0*1,1*0)=(0,0); 0+0=0; z2=0+0=0; h2=max(0,0)=0 |
| t2=(1,1) | (1*1,1*1)=(1,1); 1+1=2; z0=2+0=2; h0=max(0,2)=2 | (1*(-1),1*1)=(-1,1); -1+1=0; z1=0+0=0; h1=max(0,0)=0 | (1*1,1*0)=(1,0); 1+0=1; z2=1+0=1; h2=max(0,1)=1 |
E2’s hidden vectors are (1,0,1), (1,1,0), and (2,0,1). Its second hidden unit contributes on t1; its third contributes on t0 and t2. ReLU suppresses an actual negative preactivation on t0. Showing only two hidden coordinates would describe a different model.
Every three-product output fold, output bias, and postgain
For each output column, the product tuple is ordered (hidden0,hidden1,hidden2). In these tables F0 and F1 name output coordinates 0 and 1 of the expert named in that row. The following running sums explicitly start at +0, include all three products even when zero, and add the output bias last. Every zero in the real worksheet denotes the real number zero; signed native products are discussed separately below. An asterisk inside a literal arithmetic span means multiplication, not executable Python source.
| Expert/token; hidden vector | Feature 0 products and running sums | Feature 1 products and running sums |
|---|---|---|
| E0,t0; (1,0,1) | (1*1,0*0,1*1)=(1,0,1); 0+1=1; 1+0=1; 1+1=2; F0=2+0=2 | (1*0,0*1,1*1)=(0,0,1); 0+0=0; 0+0=0; 0+1=1; F1=1+0=1 |
| E0,t1; (0,1,0) | (0*1,1*0,0*1)=(0,0,0); 0+0=0; 0+0=0; 0+0=0; F0=0+0=0 | (0*0,1*1,0*1)=(0,1,0); 0+0=0; 0+1=1; 1+0=1; F1=1+0=1 |
| E0,t2; (1,1,0), default dropped | (1*1,1*0,0*1)=(1,0,0); 0+1=1; 1+0=1; 1+0=1; F0=1+0=1 | (1*0,1*1,0*1)=(0,1,0); 0+0=0; 0+1=1; 1+0=1; F1=1+0=1 |
| E1,t0; (1,0,1) | (1*(-1),0*0,1*(1/2))=(-1,0,1/2); 0-1=-1; -1+0=-1; -1+1/2=-1/2; F0=-1/2+0=-1/2 | (1*0,0*2,1*(-1/2))=(0,0,-1/2); 0+0=0; 0+0=0; 0-1/2=-1/2; F1=-1/2+0=-1/2 |
| E1,t1; (0,1,0) | (0*(-1),1*0,0*(1/2))=(0,0,0); 0+0=0; 0+0=0; 0+0=0; F0=0+0=0 | (0*0,1*2,0*(-1/2))=(0,2,0); 0+0=0; 0+2=2; 2+0=2; F1=2+0=2 |
| E1,t2; (1,1,0), default dropped | (1*(-1),1*0,0*(1/2))=(-1,0,0); 0-1=-1; -1+0=-1; -1+0=-1; F0=-1+0=-1 | (1*0,1*2,0*(-1/2))=(0,2,0); 0+0=0; 0+2=2; 2+0=2; F1=2+0=2 |
The E0/E1 t2 rows above are counterfactual at default capacity 2. They become admitted computations when only capacity increases to 3. Their presence in a worksheet never authorizes evaluating a rejected expert in the producer.
| Expert/token; hidden vector | Feature 0 products and running sums | Feature 1 products and running sums |
|---|---|---|
| E2,t0; (1,0,1) | (1*(1/2),0*1,1*0)=(1/2,0,0); 0+1/2=1/2; 1/2+0=1/2; 1/2+0=1/2; F0=1/2+0=1/2 | (1*(1/2),0*(-1),1*1)=(1/2,0,1); 0+1/2=1/2; 1/2+0=1/2; 1/2+1=3/2; F1=3/2+0=3/2 |
| E2,t1; (1,1,0) | (1*(1/2),1*1,0*0)=(1/2,1,0); 0+1/2=1/2; 1/2+1=3/2; 3/2+0=3/2; F0=3/2+0=3/2 | (1*(1/2),1*(-1),0*1)=(1/2,-1,0); 0+1/2=1/2; 1/2-1=-1/2; -1/2+0=-1/2; F1=-1/2+0=-1/2 |
| E2,t2; (2,0,1) | (2*(1/2),0*1,1*0)=(1,0,0); 0+1=1; 1+0=1; 1+0=1; F0=1+0=1 | (2*(1/2),0*(-1),1*1)=(1,0,1); 0+1=1; 1+0=1; 1+1=2; F1=2+0=2 |
All three E2 rows are unselected, noncomputed counterfactuals in the default. The later r2 edit admits the first two, not the third.
With default unit postgains, the separate coordinate multiplications are:
| Expert/token | Postgain vector V=(e*F0,e*F1) | Default execution status |
|---|---|---|
| E0,t0 | (1*2,1*1)=(2,1) | admitted |
| E1,t0 | (1*(-1/2),1*(-1/2))=(-1/2,-1/2) | admitted |
| E1,t1 | (1*0,1*2)=(0,2) | admitted |
| E0,t1 | (1*0,1*1)=(0,1) | admitted |
| E0,t2 | (1*1,1*1)=(1,1) | dropped: worksheet only |
| E1,t2 | (1*(-1),1*2)=(-1,2) | dropped: worksheet only |
| E2,t0 | (1*(1/2),1*(3/2))=(1/2,3/2) | unselected: worksheet only |
| E2,t1 | (1*(3/2),1*(-1/2))=(3/2,-1/2) | unselected: worksheet only |
| E2,t2 | (1*1,1*2)=(1,2) | unselected: worksheet only |
The short real formulas E0=(h0+h2,h1+h2), E1=(-h0+h2/2,2h1-h2/2), E2=(h0/2+h1,h0/2-h1+h2) help interpret the matrices. They are not alternate kernels: the source must retain the three products, initial +0, all additions and final output bias.
Combine the default admitted messages
For every original token and output feature, start Y at +0 and visit selected ranks ascending. An admitted assignment contributes g×V, using its postgain output. A dropped assignment contributes literal policy +0, which is then added; there is no multiplication by an imaginary expert result. This distinction preserves the record of work that actually occurred.
For t0 the rank-0 E0 message is (2/d,1/d), and the rank-1 E1 message is (-q/(2d),-q/(2d)). Therefore:
- Y[t0,0]=(0+2/d)+(-q/(2d))=(2-q/2)/d.
- Y[t0,1]=(0+1/d)+(-q/(2d))=(1-q/2)/d.
For t1 the rank-0 E1 message is (0,2/d), and rank-1 E0 is (0,q/d). Thus Y[t1,0]=(0+0)+0=0 and Y[t1,1]=(0+2/d)+q/d=(2+q)/d. For t2 both assignments drop. Each coordinate is (0+0)+0=0 by the branch’s explicit policy, without evaluating either MLP.
The default exact-real output is consequently Y=(((2-q/2)/d,(1-q/2)/d),(0,(2+q)/d),(0,0)). This notation lists token rows inside the one batch. The first row contains cancellation: E1’s negative message subtracts from E0’s positive one. A gate is positive while an expert’s output can be negative, so a gated combination need not behave like a probability vector.
Change capacity without changing the router
With k fixed at 2, raising C from 2 to 3 preserves all scores, full P, selected gates and the first four admission decisions. The last two visits now admit E0 and E1 on t2 into their respective slot 2. Their hidden and output products are the t2 worksheet rows above. Its messages are (1/2)×(1,1)=(1/2,1/2) and (1/2)×(-1,2)=(-1/2,1). Hence Y2=((0+1/2)-1/2,(0+1/2)+1)=(0,3/2). The first feature cancels exactly over reals although both routes are admitted. Counts become (3,3,0), with six admissions and no drops.
Lower C to 1 instead. Only t0’s E0 and E1 assignments admit, at slot 0. Both t1 routes and both t2 routes reject without incrementing counts. Loads are (1,1,0), admissions 2, drops 4, fully lost tokens 2. Y0 retains its default expression; Y1=Y2=(0,0). The per-token real kept/lost masses are (1,0), (0,1), and (0,1).
At C=0 every visit rejects because a zero count is not less than zero. All three tokens are fully lost; loads are (0,0,0). There are six drops at top-2 or three at top-1, and no expert invocation. The router still computes all nine logits, nine exponentials, full P, ranks and selected gates. A zero-capacity calculation is not an empty or invalid softmax, and it does not excuse invalid inactive raw fields.
Now change only topK to 1. The default winning experts are E0 for t0, E1 for t1, E0 for t2. Each selected gate is exactly P/P=1, rather than the winning full probability. At C=1, t0/E0 slot0 and t1/E1 slot0 admit, then t2/E0 rejects: loads (1,1,0), two admissions, one drop, Y=((2,1),(0,2),(0,0)). At C=2, t2/E0 admits into slot1, making loads (2,1,0) and Y2=(1,1). C=3 gives that same top-1 admission pattern; no expert can be selected more than once per original token, so three slots always suffice here.
One router gain exposes a partial drop
Return to default X,k=2,C=2 and all default gains/biases, then change only r2 from 1 to -1. Expert 2’s three base projections remain -1,-1,-2, but scaling and bias now give (-1)×(-1)+0=1, (-1)×(-1)+0=1, (-2)×(-1)+0=2. Other logits are unchanged.
| Token | All logits; maximum; shifts | Full exp terms; full P | Selected IDs; real gates |
|---|---|---|---|
| t0 | (1,0,1); 1; (0,-1,0) | (1,q,1); (1,q,1)/(2+q) | (0,2); (1/2,1/2) |
| t1 | (0,1,1); 1; (-1,0,0) | (q,1,1); (q,1,1)/(2+q) | (1,2); (1/2,1/2) |
| t2 | (1,1,2); 2; (-1,-1,0) | (q,q,1); (q,q,1)/(1+2q) | (2,0); (1/d,q/d) |
Each full denominator still folds from +0 in expert order: ((0+1)+q)+1, ((0+q)+1)+1, and ((0+q)+q)+1. For t0/t1 the two equal selected probabilities sum to 2/(2+q), giving equal gates. For t2 the selected sum is (0+1/(1+2q))+q/(1+2q)=d/(1+2q), giving the displayed gates over reals. These are full softmax rows followed by selected normalization, not a direct two-expert softmax substitute.
| Visit | Token,rank,expert | Count before | Decision / slot | Counts after |
|---|---|---|---|---|
| 0 | t0,0,0 | 0 | admit / 0 | (1,0,0) |
| 1 | t0,1,2 | 0 | admit / 0 | (1,0,1) |
| 2 | t1,0,1 | 0 | admit / 0 | (1,1,1) |
| 3 | t1,1,2 | 1 | admit / 1 | (1,1,2) |
| 4 | t2,0,2 | 2 | drop / no slot | (1,1,2) |
| 5 | t2,1,0 | 1 | admit / 1 | (2,1,2) |
Now E2 really runs on t0 and t1, using the complete products above. The real coordinate folds are:
Y0=((0+(1/2)*2)+(1/2)*(1/2),(0+(1/2)*1)+(1/2)*(3/2))=(5/4,5/4).Y1=((0+(1/2)*0)+(1/2)*(3/2),(0+(1/2)*2)+(1/2)*(-1/2))=(3/4,3/4).Y2=((0+0)+(q/d)*1,(0+0)+(q/d)*1)=(q/d,q/d).
E2’s t2 hidden/output values remain not computed: its rank-0 assignment dropped. E0’s t2 call is admitted and computes (1,1), but retains its original gate q/d. Y2=(1,1) would silently renormalize after the drop and violate this policy. Final loads are (2,1,2): five admitted assignments, one dropped assignment, zero fully lost tokens, and one partially dropped token. For t2, real kept mass is q/d and lost mass is 1/d. Dropping rank 0 does not imply dropping the whole token.
Zero output does not diagnose a fully lost token
A token is fully lost exactly when it has no admitted assignments. Inspect decisions, not the norm or appearance of Y. Three distinct mechanisms can produce zeros:
- Capacity 0 gives policy zeros without any MLP work.
- At default capacity 3, t2’s first feature is zero by cancellation while both experts are admitted and its second feature is 3/2.
- Set e0=e1=e2=0 at default capacity 2. All four previously admitted MLPs still run and consume slots, then postgain products vanish. Y0 and Y1 are zero vectors with admitted routes; only t2 is fully lost. Kept mass for the first two remains one over reals.
All-zero input is another distinction. With all six X coordinates zero and default router settings, every score is zero, terms are (1,1,1), Z=3, full P=(1/3,1/3,1/3), and top-2 selects (0,1) with gates (1/2,1/2). Because this specific expert bank has zero biases, its hidden values and expert outputs are zero. At C=3 all six assignments admit and all three output vectors are zero, with no fully lost token. Networks with nonzero biases need not have that zero-input property; it follows from the disclosed bank, not the phrase “MLP.”
Zero router gains are different again. With default nonzero X and r0=r1=r2=0, all router biases zero, every token ties and chooses IDs (0,1) at top-2. At C=3 the unchanged expert products combine to Y0=(3/4,1/4), Y1=(0,3/2), Y2=(0,3/2), using half-gates. At C=1 only t0 admits both routes. Exact low-ID tie-breaking concentrates traffic here; it does not balance the load.
More capacity is not a theorem that every coordinate magnitude increases. In the r2=-1 case, lower C from 2 to 1. t0 still admits E0 and E2 into slot0. t1 admits E1 into slot0 but now drops E2; both t2 routes drop. Loads become (1,1,1), with three admissions, three drops, one partial token (t1) and one fully lost token (t2). t1 retains its E1 half-gate and Y1=(0,1), rather than (3/4,3/4) at C=2. Its second coordinate increased from 3/4 to 1 because dropping E2 removed the negative contribution (1/2)×(-1/2)=-1/4. Its kept mass nevertheless fell from one to one half. Lost gate mass describes routing mass, not a quality score or an output-norm guarantee.
First-come capacity also couples token decisions: an earlier token can fill a slot needed later. Reordering tokens can change which input survives even though each expert’s MLP is position-wise. Counts reset on edits; slots do not persist from one recomputation into the next. There is no fallback network, global fairness rule, implicit identity output, or residual addition in this isolated branch.
Finite arithmetic, native evidence, and honest limits
A native operation here is the platform’s exponential evaluation. There are exactly nine actual router exponential leaves, three per token in expert-ID order, even at C=0; there is no square root. A leaf records a native call’s identity, operation, exact input, and returned value. A functional witness reconstructs the input from the same immutable saved score and maximum and saves the actual return; it is not physical interception of hardware or a timing measurement. Later arithmetic and display copies must consume that saved value rather than call exp again.
The input bounds give base-projection magnitude at most 4, logit magnitude at most 6, and shifts in [-12,0]. Real exponential terms are positive, with one maximum shift zero giving exp(0)=1. The exact-real full denominator is at most 3. For the separately specified native-admission policy, use the conservative bound below 4 rather than assuming that exact-real ceiling also constrains every admitted rounded term. Finite intermediate and positive-denominator guards remain necessary.
The independent authority’s signed policy first binds each native ID, operation kind, and exact input word. Only then may it consider the four-adjacent-binary64-step positive-finite admission allowance; exp(0) must be exactly +1. An adjacent step means the next representable value, not a decimal tolerance. The authority’s separately rounded real reference is independent of the canonical program’s native math library. These are required source semantics, not an executed error certification, a universal accuracy guarantee for a native library, or TS/Python word parity.
The maximum-score expert is always selected, so the selected sum is positive. Each gate is positive and at most one; do not infer that rounded gates sum to exactly one. Conservative hidden bounds are E0/E1 at most (2,2,4) and E2 at most (4,4,2). A loose expert-coordinate magnitude bound of 8, postgain magnitude at most 1, and at most two gated messages give a loose combined-coordinate bound of 16. This safety argument does not use an exact rounded gate sum. Tiny representable inputs may still round or underflow during products; these small shapes and bounds are not permission to discard finite guards.
Binary64 distinguishes +0 and -0 even though both are the real number zero. WORD comparison retains every binary64 bit, including a zero sign; VALUE comparison handles discrete choices, IDs, decisions, and counts. The fifteen floating raw cells and computed floating operands/copies retain WORD semantics. topK and capacity use VALUE semantics, so capacity=-0 means zero capacity. Fixed bank zeros and dropped policy zeros are +0 WORD. Actual products may be -0, and must not be globally rewritten to +0. Hidden ReLU uses max(+0,z). The router and hidden affine sums directly add two products; output folds deliberately begin at +0. Reassociation or moving a gain changes that operation sequence even when real algebra looks identical.
This branch has no mask, attention, training update, loss, load-balancing objective, router-gradient experiment, distributed communication, or measured performance. Top-k and admission are discrete, and ReLU has no unique derivative at zero; no gradient claim follows from the forward worksheet. All weights and dimensions are disclosed toy choices. An admission count is not a speed benchmark, and a gate is not evidence of learned expertise or language-model quality. Books I–III and the earlier mathematical kernels remain unchanged; IV08 and IV25 are source-protected, not runtime-frozen.
Use the single five-question set with its stated inputs
The lab contains exactly five graded questions, each with corrective reasoning after a selection. Its first question reads the current WHOLE saved root: all seventeen raw values, every selected ID/gate/admission/slot, loads, loss flags and all three Y rows. It distinguishes no drops, partial drops with every token still represented, and at least one fully lost token. Zero Y is not the criterion. Moving the trace cursor clears a chosen radio answer but does not change that question’s evidence or answer key.
The other four prompts explicitly fix their inputs. The hidden-vector question uses default token0 and expert0 to obtain all three coordinates [1,0,1]. The top-one question fixes positive full probabilities and asks why the selected gate is P/P=1 before capacity. The partial-drop question changes only r2=-1 at default topK2/capacity2, follows expert2’s rejection and expert0’s surviving original gate, and asks for [g,g]. The rounding question fixes zero X/router gains and biases [0,epsilon,-1]; it asks why computed-logit expert1 wins even when two probabilities round equal. Current edits do not silently replace these written premises. There is no second grader in the worksheets below or in the Python panels.
Read the three complete canonical files in dependency order
These panels import full repository source with ?raw. Displaying them executes no program. The new IV62 entry and MoE helper use the unchanged IV59 support for generic fault identity, freezing, trace capture, prefix validation and indexed NumPy storage. That complete support file also contains the earlier decoder’s task and checks; those older task calculations are not the MoE mechanism or its mathematical proof.
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. Independent scalar MoE helper — complete file
Follow the helper’s own scalar router: two products, direct sum, gain, bias; all three full softmax terms; computed-logit ranking; selected-P normalization; first-come expert slots; each admitted three-hidden-coordinate MLP; its post-output gain; then the original-token/rank combine. Fixed banks and unused raw operands remain captured, whereas rejected or unselected expert computations remain absent. NumPy supplies indexed storage of already computed numbers, rather than a hidden BLAS product or altered reduction order.
Public moe_state(value), moe_trace() and evaluate_moe(value, trace, prefix) correspond to the admitted state, exact generic trace factory alias and complete helper result. The Python scalar/native capture completes before its public trace callbacks; serialization copies saved operands and returns, without another exponential or a floating-point reconstruction of the mechanism. TypeScript appends frames during its own calculation. Consequently a callback failure is not a claim of the same physical arithmetic instant in both languages. Both enforce input/domain/prefix preflight before numerical work and expose the original-token context separately from local FFN token0.
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.
"""IV62 actual scalar producer and owner-adopted copy projection; checks UNRUN.
Independent FIRST arithmetic is retained. Public callbacks occur only AFTER the
complete private scalar/native capture. Serialization performs no float work.
Only generic59 freeze/trace/prefix/indexed storage is reused.
"""
import importlib.util
import math
from pathlib import Path
import sys
from types import ModuleType
def _load_owned(name, path):
"""Stage only our identity; preserve incumbents and replacement modules."""
path = str(path.resolve())
incumbent = sys.modules.get(name)
if name in sys.modules:
if (type(incumbent) is not ModuleType
or incumbent.__dict__.get("_IV62_OWNED_PATH") != path
or type(incumbent.__dict__.get("__file__")) is not str
or str(Path(incumbent.__dict__["__file__"]).resolve()) != path
or incumbent.__dict__.get("_IV62_LOAD_COMPLETE") is not True):
raise ImportError("Refusing an unknown or incomplete module identity: " + name)
return incumbent
spec = importlib.util.spec_from_file_location(name, path)
if spec is None or spec.loader is None:
raise ImportError("Cannot load owned source: " + path)
staged = importlib.util.module_from_spec(spec)
if name in sys.modules:
raise ImportError("Owned cache identity appeared before staging: " + name)
staged._IV62_OWNED_PATH = path
transaction = globals().get("_IV62_TRANSACTION")
if transaction is not None:
transaction.append((name, staged))
sys.modules[name] = staged
try:
spec.loader.exec_module(staged)
if sys.modules.get(name) is not staged:
raise ImportError("Owned module identity replaced during loading: " + name)
staged._IV62_LOAD_COMPLETE = True
except BaseException:
if sys.modules.get(name) is staged:
del sys.modules[name]
raise
return staged
_support = _load_owned("_book_iv62_generic59", Path(__file__).with_name("decoder_reference.py"))
NumericalFault = _support.NumericalFault
_freeze = _support._freeze
# Exact alias: ordinary trace creation runs no checks.
moe_trace = _support.decoder_trace
DEFAULT_IV62 = _freeze(dict(
topK=2, capacity=2, x00=1.0, x01=0.0, x10=0.0, x11=1.0,
x20=1.0, x21=1.0, r0=1.0, r1=1.0, r2=1.0,
b0=0.0, b1=0.0, b2=0.0, e0=1.0, e1=1.0, e2=1.0))
_FIELDS = tuple(DEFAULT_IV62)
_WR = ((1.0, 0.0, -1.0), (0.0, 1.0, -1.0))
_W1 = (((1.0, 0.0, 1.0), (0.0, 1.0, -1.0)),
((1.0, 0.0, 1.0), (0.0, 1.0, -1.0)),
((1.0, -1.0, 1.0), (1.0, 1.0, 0.0)))
_W2 = (((1.0, 0.0), (0.0, 1.0), (1.0, 1.0)),
((-1.0, 0.0), (0.0, 2.0), (0.5, -0.5)),
((0.5, 0.5), (1.0, -1.0), (0.0, 1.0)))
_B1 = (0.0, 0.0, 0.0)
_B2 = (0.0, 0.0)
def _finite(value, label):
if not math.isfinite(value):
raise NumericalFault("NONFINITE", label + " must be finite.")
return value
def moe_state(value):
"""Capture exact builtin data once, all finite before any raw domain."""
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}
# All numbers precede every domain, including inactive fields and huge ints.
for key, item in captured.items():
if (type(item) not in (int, float)
or not -1.7976931348623157e308 <= item <= 1.7976931348623157e308):
raise NumericalFault("NONFINITE", "state." + key + " must be an actual finite number.")
for key, item in captured.items():
if key == "topK":
if item not in (1, 2):
raise NumericalFault("INVALID_INPUT", "topK must be an integer in {1,2}.")
elif key == "capacity":
if item not in (0, 1, 2, 3):
raise NumericalFault("INVALID_INPUT", "capacity must be an integer between 0 and 3.")
else:
bound = 2 if key.startswith(("x", "b")) else 1
if not -bound <= item <= bound:
raise NumericalFault("INVALID_INPUT", f"{key} must be between {-bound} and {bound}.")
return _freeze({key: int(captured[key]) if key in ("topK", "capacity") else float(captured[key])
for key in _FIELDS})
class _Capture:
"""Immutable scalar snapshots; private identifiers are not public frame IDs."""
def __init__(self):
self.operations = []
self.natives = []
self._ids = set()
def add(self, identifier, inputs, outputs):
if identifier in self._ids:
raise RuntimeError("Duplicate private operation: " + identifier)
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 TypeError("Private captures contain numeric scalars only.")
_finite(value, identifier + "/" + key)
self._ids.add(identifier)
self.operations.append(_freeze(dict(id=identifier, inputs=before, outputs=after)))
def exp(self, identifier, argument):
_finite(argument, "exp argument")
if not -12.0 <= argument <= 0.0:
raise NumericalFault("INVALID_INPUT", "exp argument outside selected router bounds.")
output = math.exp(argument)
# Row guards follow all three calls, as in the actual stableSoftmax.
self.natives.append(dict(id=identifier, kind="exp", input=argument, output=output))
return output
def _expert(x, expert, context, capture, prefix):
"""Independent M3 loop: all hidden coordinates and all output products."""
hidden, preactivation = [], []
for m in range(3):
w0, w1 = _W1[expert][0][m], _W1[expert][1][m]
p0 = _finite(x[0] * w0, "hidden product0")
p1 = _finite(x[1] * w1, "hidden product1")
total = _finite(p0 + p1, "hidden direct sum")
z = _finite(total + _B1[m], "hidden bias last")
h = z if z > 0.0 else 0.0
preactivation.append(z)
hidden.append(h)
capture.add(f"{prefix}_hidden_{m}", dict(x0=x[0], x1=x[1], w0=w0, w1=w1, bias=_B1[m]),
dict(product0=p0, product1=p1, sum=total, preactivation=z, activation=h))
output = []
for d in range(2):
running = 0.0
inputs, outputs = dict(bias=_B2[d]), {}
for m in range(3):
weight = _W2[expert][m][d]
product = _finite(hidden[m] * weight, "output product")
inputs[f"h{m}"], inputs[f"w{m}"] = hidden[m], weight
running = _finite(running + product, "three-product output fold")
outputs[f"product{m}"], outputs[f"running{m}"] = product, running
value = _finite(running + _B2[d], "output bias last")
outputs["value"] = value
output.append(value)
capture.add(f"{prefix}_output_{d}", inputs, outputs)
return dict(context=context, input=list(x), preactivation=preactivation, hidden=hidden, output=output)
def _capture_moe(value, prefix="moe", callback=None):
"""Actual scalar producer FIRST; observers see only the COMPLETE capture."""
state = moe_state(value)
_support._prefix(prefix)
if callback is not None and not callable(callback):
raise TypeError("callback must be callable.")
capture = _Capture()
x = [[state[f"x{t}{d}"] for d in range(2)] for t in range(3)]
logits, router = [], []
for t in range(3):
row = []
for e in range(3):
p0 = _finite(x[t][0] * _WR[0][e], "router product0")
p1 = _finite(x[t][1] * _WR[1][e], "router product1")
total = _finite(p0 + p1, "router direct sum")
scaled = _finite(total * state[f"r{e}"], "router postprojection gain")
score = _finite(scaled + state[f"b{e}"], "router bias last")
record = dict(product0=p0, product1=p1, sum=total, scaled=scaled, logit=score)
capture.add(f"{prefix}_router_{t}_{e}",
dict(x0=x[t][0], x1=x[t][1], w0=_WR[0][e], w1=_WR[1][e],
gain=state[f"r{e}"], bias=state[f"b{e}"]), record)
router.append(record)
row.append(score)
logits.append(row)
rows = []
for t, scores in enumerate(logits):
maximum = scores[0]
for score in scores[1:]:
if score > maximum or (score == maximum == 0.0 and math.copysign(1.0, score) > 0.0):
maximum = score
shifts, terms, running_sums = [], [], []
for e in range(3):
shift = _finite(scores[e] - maximum, "shifted router logit")
term = capture.exp(f"{prefix}_exp_{t}_{e}", shift)
shifts.append(shift)
terms.append(term)
denominator = 0.0
for e, term in enumerate(terms):
before = denominator
denominator = _finite(denominator + term, "softmax denominator")
running_sums.append(denominator)
capture.add(f"{prefix}_sum_{t}_{e}", dict(before=before, term=term), dict(value=denominator))
if denominator <= 0.0:
raise NumericalFault("INVALID_INPUT", "router denominator must be positive.")
probabilities = []
for e, term in enumerate(terms):
probability = _finite(term / denominator, "router probability")
probabilities.append(probability)
capture.add(f"{prefix}_probability_{t}_{e}", dict(term=term, denominator=denominator), dict(value=probability))
for e in range(3):
_finite(terms[e], "router exp term")
if terms[e] <= 0.0:
raise NumericalFault("INVALID_INPUT", "router exp term must be positive.")
if probabilities[e] <= 0.0:
raise NumericalFault("INVALID_INPUT", "router probability must be positive.")
capture.add(f"{prefix}_exp_capture_{t}_{e}", dict(logit=scores[e], maximum=maximum),
dict(shifted=shifts[e], term=terms[e]))
# Insertion uses actual logits, direct comparisons and ascending-ID ties.
ranking = []
for e in range(3):
position = 0
while position < len(ranking) and not scores[e] > scores[ranking[position]]:
position += 1
ranking.insert(position, e)
selected = ranking[:state["topK"]]
selected_sum, selected_running = 0.0, []
for rank, e in enumerate(selected):
before = selected_sum
selected_sum = _finite(selected_sum + probabilities[e], "selected probability fold")
selected_running.append(selected_sum)
capture.add(f"{prefix}_selected_sum_{t}_{rank}", dict(before=before, probability=probabilities[e], expert=e),
dict(value=selected_sum))
if selected_sum <= 0.0:
raise NumericalFault("INVALID_INPUT", "selected probability sum must be positive.")
gates = []
for rank, e in enumerate(selected):
gate = _finite(probabilities[e] / selected_sum, "selected gate")
if gate <= 0.0:
raise NumericalFault("INVALID_INPUT", "selected gate must be positive.")
gates.append(gate)
capture.add(f"{prefix}_gate_{t}_{rank}", dict(expert=e, probability=probabilities[e], denominator=selected_sum),
dict(value=gate))
rows.append(dict(maximum=maximum, shifted=shifts, terms=terms, running=running_sums,
denominator=denominator, probabilities=probabilities, ranking=ranking,
selected=selected, selectedRunning=selected_running, selectedSum=selected_sum, gates=gates))
loads, assignments = [0, 0, 0], []
for t, row in enumerate(rows):
for rank, e in enumerate(row["selected"]):
before = loads[e]
admitted = before < state["capacity"]
slot = before if admitted else -1
if admitted:
loads[e] += 1
context = dict(token=t, rank=rank, expert=e, slot=slot, sourceOffset=2*t, localB=0, localT=0)
capture.add(f"{prefix}_dispatch_{t}_{rank}", dict(count=before, capacity=state["capacity"], expert=e),
dict(admitted=int(admitted), slot=slot, count=loads[e]))
invocation = None
if admitted:
invocation = _expert(x[t], e, context, capture, f"{prefix}_expert_{t}_{rank}_{e}")
gained = []
for d, source in enumerate(invocation["output"]):
result = _finite(source * state[f"e{e}"], "expert post-output gain")
gained.append(result)
capture.add(f"{prefix}_postgain_{t}_{rank}_{d}", dict(source=source, gain=state[f"e{e}"]), dict(value=result))
invocation["gained"] = gained
assignments.append(dict(context=context, admitted=admitted, gate=row["gates"][rank],
countBefore=before, countAfter=loads[e], invocation=invocation))
output, losses = [], []
for t in range(3):
routes = assignments[t*state["topK"]:(t+1)*state["topK"]]
kept, lost, accepted = 0.0, 0.0, 0
for rank, route in enumerate(routes):
before_kept, before_lost = kept, lost
if route["admitted"]:
kept = _finite(kept + route["gate"], "kept gate mass")
accepted += 1
else:
lost = _finite(lost + route["gate"], "lost gate mass")
capture.add(f"{prefix}_mass_{t}_{rank}", dict(kept=before_kept, lost=before_lost, gate=route["gate"], admitted=int(route["admitted"])),
dict(kept=kept, lost=lost))
losses.append(dict(kept=kept, lost=lost, accepted=accepted, dropped=state["topK"]-accepted, fullyLost=accepted == 0))
for d in range(2):
running = 0.0
for rank, route in enumerate(routes):
before = running
if route["admitted"]:
source = route["invocation"]["gained"][d]
contribution = _finite(route["gate"] * source, "gated contribution")
inputs = dict(before=before, gate=route["gate"], expertOutput=source, computed=1)
else:
contribution = 0.0
inputs = dict(before=before, gate=route["gate"], computed=0)
running = _finite(running + contribution, "rank-ordered combine")
capture.add(f"{prefix}_combine_{t}_{d}_{rank}", inputs, dict(contribution=contribution, value=running))
output.append(running)
result = _freeze(dict(state=state, bank=dict(router=_WR, W1=_W1, b1=_B1, W2=_W2, b2=_B2),
input=x, router=router, logits=logits, rows=rows, assignments=assignments,
loads=loads, losses=losses, output=output, natives=capture.natives, operations=capture.operations))
# No callbacks during arithmetic: observers cannot alter this private evaluation.
if callback is not None:
for operation in result["operations"]:
callback(operation)
return result
def _private_storage(capture):
"""Only indexed NumPy storage of already captured scalars; no contraction."""
return _support._storage(capture["output"], 3, 2)
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 _check_copies(saved, prefix):
"""Explicit eager private-copy check; never invoked by ordinary queries."""
if not __debug__:
raise RuntimeError("Explicit IV62 copy check refuses optimized Python (-O).")
import struct
def word(value):
if not __debug__:
raise RuntimeError("Explicit IV62 WORD helper refuses optimized Python (-O).")
return struct.pack(">d", value)
operations = {item["id"]: item for item in saved["operations"]}
assert len(operations) == len(saved["operations"])
assert len(saved["natives"]) == 9
for t in range(3):
row = saved["rows"][t]
for e in range(3):
leaf = saved["natives"][3*t+e]
assert tuple(leaf) == ("id", "kind", "input", "output")
assert leaf["id"] == f"{prefix}_exp_{t}_{e}" and leaf["kind"] == "exp"
frame = operations[f"{prefix}_exp_capture_{t}_{e}"]
assert word(leaf["input"]) == word(frame["outputs"]["shifted"]) == word(row["shifted"][e])
assert word(leaf["output"]) == word(frame["outputs"]["term"]) == word(row["terms"][e])
assert word(leaf["output"]) == word(operations[f"{prefix}_sum_{t}_{e}"]["inputs"]["term"])
assert word(leaf["output"]) == word(operations[f"{prefix}_probability_{t}_{e}"]["inputs"]["term"])
assert word(row["probabilities"][e]) == word(operations[f"{prefix}_probability_{t}_{e}"]["outputs"]["value"])
assert leaf["output"] > 0.0
if leaf["input"] == 0.0:
assert word(leaf["output"]) == word(1.0)
for d in range(2):
final = operations[f"{prefix}_combine_{t}_{d}_{saved['state']['topK']-1}"]["outputs"]["value"]
assert word(saved["output"][2*t+d]) == word(final)
for route in saved["assignments"]:
t, rank, e = (route["context"][key] for key in ("token", "rank", "expert"))
assert route["context"]["sourceOffset"] == 2*t
assert route["context"]["localB"] == route["context"]["localT"] == 0
assert word(route["gate"]) == word(saved["rows"][t]["gates"][rank])
if not route["admitted"]:
assert route["context"]["slot"] == -1 and route["invocation"] is None
for d in range(2):
frame = operations[f"{prefix}_combine_{t}_{d}_{rank}"]
assert "expertOutput" not in frame["inputs"] and frame["inputs"]["computed"] == 0
assert word(frame["outputs"]["contribution"]) == word(0.0)
continue
invocation = route["invocation"]
assert invocation["context"] == route["context"]
for d in range(2):
assert word(invocation["input"][d]) == word(saved["input"][t][d])
affine = operations[f"{prefix}_expert_{t}_{rank}_{e}_output_{d}"]
for m in range(3):
assert f"product{m}" in affine["outputs"] and f"running{m}" in affine["outputs"]
assert word(affine["inputs"][f"h{m}"]) == word(invocation["hidden"][m])
assert word(affine["outputs"]["value"]) == word(invocation["output"][d])
gain = operations[f"{prefix}_postgain_{t}_{rank}_{d}"]
combine = operations[f"{prefix}_combine_{t}_{d}_{rank}"]
assert word(gain["inputs"]["source"]) == word(invocation["output"][d])
assert word(gain["outputs"]["value"]) == word(invocation["gained"][d]) == word(combine["inputs"]["expertOutput"])
accepted = sum(int(route["admitted"]) for route in saved["assignments"])
# Manual private-event inventory only, NOT the eventual A frame inventory.
assert len(saved["operations"]) == 36 + 18*saved["state"]["topK"] + 7*accepted
def _expect_fault(value, code, prefix="moe"):
if not __debug__:
raise RuntimeError("Explicit IV62 fault check refuses optimized Python (-O).")
try:
_capture_moe(value, prefix)
except NumericalFault as error:
assert type(error) is NumericalFault and error.code == code
else:
raise AssertionError("Expected an input fault before any numerical capture.")
def check_private():
"""Authored local scalar regressions; not an independent numerical oracle."""
if not __debug__:
raise RuntimeError("Explicit IV62 scalar check refuses optimized Python (-O).")
import struct
def word(value):
if not __debug__:
raise RuntimeError("Explicit IV62 scalar WORD helper refuses optimized Python (-O).")
return struct.pack(">d", value)
default = _capture_moe(DEFAULT_IV62)
_check_copies(default, "moe")
assert default["logits"] == [[1.0, 0.0, -1.0], [0.0, 1.0, -1.0], [1.0, 1.0, -2.0]]
assert [row["selected"] for row in default["rows"]] == [[0, 1], [1, 0], [0, 1]]
assert [route["context"]["slot"] for route in default["assignments"]] == [0, 0, 1, 1, -1, -1]
assert default["loads"] == [2, 2, 0]
assert [route["invocation"]["hidden"] for route in default["assignments"][:4]] == [[1.0, 0.0, 1.0], [1.0, 0.0, 1.0], [0.0, 1.0, 0.0], [0.0, 1.0, 0.0]]
assert [route["invocation"]["output"] for route in default["assignments"][:4]] == [[2.0, 1.0], [-0.5, -0.5], [0.0, 2.0], [0.0, 1.0]]
for top_k in (1, 2):
for capacity in (0, 1, 2, 3):
current = _capture_moe(dict(DEFAULT_IV62, topK=top_k, capacity=capacity))
_check_copies(current, "moe")
expected = [min(capacity, 2), min(capacity, 1), 0] if top_k == 1 else [min(capacity, 3), min(capacity, 3), 0]
assert current["loads"] == expected
assert sum(expected) == sum(int(route["admitted"]) for route in current["assignments"])
if capacity == 0:
assert all(route["invocation"] is None for route in current["assignments"])
assert all(loss["fullyLost"] for loss in current["losses"])
assert all(word(value) == word(0.0) for value in current["output"])
top_one = _capture_moe(dict(DEFAULT_IV62, topK=1, capacity=3))
assert top_one["output"] == [2.0, 1.0, 0.0, 2.0, 1.0, 1.0]
assert all(word(row["gates"][0]) == word(1.0) for row in top_one["rows"])
capacity_three = _capture_moe(dict(DEFAULT_IV62, capacity=3))
assert [word(value) for value in capacity_three["output"][4:]] == [word(0.0), word(1.5)]
partial = _capture_moe(dict(DEFAULT_IV62, r2=-1.0))
_check_copies(partial, "moe")
assert [row["selected"] for row in partial["rows"]] == [[0, 2], [1, 2], [2, 0]]
assert partial["loads"] == [2, 1, 2]
assert [route["admitted"] for route in partial["assignments"]] == [True, True, True, True, False, True]
assert partial["assignments"][1]["invocation"]["output"] == [0.5, 1.5]
assert partial["assignments"][3]["invocation"]["output"] == [1.5, -0.5]
assert not any(loss["fullyLost"] for loss in partial["losses"])
for value in partial["output"][4:]:
assert word(value) == word(partial["rows"][2]["gates"][1])
zero_gain = _capture_moe(dict(DEFAULT_IV62, e0=0.0, e1=0.0, e2=0.0))
assert zero_gain["loads"] == default["loads"]
assert [route["invocation"]["output"] for route in zero_gain["assignments"][:4]] == [route["invocation"]["output"] for route in default["assignments"][:4]]
assert all(value == 0.0 for value in zero_gain["output"])
tied = _capture_moe(dict(DEFAULT_IV62, r0=0.0, r1=0.0, r2=0.0, capacity=3))
assert all(row["selected"] == [0, 1] and row["gates"] == [0.5, 0.5] for row in tied["rows"])
tiny = dict(DEFAULT_IV62, topK=1, capacity=3, r0=0.0, r1=0.0, r2=0.0, b1=float.fromhex("0x0.0000000000001p-1022"), b2=-1.0)
score_trap = _capture_moe(tiny)
assert all(row["selected"] == [1] for row in score_trap["rows"])
signed = _capture_moe(dict(DEFAULT_IV62, capacity=-0.0, x01=-0.0, r2=-0.0, e2=-0.0))
assert signed["state"]["capacity"] == 0
for key in ("x01", "r2", "e2"):
assert word(signed["state"][key]) == word(-0.0)
_expect_fault(dict(DEFAULT_IV62, capacity=0, e2=float("nan")), "NONFINITE")
_expect_fault(dict(DEFAULT_IV62, topK=0, e2=float("inf")), "NONFINITE")
_expect_fault(dict(DEFAULT_IV62, capacity=0, x20=3.0), "INVALID_INPUT")
_expect_fault(dict(DEFAULT_IV62, topK=True), "NONFINITE")
_expect_fault(dict(DEFAULT_IV62, e2=10**400), "NONFINITE")
_expect_fault(dict(topK=2), "INVALID_INPUT")
_expect_fault(dict(DEFAULT_IV62, extra=0), "INVALID_INPUT")
_expect_fault(DEFAULT_IV62, "INVALID_INPUT", "bad-prefix")
class Accessor(dict):
def __getitem__(self, key):
if not __debug__:
raise RuntimeError("Explicit IV62 accessor hook refuses optimized Python (-O).")
raise AssertionError("Raw accessors must never run.")
_expect_fault(Accessor(DEFAULT_IV62), "INVALID_INPUT")
trace = moe_trace()
actual_exp, calls = math.exp, []
raw = dict(DEFAULT_IV62)
def no_native(argument):
if not __debug__:
raise RuntimeError("Explicit IV62 disabled-native hook refuses optimized Python (-O).")
raise AssertionError("No native call after complete capture.")
def observe(operation):
if not __debug__:
raise RuntimeError("Explicit IV62 private-observer hook refuses optimized Python (-O).")
# Mutation cannot affect the already completed, detached capture.
raw["x00"] = -2.0
math.exp = no_native
calls.append(operation["id"])
trace.add(operation["id"], "", "", "", operation["inputs"], operation["outputs"])
try:
observed = _capture_moe(raw, callback=observe)
stored = _private_storage(observed)
assert calls == [item["id"] for item in observed["operations"]]
assert observed["state"]["x00"] == 1.0
for t in range(3):
for d in range(2):
assert word(float(stored[0, t, d])) == word(observed["output"][2*t+d])
for operation, frame in zip(observed["operations"], trace.steps):
for key, value in operation["outputs"].items():
assert word(value) == word(frame["outputs"][key]) == word(trace.outputs[frame["id"] + "_" + key])
finally:
math.exp = actual_exp
marker = RuntimeError("Observer identity sentinel")
def failed_observer(operation):
if not __debug__:
raise RuntimeError("Explicit IV62 private-failure hook refuses optimized Python (-O).")
raise marker
try:
_capture_moe(DEFAULT_IV62, callback=failed_observer)
except RuntimeError as error:
assert error is marker
else:
raise AssertionError("Unknown observer error must escape unchanged.")
try:
default["output"][0] = 9.0
except TypeError:
pass
else:
raise AssertionError("Capture must be frozen.")
def _project_moe(saved, prefix):
"""Copy only saved operands; arithmetic below is structural indexing/counting."""
state, rows = saved["state"], saved["rows"]
K = state["topK"]
ops = {item["id"]: item for item in saved["operations"]}
frames, invocation_tensors, invocation_prefixes = [], [], []
contributions = [0.0] * (6 * K)
bank = saved["bank"]
def add(identifier, label, equation, explanation, inputs, outputs):
frames.append(dict(id=identifier, label=label, equation=equation,
explanation=explanation, inputs=inputs, outputs=outputs))
def tensor(suffix, shape, axes, values, provenance, dtype="float64"):
return _tensor(prefix + "_" + suffix, shape, axes, values, provenance, dtype)
for t in range(3):
for expert in range(3):
op = ops[f"{prefix}_router_{t}_{expert}"]
add(op["id"], f"Router at token {t}, expert {expert}",
"product0=x0*w0; product1=x1*w1; sum=product0+product1; scaled=sum*gain; logit=scaled+bias",
"Compute both feature products, add them directly, multiply this expert router gain, then add its bias last. Zero coefficients and capacity zero do not skip work.",
dict(t=t, expert=expert, **op["inputs"]), dict(op["outputs"]))
for t, row in enumerate(rows):
inputs = dict(t=t, logit0=saved["logits"][t][0], logit1=saved["logits"][t][1], logit2=saved["logits"][t][2])
outputs = dict(max=row["maximum"])
for expert in range(3):
outputs[f"shifted{expert}"] = row["shifted"][expert]
outputs[f"term{expert}"] = row["terms"][expert]
outputs["denominator"] = row["denominator"]
outputs.update({f"probability{expert}": row["probabilities"][expert] for expert in range(3)})
add(f"{prefix}_softmax_{t}", f"Full three-expert stable softmax at token {t}",
"max=Math.max(logits); term_e=exp(logit_e-max); denominator=((+0+term0)+term1)+term2; probability_e=term_e/denominator",
"The unchanged stableSoftmax computes all three native exponentials before top-k or capacity. Saved shifts reconstruct its arguments from identical immutable operands; this is a functional witness, not physical interception.", inputs, outputs)
add(f"{prefix}_rank_{t}", f"Rank actual computed logits at token {t}",
"descending computed logit; exact ties ascending expert ID",
"Compare saved finite logits directly with greater/less. Rounded probabilities and display decimals never choose an expert.",
dict(inputs), {f"expert{rank}": expert for rank, expert in enumerate(row["ranking"])})
for rank, expert in enumerate(row["selected"]):
op = ops[f"{prefix}_selected_sum_{t}_{rank}"]
add(f"{prefix}_selectedSum_{t}_{rank}", f"Selected-probability fold at token {t}, rank {rank}",
"sum=previous+probability",
"Start from literal +0 and add selected full-softmax probabilities in rank order before any admission decision.",
dict(t=t, rank=rank, expert=expert, previous=op["inputs"]["before"], probability=op["inputs"]["probability"]),
dict(sum=op["outputs"]["value"]))
for rank, expert in enumerate(row["selected"]):
add(f"{prefix}_gate_{t}_{rank}", f"Pre-drop gate at token {t}, rank {rank}",
"gate=probability/selectedSum",
"Divide the saved selected probability by the completed selected-probability sum. Do not replace this operation with a selected-only softmax or renormalize after drops.",
dict(t=t, rank=rank, expert=expert, probability=row["probabilities"][expert], selectedSum=row["selectedSum"]),
dict(gate=row["gates"][rank]))
for route in saved["assignments"]:
context = route["context"]
t, rank, expert, slot = (context[key] for key in ("token", "rank", "expert", "slot"))
mass = ops[f"{prefix}_mass_{t}_{rank}"]
add(f"{prefix}_dispatch_{t}_{rank}", f"Admission at token {t}, rank {rank}, expert {expert}",
"admitted=countBefore<capacity; slot=admitted?countBefore:-1; increment only admitted expert; fold kept or lost gate separately",
"Visit tokens then ranks. Capacity counts assignments per expert; rejection does not increment load, reroute, add a residual or redistribute a gate.",
dict(t=t, rank=rank, expert=expert, capacity=state["capacity"], countBefore=route["countBefore"],
gate=route["gate"], keptBefore=mass["inputs"]["kept"], lostBefore=mass["inputs"]["lost"]),
dict(admitted=int(route["admitted"]), slot=slot, countAfter=route["countAfter"],
keptMass=mass["outputs"]["kept"], lostMass=mass["outputs"]["lost"]))
if not route["admitted"]:
continue
call = f"{prefix}_t{t}_r{rank}_e{expert}_s{slot}"
invocation_prefixes.append(call)
inv = route["invocation"]
x0, x1 = inv["input"]
add(call + "_context", f"Dispatch original token {t}, rank {rank} to expert {expert}, slot {slot}",
"localX[0,0,0]=X[sourceOffset]; localX[0,0,1]=X[sourceOffset+1]",
"Original token/rank/expert/slot identify this invocation. The unchanged feedForward uses a separate local batch 0 and local token 0; its local t is never the original token index.",
dict(originalToken=t, rank=rank, expert=expert, slot=slot, sourceOffset=context["sourceOffset"], localB=0, localT=0, x0=x0, x1=x1),
dict(localX0=x0, localX1=x1))
for m in range(3):
op = ops[f"{prefix}_expert_{t}_{rank}_{expert}_hidden_{m}"]
add(f"{call}_ffn_hidden_0_0_{m}", f"Hidden affine [0,0,{m}]",
"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=0, m=m, **op["inputs"]),
{key: op["outputs"][key] for key in ("product0", "product1", "sum", "preactivation")})
for m in range(3):
add(f"{call}_ffn_relu_0_0_{m}", f"ReLU [0,0,{m}]", "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=0, m=m, preactivation=inv["preactivation"][m]), dict(activation=inv["hidden"][m]))
for d in range(2):
op = ops[f"{prefix}_expert_{t}_{rank}_{expert}_output_{d}"]
before, after = op["inputs"], op["outputs"]
add(f"{call}_ffn_output_0_0_{d}", f"FFN output [0,0,{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.",
dict(b=0, t=0, d=d, h0=before["h0"], w0=before["w0"], h1=before["h1"], w1=before["w1"], h2=before["h2"], w2=before["w2"], bias=before["bias"]),
dict(product0=after["product0"], product1=after["product1"], product2=after["product2"],
running0=after["running0"], running1=after["running1"], running2=after["running2"], sum=after["running2"], value=after["value"]))
for d in range(2):
op = ops[f"{prefix}_postgain_{t}_{rank}_{d}"]
add(f"{call}_gain_{d}", f"Post-output expert gain at original token {t}, rank {rank}, feature {d}", "scaled=value*gain",
"Multiply the actual completed M3 expert output by its gain after all hidden/output products, ReLUs and biases. A zero gain still follows a full admitted expert invocation.",
dict(t=t, rank=rank, expert=expert, slot=slot, d=d, value=op["inputs"]["source"], gain=op["inputs"]["gain"]),
dict(scaled=op["outputs"]["value"]))
invocation_tensors.extend([
_tensor(call + "_Context", [7], ["ContextField"], [t, rank, expert, slot, context["sourceOffset"], 0, 0],
"Original token,rank,expert,slot,sourceOffset,localB,localT in that order; local B/T indices are 0, not original token IDs.", "int32"),
_tensor(call + "_Input", [1, 1, 2], ["B", "T", "D"], inv["input"],
"Exact original token feature words copied to local B=1,T=1,D=2; context records the original token, rank, expert and admitted slot."),
_tensor(call + "_ffn_W1", [2, 3], ["D", "HiddenFeature"], [v for row in bank["W1"][expert] for v in row],
"Shared input-to-hidden weights, f1{d}{m}; M=3 hidden features."),
_tensor(call + "_ffn_b1", [3], ["HiddenFeature"], bank["b1"], "Shared hidden bias, added after the two products."),
_tensor(call + "_ffn_Z", [1, 1, 3], ["B", "T", "HiddenFeature"], inv["preactivation"], "Hidden preactivations X W1+b1; no batch or token mixing."),
_tensor(call + "_ffn_Hidden", [1, 1, 3], ["B", "T", "HiddenFeature"], inv["hidden"], "ReLU(Z)=max(0,Z), before the second affine layer."),
_tensor(call + "_ffn_W2", [3, 2], ["HiddenFeature", "D"], [v for row in bank["W2"][expert] for v in row], "Shared hidden-to-output weights, f2{m}{d}."),
_tensor(call + "_ffn_b2", [2], ["D"], bank["b2"], "Shared output bias, added after all three running sums."),
_tensor(call + "_ffn_F", [1, 1, 2], ["B", "T", "D"], inv["output"], "ReLU(X W1+b1) W2+b2, independently per token with shared parameters."),
_tensor(call + "_PostGain", [1, 1, 2], ["B", "T", "D"], inv["gained"], "Actual completed expert F words multiplied by the selected expert post-output gain; no gain moved into weights or before ReLU."),
])
for t in range(3):
for d in range(2):
for rank in range(K):
route = saved["assignments"][t*K+rank]
expert = route["context"]["expert"]
op = ops[f"{prefix}_combine_{t}_{d}_{rank}"]
before, after = op["inputs"], op["outputs"]
inputs = dict(t=t, rank=rank, expert=expert, d=d, admitted=int(route["admitted"]))
if route["admitted"]:
inputs.update(gate=before["gate"], expertOutput=before["expertOutput"], previous=before["before"])
label, equation, explanation = (f"Combine token {t}, feature {d}, rank {rank}",
"contribution=gate*expertOutput; value=previous+contribution",
"Use the original pre-drop gate and the saved postgain output of this admitted invocation. Start each output coordinate at +0 and fold ranks in order.")
else:
inputs["previous"] = before["before"]
label, equation, explanation = (f"Dropped contribution at token {t}, feature {d}, rank {rank}",
"contribution=+0 (drop policy); value=previous+contribution",
"This literal +0 is a dropped message policy, not a computed expert output. No MLP or multiplication by an unevaluated expert result occurs.")
add(op["id"], label, equation, explanation, inputs, dict(after))
contributions[2*(t*K+rank)+d] = after["contribution"]
assignment_shape, assignment_axes = [3, K], ["T", "Rank"]
routes, losses = saved["assignments"], saved["losses"]
counts = [3*K, sum(loss["accepted"] for loss in losses), sum(loss["dropped"] for loss in losses),
sum(int(loss["fullyLost"]) for loss in losses), sum(int(0 < loss["accepted"] < K) for loss in losses)]
tensors = [
tensor("Raw", [17], ["RawField"], [state[key] for key in _FIELDS], "Captured raw17 in rawFields order; topK/capacity are VALUE, all other raw cells WORD including -0."),
tensor("X", [1, 3, 2], ["B", "T", "D"], [v for row in saved["input"] for v in row], "Six actual raw input feature words in original token order; no lookup or token reordering."),
tensor("RouterWeights", [2, 3], ["D", "Expert"], [v for row in bank["router"] for v in row], "Fixed row-feature router matrix [[1,+0,-1],[+0,1,-1]]; gains are applied after both products and their direct sum."),
tensor("RouterGains", [3], ["Expert"], [state[f"r{e}"] for e in range(3)], "Actual r0,r1,r2 postprojection gain words."),
tensor("RouterBiases", [3], ["Expert"], [state[f"b{e}"] for e in range(3)], "Actual b0,b1,b2 words, added after router gain."),
tensor("ExpertGains", [3], ["Expert"], [state[f"e{e}"] for e in range(3)], "Actual e0,e1,e2 post-output gain words, including unused experts."),
tensor("ExpertW1", [3, 2, 3], ["Expert", "D", "HiddenFeature"], [v for expert in bank["W1"] for row in expert for v in row], "All three fixed meaningful M3 expert W1 banks in row-feature storage, including unselected experts."),
tensor("ExpertB1", [3, 3], ["Expert", "HiddenFeature"], list(bank["b1"])*3, "All three fixed hidden bias banks; every coordinate is literal +0 and is added last."),
tensor("ExpertW2", [3, 3, 2], ["Expert", "HiddenFeature", "D"], [v for expert in bank["W2"] for row in expert for v in row], "All three fixed output banks; all three hidden products and ordered running sums remain real work."),
tensor("ExpertB2", [3, 2], ["Expert", "D"], list(bank["b2"])*3, "All three fixed output bias banks, literal +0 added after three products and running sums."),
tensor("RouterStages", [1, 3, 3, 5], ["B", "T", "Expert", "RouterField"], [value for record in saved["router"] for value in record.values()], "Actual product0,product1,sum,scaled,logit in token/expert order."),
tensor("Logits", [1, 3, 3], ["B", "T", "Expert"], [v for row in saved["logits"] for v in row], "Actual computed finite router logits; these words alone determine expert ranking."),
tensor("Maxima", [3], ["T"], [row["maximum"] for row in rows], "Actual Math.max-selected full-row maxima, including its +0 preference."),
tensor("Shifted", [1, 3, 3], ["B", "T", "Expert"], [v for row in rows for v in row["shifted"]], "Functional native-argument witnesses: the identical immutable logit-minus-max subtraction used by unchanged stableSoftmax, without another exp."),
tensor("Terms", [1, 3, 3], ["B", "T", "Expert"], [v for row in rows for v in row["terms"]], "All nine actual native exp outputs, including capacity zero."),
tensor("Denominators", [3], ["T"], [row["denominator"] for row in rows], "Actual stableSoftmax denominators from +0 then term0,term1,term2 in expert order."),
tensor("Probabilities", [1, 3, 3], ["B", "T", "Expert"], [v for row in rows for v in row["probabilities"]], "Full three-expert probabilities before top-k selection or capacity."),
tensor("Ranking", [3, 3], ["T", "Rank"], [v for row in rows for v in row["ranking"]], "All expert IDs sorted by descending actual computed logits and exact lower-ID ties.", "int32"),
tensor("SelectedExperts", assignment_shape, assignment_axes, [route["context"]["expert"] for route in routes], "First topK distinct expert IDs from each full computed-logit ranking.", "int32"),
tensor("SelectedProbabilities", assignment_shape, assignment_axes, [row["probabilities"][e] for row in rows for e in row["selected"]], "Unchanged selected full-softmax probability words in token/rank order."),
tensor("SelectedSums", [3], ["T"], [row["selectedSum"] for row in rows], "Completed +0 rank folds over selected full probabilities, before admission."),
tensor("Gates", assignment_shape, assignment_axes, [v for row in rows for v in row["gates"]], "Actual selected probability divided by selected sum before capacity; never renormalized after drops."),
tensor("Admitted", assignment_shape, assignment_axes, [int(route["admitted"]) for route in routes], "1 if this token/rank assignment was admitted, 0 if capacity dropped it; not an expert-output value.", "int32"),
tensor("Slots", assignment_shape, assignment_axes, [route["context"]["slot"] for route in routes], "Per-expert zero-based admitted slot; -1 means dropped and allocates no slot.", "int32"),
*invocation_tensors,
tensor("Loads", [3], ["Expert"], saved["loads"], "Final per-expert admitted assignment counts, reset for every evaluation.", "int32"),
tensor("TokenAccepted", [3], ["T"], [loss["accepted"] for loss in losses], "Number of admitted assignments for each original token.", "int32"),
tensor("TokenDropped", [3], ["T"], [loss["dropped"] for loss in losses], "Number of dropped selected assignments for each original token.", "int32"),
tensor("FullyLost", [3], ["T"], [int(loss["fullyLost"]) for loss in losses], "1 exactly when no assignment was admitted for this token; zero output alone does not establish loss.", "int32"),
tensor("PartiallyDropped", [3], ["T"], [int(0 < loss["accepted"] < K) for loss in losses], "1 exactly when some but not all selected assignments were dropped.", "int32"),
tensor("KeptMass", [3], ["T"], [loss["kept"] for loss in losses], "Independent +0 rank fold of admitted pre-drop gates; not computed as one minus lost mass."),
tensor("LostMass", [3], ["T"], [loss["lost"] for loss in losses], "Independent +0 rank fold of dropped pre-drop gates; not a quality, norm or probability of failure."),
tensor("GatedContributions", [1, 3, K, 2], ["B", "T", "Rank", "D"], contributions, "Admitted gate times saved postgain output; dropped cells are literal +0 policy messages, not computed expert outputs."),
tensor("Y", [1, 3, 2], ["B", "T", "D"], saved["output"], "Actual per-original-token branch output, +0 then rank-ordered admitted gated messages and explicit dropped-policy +0 additions. No residual or fallback."),
tensor("Counts", [5], ["CountField"], counts, "Selected assignments,accepted assignments,dropped assignments,fully lost tokens,partially dropped tokens in that order.", "int32"),
tensor("NativeArguments", [9, 2], ["Native", "NativeField"], [v for leaf in saved["natives"] for v in (leaf["input"], leaf["output"])], "Actual exp argument functional witnesses and actual exp outputs in token/expert occurrence order; no native call during serialization."),
tensor("NativeKinds", [9], ["Native"], [1]*9, "Native kind code exp=1 for all nine occurrences; no sqrt occurs.", "int32"),
]
texts = dict(
rawFields=list(_FIELDS), routerFields=["product0", "product1", "sum", "scaled", "logit"],
contextFields=["originalToken", "rank", "expert", "slot", "sourceOffset", "localB", "localT"],
countFields=["selectedAssignments", "acceptedAssignments", "droppedAssignments", "fullyLostTokens", "partiallyDroppedTokens"],
nativeIds=[leaf["id"] for leaf in saved["natives"]], nativeKinds=[leaf["kind"] for leaf in saved["natives"]], nativeFields=["input", "output"], invocationPrefixes=invocation_prefixes,
inputPolicy="Exact raw17 own data fields on a plain/null-prototype object: all descriptors, then all finite actual numbers, then domains in raw order, then ASCII prefix. Validate unused values even at capacity zero; no coercion, clamp, default merge or getter call.",
architecturePolicy="Isolated hand-set MoE branch B1,T3,D2,E3,M3. Router has two products, direct sum, per-expert gain, bias last. Full stable three-expert softmax precedes top-k. Each admitted assignment alone calls the unchanged lower p07 feedForward with B1,T1 and the complete M3 bank.",
routingPolicy="Rank actual computed logits descending and exact ties by lowest expert ID. Fold selected full probabilities from +0 in rank order, then divide each by that completed sum before capacity. No sorting rounded probabilities or selected-only softmax substitution.",
capacityPolicy="Reset expert loads each evaluation; visit token then rank. Admit if that expert load is below capacity, allocate its old count as slot and increment only on admission. No reroute, fallback, implicit residual or post-drop redistribution. Fully lost means no admitted assignment, not merely a zero vector.",
invocationPolicy="Only accepted invocations have Context, Input, detached namespaced unchanged W1,b1,Z,Hidden,W2,b2,F tensors and PostGain. Prefix records original token/rank/expert/slot; unchanged FFN frames use local b=0,t=0. No unselected or dropped hidden/output tensor is fabricated.",
combinePolicy="Complete every admitted M3 affine/ReLU/affine before multiplying expert post-output gain. For each original token and feature start +0 and fold selected ranks: admitted gate times saved postgain output, dropped literal +0 message, then addition. Keep and lost gate masses are separate +0 rank folds.",
nativePolicy="Exactly nine actual stableSoftmax exp calls in token/expert order at every valid capacity, including zero; no sqrt/log. Returned max/terms/denominator/probabilities are actual helper values. Argument witnesses repeat identical immutable-operand subtractions; no physical interception and no native call during projection or serialization.",
nativeAdmissionPolicy="Future independent admission binds each native ID/kind/WORD input before positive finite output and CAP4 distance from independent RN-even exp, argument [-256,0]; exp(0) must be exact +1. Actual router shifts lie in [-12,0]. This declared policy is not executed evidence or a libm WORD-parity claim.",
zeroPolicy="Every floating operand, intermediate and copy retains binary64 WORD including -0. Only raw topK/capacity and explicit dimensions, IDs, indices, decisions, slots, loads and source counts use VALUE. Structural drop contributions and accumulator initializers are literal +0. ReLU uses unchanged Math.max(+0,z).",
limitsPolicy="Untrained fixed toy; forward only. No attention, residual, load-balancing loss, gradients, training, sampling, model API, measured speed or quality claim. Capacity counts assignments, not features; discarded signed messages can remove cancellation. All runtime validation remains deferred.",
provenance="Signed IV62 owner-selected meaningful M3/raw17 model, distinct from the independent preparation paper M2 candidate. Hand-set banks, no external dataset or model.")
return _freeze(dict(frames=frames, tensors=tensors, texts=texts))
def evaluate_moe(value, trace, prefix):
"""Scalar capture, consumed indexed NumPy Y storage, projection, callbacks."""
captured = _capture_moe(value, prefix)
stored = _private_storage(captured)
# Copy binary64 cells back to ordinary words; no arithmetic or contraction.
captured = _freeze(dict(captured, output=[float(stored[0, t, d]) for t in range(3) for d in range(2)]))
projected = _project_moe(captured, prefix)
saved = _freeze(dict(state=captured["state"], natives=captured["natives"],
tensors=projected["tensors"], texts=projected["texts"]))
for frame in projected["frames"]:
trace.add(frame["id"], frame["label"], frame["equation"], frame["explanation"], frame["inputs"], frame["outputs"])
# Construct once without recursively copying the selected Y a second time.
return _support._FrozenDict(dict(state=saved["state"], output=saved["tensors"][-4],
natives=saved["natives"], tensors=saved["tensors"], texts=saved["texts"]))
def _check_public_copies(saved, result, trace, prefix):
"""Local capture-to-public consistency, never an RN/native admission oracle."""
if not __debug__:
raise RuntimeError("Explicit IV62 public-copy check refuses optimized Python (-O).")
import struct
def word(value):
if not __debug__:
raise RuntimeError("Explicit IV62 public WORD helper refuses optimized Python (-O).")
return struct.pack(">d", value)
def words(values):
if not __debug__:
raise RuntimeError("Explicit IV62 public WORD-list helper refuses optimized Python (-O).")
return [word(value) for value in values]
K = saved["state"]["topK"]
A = sum(int(route["admitted"]) for route in saved["assignments"])
assert tuple(result) == ("state", "output", "natives", "tensors", "texts")
assert tuple(result["state"]) == _FIELDS
assert words(result["state"].values()) == words(saved["state"].values())
assert result["output"] is result["tensors"][32+10*A]
assert len(trace.steps) == 15+15*K+11*A
assert len(trace.outputs) == 87+33*K+35*A
assert len(result["tensors"]) == 36+10*A
assert sum(len(tensor["values"]) for tensor in result["tensors"]) == 247+21*K+36*A
assert len(result["texts"]) == 19
tensors = {tensor["id"]: tensor for tensor in result["tensors"]}
steps = {frame["id"]: frame for frame in trace.steps}
ops = {op["id"]: op for op in saved["operations"]}
assert len(tensors) == len(result["tensors"]) and len(steps) == len(trace.steps)
for tensor in result["tensors"]:
assert tuple(tensor) == ("id", "shape", "axes", "dtype", "values", "provenance", "precision")
assert len(tensor["shape"]) == len(tensor["axes"]) and len(set(tensor["axes"])) == len(tensor["axes"])
size = 1
for dimension in tensor["shape"]:
assert 1 <= dimension <= 64
size *= dimension
assert size == len(tensor["values"])
assert tensor["precision"] == (0 if tensor["dtype"] == "int32" else 8)
for frame in trace.steps:
assert tuple(frame) == ("id", "label", "equation", "explanation", "inputs", "outputs")
for key, value in frame["outputs"].items():
assert word(trace.outputs[frame["id"]+"_"+key]) == word(value)
def cells(suffix):
if not __debug__:
raise RuntimeError("Explicit IV62 tensor-cell helper refuses optimized Python (-O).")
return tensors[prefix+"_"+suffix]["values"]
assert words(cells("Raw")) == words(saved["state"].values())
assert words(cells("X")) == words(v for row in saved["input"] for v in row)
assert words(cells("RouterWeights")) == words(v for row in saved["bank"]["router"] for v in row)
assert words(cells("ExpertW1")) == words(v for expert in saved["bank"]["W1"] for row in expert for v in row)
assert words(cells("ExpertW2")) == words(v for expert in saved["bank"]["W2"] for row in expert for v in row)
assert words(cells("ExpertB1")) == words(list(saved["bank"]["b1"])*3)
assert words(cells("ExpertB2")) == words(list(saved["bank"]["b2"])*3)
for suffix, stem in (("RouterGains", "r"), ("RouterBiases", "b"), ("ExpertGains", "e")):
assert words(cells(suffix)) == words(saved["state"][f"{stem}{e}"] for e in range(3))
assert words(cells("RouterStages")) == words(v for record in saved["router"] for v in record.values())
for suffix, key in (("Logits", "logits"),):
assert words(cells(suffix)) == words(v for row in saved[key] for v in row)
for suffix, key in (("Maxima", "maximum"), ("Denominators", "denominator"), ("SelectedSums", "selectedSum")):
assert words(cells(suffix)) == words(row[key] for row in saved["rows"])
for suffix, key in (("Shifted", "shifted"), ("Terms", "terms"), ("Probabilities", "probabilities"), ("Gates", "gates")):
assert words(cells(suffix)) == words(v for row in saved["rows"] for v in row[key])
assert cells("Ranking") == [e for row in saved["rows"] for e in row["ranking"]]
assert cells("SelectedExperts") == [route["context"]["expert"] for route in saved["assignments"]]
assert words(cells("SelectedProbabilities")) == words(row["probabilities"][e] for row in saved["rows"] for e in row["selected"])
assert cells("Admitted") == [int(route["admitted"]) for route in saved["assignments"]]
assert cells("Slots") == [route["context"]["slot"] for route in saved["assignments"]]
assert cells("Loads") == saved["loads"]
for suffix, key in (("TokenAccepted", "accepted"), ("TokenDropped", "dropped"), ("FullyLost", "fullyLost")):
assert cells(suffix) == [int(loss[key]) for loss in saved["losses"]]
assert cells("PartiallyDropped") == [int(0 < loss["accepted"] < K) for loss in saved["losses"]]
assert words(cells("KeptMass")) == words(loss["kept"] for loss in saved["losses"])
assert words(cells("LostMass")) == words(loss["lost"] for loss in saved["losses"])
assert words(cells("Y")) == words(saved["output"])
assert cells("Counts") == [3*K, A, 3*K-A, sum(int(loss["fullyLost"]) for loss in saved["losses"]), sum(cells("PartiallyDropped"))]
assert cells("NativeKinds") == [1]*9
assert words(cells("NativeArguments")) == words(v for leaf in saved["natives"] for v in (leaf["input"], leaf["output"]))
assert result["texts"]["nativeIds"] == [leaf["id"] for leaf in saved["natives"]]
for index, leaf in enumerate(result["natives"]):
assert tuple(leaf) == ("id", "kind", "input", "output")
assert leaf["id"] == saved["natives"][index]["id"] and leaf["kind"] == "exp"
assert words((leaf["input"], leaf["output"])) == words((saved["natives"][index]["input"], saved["natives"][index]["output"]))
expected_ids = [f"{prefix}_router_{t}_{e}" for t in range(3) for e in range(3)]
for t, row in enumerate(saved["rows"]):
expected_ids.extend([f"{prefix}_softmax_{t}", f"{prefix}_rank_{t}"])
expected_ids.extend(f"{prefix}_selectedSum_{t}_{rank}" for rank in range(K))
expected_ids.extend(f"{prefix}_gate_{t}_{rank}" for rank in range(K))
soft = steps[f"{prefix}_softmax_{t}"]
assert tuple(soft["outputs"]) == ("max", "shifted0", "term0", "shifted1", "term1", "shifted2", "term2", "denominator", "probability0", "probability1", "probability2")
for e in range(3):
router = steps[f"{prefix}_router_{t}_{e}"]
assert words(router["outputs"].values()) == words(saved["router"][3*t+e].values())
assert word(soft["inputs"][f"logit{e}"]) == word(router["outputs"]["logit"])
assert word(soft["outputs"][f"shifted{e}"]) == word(result["natives"][3*t+e]["input"])
assert word(soft["outputs"][f"term{e}"]) == word(result["natives"][3*t+e]["output"])
for rank, e in enumerate(row["selected"]):
fold = steps[f"{prefix}_selectedSum_{t}_{rank}"]
gate = steps[f"{prefix}_gate_{t}_{rank}"]
assert word(fold["inputs"]["probability"]) == word(row["probabilities"][e])
assert word(fold["outputs"]["sum"]) == word(row["selectedRunning"][rank])
assert word(gate["inputs"]["selectedSum"]) == word(row["selectedSum"])
assert word(gate["outputs"]["gate"]) == word(row["gates"][rank])
invocations = []
for route in saved["assignments"]:
t, rank, e, slot = (route["context"][key] for key in ("token", "rank", "expert", "slot"))
dispatch_id = f"{prefix}_dispatch_{t}_{rank}"
expected_ids.append(dispatch_id)
dispatch = steps[dispatch_id]
mass = ops[f"{prefix}_mass_{t}_{rank}"]
assert word(dispatch["inputs"]["gate"]) == word(route["gate"])
assert dispatch["outputs"]["countAfter"] == route["countAfter"]
assert words(dispatch["outputs"][key] for key in ("keptMass", "lostMass")) == words(mass["outputs"].values())
for d in range(2):
combine = steps[f"{prefix}_combine_{t}_{d}_{rank}"]
private = ops[combine["id"]]
assert words(combine["outputs"].values()) == words(private["outputs"].values())
assert word(cells("GatedContributions")[2*(t*K+rank)+d]) == word(private["outputs"]["contribution"])
if not route["admitted"]:
assert tuple(combine["inputs"]) == ("t", "rank", "expert", "d", "admitted", "previous")
if not route["admitted"]:
assert not any(identifier.startswith(f"{prefix}_t{t}_r{rank}_") for identifier in tensors)
continue
c = f"{prefix}_t{t}_r{rank}_e{e}_s{slot}"
invocations.append(c)
expected_ids.append(c+"_context")
expected_ids.extend(f"{c}_ffn_hidden_0_0_{m}" for m in range(3))
expected_ids.extend(f"{c}_ffn_relu_0_0_{m}" for m in range(3))
expected_ids.extend(f"{c}_ffn_output_0_0_{d}" for d in range(2))
expected_ids.extend(f"{c}_gain_{d}" for d in range(2))
inv = route["invocation"]
assert tensors[c+"_Context"]["values"] == [t, rank, e, slot, 2*t, 0, 0]
for suffix, key in (("Input", "input"), ("ffn_Z", "preactivation"), ("ffn_Hidden", "hidden"), ("ffn_F", "output"), ("PostGain", "gained")):
assert words(tensors[c+"_"+suffix]["values"]) == words(inv[key])
for m in range(3):
hidden = steps[f"{c}_ffn_hidden_0_0_{m}"]
relu = steps[f"{c}_ffn_relu_0_0_{m}"]
op = ops[f"{prefix}_expert_{t}_{rank}_{e}_hidden_{m}"]
assert words(hidden["outputs"].values()) == words(op["outputs"][key] for key in ("product0", "product1", "sum", "preactivation"))
assert word(relu["inputs"]["preactivation"]) == word(hidden["outputs"]["preactivation"])
assert word(relu["outputs"]["activation"]) == word(inv["hidden"][m])
for d in range(2):
output = steps[f"{c}_ffn_output_0_0_{d}"]
op = ops[f"{prefix}_expert_{t}_{rank}_{e}_output_{d}"]
assert tuple(output["outputs"]) == ("product0", "product1", "product2", "running0", "running1", "running2", "sum", "value")
assert word(output["outputs"]["sum"]) == word(op["outputs"]["running2"])
for key, value in op["outputs"].items():
assert word(output["outputs"][key]) == word(value)
gain = steps[f"{c}_gain_{d}"]
combine = steps[f"{prefix}_combine_{t}_{d}_{rank}"]
assert word(gain["inputs"]["value"]) == word(output["outputs"]["value"])
assert word(gain["outputs"]["scaled"]) == word(combine["inputs"]["expertOutput"])
expected_ids.extend(f"{prefix}_combine_{t}_{d}_{rank}" for t in range(3) for d in range(2) for rank in range(K))
assert [frame["id"] for frame in trace.steps] == expected_ids
assert result["texts"]["invocationPrefixes"] == invocations
def check_public():
if not __debug__:
raise RuntimeError("Explicit IV62 public check refuses optimized Python (-O).")
for K in (1, 2):
for C in (0, 1, 2, 3):
for r2 in (1.0, -1.0):
state = dict(DEFAULT_IV62, topK=K, capacity=C, r2=r2, x01=-0.0, e2=-0.0)
saved = _capture_moe(state, "copy")
trace = moe_trace()
result = evaluate_moe(state, trace, "copy")
_check_public_copies(saved, result, trace, "copy")
state["x00"] = -2.0
assert result["state"]["x00"] == 1.0
try:
result["output"]["values"][0] = 99.0
except TypeError:
pass
else:
raise AssertionError("Public tensors must be frozen.")
trace = moe_trace()
marker = RuntimeError("Unknown public collector sentinel")
class Observer:
def add(self, *args):
if not __debug__:
raise RuntimeError("Explicit IV62 observer hook refuses optimized Python (-O).")
raise marker
try:
evaluate_moe(DEFAULT_IV62, Observer(), "copy")
except RuntimeError as error:
assert error is marker
else:
raise AssertionError("Unknown public callback exception must retain identity.")
actual_exp = math.exp
def disabled(argument):
if not __debug__:
raise RuntimeError("Explicit IV62 native hook refuses optimized Python (-O).")
raise AssertionError("No native during public callbacks/projection.")
class CapturedObserver:
def add(self, *args):
if not __debug__:
raise RuntimeError("Explicit IV62 capture hook refuses optimized Python (-O).")
math.exp = disabled
trace.add(*args)
try:
result = evaluate_moe(DEFAULT_IV62, CapturedObserver(), "captured")
assert len(trace.steps) == 89 and len(result["natives"]) == 9
assert result["output"] is result["tensors"][-4]
finally:
math.exp = actual_exp
marker = RuntimeError("Unknown native sentinel")
def fail_native(argument):
if not __debug__:
raise RuntimeError("Explicit IV62 failure hook refuses optimized Python (-O).")
raise marker
try:
math.exp = fail_native
try:
evaluate_moe(DEFAULT_IV62, moe_trace(), "unknown")
except RuntimeError as error:
assert error is marker
else:
raise AssertionError("Unknown native exception must retain identity.")
finally:
math.exp = actual_exp
trace = moe_trace()
try:
evaluate_moe(dict(DEFAULT_IV62, capacity=0, e2=float("nan")), trace, "bad-prefix")
except NumericalFault as error:
assert error.code == "NONFINITE" and error.reason == "state.e2 must be an actual finite number."
assert trace.steps == []
else:
raise AssertionError("Raw finite guard must precede prefix and callbacks.")
def check_trace():
if not __debug__:
raise RuntimeError("Explicit IV62 trace check refuses optimized Python (-O).")
import struct
assert moe_trace is _support.decoder_trace
trace = moe_trace()
calls = []
class Once:
def items(self):
if not __debug__:
raise RuntimeError("Explicit IV62 operand hook refuses optimized Python (-O).")
calls.append("items")
if len(calls) != 1:
raise AssertionError("Capture operands exactly once.")
return [("2", -0.0), ("1", 1), ("plain", 2.0)]
trace.add("ordered", "label", "equation", "explanation", Once(), {"out": -0.0})
assert calls == ["items"] and tuple(trace.steps[0]["inputs"]) == ("1", "2", "plain")
assert struct.pack(">d", trace.outputs["ordered_out"]) == struct.pack(">d", -0.0)
class Unreadable:
def items(self):
if not __debug__:
raise RuntimeError("Explicit IV62 unreadable hook refuses optimized Python (-O).")
raise AssertionError("ID rejection must precede operand access.")
for identifier in ("", "ordered"):
try:
trace.add(identifier, "", "", "", Unreadable(), {})
except NumericalFault as error:
assert error.code == "INVALID_INPUT" and error.reason == "Trace IDs must be nonempty and unique."
else:
raise AssertionError("Reject empty/duplicate ID.")
trace.add("_", "", "", "", {}, {"proto__": 1})
assert "__proto__" not in trace.outputs
trace.add("a", "", "", "", {}, {"b_c": 1.0})
trace.add("a_b", "", "", "", {}, {"c": 2.0})
assert trace.outputs["a_b_c"] == 2.0
frame = trace.steps[0]
trace.add("reuse", "", "", "", frame["inputs"], frame["outputs"])
assert trace.steps[-1]["inputs"] == frame["inputs"]
capped = moe_trace()
for index in range(512):
capped.add(str(index), "", "", "", {}, {})
try:
capped.add("over", "", "", "", {"huge": 10**400}, {})
except NumericalFault as error:
assert error.code == "NONFINITE"
else:
raise AssertionError("Finite guard must precede frame cap and integer conversion.")
try:
capped.add("over", "", "", "", {}, {})
except NumericalFault as error:
assert error.code == "UNSUPPORTED_SIZE" and len(capped.steps) == 512
else:
raise AssertionError("Enforce the inherited 512-frame cap.")
marker = RuntimeError("Unknown operand sentinel")
class Fails:
def items(self):
if not __debug__:
raise RuntimeError("Explicit IV62 operand-failure hook refuses optimized Python (-O).")
raise marker
try:
trace.add("unknown", "", "", "", Fails(), {})
except RuntimeError as error:
assert error is marker
else:
raise AssertionError("Unknown operand error must retain identity.")
def check_storage():
"""Pin actual consumed indexed Y storage and its completion before observers."""
if not __debug__:
raise RuntimeError("Explicit IV62 storage check refuses optimized Python (-O).")
import struct
actual_storage = _private_storage
def word(value):
if not __debug__:
raise RuntimeError("Explicit IV62 storage WORD helper refuses optimized Python (-O).")
return struct.pack(">d", value)
for inject_sign in (False, True):
calls, stored_words, captures = [], [], []
trace = moe_trace()
def storage_spy(captured):
if not __debug__:
raise RuntimeError("Explicit IV62 storage hook refuses optimized Python (-O).")
calls.append("storage")
captures.append(captured)
storage = actual_storage(captured)
assert storage.shape == (1, 3, 2) and str(storage.dtype) == "float64"
for t in range(3):
for d in range(2):
assert word(float(storage[0, t, d])) == word(captured["output"][2*t+d])
if inject_sign:
# Fault injection proves the public Y consumes storage, even -0.
storage[0, 0, 0] = -0.0
stored_words.extend(word(float(storage[0, t, d])) for t in range(3) for d in range(2))
return storage
class StoredObserver:
def add(self, *args):
if not __debug__:
raise RuntimeError("Explicit IV62 stored-observer hook refuses optimized Python (-O).")
assert calls == ["storage"] and len(stored_words) == 6
trace.add(*args)
try:
globals()["_private_storage"] = storage_spy
result = evaluate_moe(dict(DEFAULT_IV62, capacity=0, x01=-0.0), StoredObserver(), "store")
assert calls == ["storage"]
assert [word(value) for value in result["output"]["values"]] == stored_words
assert result["output"] is result["tensors"][-4]
if inject_sign:
assert word(result["output"]["values"][0]) == word(-0.0)
assert word(trace.outputs["store_combine_0_0_1_value"]) == word(0.0)
else:
_check_public_copies(captures[0], result, trace, "store")
finally:
globals()["_private_storage"] = actual_storage
3. IV62 entry and ordinary command line — complete file
derive_iv62(value) accepts one complete state; it does not merge a supplied partial state with defaults. DEFAULT_IV62 provides the reset worksheet. The zero-argument run() reads process arguments: no arguments selects that default, a JSON argument supplies a full replacement, - reads one full state from stdin, and --self-check is explicit local checking. Known input faults have a typed unavailable record; unsupported command-line modes are usage errors. Unknown exceptions are not a fabricated successful numerical result.
Imports and ordinary calculations do not invoke self-checks. Explicit checks refuse optimized Python (-O); ordinary input guards remain active. These canonical checks are local regressions, not a second RN authority. The separate independent oracle owns complete captured-record/native admission and exact copy/WORD/VALUE verification. A native return recorded by Python is not proof that its library agrees word-for-word with TypeScript or an exact-real exponential.
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.
"""IV62 canonical actual producer: strict input and owner-adopted public binding.
Actual native scalar producer, not an RN oracle or verifier. Checks UNRUN.
"""
import importlib.util
import json
import math
from pathlib import Path
import sys
from types import ModuleType
def _load_reference():
name = "_book_iv62_mechanism"
path = str(Path(__file__).with_name("moe_reference.py").resolve())
incumbent = sys.modules.get(name)
if name in sys.modules:
if (type(incumbent) is not ModuleType
or incumbent.__dict__.get("_IV62_OWNED_PATH") != path
or type(incumbent.__dict__.get("__file__")) is not str
or str(Path(incumbent.__dict__["__file__"]).resolve()) != path
or incumbent.__dict__.get("_IV62_LOAD_COMPLETE") is not True):
raise ImportError("Refusing unknown or incomplete IV62 reference identity.")
return incumbent
spec = importlib.util.spec_from_file_location(name, path)
if spec is None or spec.loader is None:
raise ImportError("Cannot load owned IV62 reference source.")
staged = importlib.util.module_from_spec(spec)
if name in sys.modules:
raise ImportError("IV62 reference identity appeared before staging.")
staged._IV62_OWNED_PATH = path
transaction = [(name, staged)]
staged._IV62_TRANSACTION = transaction
sys.modules[name] = staged
try:
spec.loader.exec_module(staged)
if sys.modules.get(name) is not staged:
raise ImportError("IV62 reference identity replaced during loading.")
staged._IV62_LOAD_COMPLETE = True
staged.__dict__.pop("_IV62_TRANSACTION", None)
except BaseException:
for owned_name, owned_object in reversed(transaction):
if sys.modules.get(owned_name) is owned_object:
del sys.modules[owned_name]
raise
return staged
_reference = _load_reference()
DEFAULT_IV62 = _reference.DEFAULT_IV62
NumericalFault = _reference.NumericalFault
class InputMisuse(ValueError):
"""CLI argument misuse; JSON parse faults use NumericalFault instead."""
class _JsonInputError(ValueError):
"""Local parser admission failure, converted at the JSON boundary only."""
def _integer(token):
# Local limit only; never change Python's global integer conversion policy.
digits = token[1:] if token.startswith("-") else token
if len(digits) > 309:
raise _JsonInputError("JSON integer exceeds the local 309-digit limit.")
number = float(token)
if not math.isfinite(number):
raise _JsonInputError("JSON numbers must be finite binary64 values.")
return number # float('-0') retains the WORD sign; choices later use VALUE.
def _real(token):
number = float(token)
if not math.isfinite(number):
raise _JsonInputError("JSON numbers must be finite binary64 values.")
return number
def _constant(token):
raise _JsonInputError("Non-JSON numeric constant: " + token)
def _object(pairs):
value = {}
for key, item in pairs:
if key in value:
raise _JsonInputError("Duplicate JSON object field: " + key)
value[key] = item
return value
def _parse(text):
try:
return json.loads(text, parse_int=_integer, parse_float=_real,
parse_constant=_constant, object_pairs_hook=_object)
except (json.JSONDecodeError, _JsonInputError) as error:
# Only local syntax/admission errors are known; unknown failures escape.
raise NumericalFault("INVALID_INPUT", "Expected one finite strict JSON value.") from error
def derive_iv62(value):
"""One full-replacement state; no implicit checking or fabricated schema."""
try:
trace = _reference.moe_trace()
evaluated = _reference.evaluate_moe(value, trace, "moe")
state, tensors, natives = (evaluated[key] for key in ("state", "tensors", "natives"))
counts = next(record["values"] for record in tensors if record["id"] == "moe_Counts")
summary = dict(topK=state["topK"], capacity=state["capacity"], tokens=3, experts=3, hiddenWidth=3,
selectedAssignments=counts[0], acceptedAssignments=counts[1], droppedAssignments=counts[2],
fullyLostTokens=counts[3], partiallyDroppedTokens=counts[4], expCalls=len(natives), sqrtCalls=0,
nativeElementaryCalls=len(natives), frames=len(trace.steps)+1, tensorCount=len(tensors))
trace.add("finish", "Retain every original token and disclose routing losses",
"output=moe_Y; counts=moe_Counts; no post-drop redistribution",
"Copy the saved dispatch counts after all router, admitted expert and combine work. A fully lost token has no admitted assignment; a zero output can also be real expert cancellation. Source graph counts are not measured hardware performance.",
{key: summary[key] for key in tuple(summary)[:10]}, summary)
texts = dict(evaluated["texts"])
texts.update(
graphStages=["Fixed router and full meaningful M3 expert banks", "All nine router logits", "Full stable three-expert probabilities", "Computed-logit ranking and pre-drop selected gates", "Token/rank first-come per-expert capacity", "Only admitted actual M3 expert invocations", "Expert post-output gains", "Original-token feature/rank gated combine and explicit drop messages"],
graphTensorIds=["moe_X", "moe_RouterWeights", "moe_Logits", "moe_Probabilities", "moe_Ranking", "moe_SelectedExperts", "moe_Gates", "moe_Admitted", "moe_Slots", "moe_Loads", "moe_KeptMass", "moe_LostMass", "moe_GatedContributions", "moe_Y", "moe_Counts"],
tracePolicy="Exact unchanged decoderTrace factory alias: detached finite frame operands captured once; empty/duplicate IDs rejected before operands; 512-frame cap after operands. No frame precedes full raw/domain/prefix preflight. All numerical frames precede finish. Every frame output is copied to root outputs as frameId_key.",
summaryPolicy="All fifteen primary summary fields use VALUE dimensions, choices or source counts. Dispatch counts copy moe_Counts; nine native exp and zero sqrt occur even at capacity zero. All other floating operands/results/copies use WORD including -0, except explicitly structural integers. Helper output is the same saved Y TensorRecord in its tensor list.",
validationPolicy="SOURCE IMPLEMENTATION ONLY. Tests, independent authority, canonical parity, typecheck, build, browser, accessibility and offline checks are UNRUN under the human FluxGeo hold. Owner adoption and validation are pending; no runtime acceptance or freeze is claimed.")
outputs = dict(summary)
for frame in trace.steps:
for key, item in frame["outputs"].items():
alias = frame["id"] + "_" + key
if alias in outputs:
raise RuntimeError("IV62 output aliases must be unique.")
outputs[alias] = item
return _reference._freeze(dict(status="defined", outputs=outputs, steps=trace.steps, tensors=tensors, texts=texts))
except NumericalFault as error:
if type(error) is not NumericalFault:
raise
return _fault_record(error)
def _fault_record(error):
if type(error) is not NumericalFault:
raise error
return _reference._freeze(dict(status="unavailable", code=error.code, reason=error.reason))
def check_parser():
if not __debug__:
raise RuntimeError("Explicit IV62 parser check refuses optimized Python (-O).")
import struct
assert struct.pack(">d", _parse("-0")) == struct.pack(">d", -0.0)
assert struct.pack(">d", _parse("-0.0")) == struct.pack(">d", -0.0)
assert _parse("1" + "0" * 308) == 1e308
assert _parse('{"topK":1}') == {"topK": 1.0}
for text in ("1" + "0" * 309, "9" * 309, "1e309", "NaN", "Infinity", "-Infinity",
'{"a":1,"a":2}', "{} {}", "", '{"a":01}'):
try:
_parse(text)
except NumericalFault as error:
assert type(error) is NumericalFault and error.code == "INVALID_INPUT"
else:
raise AssertionError("Malformed/nonfinite JSON must be a known fault.")
try:
_reference.moe_state(_parse('{"topK":1}'))
except NumericalFault as error:
assert type(error) is NumericalFault and error.code == "INVALID_INPUT"
else:
raise AssertionError("Partial JSON must not merge defaults.")
def self_check():
if not __debug__:
raise RuntimeError("Explicit IV62 aggregate check refuses optimized Python (-O).")
_reference.check_private()
_reference.check_storage()
_reference.check_public()
_reference.check_trace()
check_parser()
check_root()
check_cli()
check_loaders()
return {"status": "checked", "chapter": "IV-62", "scope": "canonical-actual-producer"}
def run():
"""Strict zero-argument process-argv entry; import performs no checks."""
arguments = sys.argv[1:]
try:
if arguments == ["--self-check"]:
if not __debug__:
raise RuntimeError("Explicit IV62 CLI check refuses optimized Python (-O).")
result = self_check()
else:
if len(arguments) > 1 or (arguments and arguments[0].startswith("--")):
raise InputMisuse("Usage: iv62.py [JSON | - | --self-check]")
try:
if not arguments:
value = DEFAULT_IV62
elif arguments == ["-"]:
value = _parse(sys.stdin.read())
else:
value = _parse(arguments[0])
result = derive_iv62(value)
except NumericalFault as error:
if type(error) is not NumericalFault:
raise
result = _fault_record(error)
except InputMisuse as error:
print(str(error), file=sys.stderr)
return 2
print(json.dumps(result, allow_nan=False, separators=(",", ":")))
return 0
def check_root():
if not __debug__:
raise RuntimeError("Explicit IV62 root check refuses optimized Python (-O).")
import struct
def word(value):
if not __debug__:
raise RuntimeError("Explicit IV62 root WORD helper refuses optimized Python (-O).")
return struct.pack(">d", value)
for patch in ({}, {"capacity": 0}, {"capacity": 3}, {"topK": 1}, {"r2": -1.0},
{"capacity": -0.0, "x01": -0.0}, {"e0": 0.0, "e1": 0.0}):
raw = dict(DEFAULT_IV62, **patch)
result = derive_iv62(raw)
assert tuple(result) == ("status", "outputs", "steps", "tensors", "texts")
assert result["status"] == "defined"
outputs = result["outputs"]
K, A = outputs["topK"], outputs["acceptedAssignments"]
assert len(result["steps"]) == outputs["frames"] == 16+15*K+11*A
assert len(result["tensors"]) == outputs["tensorCount"] == 36+10*A
assert len(outputs) == 117+33*K+35*A and len(result["texts"]) == 24
primary = ("topK", "capacity", "tokens", "experts", "hiddenWidth", "selectedAssignments", "acceptedAssignments", "droppedAssignments", "fullyLostTokens", "partiallyDroppedTokens", "expCalls", "sqrtCalls", "nativeElementaryCalls", "frames", "tensorCount")
assert tuple(outputs)[:15] == primary
finish = result["steps"][-1]
assert finish["id"] == "finish" and tuple(finish["inputs"]) == primary[:10] and tuple(finish["outputs"]) == primary
assert outputs["expCalls"] == outputs["nativeElementaryCalls"] == 9 and outputs["sqrtCalls"] == 0
aliases = []
for frame in result["steps"]:
for key, value in frame["outputs"].items():
alias = frame["id"]+"_"+key
aliases.append(alias)
assert word(value) == word(outputs[alias])
assert tuple(outputs)[15:] == tuple(aliases)
counts = next(t["values"] for t in result["tensors"] if t["id"] == "moe_Counts")
assert [outputs[key] for key in primary[5:10]] == counts
raw["x00"] = -2.0
assert next(t["values"][2] for t in result["tensors"] if t["id"] == "moe_Raw") == 1.0
try:
result["outputs"]["topK"] = 99
except TypeError:
pass
else:
raise AssertionError("Root must be detached and frozen.")
for raw, reason in (({}, "state must have exactly " + ", ".join(DEFAULT_IV62) + " as own fields."),
(dict(DEFAULT_IV62, capacity=4), "capacity must be an integer between 0 and 3."),
(dict(DEFAULT_IV62, e2=2), "e2 must be between -1 and 1.")):
assert derive_iv62(raw) == {"status": "unavailable", "code": "INVALID_INPUT", "reason": reason}
assert derive_iv62(dict(DEFAULT_IV62, topK=0, e2=10**400)) == {
"status": "unavailable", "code": "NONFINITE", "reason": "state.e2 must be an actual finite number."}
actual_exp = _reference.math.exp
marker = RuntimeError("Unknown root native sentinel")
def fail(argument):
if not __debug__:
raise RuntimeError("Explicit IV62 root-failure hook refuses optimized Python (-O).")
raise marker
try:
_reference.math.exp = fail
try:
derive_iv62(DEFAULT_IV62)
except RuntimeError as error:
assert error is marker
else:
raise AssertionError("Root must preserve unknown native identity.")
finally:
_reference.math.exp = actual_exp
def _check_cli_case(arguments, stdin=""):
if not __debug__:
raise RuntimeError("Explicit IV62 CLI-case check refuses optimized Python (-O).")
import io
old_argv, old_in, old_out, old_err = sys.argv, sys.stdin, sys.stdout, sys.stderr
stdout, stderr = io.StringIO(), io.StringIO()
try:
sys.argv, sys.stdin, sys.stdout, sys.stderr = [__file__, *arguments], io.StringIO(stdin), stdout, stderr
status = run()
return status, stdout.getvalue(), stderr.getvalue()
finally:
sys.argv, sys.stdin, sys.stdout, sys.stderr = old_argv, old_in, old_out, old_err
def check_cli():
if not __debug__:
raise RuntimeError("Explicit IV62 CLI check refuses optimized Python (-O).")
status, text, errors = _check_cli_case([])
assert status == 0 and errors == "" and _parse(text)["status"] == "defined"
status, text, errors = _check_cli_case(["-"], json.dumps(dict(DEFAULT_IV62, capacity=0)))
record = _parse(text)
assert status == 0 and errors == "" and record["outputs"]["acceptedAssignments"] == 0
for arguments in (["{}"], ["NaN"], ['{"topK":1}'], ["9"*309], ['{"x":1,"x":2}']):
status, text, errors = _check_cli_case(arguments)
assert status == 0 and errors == "" and tuple(_parse(text)) == ("status", "code", "reason")
assert _parse(text)["status"] == "unavailable"
status, text, errors = _check_cli_case([json.dumps(dict(DEFAULT_IV62, topK=1, capacity=3))])
assert status == 0 and errors == "" and _parse(text)["outputs"]["topK"] == 1
for arguments in (["--verify"], ["--stdin"], ["--unknown"], ["{}", "{}"], ["--self-check", "extra"]):
status, text, errors = _check_cli_case(arguments)
assert status == 2 and text == "" and errors.startswith("Usage: iv62.py ")
original = globals()["derive_iv62"]
marker = RuntimeError("Unknown CLI sentinel")
def fail(value):
if not __debug__:
raise RuntimeError("Explicit IV62 CLI-failure hook refuses optimized Python (-O).")
raise marker
try:
globals()["derive_iv62"] = fail
try:
_check_cli_case([])
except RuntimeError as error:
assert error is marker
else:
raise AssertionError("CLI must not relabel an unknown failure.")
finally:
globals()["derive_iv62"] = original
original_parse = json.loads
def failed_parse(*args, **kwargs):
if not __debug__:
raise RuntimeError("Explicit IV62 parser-failure hook refuses optimized Python (-O).")
raise marker
try:
json.loads = failed_parse
try:
_parse("{}")
except RuntimeError as error:
assert error is marker
else:
raise AssertionError("Parser must preserve unknown exception identity.")
finally:
json.loads = original_parse
def check_loaders():
"""Explicit real owned-loader transactions, with no support source mutation."""
if not __debug__:
raise RuntimeError("Explicit IV62 loader check refuses optimized Python (-O).")
helper, support = "_book_iv62_mechanism", "_book_iv62_generic59"
absent = object()
originals = {name: sys.modules.get(name, absent) for name in (helper, support)}
spec_factory = importlib.util.spec_from_file_location
marker = RuntimeError("Original unknown loader sentinel")
helper_path = str(Path(__file__).with_name("moe_reference.py").resolve())
support_path = str(Path(__file__).with_name("decoder_reference.py").resolve())
def restore():
if not __debug__:
raise RuntimeError("Explicit IV62 cache-restore helper refuses optimized Python (-O).")
for name, incumbent in originals.items():
if incumbent is absent:
sys.modules.pop(name, None)
else:
sys.modules[name] = incumbent
def expect_unknown(call):
if not __debug__:
raise RuntimeError("Explicit IV62 loader-fault helper refuses optimized Python (-O).")
try:
call()
except RuntimeError as error:
assert error is marker
else:
raise AssertionError("Original load failure must escape unchanged.")
def intercepted_factory(name, path, *args, **kwargs):
if not __debug__:
raise RuntimeError("Explicit IV62 loader-spec hook refuses optimized Python (-O).")
spec = spec_factory(name, path, *args, **kwargs)
wrapped = spec.loader
class Loader:
def create_module(self, module_spec):
if not __debug__:
raise RuntimeError("Explicit IV62 module hook refuses optimized Python (-O).")
created = wrapped.create_module(module_spec)
if name == appeared:
sys.modules[name] = None
return created
def exec_module(self, staged):
if not __debug__:
raise RuntimeError("Explicit IV62 load hook refuses optimized Python (-O).")
wrapped.exec_module(staged)
if name == fail_at:
if replacement_key is not None:
if replacement is absent:
sys.modules.pop(replacement_key, None)
else:
sys.modules[replacement_key] = replacement
if unknown_failure:
raise marker
spec.loader = Loader()
return spec
def load_support():
if not __debug__:
raise RuntimeError("Explicit IV62 support-load helper refuses optimized Python (-O).")
return _reference._load_owned(support, Path(support_path))
try:
assert _load_reference() is _reference
assert _reference._load_owned(support, Path(support_path)) is _reference._support
for name, expected_path, loader in (
(helper, helper_path, _load_reference),
(support, support_path, load_support)):
forged = ModuleType(name)
forged.__dict__.update(_IV62_OWNED_PATH=expected_path, _IV62_LOAD_COMPLETE=True, __file__=str(Path(expected_path).with_name("wrong.py")))
sys.modules[name] = forged
try:
loader()
except ImportError:
assert sys.modules[name] is forged
else:
raise AssertionError("Markers cannot override actual source identity.")
for incumbent in (None, ModuleType(name)):
sys.modules[name] = incumbent
try:
loader()
except ImportError:
assert sys.modules[name] is incumbent
else:
raise AssertionError("Unknown/incomplete incumbents must survive refusal.")
restore()
# Relative spelling of the correct actual path resolves to the same source.
valid = _reference
actual_file = valid.__dict__["__file__"]
try:
valid.__dict__["__file__"] = str(Path(helper_path).parent / ".." / "p15" / "moe_reference.py")
assert _load_reference() is valid
finally:
valid.__dict__["__file__"] = actual_file
valid_support = _reference._support
actual_file = valid_support.__dict__["__file__"]
try:
valid_support.__dict__["__file__"] = str(Path(support_path).parent / ".." / "p15" / "decoder_reference.py")
assert load_support() is valid_support
finally:
valid_support.__dict__["__file__"] = actual_file
# Actual-file resolution failures escape, leaving the cached object intact.
real_path, support_real_path = Path, _reference.Path
def failed_path(value):
if not __debug__:
raise RuntimeError("Explicit IV62 path-failure hook refuses optimized Python (-O).")
if value == fault_path:
raise marker
return real_path(value)
try:
fault_path = helper_path
globals()["Path"] = failed_path
expect_unknown(_load_reference)
assert sys.modules[helper] is valid
globals()["Path"] = real_path
fault_path = support_path
_reference.Path = failed_path
expect_unknown(load_support)
assert sys.modules[support] is valid_support
finally:
globals()["Path"], _reference.Path = real_path, support_real_path
importlib.util.spec_from_file_location = intercepted_factory
appeared = None
replacement_key, replacement, unknown_failure = None, absent, True
fail_at = helper
# Preexisting valid support must survive a later newly staged helper failure.
sys.modules.pop(helper, None)
expect_unknown(_load_reference)
assert helper not in sys.modules and sys.modules[support] is originals[support]
# Register support before it runs: aggregate rollback sees it even on failure.
for fail_at in (support, helper):
sys.modules.pop(helper, None)
sys.modules.pop(support, None)
expect_unknown(_load_reference)
assert helper not in sys.modules and support not in sys.modules
# Replacements, None and deletion are never removed or overwritten by cleanup.
for fail_at in (support, helper):
for replacement_key in (support, helper):
for replacement in (ModuleType("replacement"), None, absent):
sys.modules.pop(helper, None)
sys.modules.pop(support, None)
expect_unknown(_load_reference)
if replacement is absent:
assert replacement_key not in sys.modules
else:
assert replacement_key in sys.modules and sys.modules[replacement_key] is replacement
other = support if replacement_key == helper else helper
assert other not in sys.modules
# Successful execution with changed identity fails separately, retaining replacement.
unknown_failure = False
for fail_at in (support, helper):
replacement_key = fail_at
for replacement in (ModuleType("replacement"), None, absent):
sys.modules.pop(helper, None)
sys.modules.pop(support, None)
try:
_load_reference()
except ImportError:
if replacement is absent:
assert replacement_key not in sys.modules
else:
assert sys.modules[replacement_key] is replacement
else:
raise AssertionError("Successful load identity replacement must be detected.")
for appeared in (helper, support):
sys.modules.pop(helper, None)
sys.modules.pop(support, None)
try:
_load_reference()
except ImportError:
assert appeared in sys.modules and sys.modules[appeared] is None
assert (support if appeared == helper else helper) not in sys.modules
else:
raise AssertionError("An incumbent installed during spec creation must be preserved.")
finally:
importlib.util.spec_from_file_location = spec_factory
restore()
if __name__ == "__main__":
raise SystemExit(run())
The panels display executable source. Displaying it alone does not establish canonical parity, independent numerical admission, accessible interaction or offline behavior.
Carry the policy forward
Keep five concrete ideas: router scores choose distinct experts; full softmax and selected gates are different quantities; capacity counts admitted assignments in a declared order; each admitted expert computes a complete three-hidden-unit MLP; combining retains original gates after drops. Inspect decisions to distinguish full loss from zero or cancelling messages. The next curriculum topic, Quantization and Numerical Approximation, asks what changes when numerical representations themselves are restricted; it is a later lesson, not an implemented continuation claimed here.
This worksheet explains the mechanism; its derivation is separate from numerical, interaction and accessibility validation.