The neural notebook
← All chapters

IV-18 / Part III · Embeddings

How Embeddings Learn From Gradients

Derive actual repeated-index embedding gradients, simultaneous classifier updates and fresh losses in a tiny binary task.

Review the ideas this chapter uses

An embedding lookup retrieves numbers, but retrieval alone cannot teach the table anything. To learn, we need a task, a score for mistakes and a rule for changing parameters. This lesson supplies the smallest useful example: retrieve one row per position, use it to predict a binary target, then update the actual table coordinates and classifier together.

Review row selection in IV-16 — Token IDs and Embedding Lookup Tables and the hand-derived reverse pass in IV-08 — One Training Step: Hand-Derived Backpropagation. The new issue is parameter sharing. When a row appears twice, its gradient must collect both uses. A second occurrence neither creates a second parameter nor overwrites the first occurrence’s contribution.

Inspect a real update

Compute it yourself

Learn actual lookup rows by scatter-ADD

These controls recompute the actual example. Trace navigation shows saved calculation steps; editing starts a new trace from the displayed inputs.

Complete results from this trace’s starting inputs

Starting inputs for these results
e00
1
e01
0
e10
0
e11
1
e20
1
e21
1
T
3
i0
2
i1
0
i2
2
y0
1
y1
0
y2
1
u0
1
u1
0
b
-1
eta
0.25
steps
1
initialLoss0.6931471805599453
finalLoss0.6207177056975478
steps1
updatedRows2

initialLoss 0.6931471805599453. finalLoss 0.6207177056975478. steps 1. updatedRows 2. initial: forward position 0. Read the entire current parameter snapshot. Loss is evaluated from logits, never log of a rounded probability.. initial_z0 0. initial_p0 0.5. initial_BCE0 0.6931471805599453

initial: forward position 0

h=E[id]; z=u0*h0+u1*h1+b; p=sigmoid(z); BCE=max(z,0)-z*y+log1p(exp(-abs(z)))

Read the entire current parameter snapshot. Loss is evaluated from logits, never log of a rounded probability.

Inputs

t
0
ID
2
h0
1
h1
1
u0
1
u1
0
b
-1
y
1

Outputs

initial_z0
0
initial_p0
0.5
initial_BCE0
0.6931471805599453

Initial mean loss: 0.6931471805599453. Final mean loss: 0.6207177056975478 after 1 actual simultaneous updates. 2 embedding rows differ from their initial values. All histories start from the controls above; trace navigation does not restart training.

Embedding parameters: initial, initial gradient, actual final
Vocabulary rowFeatureInitial EInitial dEFinal E
0: oak010.166666666666666660.9583333333333334
0: oak1000
1: river0000
1: river1101
2: sun01-0.33333333333333331.0833333333333333
2: sun1101

Initial classifier gradients dU=[-0.16666666666666666,-0.3333333333333333], dB=-0.16666666666666666. Final classifier row u=[1.0416666666666667,0.08333333333333333], bias=-0.9583333333333334.

Fresh loss at every actual parameter snapshot
SnapshotMean BCE from logits
Initial0.6931471805599453
After update 10.6207177056975478

The selected trace shows one calculation within this full history. Initial gradient columns always describe the starting state. Finite updated weights can leave [−4,4]; they stay unclamped in the history.

Inspect tensor shapes and full precision

All computed outputs

initialLoss
0.6931471805599453
finalLoss
0.6207177056975478
steps
1
updatedRows
2
initial_z0
0
initial_p0
0.5
initial_BCE0
0.6931471805599453
initial_z1
0
initial_p1
0.5
initial_BCE1
0.6931471805599453
initial_z2
0
initial_p2
0.5
initial_BCE2
0.6931471805599453
initial_loss
0.6931471805599453
step1_dZ0
-0.16666666666666666
contribution0
-0.16666666666666666
runningE20
-0.3333333333333333
readoutContribution0
-0.16666666666666666
runningU0
-0.16666666666666666
contribution1
0
runningE21
0
readoutContribution1
-0.16666666666666666
runningU1
-0.3333333333333333
runningB
-0.16666666666666666
step1_dZ1
0.16666666666666666
runningE00
0.16666666666666666
runningE01
0
step1_dZ2
-0.16666666666666666
step1_dU0
-0.16666666666666666
step1_dU1
-0.3333333333333333
step1_dB
-0.16666666666666666
step1_dE00
0.16666666666666666
step1_dE01
0
step1_dE10
0
step1_dE11
0
step1_dE20
-0.3333333333333333
step1_dE21
0
step1_b
-0.9583333333333334
step1_u0
1.0416666666666667
step1_u1
0.08333333333333333
step1_e00
0.9583333333333334
step1_e01
0
step1_e10
0
step1_e11
1
step1_e20
1.0833333333333333
step1_e21
1
step1_z0
0.2534722222222222
step1_p0
0.5630309477919891
step1_BCE0
0.5744206829180613
step1_z1
0.03993055555555558
step1_p1
0.5099813126994045
step1_BCE1
0.7133117512565207
step1_z2
0.2534722222222222
step1_p2
0.5630309477919891
step1_BCE2
0.5744206829180613
step1_loss
0.6207177056975478
dU0
-0.16666666666666666
dU1
-0.3333333333333333
dB
-0.16666666666666666
dE00
0.16666666666666666
dE01
0
dE10
0
dE11
0
dE20
-0.3333333333333333
dE21
0
dZ0
-0.16666666666666666
dZ1
0.16666666666666666
dZ2
-0.16666666666666666
finalU0
1.0416666666666667
finalU1
0.08333333333333333
finalB
-0.9583333333333334
finalE00
0.9583333333333334
finalE01
0
finalE10
0
finalE11
1
finalE20
1.0833333333333333
finalE21
1

