0Pricing
Deep Learning Academy · Lezione

Leggere e azzerare .grad

Scopra perché i gradienti si accumulano e devono essere reimpostati

Leggere e azzerare .grad è una lezione Deep Learning Academy gratuita su CoddyKit. Questa è la lezione 3 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Deep Learning Academy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Deep Learning Academy include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

The .grad Attribute

After backward, every trained tensor stores its gradient in .grad. Reading it tells you how the loss responds to changes in that tensor.

print(weight.grad)

Gradients Start as None

Before any backward call, .grad is None, not zero. PyTorch only allocates it once the first set of gradients actually arrives.

Gradients Accumulate

Here is the surprise: backward adds to .grad rather than replacing it. Call backward twice without clearing and the numbers pile up.

Why Accumulation Exists

This adding behavior is on purpose. It lets you sum gradients from several mini-batches before one update, handy for simulating a larger batch.

The Hidden Bug

Forget to clear and old gradients poison your next step, so the model trains on the wrong numbers. This silent bug trips up almost everyone once.

Zero Them Each Step

The fix is to reset gradients before each backward. With an optimizer you simply call zero_grad() at the top of every training step.

optimizer.zero_grad()

The Right Order

The loop rhythm is fixed: zero_grad, forward, loss, backward, step. Zeroing first guarantees each step uses only this batch's gradients.

optimizer.zero_grad()
loss.backward()
optimizer.step()

Clearing Without an Optimizer

No optimizer yet? You can null the gradients yourself by setting each tensor's .grad back to None before the next backward call.

w.grad = None

set_to_none Is Cheaper

Newer code prefers zero_grad(set_to_none=True). Setting grads to None instead of filling zeros saves a little memory and time.

Reading Grads to Debug

Peeking at .grad is great for debugging. All zeros may mean a dead neuron, and huge values warn of exploding gradients before training blows up.

A Habit Worth Forming

Make zeroing automatic in your head. Every reliable training loop clears gradients first, so the model only ever learns from the current batch.

Quick Check

Check the accumulation gotcha.

Recap

Gradients live in .grad and accumulate across backward calls, so you must clear them each step with zero_grad. Forgetting that quietly breaks training. 🧹

Domande Frequenti

La lezione «Leggere e azzerare .grad» è gratuita?

Sì — il testo completo di «Leggere e azzerare .grad» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Deep Learning Academy, passa a CoddyKit PRO. Il corso Deep Learning Academy include 4 lezioni in totale.

Cosa imparerò in «Leggere e azzerare .grad»?

Scopra perché i gradienti si accumulano e devono essere reimpostati Eserciti Deep Learning Academy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Deep Learning Academy?

Non è richiesta alcuna esperienza precedente. Deep Learning Academy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 3 di 4.

Quanto tempo richiede la lezione «Leggere e azzerare .grad»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Deep Learning Academy?

Sì. Ogni lezione Deep Learning Academy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. requires_grad e il grafo computazionale
  2. Chiami backward() per ottenere i gradienti
  3. Leggere e azzerare .grad
  4. torch.no_grad() per l'inferenza
← Torna a Deep Learning Academy