Skip to content
AI from Scratch
EN

When something goes wrong

The real failures you are going to hit, symptom first. Look it up by what you SEE, not by what you think is happening.


Training

The loss goes to NaN

Symptom: perdida: nan and it never comes back.

CauseHow to check itFix
Learning rate too highwas the gradient norm growing before it broke?drop it ×10
No warm-updid it break in the first 200 steps?larger --pasos, or more warmup
No gradient clippinglook at `grad` on the previous stepclip_grad_norm_(..., 1.0)
log(0) somewherelook for unprotected logarithmsadd 1e-9 inside the log
Division by zeroa denominator that can vanish+ eps

NaN spreads: the moment one appears, the whole model is contaminated. That is why you have to catch it on the step where it is born, not afterwards.

The loss will not go below log(V)

log(65) = 4.17 and there it sits.

  • Are you calling zero_grad()? If not, gradients accumulate between steps.
  • Are you calling opt.step()? Sounds silly, and it happens.
  • Is the learning rate absurdly low? Try ×100.
  • Is the data noise? Print a batch and look at it with your eyes.

The loss drops far too fast

Suspect data leakage immediately. The model is seeing the answer.

  • Is the shift between x and y exactly ONE position?
  • Is the causal mask in place? Without it the model looks at the future and trains beautifully, and then generates rubbish.
  • Do validation and training overlap?

Rule: if the validation loss is lower than the training loss, there is almost certainly a leak.

Validation rises while training falls

Overfitting, and it is normal. In order of effectiveness:

  1. More data. It beats everything else. You measure it in etapas/07_entrenamiento/03_sobreajuste.py.
  2. Early stopping at the validation minimum.
  3. Dropout, weight decay.
  4. A smaller model.

It is painfully slow

python comprobar_entorno.py     # tells you the real ms/step on your machine
  • mininn is NumPy on CPU: ~116 ms/step is normal.
  • To go 17 times faster: etapas/06_transformer/04_el_mismo_gpt_en_pytorch.py
  • Reduce --contexto before --dim: attention is quadratic in the context.

Memory

The process dies with no message (code 137)

That is SIGKILL: the system killed you for running out of memory.

FixEffect
--lote 8 instead of 16memory halved
Shorter --contextomemory falls with the SQUARE
Evaluate in batches, not all at oncethis is the most frequent failure

It really happened while building this project: evaluating 90 examples at once with context 192 reached 8.9 GB and died. It is documented in etapas/09_finetuning_lora/README.md.

The baffling part: training was fine and it died while evaluating, which is when you think you are not doing anything heavy.

mininn uses an enormous amount of memory

That is expected: it keeps the whole graph with no optimization. PyTorch uses a fraction because it frees intermediates. It is the difference between a teaching engine and a production one.


The tokenizer

Text gets corrupted or letters go missing

The most dangerous silent failure of them all.

assert tok.decode(tok.encode(x)) == x

If that fails, the tokenizer is dropping characters. It happens when the new text has symbols the training corpus did not have.

It happened to me building this: the corpus had no capital 'R', so "Reparte el error" was trained as "eparte el error". The loss went down quite happily. It is written up in etapas/09_finetuning_lora/README.md.

Fix: tok.desconocidos(texto) tells you what is missing, and tok.registrar_caracteres(...) adds it.

Strange characters appear when generating (�)

A token can be half a UTF-8 character. When streaming you have to accumulate bytes until you have complete characters. → DecodificadorEnStreaming in etapas/11_servidor_chat/servidor.py.


The trained model

It generates nonsense

  • Did the loss actually go down? If it stayed around ~log(V), it learned nothing.
  • Are you using the same tokenizer you trained with? The ids mean nothing without their table.
  • Is the temperature absurd? At T=5 everything is noise.

It repeats itself in a loop

That is greedy (T=0). It is a known and explained failure: repeated text is a region of extremely high local probability.

Fix: temperature > 0, top-p 0.9, or a repetition penalty of 1.1. → Measured in etapas/08_inferencia/01_muestreo.py: repetition 0.567 with greedy against 0.04 when sampling.

The chat does not answer, it continues the text

It has not been through SFT. It is a base model. → etapas/09_finetuning_lora/01_sft_chat.py

It answers some questions well and others terribly

Normal with 20 training examples. SFT teaches format, not knowledge. → etapas/11_servidor_chat/README.md


The course exercises

ModuleNotFoundError: No module named 'mininn'

Run them from the root of the project:

cd ~/Documents/Ia-desde-cero
.venv/bin/python curso/03_autograd/e1_backward.py

NotImplementedError

That is not an error: it is the exercise, not started. Look for TU CÓDIGO AQUÍ.

The test fails and I do not understand why

The message says what it expected and what it got. Start with the smallest failing case and do it by hand on paper.


How you debug this sort of thing, in general

  1. Shrink it until it works. One example, two layers, ten steps. If it still fails there, the bug is logic, not scale.
  2. Check the shapes. 90% of neural network errors are dimensions that do not line up.
  3. The sanity check: initial loss ≈ log(V). Five seconds that save hours.
  4. Numerical gradient check. If you doubt a derivative, compare it against (f(x+h)-f(x-h))/2h. → etapas/03_autograd/verificar_gradientes.py
  5. Deliberately overfit a small batch. If your model cannot memorize 10 examples, there is a bug. If it can, the code is fine and the problem is data or hyperparameters.

Point 5 is the best debugging advice in this whole document.