Values below are stored binary64 numbers, shown without display rounding. Axes specify what each dimension counts; flattened storage is in row-major order.

initialE

Vocab=3 × D=2 · float64 · display precision 8 · Starting embedding parameters.

Storage indexValue
01
10
20
31
41
51

initialU

Output=1 × D=2 · float64 · display precision 8 · Mathematical output row u; h is stored as a feature row, so z=h*u^T+b.

Storage indexValue
01
10

ids

B=1 × T=3 · int32 · display precision 8 · Discrete routing IDs, no ID derivative.

Storage indexValue
02
10
22

targets

B=1 × T=3 · float64 · display precision 8 · Binary target at each active position.

Storage indexValue
01
10
21

initial_X

B=1 × T=3 × D=2 · float64 · display precision 8 · initial: freshly gathered features.

Storage indexValue
01
11
21
30
41
51

initial_logits

B=1 × T=3 · float64 · display precision 8 · initial: actual logits.

Storage indexValue
00
10
20

initial_probabilities

B=1 × T=3 · float64 · display precision 8 · initial: stable sigmoid outputs.

Storage indexValue
00.5
10.5
20.5

step1_dE

Vocab=3 × D=2 · float64 · display precision 8 · Update 1: old-snapshot scatter sums.

Storage indexValue
00.16666666666666666
10
20
30
4-0.3333333333333333
50

step1_dU

Output=1 × D=2 · float64 · display precision 8 · Update 1: old-snapshot classifier gradient.

Storage indexValue
0-0.16666666666666666
1-0.3333333333333333

step1_dZ

B=1 × T=3 · float64 · display precision 8 · Update 1: mean-loss logit derivatives.

Storage indexValue
0-0.16666666666666666
10.16666666666666666
2-0.16666666666666666

step1_X

B=1 × T=3 × D=2 · float64 · display precision 8 · step1: freshly gathered features.

Storage indexValue
01.0833333333333333
11
20.9583333333333334
30
41.0833333333333333
51

step1_logits

B=1 × T=3 · float64 · display precision 8 · step1: actual logits.

Storage indexValue
00.2534722222222222
10.03993055555555558
20.2534722222222222

step1_probabilities

B=1 × T=3 · float64 · display precision 8 · step1: stable sigmoid outputs.

Storage indexValue
00.5630309477919891
10.5099813126994045
20.5630309477919891

finalE

Vocab=3 × D=2 · float64 · display precision 8 · Actual final embedding parameters.

Storage indexValue
00.9583333333333334
10
20
31
41.0833333333333333
51

finalU

Output=1 × D=2 · float64 · display precision 8 · Actual final classifier row.

Storage indexValue
01.0416666666666667
10.08333333333333333

lossHistory

Snapshot=2 · float64 · display precision 8 · Initial loss followed by fresh loss after each full update.

Storage indexValue
00.6931471805599453
10.6207177056975478

EHistory

Snapshot=2 × Vocab=3 × D=2 · float64 · display precision 8 · Detached full embedding snapshots, initial first.

Storage indexValue
01
10
20
31
41
51
60.9583333333333334
70
80
91
101.0833333333333333
111

UHistory

Snapshot=2 × Output=1 × D=2 · float64 · display precision 8 · Detached classifier rows, initial first.

Storage indexValue
01
10
21.0416666666666667
30.08333333333333333

bHistory

Snapshot=2 · float64 · display precision 8 · Initial and actual updated biases.

Storage indexValue
0-1
1-0.9583333333333334

