Calculus & Probability for AI Infrastructure
Softmax stability, cross-entropy, backpropagation, gradient problems, and numerical precision β the math behind training and serving.
If linear algebra is the language of the forward pass, then calculus and probability are the language of training. This chapter covers the math that directly impacts AI infrastructure: stable softmax computation, cross-entropy loss, backpropagation mechanics, gradient stability, and the numerical precision tradeoffs behind mixed-precision training.
1. Probability Essentials
Random Variables and Distributions
A language model outputs a probability distribution over the vocabulary at each step. The key concepts:
- Discrete distribution: where
- Expectation: β the probability-weighted average
- Variance: β spread around the mean
- Mini-batch estimates: sample mean approximates
Maximum Likelihood and Negative Log-Likelihood
Given training data, maximum likelihood estimation (MLE) finds parameters that maximize . Taking the log turns the product into a sum, and negating turns maximization into minimization:
This is negative log-likelihood (NLL) β the loss function used for language model training. Minimizing NLL = maximizing the probability of the training data.
2. Softmax: From Logits to Probabilities
Logits Are Not Probabilities
The modelβs final layer outputs arbitrary real numbers (logits):
Softmax converts them to a valid probability distribution:
Clearly and . Softmax is invariant to uniform shifts: . This property is the basis of the stable implementation.
Numerically Stable Softmax
Computing directly overflows. The fix: subtract the maximum first.
The largest exponent input becomes 0, so the largest exponential value is 1. All others are β€ 1.
def stable_softmax(x):
m = max(x)
exps = [exp(v - m) for v in x]
total = sum(exps)
return [v / total for v in exps]
If you need afterward, compute
log_softmaxdirectly β donβt softmax first then log, because softmax may underflow to 0, making .
LogSumExp
Then:
Why this matters for infrastructure: Cross-entropy implementations fuse log_softmax + NLLLoss into a single kernel. This reduces intermediate tensors (less memory), reduces HBM access (fewer kernel launches), and avoids the numerical instability of βsoftmax then log.β
Temperature
- : distribution becomes one-hot (greedy)
- : standard softmax
- : flatter distribution (more random)
Temperature is a serving parameter β the same model weights produce different behavior. Infrastructure must support per-request temperature.
3. Cross-Entropy and Related Concepts
Cross-Entropy Loss
Given true distribution (one-hot: for the correct class) and predicted :
For language models, this is computed per token and averaged over the sequence.
Perplexity
Perplexity = βhow many choices the model is confused between.β Lower is better. PPL of 10 means the model is, on average, choosing between 10 equally likely next tokens.
Perplexity is the standard evaluation metric reported for language models and is directly derived from cross-entropy loss.
KL Divergence
KL divergence measures how one distribution differs from another :
Properties: , equals 0 only when , and is not symmetric ().
Where it appears in AI infra:
- RLHF: KL penalty prevents the policy from diverging too far from the reference model:
- Knowledge distillation: student minimizes
- Evaluating distribution shift in production monitoring
Top-k and Top-p Sampling
Sampling strategies for generation β these are serving parameters, not training parameters:
Top-k: Keep only the highest-probability tokens, redistribute mass among them.
Top-p (nucleus): Keep the smallest set of tokens whose cumulative probability β₯ .
| Parameter | Effect | Typical value |
|---|---|---|
| Temperature | Controls sharpness | 0.0β2.0 |
| Top-k | Hard cutoff on candidates | 50 |
| Top-p | Adaptive cutoff | 0.9β0.95 |
Infrastructure must support per-request sampling parameters β the same model weights produce different behavior depending on these settings.
4. Backpropagation
Chain Rule
For composed functions :
A multi-layer network is just a deep composition:
Gradients flow backward:
In practice, automatic differentiation computes vector-Jacobian products β never materializing the full Jacobian matrix.
Linear Layer Backward Pass
For with incoming gradient :
Both backward operations are matrix multiplies β same GEMM kernels as the forward pass. Backward is approximately 2Γ the compute of forward (two GEMMs vs one), which is why the rule of thumb is: total training FLOPs β 3Γ forward FLOPs.
Softmax + Cross-Entropy: The Clean Gradient
The combined gradient of softmax cross-entropy has a remarkably simple form:
For the correct class: . For all others: . Just βprediction minus target.β
This is why fused softmax-cross-entropy kernels are both numerically stable AND computationally efficient β the gradient doesnβt require recomputing the full Jacobian.
5. Gradient Problems and Solutions
Gradient Vanishing and Exploding
In a deep network, backward gradients are products of many Jacobians:
If for most layers β gradients vanish (early layers stop learning). If for most layers β gradients explode (training diverges).
Residual Connections
The gradient becomes:
The identity matrix ensures gradients have a direct path through the network β even if is small, the gradient doesnβt vanish. This is why every Transformer block uses residual connections.
LayerNorm and RMSNorm
LayerNorm normalizes across the hidden dimension:
RMSNorm (used in LLaMA, Qwen) skips mean centering:
Both stabilize gradient magnitudes across layers. RMSNorm is ~10-15% faster (fewer operations) with comparable quality.
Gradient Clipping
If , scale it down:
A last-resort safety net. Modern LLM training typically clips at gradient norm 1.0.
Adam Optimizer
Adam is the optimizer used in virtually all LLM training. It maintains two running averages per parameter:
- First moment \ (momentum \ gradient direction)
- Second moment \ (adaptive learning rate per parameter)
With bias correction and update:
Why this matters for infrastructure: Adam stores and for every parameter \ both in FP32. For a model with parameters:
- Parameters: bytes (BF16)
- Gradients: bytes (FP32)
- Adam : bytes (FP32)
- Adam : bytes (FP32)
- FP32 master weights: bytes
- Total: 18 bytes per parameter
Typical values: , , , to .
AdamW (Adam with decoupled weight decay) is the standard variant for LLM training \ it separates weight decay from the gradient update.
6. Numerical Precision and Mixed-Precision Training
Floating-Point Is a Finite Set
Every floating-point format trades off dynamic range (exponent bits) vs precision (mantissa bits). See GPU Evolution & Tensor Cores for the full format comparison and bit layout diagram.
The key tradeoff for training: BF16 has the same dynamic range as FP32 (8 exponent bits) but less precision (7 mantissa bits). FP16 has more precision (10 mantissa bits) but much smaller range (max 65,504 β easily overflows).
The update is silently dropped. This is why optimizers keep FP32 master weights β low-precision weights would swallow small gradient updates.
Non-Associativity
Due to rounding at each step:
Parallel reductions using tree-structured addition may produce slightly different results with different thread counts or block sizes. This is not a bug β but results must be within acceptable error bounds.
Mixed-Precision Training Pattern
The standard recipe:
- Forward: compute in BF16 (fast, fits in memory)
- Backward: compute gradients in BF16
- Update: accumulate in FP32 master weights (preserves small updates)
FP32 master weights β cast to BF16 β forward β backward (BF16 gradients)
β β
βββββββββ FP32 optimizer update βββββ cast gradients to FP32
Why BF16 over FP16: BF16 has the same dynamic range as FP32, so it rarely overflows. FP16 maxes at 65,504 β a single large activation can overflow, requiring loss scaling (multiply loss by a large constant before backward, then divide gradients after). BF16 eliminates this complexity.
Loss Scaling (FP16 only)
When using FP16, small gradients underflow to zero. Loss scaling artificially inflates them:
- Multiply loss by scale factor (e.g., 1024)
- Backward pass computes scaled gradients:
- Divide gradients by before the optimizer step
- If overflow is detected, skip the update and halve
Dynamic loss scaling adjusts automatically. But this is extra infrastructure complexity β another reason BF16 is now preferred.
Self-Check
- Explain why raw logits need softmax before theyβre probabilities
- Implement numerically stable softmax (subtract max first)
- Explain why fused
log_softmax + cross_entropyis both faster and more stable - Write the backward pass for a linear layer
- Explain why training FLOPs β 3Γ forward FLOPs
- Explain gradient vanishing and how residual connections solve it
- Explain why BF16 is preferred over FP16 for training
- Explain why FP32 master weights are needed with BF16 training
- Explain non-associativity and why parallel reductions can produce different results