AI from scratch · Reference

When You're Stuck

A diagnostic triage guide for common mistakes in linear algebra, PyTorch training, tabular pipelines, and cloud runners. For each failure, look up the symptom, run the check, apply the fix, and review the concept.

1. Shapes That Don't Match

Dimension Mismatch
RuntimeError: mat1 and mat2 shapes cannot be multiplied (32x10 and 64x10)
# or in NumPy:
ValueError: operands could not be broadcast together with shapes (32, 10) (64, 10)

Print the shape of every tensor before the multiplying line. In matrix multiplication $A \times B$, the inner dimensions must match: $(N, K) \times (K, M) \to (N, M)$.

print(f"X: {X.shape}, W: {W.shape}")
# If X is (32, 10) and W is (64, 10), inner dimensions are 10 and 64 — they do not match!

Transpose the weight matrix with .T or .t(), or check your nn.Linear(in_features, out_features) definition. In PyTorch, nn.Linear(10, 64) stores weight with shape (64, 10) and performs $x W^T$.

# NumPy fix: transpose W
out = X @ W.T  # (32, 10) @ (10, 64) -> (32, 64)

# PyTorch Flatten fix after Conv2d:
x = torch.flatten(x, start_dim=1)  # preserve batch dimension (N, -1)

2. NaNs in Loss or Weights

Numerical Instability

The loss prints nan after a few training steps, or weights turn into nan / inf.

Check if raw probabilities hit $0$ or $1$, or if activations produce huge numbers before an exponential.

assert not torch.isnan(loss), "Loss is NaN!"
print("max logit:", logits.max().item(), "min prob:", probs.min().item())

Never take the raw torch.log(torch.softmax(logits)) or torch.log(torch.sigmoid(logits)). Use numerically stable fused loss functions that work in logit space: nn.CrossEntropyLoss() or nn.BCEWithLogitsLoss(). In custom code, clamp probabilities with an epsilon $\varepsilon = 10^{-12}$.

# Bad: prone to log(0) -> -inf -> NaN
loss = -torch.log(torch.sigmoid(logits))

# Good: numerically stable log-sum-exp
loss_fn = nn.BCEWithLogitsLoss()
loss = loss_fn(logits, targets)

3. Loss Not Falling (Flatlining)

Vanishing Gradients / Zero Updates

The loss sits exactly at the baseline value (e.g., $-\ln(1/C) \approx 2.30$ for 10 classes) and refuses to budge after dozens of epochs.

Confirm gradients exist, are non-zero, and that the optimizer step actually updates the model parameters:

# Check gradient magnitudes:
for name, p in model.named_parameters():
    print(name, p.grad.abs().mean().item() if p.grad is not None else "NO GRAD")
  1. Verify the loop order: optimizer.zero_grad() → loss.backward() → optimizer.step(). Omitting optimizer.step() is the most common typo.
  2. Check the learning rate: if it's too small (e.g., $10^{-7}$), increase it to $10^{-3}$ or $3 \times 10^{-4}$.
  3. Check input scaling: if inputs have huge values ($> 1000$), standard scale them to mean 0, variance 1 with StandardScaler().
  4. If using ReLUs with high learning rates, check for dead neurons (zero gradients everywhere). Switch to nn.GELU() or nn.LeakyReLU().

4. Exploding Loss / Gradients

Divergence

Loss starts normally (e.g., 2.5), then jumps to 40, then 10,000, then inf within a handful of batches.

Check parameter gradient norms:

total_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), float('inf'))
print("gradient norm:", total_norm.item())
  1. Lower the learning rate by a factor of 10 or 100.
  2. Clip gradients before the step: torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0).
  3. Check unnormalized inputs or uninitialized weights. Use He / Kaiming initialization for ReLU layers: nn.init.kaiming_normal_(layer.weight).

5. Suspiciously Perfect Score (Data Leakage)

Feature Leakage

Validation accuracy is 99.8% or $R^2 = 1.00$ on the very first attempt on dirty tabular data, but drops to chance when evaluated in production.