Try eta=0 to keep every parameter unchanged, then compare one and three steps. Use the cancellation setup from exercise 5. The classifier is a tiny binary predictor per position, not a language model.

Check your understanding

Work from the starting inputs shown above. Each answer includes the reasoning; editing the example resets your answers.

1. What receives a derivative through a lookup?
2. Read the initial-gradient column. What is the current initial dE20?
3. Reset. With E20=1, dE20=−1/3 and eta=1/4, what is the updated E20?
4. Reset. Which prediction follows when only the number of steps changes from 1 to 3?
5. Use T=2, both IDs=2, targets 0 and 1, and reset-like parameters giving both logits zero. What happens?

Reset supplies IDs [2,0,2] and targets [1,0,1]. The initial-gradient column describes exactly those starting parameters. The final columns describe parameters after the selected number of steps. Follow step1_scatter_0, step1_scatter_1, step1_scatter_2, then step1_update to see contributions accumulate before any parameter changes. The loss table contains a fresh forward calculation after every full update, rather than an invented descending curve.

The controls always describe the starting state. Trace navigation explains saved operations within its history; it does not resume from the selected intermediate parameters. Changing a control begins a new calculation and clears exercise grading. Try learning rate eta=0, then reset and select three steps. Zero learning rate preserves all parameters, whereas multiple steps use each newly updated snapshot for the next forward and backward pass.

Define the task and its shapes

The vocabulary is still oak,river,sun, IDs 0,1,2. The embedding matrix EE has shape [Vocab=3,D=2], initially rows [1,0], [0,1], [1,1]. At active position t, the integer iti_t chooses features ht=Eit,:h_t=E_{i_t,:}. The colon means both feature columns. The gathered tensor X has shape [B=1,T,D=2]; T is the active position count, between 1 and 3.

The classifier converts each retrieved vector into a prediction for target yty_t, which is exactly 0 or 1. It has output row u=[u0,u1]u=[u_0,u_1], shape [Output=1,D=2], and scalar bias b. Since hth_t is stored as a row, its scalar logit, the real score before converting to a probability, is

zt=htuT+b=u0ht0+u1ht1+b.z_t=h_tu^T+b=u_0h_{t0}+u_1h_{t1}+b.

Superscript T means transpose. Equivalently, earlier column-feature notation would write uhtT+bu h_t^T+b. Both arrangements produce one number and use the same coordinate products. Logits, probabilities and targets each have shape [B=1,T]; no feature axis remains after the readout.

The sigmoid maps a logit to a probability pt=1/(1+e−zt)p_t=1/(1+e^{-z_t}), where e is the natural exponential base. The implementation uses a sign-dependent stable expression to avoid an unnecessarily large exponential. A positive target asks for high probability; a zero target asks for low probability. These targets are hand-set binary labels, not next-token vocabulary distributions. This classifier is not a language model.

Make the loss stable before differentiating

Binary cross-entropy, abbreviated BCE, penalizes wrong binary predictions. For logit z and target y its real expression can be written

ℓ(z,y)=max⁡(z,0)−zy+log⁡(1+e−∣z∣).\ell(z,y)=\max(z,0)-zy+\log(1+e^{-|z|}).

The absolute value ∣z∣|z| is z’s nonnegative magnitude. The implementation evaluates the final logarithm as log1p(exp(-abs(z))); log1p(q) computes log⁡(1+q)\log(1+q) accurately for small q. It never takes log(p) or log(1-p) from a stored probability that might already have rounded to zero or one.

The scalar objective L is the mean over active positions:

L=1T∑t=0T−1ℓ(zt,yt).L=\frac1T\sum_{t=0}^{T-1}\ell(z_t,y_t).

There is one factor 1/T1/T, and no averaging over the two feature coordinates. In real arithmetic the equivalent expression log⁡(1+ez)−yz\log(1+e^z)-yz has derivative p−yp-y: the logarithm contributes ez/(1+ez)=pe^z/(1+e^z)=p, while −yz-yz contributes −y-y. Averaging supplies

gt=∂L∂zt=pt−ytT.g_t=\frac{\partial L}{\partial z_t}=\frac{p_t-y_t}{T}.

The trace calls this derivative dZ. A gradient is a loss sensitivity evaluated at current parameters. It has not yet changed those parameters.

Finish the default forward pass by hand

Initially u=[1,0]u=[1,0] and b=−1b=-1. Sun retrieves [1,1], and oak retrieves [1,0]. Both give logit (1)(1)+(0)(second feature)−1=0(1)(1)+(0)(\text{second feature})-1=0. Therefore all three probabilities are 1/21/2, all three losses are log⁡2\log2, and their mean is also log⁡2\log2.

Subtract the targets and divide by T=3:

