Ridurre l'uso della memoria della GPU
Checkpointing e gestione più efficiente dei tensori
Ridurre l'uso della memoria della GPU è una lezione Deep Learning Academy gratuita su CoddyKit. Questa è la lezione 4 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 Dreaded OOM
Run out of GPU memory and training crashes with an out-of-memory error. The good news is several simple tactics free up space fast.
Where Memory Goes
Your GPU holds the model weights, the gradients, the optimizer state, and the activations saved for backward. Activations are often the biggest.
Shrink the Batch
The fastest fix is a smaller batch size. Fewer samples per step means fewer activations to store, and accumulation can recover the effective size.
No Grad for Inference
During evaluation you do not need gradients. Wrapping inference in torch.no_grad skips storing activations and saves a lot of memory.
with torch.no_grad():
preds = model(x)Mixed Precision Helps Here Too
Half-precision tensors are simply smaller. Turning on autocast cuts activation and weight memory roughly in half during training.
with torch.autocast(device_type='cuda'):
out = model(x)Gradient Checkpointing
Checkpointing trades compute for memory: it drops most activations and recomputes them during backward instead of keeping them all.
from torch.utils.checkpoint import checkpointApply Checkpointing
Wrap a heavy block in checkpoint so its activations are rebuilt on the backward pass. You save memory at the cost of extra recompute.
out = checkpoint(heavy_block, x)Detach What You Log
Keeping a loss tensor around holds its whole graph in memory. Call .item() to log just the number and let the graph be freed.
running_loss += loss.item()Use set_to_none
Pass set_to_none to zero_grad so gradient tensors are released instead of merely filled with zeros, freeing their memory between steps.
optimizer.zero_grad(set_to_none=True)Clear the Cache
PyTorch caches freed blocks for reuse. When you truly need space back, empty_cache returns it to the GPU, though it rarely fixes real leaks.
torch.cuda.empty_cache()Inspect Your Usage
Check how much you hold with memory_allocated. Watching this number while you tune confirms which change actually freed space.
print(torch.cuda.memory_allocated())Quick Check
Which technique saves memory by recomputing activations during backward?
Recap
Beat out-of-memory by shrinking batches, using no_grad for inference, autocast, gradient checkpointing, and set_to_none. Measure with memory_allocated. 🧹
Domande Frequenti
La lezione «Ridurre l'uso della memoria della GPU» è gratuita?
Sì — il testo completo di «Ridurre l'uso della memoria della GPU» è 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 «Ridurre l'uso della memoria della GPU»?
Checkpointing e gestione più efficiente dei tensori 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 4 di 4.
Quanto tempo richiede la lezione «Ridurre l'uso della memoria della GPU»?
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
- Precisione mista con autocast e GradScaler
- Accumulo dei gradienti per batch grandi
- Profilare il collo di bottiglia
- Ridurre l'uso della memoria della GPU