Mixed precision with loss scaling#
Numerical bugs#
| Symptom | Cause | Fix |
|---|
| Loss is NaN after a few epochs | Logits too large, softmax overflowed | Stable softmax, lower LR, clip gradients |
|---|
| Loss stuck at log(num_classes) | Near-uniform outputs, no learning | Check labels, loss and dead ReLUs |
|---|
| Val accuracy 1-3% low | Mixed precision without loss scaling | Dynamic loss scaling or bfloat16 |
|---|
| Gradient norm 0.0 in some layers | Dead ReLUs or float16 underflow | LeakyReLU or GELU, gradient scaling |
|---|
| Results differ between GPUs | Float addition is not associative | torch.use_deterministic_algorithms(True) |
|---|
exp() returns inf in the loss | Raw logits without max subtraction | torch.nn.functional.log_softmax() |
|---|
| Diverges after float16 switch | Grads below 6e-8, values above 65,504 | AMP with loss scaling, or bfloat16 |
|---|
| Wrong variance for large values | Catastrophic cancellation | welford_variance or center the data |
|---|
Pick a distance#
| Command | What it does |
|---|
cosine_similarity(a, b) | Text and embeddings. Ignores magnitude |
|---|
dot_product(a, b) | Recommendation. Magnitude encodes popularity |
|---|
l2_distance(a, b) | Pixels and spatial data at comparable scale |
|---|
l1_distance(a, b) | Sparse high-dim features. Robust to outliers |
|---|
linf_distance(a, b) | Worst-case deviation in one dimension |
|---|
mahalanobis_distance(x, y, cov_matrix) | Outliers with correlated features |
|---|
jaccard_similarity(set_a, set_b) | Sets and tags. IoU for segmentation |
|---|
edit_distance(s1, s2) | Strings. Insert, delete or substitute |
|---|
Reduce dimensions#
- Curse of dimensionality
- at 1000 dimensions the max/min distance ratio is ~1.02.
- PCA
- center, covariance,
np.linalg.eigh, sort by eigenvalue, keep the top k. - Explained ratio
- one eigenvalue divided by the sum of all eigenvalues.
- Pick k
- keep 90-95% of variance, find the elbow, or sweep k on the task.
- Reconstruction error
- the sum of the dropped eigenvalues. High error marks an outlier.
- t-SNE
- keeps local neighbors. Stochastic and O(n^2). Cluster gaps mean nothing.
- UMAP
- faster than t-SNE. It keeps more global structure.
- Kernel PCA
- PCA in a kernel feature space. RBF separates concentric circles.
Questions#
- Why subtract the max?
- The largest term becomes exp(0) = 1. The sum is at least 1.
- Why bfloat16 for training?
- It has the float32 range. Loss scaling is usually unnecessary.
- Why minimize cross-entropy?
- It equals negative log-likelihood. H(P) is constant.
- Why is KL not a distance?
- It is not symmetric and fails the triangle inequality.
- Why Wasserstein for GANs?
- It gives gradients when distributions do not overlap.
- Why does L1 give sparse weights?
- Loss contours touch the L1 diamond at a corner.
- Why centered differences?
- The error is O(h^2). Forward differences give O(h).
Tips#
- Do not compare floats with
==. Use math.isclose(). - Check for nan and inf after each forward pass while you debug:
math.isfinite(x). - Clamp inputs to exp:
exp(clamp(x, -80, 80)). - Clip by norm with
torch.nn.utils.clip_grad_norm_(). It keeps the gradient direction. - Check each new layer or loss with
torch.autograd.gradcheck(). - With L2-normalized embeddings, cosine and dot product give the same result.