(g0,g1,g2)=((−1/2)/3,(1/2)/3,(−1/2)/3)=(−1/6,1/6,−1/6).(g_0,g_1,g_2)=((-1/2)/3,(1/2)/3,(-1/2)/3) =(-1/6,1/6,-1/6).

The sign says how increasing a logit affects loss. At a positive target, a larger logit locally decreases loss, hence a negative derivative. At the zero target it locally increases loss, hence a positive derivative.

Scatter-ADD follows every shared path

For one position, differentiating zt=u0ht0+u1ht1+bz_t=u_0h_{t0}+u_1h_{t1}+b with respect to a feature gives ∂zt/∂htd=ud\partial z_t/\partial h_{td}=u_d. Multiply by upstream derivative gtg_t. Lookup routes that contribution to its selected parameter row:

∂L∂Er,d=∑t:it=rgtud.\frac{\partial L}{\partial E_{r,d}} =\sum_{t:i_t=r}g_tu_d.

The row index r ranges over 0,1,2 and feature d over 0,1. Scatter-ADD names this operation: distribute position contributions to their addressed rows and add whenever addresses repeat. Initialize every gradient cell to zero. Add each contribution, then finish the sum before updating.

At position 0, sun receives (−1/6)[1,0]=[−1/6,0](-1/6)[1,0]=[-1/6,0]. At position 1, oak receives (1/6)[1,0]=[1/6,0](1/6)[1,0]=[1/6,0]. At position 2, sun receives another [-1/6,0], changing its running sum to [-1/3,0]. River is never selected. The complete result is

dE=[1/6000−1/30].dE=\begin{bmatrix}1/6&0\\0&0\\-1/3&0\end{bmatrix}.

Do not divide sun’s result by two because it occurred twice. The mean objective already divided each contribution by T. An additional occurrence-count divisor would change the derivative. Overwriting instead of adding would also be wrong: it would lose the first sun path.

The classifier receives contributions too:

dud=∑tgthtd,db=∑tgt.du_d=\sum_t g_t h_{td},\qquad db=\sum_tg_t.

Using the same old retrieved features gives

du0=(−1/6)(1)+(1/6)(1)+(−1/6)(1)=−1/6,du_0=(-1/6)(1)+(1/6)(1)+(-1/6)(1)=-1/6, du1=(−1/6)(1)+(1/6)(0)+(−1/6)(1)=−1/3,db=−1/6+1/6−1/6=−1/6.du_1=(-1/6)(1)+(1/6)(0)+(-1/6)(1)=-1/3, \qquad db=-1/6+1/6-1/6=-1/6.

Even though old u1=0u_1=0 makes the second embedding-coordinate gradients zero, du1du_1 is nonzero. Its local derivative is the old second feature, not the old readout weight. Differentiating each operand of a product supplies the other operand; confusing these factors would freeze a trainable classifier coordinate incorrectly.

Update every parameter from the same old snapshot

Stochastic gradient descent, SGD here, subtracts learning rate eta times the gradient. All positions in this tiny supplied sequence contribute to the stated mean; there is no random sampling in this demonstration. For eta=1/41/4,

E′=E−14dE=[23/2400113/121],E'=E-\tfrac14dE =\begin{bmatrix}23/24&0\\0&1\\13/12&1\end{bmatrix}, u′=u−14du=[25/24,1/12],b′=−23/24.u'=u-\tfrac14du=[25/24,1/12],\qquad b'=-23/24.

The prime marks new parameters. Oak feature 0 decreases by 1/241/24. Sun feature 0 increases by 1/121/12. River stays exactly [0,1]. This is a simultaneous update: every gradient used old E, old u and old b. Updating u first and using it to form dE would differentiate a different snapshot. The selected update trace includes the full old parameters and completed gradients as operands.

Now gather again from E′E' and recompute with u′,b′u',b'. For each sun occurrence,

zsun′=(25/24)(13/12)+(1/12)(1)−23/24=325/288+24/288−276/288=73/288.z'_{sun}=(25/24)(13/12)+(1/12)(1)-23/24 =325/288+24/288-276/288=73/288.

For oak,

zoak′=(25/24)(23/24)+(1/12)(0)−23/24=575/576−552/576=23/576.z'_{oak}=(25/24)(23/24)+(1/12)(0)-23/24 =575/576-552/576=23/576.

Thus fresh logits are [73/288,23/576,73/288]. The new real mean loss is

L′=2log⁡(1+e−73/288)+23/576+log⁡(1+e−23/576)3.L'=\frac{2\log(1+e^{-73/288})+23/576+\log(1+e^{-23/576})}{3}.