Inspect feature importances or correlations with the target. If one feature has feature importance $> 0.85$ or correlation $> 0.95$, suspect leakage.

# Check feature correlation with target:
corrs = df.corr()['target'].abs().sort_values(ascending=False)
print(corrs.head())
  1. Proxy / Consequent variables: Drop columns recorded after the outcome happened (e.g., outage_end_time when predicting outage duration, or resolution_code).
  2. Split before preprocessing: Never fit a StandardScaler, SimpleImputer, or CountVectorizer on the entire dataset. Always use a Pipeline fit strictly on X_train:
    from sklearn.pipeline import make_pipeline
    pipe = make_pipeline(StandardScaler(), LogisticRegression())
    pipe.fit(X_train, y_train)  # Scaler never sees X_test!
  3. Time structure: When rows represent time series or events, use TimeSeriesSplit or date cutoffs rather than random train_test_split.

6. Overfitting (Train Loss Falls, Val Loss Rises)

High Variance

Training loss approaches 0, but validation loss reaches a minimum and climbs steadily higher.

Plot both curves on the same axes. The minimum of the validation loss curve marks the point of optimal generalization.

7. Kaggle Notebook Without Internet

Kaggle Environment
urllib.error.URLError: <urlopen error [Errno -3] Temporary failure in name resolution>
# or pip install hangs indefinitely

Check the right-hand Settings drawer in your Kaggle Notebook under Notebook options.

  1. Verify your Kaggle account is phone-verified (unverified accounts cannot toggle internet).
  2. In the right sidebar, expand Settings → find Internet → toggle it to Internet on. The notebook kernel will restart with external networking enabled.
  3. For competition kernels where Internet must be disabled at submission time, upload your package wheels or pretrained weights as a private Kaggle Dataset, then install locally:
    !pip install --no-index --find-links=/kaggle/input/my-wheels-dataset/ package_name

8. Google Colab Out of Memory (CUDA OOM)

Resource Exhaustion
torch.cuda.OutOfMemoryError: CUDA out of memory. Tried to allocate 512.00 MiB
# or "Your session crashed after using all available RAM"
import torch
print("Allocated:", torch.cuda.memory_allocated() / 1e9, "GB")
print("Reserved: ", torch.cuda.memory_reserved() / 1e9, "GB")
  1. Halve the batch size: If using batch_size=64, reduce it to 32 or 16.
  2. Use gradient accumulation: Simulate larger batch sizes without the VRAM footprint:
    accum_steps = 4
    for i, (x, y) in enumerate(loader):
        loss = loss_fn(model(x), y) / accum_steps
        loss.backward()
        if (i + 1) % accum_steps == 0:
            optimizer.step()
            optimizer.zero_grad()
  3. Disable gradients during evaluation: Wrap validation in with torch.no_grad():.
  4. Release unused memory: del outputs, loss; torch.cuda.empty_cache().
  5. Mixed precision: Use torch.cuda.amp.autocast() to compute in 16-bit floats.

9. Browser Code Box Won't Run

In-Browser Pyodide

Clicking "Run" on an interactive code box in a lesson keeps spinning, produces no output, or shows an error in the developer console.

Open Developer Tools (F12 or Cmd+Option+I) and select the Console tab. Look for failed requests to cdn.jsdelivr.net/pyodide/ or Content Security Policy warnings.

  1. Initial download: Pyodide compiles Python to WebAssembly in your browser (~10 MB one-time cache). On slower connections, the first run can take 5–10 seconds to load the runtime.
  2. Supported packages: In-browser code boxes support Python standard library, NumPy, pandas, scikit-learn, and sqlite3. They do not run full PyTorch or CUDA code (PyTorch code runs in Colab or Kaggle).
  3. Content blockers: If an aggressive privacy extension or ad blocker blocks scripts from jsdelivr.net, allow the domain or disable extensions for the page.
  4. State reset: If variable definitions get tangled across cells, refresh the page to restart a clean WebAssembly session.

Last updated