0Pricing
Deep Learning Academy · Aula

Lendo e Zerando .grad

Entenda por que os gradientes se acumulam e precisam ser redefinidos

Lendo e Zerando .grad é uma aula grátis de Deep Learning Academy no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Deep Learning Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Deep Learning Academy inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

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. 🧹

Perguntas Frequentes

A aula “Lendo e Zerando .grad” é grátis?

Sim — o texto completo de “Lendo e Zerando .grad” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Deep Learning Academy, atualize para CoddyKit PRO. O curso de Deep Learning Academy inclui 4 aulas no total.

O que vou aprender em “Lendo e Zerando .grad”?

Entenda por que os gradientes se acumulam e precisam ser redefinidos Você pratica Deep Learning Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Deep Learning Academy?

Nenhuma experiência prévia é necessária. Deep Learning Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.

Quanto tempo leva a aula “Lendo e Zerando .grad”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Deep Learning Academy?

Sim. Cada aula de Deep Learning Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. requires_grad e o Grafo Computacional
  2. Chame backward() para Obter Gradientes
  3. Lendo e Zerando .grad
  4. torch.no_grad() para Inferência
← Voltar para Deep Learning Academy