Those fractions and symbolic expressions are hand derivations, not measured decimal results. The live record evaluates the stable expression in binary64, displaying its actual stored values. It does not reuse the initial logits or claim a loss without recalculating it.

Reinforcement, cancellation and unseen rows

The two sun targets agree at the default, so their embedding contributions reinforce. Repetition alone does not guarantee reinforcement. Set T=2, both IDs to 2, targets to 0 and 1, and use the reset parameters. Both logits are zero, giving g=[1/4,−1/4]g=[1/4,-1/4]. Their shared-row gradient is (1/4)u+(−1/4)u=[0,0](1/4)u+(-1/4)u=[0,0]. Because both retrieved features are identical, the classifier contributions cancel too, and the bias sum is zero.

The model cannot give two different probabilities to the same row with this same position-independent readout. For these balanced opposite targets, their shared prediction p gives mean loss L=−12log⁡(p)−12log⁡(1−p)=−12log⁡(p(1−p))L=-\tfrac12\log(p)-\tfrac12\log(1-p)=-\tfrac12\log(p(1-p)). The product p(1−p)=1/4−(p−1/2)2p(1-p)=1/4-(p-1/2)^2 is largest at p=1/2, so the smallest possible mean loss is log⁡2\log2, not zero. At p=1/2, each target still has loss log⁡2\log2, while their summed parameter gradients are zero. This is conflicting data for this context-free model, not a scatter-ADD bug.

There is no position feature, context or recurrent state here. Reordering paired IDs and targets changes their order in the record but not the real mean objective; the next Part introduces sequence context, allowing a representation to depend on more than the current ID alone.

An unseen row has no data-loss path, so every contribution to its gradient is zero. In this model it remains unchanged on every step, even though the readout changes. This statement depends on the specified objective: adding parameter regularization or another loss could update unseen rows, but neither is present here. IDs remain discrete routing data; no derivative with respect to an integer ID is claimed.

Numerical and interaction limits

All eighteen fields are required, including inactive ID and target slots. E coordinates, readout weights and bias begin in [−4,4]; eta is in [0,1]; T and steps are integer 1 through 3. IDs must be integers 0 through 2, and targets exactly 0 or 1. An invalid index or target 0.5 is rejected, never rounded into a different problem.

Each new forward pass and gradient is finite-checked. Updated weights may leave the editor’s starting range; the actual finite values remain in history without clipping. Three steps are three genuine applications of this rule, not a claim to have trained a useful system. A large learning rate need not improve loss; the complete loss table lets the actual computation speak.

Binary64 also separates the ideal derivative from its stored evaluation. The gradient operation is the declared (p-y)/T. For a large positive logit, stored sigmoid may round to 1, or subtracting 1 may lose relative accuracy, while the stable positive-target logit loss still has a nonzero tail. The implementation preserves those actual operations rather than claiming an exact real derivative at saturation. Stable loss evaluation prevents one avoidable failure; it does not eliminate all rounding or underflow.

Read the sources and consolidate

The Python program mirrors the scalar forward arithmetic, explicit per-position scatter sums and full simultaneous update. NumPy arrays hold parameters and gradients; new arrays are constructed only after all derivatives are complete. The helper copies numerical records so a later step cannot rewrite an earlier snapshot.

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.

"""IV18: a tiny real lookup-plus-binary-classifier, with simultaneous SGD."""
import math
import numpy as np
from embedding_reference import EMBEDDING_DEFAULTS, Trace, embedding_rows, finite, fixed_state, guarded, run, sigmoid, tensor

DEFAULT_IV18 = {**EMBEDDING_DEFAULTS, "T": 3, "i0": 2, "i1": 0, "i2": 2,
                "y0": 1, "y1": 0, "y2": 1, "u0": 1, "u1": 0, "b": -1, "eta": 0.25, "steps": 1}


