Trace the arithmetic, change the record, and test the result. This original laboratory supplies complete synthetic examples and pure-Python implementations of a ReLU layer, stable softmax, single-head attention and output-logit cross-entropy. It computes model components; it does not claim to be a trained language model or an authorization service.
Backpropagation is a calculation over paths
A gradient describes how a specified numerical objective changes under a local change in a parameter. It is not an instruction that a parameter must be causal in the real world, and it is not a guarantee that reducing the objective improves the intended task. Before differentiating, state the input, computation, target and loss. Otherwise two people can calculate different gradients while correctly differentiating different objectives.
Consider a scalar input x and hidden units zi=wix+bi, hi=max(0,zi). Their scalar output is o=Σvihi, and squared-error loss is L=(o−y)²/2. The output residual e=o−y supplies dL/do=e. The derivative with respect to output weight vi is ehi. For a hidden preactivation strictly above zero, dhi/dzi=1; below zero it is zero. Consequently dL/dwi=evi1[zi>0]x and dL/dbi=evi1[zi>0]. The indicator records which side of the activation boundary the computation occupies.
The factors have distinct roles. The residual measures the loss sensitivity to output, vi transmits it back along one branch, the activation derivative gates the branch, and x connects the preactivation to its weight. Omitting a factor can produce a plausible-looking number with the wrong meaning. The derivative do/dw is not the same quantity as dL/dw because the latter also includes the loss derivative. When a parameter feeds several branches, add its path contributions; do not keep only the last branch visited by an implementation.
At z=0 the ordinary ReLU derivative is not uniquely defined. An implementation must choose a convention for optimization. The supplied laboratory uses zero at this point and avoids treating a central finite-difference comparison at the kink as proof that the chosen convention is wrong. Away from a kink, a central difference [L(w+ε)−L(w−ε)]/(2ε) provides an independent numerical check. Choose ε small enough to approximate a local change, but not so small that subtraction and floating-point error dominate. Check more than one parameter and more than one example.
Worked record: an inactive branch does not freeze the whole network
Use x=2 and target y=0. Unit 1 has w1=1,b1=−1,v1=3. Unit 2 has w2=−1,b2=0,v2=5. Preactivations are 1 and −2; hidden outputs are 1 and 0. Output is 3×1+5×0=3 and loss is 4.5. The residual is 3.
For unit 1, dL/dv1=3, dL/dw1=3×3×1×2=18 and dL/db1=9. For unit 2, its hidden output and activation derivative are both zero, so these three parameter gradients are zero on this example. The active branch can nevertheless change. Updating only v1 by learning rate 0.01 gives v1=2.97 and lowers this example’s loss to 2.97²/2=4.41045. This is a local improvement in the stated objective, not held-out evidence that the model became more useful.
A parameter update is itself a choice. Updating all parameters simultaneously means using gradients computed at the same old parameter values. Updating one parameter and then accidentally using its new value to compute another gradient implements a different procedure. Larger steps can cross activation boundaries or increase loss; a successful tiny step is not evidence that every learning rate works. Record the objective, reduction convention, input scaling and update rule before debugging a disagreement.
Independent transfer
Use the same two-unit record, but replace squared-error loss with (o−y)², without the factor one half. Predict every gradient and an output-weight-only update at learning rate 0.01. Then change x to −2 while restoring the original parameters and half-squared loss. Identify the active unit and calculate output, loss and all six parameter gradients. Finally describe a finite-difference test that avoids crossing a ReLU kink.
Compare the reasoning after your attempt
Removing the factor one half doubles the gradients at the same forward state. They become 6,36,18 for v1,w1,b1, with zeros for unit 2. Updating only v1 gives 2.94; the changed loss is 2.94²=8.6436, down from 9. With x=−2 and restored parameters, z1=−3 and z2=2, so h1=0,h2=2, output=10 and half-squared loss=50. Unit 1 gradients are zero. Unit 2 has dL/dv2=20, dL/dw2=10×5×1×(−2)=−100 and dL/db2=50. The negative input gives a negative weight gradient even though the residual is positive. For numerical verification, perturb one parameter at a time with an ε that leaves its preactivation on the same nonzero side, compare against the analytic derivative, and report the loss definition used.
Attention needs shapes, eligible context and a stable normalization
An attention calculation mixes supplied representations. A query asks for a combination; keys are compared with the query; values are combined using the resulting weights. Keep these roles separate even when all originate from the same sequence. A numerical weight does not label a sentence as true, authorized, endorsed or relevant to every question. Those are evidence and system-boundary questions outside the normalization itself.
For n queries with d features, Q has shape n×d. With m keys, K has shape m×d, so QKᵀ has shape n×m. Each query therefore receives m compatibility scores. Dividing by √d rescales those dot products before normalization. If V has shape m×p, multiplying the n×m weight matrix by V yields n×p outputs. A transposed array can contain all the expected numbers and still represent the wrong operation, so write the intended dimensions before implementing the loops.
For one query’s eligible scores si, softmax gives pi=exp(si)/Σexp(sj). The weights are nonnegative and sum to one. Subtracting the same finite constant M preserves the ratios because exp(si−M)=exp(si)exp(−M), and the shared factor cancels. Choosing the largest eligible score makes every exponent nonpositive and avoids overflow from directly exponentiating a large positive logit. This transformation cannot make invalid input, an overflowing dot product or every conceivable finite-precision operation safe; validate the numerical contract explicitly.
A mask excludes a key from this particular combination. Compute the maximum and denominator over eligible keys only. If a masked score of 10000 participates in the maximum while the only allowed score is 2, the allowed exponential can underflow and leave a zero denominator. Removing the masked key after normalization is also wrong: the remaining weights no longer sum to one unless they are normalized again. When no keys are eligible, the laboratory returns None as an explicit empty-result state. Returning a uniform average would invent a result from excluded items.
A causal mask is a model information-flow rule: a representation at one sequence position must not use future positions under the specified prediction setup. It differs from authorization. A permission boundary must exclude restricted material before it reaches model context; multiplying an already exposed representation by zero is not a complete access-control design. Keep a causal arithmetic mask and a document-authorization decision as separately testable properties.
Worked record: the same scores under different masks
Two queries each have pre-mask scores [0,ln(3)] over scalar values [10,30]. For query 1 allow only the first key; for query 2 allow both. The first query gives weight [1,0] and output 10. The second gives [1/4,3/4] and output 25. Replacing the second value with 100000 must leave query 1 unchanged under the mask, while query 2 changes. If no key is eligible, the output is None rather than 20 or zero. Zero is a valid numerical output in other records and should not silently mean that no information was available.
The laboratory also constructs scores from two-feature vectors: query [1,0], keys [0,0] and [√2 ln(3),0]. Dividing the dot products by √2 produces exactly the specified score pair. This makes the relation between the scalar worked calculation and the matrix-shaped implementation inspectable. It is a single attention head over synthetic values; it does not instantiate a complete trained language model.
From logits to a loss gradient
A vocabulary prediction can use a separate softmax over output logits z. For target class y, cross-entropy is L=−ln(py). A stable equivalent is logΣexp(zj−M)−(zy−M). Differentiating gives dL/dzi=pi−1[i=y]. This gradient refers to output logits and a chosen training target. It must not be confused with attention weights over input keys, even though both calculations use softmax.
With logits [0,ln(3)] and target class 0, probabilities are [0.25,0.75], loss is ln4≈1.38629, and the logit gradient is [−0.75,+0.75]. A learning-rate-0.1 descent step gives logits [0.075,ln(3)−0.075], increasing the target probability and reducing this loss. Changing the target to class 1 changes the gradient even though the original probabilities are unchanged. A coherent probability distribution can still be poorly calibrated or factually wrong in a real task; arithmetic consistency is necessary for the computation, not sufficient evidence for the application.
Independent transfer
Repeat the masked calculation with scalar values [−10,50], leaving scores and masks fixed. Then add 1000 to both eligible scores and explain which outputs should change. Finally change the cross-entropy target to class 1 and calculate its loss and logit gradient. Write tests for an entirely masked query, incompatible Q/K dimensions, a mismatched key/value count and a nonfinite score. Explain why a successful causal-mask test does not certify document authorization.
Compare the reasoning after your attempt
The first masked output is −10 and the second is (−10)/4+3×50/4=35. Adding the same score shift leaves their normalized weights and outputs unchanged within numerical tolerance. For target class 1 the loss is −ln(0.75)=ln(4/3)≈0.287682 and the gradient is [+0.25,−0.25]. The all-masked branch should return an explicit empty state; invalid dimensions and nonfinite numerical inputs should fail rather than silently truncate a zip operation or produce a plausible average. Authorization additionally needs tests of what material entered the model boundary and which identity and current permission justified it. These arithmetic tests deliberately do not claim to perform that larger system review.
Run the laboratory
Copy the complete source into attention_lab.py and run python attention_lab.py with Python 3. Only the standard library is used. Ten test groups exercise finite-difference gradients, active/inactive paths, target changes, shifted large logits, causal and empty masks, shape and numerical boundaries, joint key/value permutations and numerical weighting.
Read the original architecture alongside this component laboratory: learned projections, multiple heads, position representations, residual connections, normalization and feed-forward blocks connect these mechanisms into a larger model. The numerical records, prose and implementation above are original Academy teaching. Complete assigned course texts remain part of the study sequence; this expansion is not a full-catalog academic acceptance certificate.