# Exact LM-head masked-row compaction
Given final hidden states H [N,D], vocabulary head W [V,D] and bias b [V],
selected set S = {i: y_i != -100}, the unweighted CE sum is
Σ_{i∈S}[logsumexp(W h_i + b) - (W h_i + b)_{y_i}]. Its mean divides
by |S|, not N. Thus projecting only H[S] gives the same real-arithmetic
loss. If E = softmax(H[S] Wᵀ + b) - onehot(y[S]), scale E by 1/|S| for
mean. Then dW = Eᵀ H[S], db = Σ E, dH[S] = E W, and all other *final*
hidden rows receive zero head-direct gradient by index-select backward.
Earlier states at ignored positions can still receive contextual gradient
through causal attention. This does not remove prompt rows from transformer
blocks or the vocabulary dimension from softmax.

Raw PyTorch gives sum=0, mean=NaN and zero gradients for all ignored (also
empty rows). We explicitly choose zero plus connected zero gradients for
both reductions for the empty-selected case; this is an intentional
change from raw mean semantics, shared by both benchmark methods. For
multi-microbatch or distributed training, accumulate selected **sums** and
counts and divide globally, rather than average each local guarded mean.
An all-skipped optimizer step can still move parameters via momentum or
weight decay; this snippet does not decide optimizer-step semantics.

Approximate three GEMM costs for forward, input-gradient and
weight-gradient, counting a multiply-add as two FLOPs: 6NDV vs 6KDV,
K=|S|, excluding gather/scatter, bias/CE, and model blocks. Full head
logit materialization changes from NV to KV entries (not whole step
peak memory). Real floating-point GEMM reduction order can differ;
22 FP64 loss and full-gradient parity cases passed at 1e-12 tolerance.
Assume finite defined logits, integer labels and no auxiliary logits
consumers, class reweighting or other loss changes. Doesn't measure
GPU and doesn't imply a whole-transformer step speedup.

## Reproduce
Use Python with PyTorch 2.9.1+cpu. Example:
```sh
OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 CUDA_VISIBLE_DEVICES='' \
  python compact_head.py --out result.json
```

Fixed seeds, N=256 D=256 V=4096 float32 timing, same inputs/labels, 4 warmup
pairs followed by 17 recorded pairs per mask fraction in pseudorandom
within-pair order. The JSON includes raw paired measurements, model,
CPU, torch build and two speed-ratio summaries. The cited headlines
use the ratio of the two median totals. Full retention's fast path keeps
the real selection-check overhead; both all-ignored paths avoid projection.
Time is loss-forward and autograd.grad backward, not optimiser or block
computation.