@guarded
def derive_iv18(state):
    """Mean position BCE; gather forward, scatter-ADD backward, update all at once."""
    bounds = {key: (-4, 4) for key in (*EMBEDDING_DEFAULTS, "u0", "u1", "b")}
    for t in range(3):
        bounds[f"i{t}"], bounds[f"y{t}"] = (0, 2), (0, 1)
    bounds.update(T=(1, 3), eta=(0, 1), steps=(1, 3))
    s = fixed_state(state, DEFAULT_IV18, bounds, ("T", "steps", "i0", "i1", "i2", "y0", "y1", "y2"))
    ids, targets = [s[f"i{t}"] for t in range(s["T"])], [s[f"y{t}"] for t in range(s["T"])]
    E, U, bias = embedding_rows(s), np.array([s["u0"], s["u1"]], dtype=np.float64), s["b"]
    initialE, trace = E.copy(), Trace()
    tensors = [tensor("initialE", [3, 2], ["Vocab", "D"], E, "Starting embedding parameters."),
               tensor("initialU", [1, 2], ["Output", "D"], U, "Starting output row u; z=h*u^T+b."),
               tensor("ids", [1, s["T"]], ["B", "T"], ids, "Discrete routing choices.", "int32"),
               tensor("targets", [1, s["T"]], ["B", "T"], targets, "Active binary targets.")]

    def forward(e, u, b, prefix):
        X, z, p, losses, total = [], [], [], [], 0.0
        for t, identifier in enumerate(ids):
            h0, h1 = float(e[2 * identifier]), float(e[2 * identifier + 1])
            X.extend([h0, h1])
            term0, term1 = finite(u[0] * h0, "u0*h0"), finite(u[1] * h1, "u1*h1")
            logit = finite(finite(term0 + term1, "readout sum") + b, "logit")
            probability = finite(sigmoid(logit), "probability")
            # This remains a logit loss even when probability rounds to 0 or 1.
            positive, target_term = max(logit, 0), finite(logit * targets[t], "z*y")
            tail = finite(math.exp(-abs(logit)), "exp tail")
            log_tail = finite(math.log1p(tail), "log1p tail")
            loss = finite(finite(positive - target_term, "BCE linear term") + log_tail, "BCE from logit")
            total = finite(total + loss, "loss sum")
            z.append(logit); p.append(probability); losses.append(loss)
            trace.add(f"{prefix}_position_{t}", f"{prefix}: forward position {t}",
                      "h=E[id]; z=u0*h0+u1*h1+b; p=sigmoid(z); BCE=max(z,0)-z*y+log1p(exp(-abs(z)))",
                      "Use one full current parameter snapshot; evaluate loss from logits.",
                      dict(t=t, ID=identifier, h0=h0, h1=h1, u0=u[0], u1=u[1], b=b, y=targets[t]),
                      {f"{prefix}_z{t}": logit, f"{prefix}_p{t}": probability, f"{prefix}_BCE{t}": loss})
        loss = finite(total / s["T"], "mean loss")
        trace.add(f"{prefix}_loss", f"{prefix}: mean position loss", "loss=sum(BCE_t)/T",
                  "Average over positions exactly once, not features or occurrences.", dict(sum=total, T=s["T"]), {f"{prefix}_loss": loss})
        tensors.extend([tensor(f"{prefix}_X", [1, s["T"], 2], ["B", "T", "D"], X, f"{prefix}: freshly gathered features."),
                        tensor(f"{prefix}_logits", [1, s["T"]], ["B", "T"], z, f"{prefix}: actual logits."),
                        tensor(f"{prefix}_probabilities", [1, s["T"]], ["B", "T"], p, f"{prefix}: stable sigmoid outputs.")])
        return dict(X=X, z=z, p=p, loss=loss)

    current = forward(E, U, bias, "initial")
    initial_loss = current["loss"]
    loss_history, E_history, U_history, b_history = [initial_loss], E.tolist(), U.tolist(), [bias]
    initial_gradients = {}
    for k in range(1, s["steps"] + 1):
        dE, dU, dZ, dB = np.zeros(6, dtype=np.float64), np.zeros(2, dtype=np.float64), [], 0.0
        for t, identifier in enumerate(ids):
            # Operation contract is stored (p-y)/T, not exact real tail arithmetic.
            dz = finite(finite(current["p"][t] - targets[t], "p-y") / s["T"], "dZ")
            dZ.append(dz)
            contribution = {}
            for d in range(2):
                c = finite(dz * U[d], "embedding contribution")
                index = 2 * identifier + d
                dE[index] = finite(dE[index] + c, "scatter-add row sum")
                readout_c = finite(dz * current["X"][2 * t + d], "readout contribution")
                dU[d] = finite(dU[d] + readout_c, "readout sum")
                contribution.update({f"contribution{d}": c, f"runningE{identifier}{d}": dE[index], f"readoutContribution{d}": readout_c, f"runningU{d}": dU[d]})
            dB = finite(dB + dz, "bias gradient")
            trace.add(f"step{k}_scatter_{t}", f"Update {k}: scatter-ADD position {t}",
                      "dZ=(p-y)/T; dE[id,d]+=dZ*u_d; dU_d+=dZ*h_d; dB+=dZ",
                      "Use the same old snapshot for every contribution, adding all repeated uses before updating.",
                      dict(t=t, ID=identifier, p=current["p"][t], y=targets[t], T=s["T"], oldU0=U[0], oldU1=U[1], h0=current["X"][2*t], h1=current["X"][2*t+1]),
                      {f"step{k}_dZ{t}": dz, **contribution, "runningB": dB})
        gradient = dict(dU0=dU[0], dU1=dU[1], dB=dB)
        gradient.update({f"dE{j//2}{j%2}": v for j, v in enumerate(dE)})
        gradient.update({f"dZ{t}": v for t, v in enumerate(dZ)})
        if k == 1:
            initial_gradients = dict(gradient)
        trace.add(f"step{k}_gradients", f"Update {k}: complete OLD-parameter gradients", "dE[r,d]=sum_{t:id_t=r}(dZ_t*u_d)",
                  "Unseen rows have zero data gradient; no occurrence-count divisor.", dict(eta=s["eta"]), {f"step{k}_{key}": v for key, v in gradient.items()})
        tensors.extend([tensor(f"step{k}_dE", [3, 2], ["Vocab", "D"], dE, f"Update {k}: old-snapshot scatter sums."),
                        tensor(f"step{k}_dU", [1, 2], ["Output", "D"], dU, f"Update {k}: old-snapshot classifier gradient."),
                        tensor(f"step{k}_dZ", [1, s["T"]], ["B", "T"], dZ, f"Update {k}: mean-loss logit derivatives.")])
        old = {"eta": s["eta"], "oldU0": U[0], "oldU1": U[1], "oldB": bias, **gradient}
        old.update({f"oldE{j//2}{j%2}": v for j, v in enumerate(E)})
        # Build new arrays only after completing ALL old-snapshot derivatives.
        E = np.array([finite(v - finite(s["eta"] * dE[j], "eta*dE"), "updated E") for j, v in enumerate(E)], dtype=np.float64)
        U = np.array([finite(v - finite(s["eta"] * dU[d], "eta*dU"), "updated U") for d, v in enumerate(U)], dtype=np.float64)
        bias = finite(bias - finite(s["eta"] * dB, "eta*dB"), "updated bias")
        updated = {f"step{k}_b": bias, f"step{k}_u0": U[0], f"step{k}_u1": U[1]}
        updated.update({f"step{k}_e{j//2}{j%2}": v for j, v in enumerate(E)})
        trace.add(f"step{k}_update", f"Update {k}: simultaneous SGD", "Enew=Eold-eta*dE; unew=uold-eta*dU; bnew=bold-eta*dB",
                  "Actual unclamped history from the controls, not a resumable intermediate state.", old, updated)
        current = forward(E, U, bias, f"step{k}")
        loss_history.append(current["loss"]); E_history.extend(E.tolist()); U_history.extend(U.tolist()); b_history.append(bias)
    final = dict(finalU0=U[0], finalU1=U[1], finalB=bias)
    final.update({f"finalE{j//2}{j%2}": v for j, v in enumerate(E)})
    tensors.extend([tensor("finalE", [3, 2], ["Vocab", "D"], E, "Actual final embedding parameters."),
                    tensor("finalU", [1, 2], ["Output", "D"], U, "Actual final classifier row."),
                    tensor("lossHistory", [s["steps"]+1], ["Snapshot"], loss_history, "Initial then fresh loss after each full update."),
                    tensor("EHistory", [s["steps"]+1, 3, 2], ["Snapshot", "Vocab", "D"], E_history, "Detached full embedding snapshots, initial first."),
                    tensor("UHistory", [s["steps"]+1, 1, 2], ["Snapshot", "Output", "D"], U_history, "Detached classifier rows, initial first."),
                    tensor("bHistory", [s["steps"]+1], ["Snapshot"], b_history, "Initial and actual updated biases.")])
    changed = sum(E[2*r] != initialE[2*r] or E[2*r+1] != initialE[2*r+1] for r in range(3))
    return trace.result(dict(initialLoss=initial_loss, finalLoss=current["loss"], steps=s["steps"], updatedRows=changed, **trace.outputs, **initial_gradients, **final), tensors)


if __name__ == "__main__":
    run(derive_iv18, DEFAULT_IV18)
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.

"""Shared source for IV16–18: strict scalar state, detached records and JSON CLI.

Keep this file beside the three lesson programs. NumPy holds real float64 tensor
storage; explicit scalar operations keep the lesson's order of arithmetic visible.
Authored during the runtime hold; no execution or validation is claimed.
"""
import argparse
from functools import wraps
import json
import math
import sys
import numpy as np


class ParseFault(ValueError):
    """Owned JSON syntax/profile failure, separate from numerical validation."""


_JSON_INT = int


def _members(pairs):
    value = {}
    for key, member in pairs:
        if key in value:
            raise ParseFault("Duplicate JSON object members are not allowed.")
        value[key] = member
    return value


def _constant(token):
    raise ParseFault(f"Nonstandard JSON constant {token} is not allowed.")


def _integer(token):
    if token == "-0":
        return -0.0
    try:
        return _JSON_INT(token)
    except ValueError as error:
        if type(error) is not ValueError:
            raise
        raise ParseFault("JSON integer exceeds the interpreter's conversion capacity.") from error


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


def finite(value, label):
    if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    try:
        value = float(value)
    except (ValueError, OverflowError) as error:
        raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
    if not math.isfinite(value):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    return value


def fixed_state(state, defaults, bounds, integers=()):
    # Full replacement, including inactive slots: no coercion, defaults or clipping.
    if type(state) is not dict or set(state) != set(defaults):
        raise NumericalFault("INVALID_INPUT", "Provide exactly every named scalar field, including inactive slots.")
    result = {}
    for key in defaults:
        value = finite(state[key], key)
        low, high = bounds[key]
        if value < low or value > high:
            raise NumericalFault("INVALID_INPUT", f"{key} must be between {low} and {high}.")
        if key in integers and not value.is_integer():
            raise NumericalFault("INVALID_INPUT", f"{key} must be an integer choice.")
        result[key] = int(value) if key in integers else value
    return result


def guarded(derive):
    @wraps(derive)
    def call(state):
        try:
            return derive(state)
        except NumericalFault as error:
            return {"status": "unavailable", "code": error.code, "reason": str(error)}
        except (OverflowError, FloatingPointError) as error:
            return {"status": "unavailable", "code": "NONFINITE", "reason": str(error)}
    return call


def numbers(values):
    return {key: finite(value, key) for key, value in values.items()}


class Trace:
    def __init__(self):
        self.outputs = {}
        self.steps = []

    def add(self, identifier, label, equation, explanation, inputs, values):
        inputs, values = numbers(inputs), numbers(values)
        self.outputs.update(values)
        self.steps.append({"id": identifier, "label": label, "equation": equation,
                           "explanation": explanation, "inputs": inputs, "outputs": values})

    def result(self, summary, tensors):
        return {"status": "defined", "outputs": numbers({**summary, **self.outputs}),
                "steps": self.steps, "tensors": tensors}


def tensor(identifier, shape, axes, values, provenance, dtype="float64"):
    array = np.asarray(values, dtype=np.float64)
    if array.size != math.prod(shape) or len(shape) != len(axes) or len(set(axes)) != len(axes):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: storage must match the named dimensions.")
    flat = [finite(v, identifier) for v in array.reshape(-1)]
    if dtype == "int32":
        if any(not v.is_integer() for v in flat):
            raise NumericalFault("INVALID_INPUT", "IDs must be integers.")
        flat = [int(v) for v in flat]
    return {"id": identifier, "shape": list(shape), "axes": list(axes), "dtype": dtype,
            "values": flat, "provenance": provenance, "precision": 8}


EMBEDDING_DEFAULTS = dict(e00=1, e01=0, e10=0, e11=1, e20=1, e21=1)
VOCABULARY = ("oak", "river", "sun")


def embedding_rows(s):
    return np.array([s["e00"], s["e01"], s["e10"], s["e11"], s["e20"], s["e21"]], dtype=np.float64)


def sigmoid(z):
    # Stable sign branch, evaluated in stored binary64; positive tails may round to 1.
    z = finite(z, "sigmoid input")
    if z >= 0:
        return 1 / (1 + math.exp(-z))
    exponential = math.exp(z)
    return exponential / (1 + exponential)


def run(derive, defaults):
    """No state argument: defaults. Full JSON object: replacement. '-': stdin."""
    parser = argparse.ArgumentParser(description=derive.__doc__)
    parser.add_argument("state", nargs="?")
    args = parser.parse_args()
    if args.state is not None:
        source = sys.stdin.read() if args.state == "-" else args.state
        try:
            state = json.loads(source, object_pairs_hook=_members, parse_constant=_constant, parse_int=_integer)
        except (json.JSONDecodeError, ParseFault) as error:
            result = {"status": "unavailable", "code": "INVALID_INPUT", "reason": str(error)}
        else:
            result = derive(state)
    else:
        state = dict(defaults)
        result = derive(state)
    print(json.dumps(result, allow_nan=False, separators=(",", ":")))

Keep the files together. The CLI accepts no argument for defaults, a complete JSON replacement, or - for stdin.

Use the five graded exercises to connect routing, a current gradient, the exact sun update, unseen rows and cancellation. The essential chain is gather, predict, evaluate mean loss, add every shared-row contribution, update simultaneously and recompute. Embeddings learn here because their real parameter rows change under a stated loss. The next Part adds ordered state so a representation can depend on more than the current ID alone.