GUIDA TECNICA

ZeRO e ottimizzatori frammentati

ZeRO (Zero Redundancy Optimizer) è una tecnica di risparmio di memoria per l'addestramento in parallelo dei dati che divide gli stati dell'ottimizzatore, i gradienti e infine i pesi stessi tra le GPU invece di copiarli su ogni GPU.

Ascolta questa guidaNarrato dall'IA · ~8 min

In questa pagina9 minuti di lettura
  1. Panoramica
  2. Punti chiave
  3. Immersione profonda
  4. Stima della memoria per GPU per un modello 13B sotto ciascun stadio ZeRO
  5. Implementazione nel mondo reale
  6. Il futuro di ZeRO e degli ottimizzatori frammentati
  7. Metterlo in pratica
  8. Fonti e approfondimenti
  9. Continua a esplorare
  10. Domande frequenti

Panoramica

Introdotto da Microsoft nel 2019 e distribuito in DeepSpeed, lui e il suo contropartita PyTorch FSDP sono come la maggior parte delle squadre ora adattano modelli con multi-miliardi di parametri su cluster GPU ordinari.

Punti chiave

  1. Adam a precisione mista richiede circa 16 byte per parametro, quindi un modello con 7,5 miliardi di parametri richiede circa 120 GB di stato del modello prima delle attivazioni.
  2. Lo stadio 1 di ZeRO divide lo stato dell'ottimizzatore, lo stadio 2 divide anche i gradienti, e lo stadio 3 divide anche i pesi del modello stessi.
  3. Gli stadi 1 e 2 hanno lo stesso costo di comunicazione dell'ordinario parallelismo dei dati, mentre lo stadio 3 costa circa 1,5 volte di più.
  4. Il paper ZeRO del 2019 di Microsoft riportava l'addestramento di modelli con oltre 100 miliardi di parametri su 400 GPU a circa 15 petaflop.
  5. PyTorch FSDP fornisce sharding completo in stile ZeRO nativamente, e ZeRO-Offload e ZeRO-Infinity lo estendono alla CPU e alla memoria NVMe.

Immersione profonda

ZeRO, the Zero Redundancy Optimizer, is a way to train neural networks that are too big for one GPU's memory while keeping the simple programming model of data parallelism. In ordinary data parallelism, every GPU holds a full copy of the model, processes a different slice of the training batch, and the GPUs average their gradients after each step. That is easy to use but wasteful: with 64 GPUs, there are 64 identical copies of everything. ZeRO removes that duplication by giving each GPU responsibility for only a fraction of the training state, and fetching the rest from its peers just when it is needed. A sharded optimizer is the general name for this pattern; PyTorch's Fully Sharded Data Parallel (FSDP) is the best-known implementation outside Microsoft's DeepSpeed library.

The reason duplication hurts is that the weights are not the biggest item. The ZeRO paper does the accounting for mixed-precision training with the Adam optimizer, where each parameter needs 2 bytes for a 16-bit copy of the weight, 2 bytes for its 16-bit gradient, and 12 bytes of 32-bit optimizer state: a master copy of the weight plus Adam's two running averages, momentum and variance. That is 16 bytes per parameter, so a 7.5-billion-parameter model needs about 120 GB just for model state, before counting activations, the intermediate values saved for the backward pass. The optimizer state alone is three quarters of the total, which is why sharding it first gives the biggest win.

ZeRO works in three cumulative stages. Stage 1 partitions the optimizer states: each of N GPUs keeps Adam's state for only 1/N of the parameters and updates only that slice, after which the updated weights are shared with everyone. Stage 2 also partitions the gradients: instead of every GPU receiving the full averaged gradient, a reduce-scatter operation sums gradients across GPUs and delivers each GPU only the slice it will update. Stage 3 partitions the 16-bit parameters too: each GPU stores only its shard of the weights, and before each layer runs in the forward or backward pass, the GPUs perform an all-gather to temporarily rebuild that layer's full weights, then free them afterwards. For the 7.5B example on 64 GPUs, the paper computes per-GPU model state falling from 120 GB to about 31.4 GB at stage 1, 16.6 GB at stage 2 and 1.88 GB at stage 3.

The idea was introduced by Samyam Rajbhandari, Jeff Rasley, Olatunji Ruwase and Yuxiong He of Microsoft in a paper first posted to arXiv in October 2019 and revised in May 2020. It reported training models of over 100 billion parameters on 400 GPUs at about 15 petaflops of throughput, an 8 times increase in trainable model size and up to 10 times better performance than the prior state of the art, and training models of up to 13 billion parameters without any model parallelism. A family of follow-ups came next. ZeRO-Offload (January 2021) moved optimizer state and the optimizer step onto CPU memory, reaching 40 teraflops on one V100 for a 10B model. ZeRO-Infinity (April 2021) added NVMe solid-state storage as a third memory tier and reported over 25 petaflops on 512 V100 GPUs. ZeRO++ (June 2023) attacked communication instead, cutting ZeRO's communication volume by 4 times with quantized collectives. PyTorch documented its own FSDP design in an April 2023 paper reporting performance comparable to standard Distributed Data Parallel on models that DDP cannot hold.

ZeRO is one of several ways to split a model. Tensor parallelism, as in NVIDIA's Megatron-LM, cuts individual matrix multiplications across GPUs, which needs very fast links and changes the model code. Pipeline parallelism assigns different layers to different GPUs and streams micro-batches through them, which introduces idle bubbles and scheduling complexity. ZeRO instead keeps every GPU running the whole model on its own data and only changes where state is stored, so model code usually needs no rewriting. In practice, the largest training runs combine all three, with ZeRO or FSDP handling the data-parallel dimension. The ZeRO paper itself paired its stages with Megatron-style model parallelism to reach its 100-billion-parameter results.

The costs are mostly communication. Stages 1 and 2 move the same amount of data per step as plain data parallelism, which the paper counts as twice the parameter count, because the all-reduce that DDP already performs can be split into a reduce-scatter and an all-gather. Stage 3 raises that to three times the parameter count, a 1.5 times increase, because weights must be gathered once in the forward pass and again in the backward pass. On fast interconnects that overhead can be hidden by overlapping communication with computation, but on slower networks stage 3 can become network-bound. Offloading to CPU or NVMe trades GPU memory for PCIe bandwidth, so it can enable a model that would otherwise not fit while training it noticeably more slowly. Sharding also does nothing for activation memory on its own, so activation checkpointing is usually needed alongside it.

Using ZeRO in practice is mainly configuration. In DeepSpeed, a JSON block named zero_optimization sets the stage and options such as reduce_bucket_size, overlap_comm, and offload_optimizer or offload_param with a device of cpu or nvme. In PyTorch, applying fully_shard to each transformer block and then to the root module gives stage 3 behavior, with reshard_after_forward controlling whether weights are freed after the forward pass. One operational detail catches many users: sharded checkpoints are saved as many per-rank files, so producing a single ordinary weight file requires a consolidation step, such as DeepSpeed's zero_to_fp32.py script, which the docs say needs about twice the final checkpoint size in CPU memory. Choosing a stage is a trade-off: use the lowest stage that fits the model, because each higher stage adds communication.

04Esempio lavorato

Stima della memoria per GPU per un modello 13B sotto ciascun stadio ZeRO

  1. Prendi un modello di 13 miliardi di parametri addestrato con Adam a precisione mista, quindi P = 13e9 e lo stato del modello è di 16 byte per parametro.

  2. Senza ZeRO, ogni GPU contiene 16 x 13e9 = 208 GB, che supera una GPU da 80 GB.

  3. Con lo stage 1 su N = 8 GPU: 4P + 12P/8 = 52 GB + 19,5 GB = 71,5 GB per GPU.

  4. Con lo stage 2 su 8 GPU: 2P + 14P/8 = 26 GB + 22,75 GB = 48,75 GB per GPU.

  5. Con lo stage 3 su 8 GPU: 16P/8 = 26 GB per GPU.

  6. Aggiungi margine per attivazioni, buffer all-gather temporanei e frammentazione, e confronta ogni totale con i 80 GB disponibili.

Cosa mostra

Lo stage 1 si adatta a malapena con quasi nessuno spazio per le attivazioni, lo stage 2 lascia circa 31 GB di margine, e lo stage 3 lascia circa 54 GB a 1,5 volte la comunicazione. Verifica l'aritmetica rispetto alle formule nel paper ZeRO e conferma con i report di memoria del framework durante una breve esecuzione di prova.

Implementazione nel mondo reale

Microsoft ha addestrato Turing-NLG, un modello linguistico da 17 miliardi di parametri, con ZeRO, come riportato nel paper ZeRO.

Il tutorial ufficiale ZeRO di DeepSpeed mostra un GPT-2 da 1,5 M di parametri che esaurisce la memoria su otto GPU V100 da 32 GB, per poi adattarsi una volta che lo stage 1 di ZeRO riduce la memoria dell'ottimizzatore per GPU da circa 18 GB a 2,25 GB.

ZeRO-Offload, pubblicato a gennaio 2021, addestra modelli con oltre 13 miliardi di parametri su un singolo NVIDIA V100 spostando il lavoro dell'ottimizzatore nella memoria CPU, circa 10 volte ciò che PyTorch gestisce normalmente.

L'API fully_shard di PyTorch (FSDP2) suddivide ogni parametro tra il gruppo di data parallel e offre una CPUOffloadPolicy, fornendo agli utenti PyTorch il comportamento dello stage 3 di ZeRO senza DeepSpeed.

ZeRO-Infinity estende lo sharding a CPU e storage NVMe, e il suo paper di aprile 2021 riporta il fine‑tuning di modelli da trilioni di parametri su un singolo nodo NVIDIA DGX-2.

Il futuro di ZeRO e degli ottimizzatori frammentati

The memory wall that motivated ZeRO keeps widening: the ZeRO-Infinity authors noted in 2021 that the largest dense models had grown over 1,000 times in three years while GPU memory grew about 5 times, from 16 GB to 80 GB. That pressure has shifted research from fitting state toward moving it efficiently. ZeRO++ (June 2023) showed that quantizing the collectives themselves can cut communication volume by 4 times, and PyTorch's per-parameter FSDP2 design reflects a push to make sharding compose cleanly with tensor parallelism, compilers and distributed checkpointing. Open problems include training efficiently over slower or heterogeneous networks, where stage 3's extra gather traffic dominates; keeping offloading to CPU and NVMe from bottlenecking on PCIe bandwidth; and reducing the operational friction of sharded checkpoints. How these trade-offs settle will depend on future interconnect speeds and accelerator memory sizes, which are not known in advance, so teams generally benchmark the lowest workable stage on their own hardware rather than assuming one setting is best.

Metterlo in pratica

Perché è importante

  • Costo e budget. Le decisioni relative all'architettura determinano prestazioni e costi operativi per anni.
  • Decisioni più chiare. La formazione tecnica aiuta i team a scegliere lo stack giusto, non solo quello più nuovo.
  • Controllo di qualità. Migliori scelte ingegneristiche riducono gli incidenti legati all’affidabilità nella produzione.

Attenzione

  • L'ottimizzazione di un benchmark può nascondere debolezze di sistema più ampie.
  • I costi delle infrastrutture e della manutenzione sono spesso sottostimati.
  • Le lacune in termini di sicurezza e osservabilità possono aumentare man mano che i sistemi diventano più complessi.

Prossimi passi

  1. Definire obiettivi di latenza, qualità e costi prima dell'implementazione.
  2. Benchmark in condizioni di carico e dati realistiche.
  3. Monitoraggio dello strumento per errori, deriva e impatto sull'utente.
  4. Preparare percorsi di rollback e risposta agli incidenti prima della scalabilità.

Fonti e approfondimenti

  1. arXiv (Rajbhandari, Rasley, Ruwase, He, Microsoft)ZeRO: Ottimizzazioni di Memoria per l'Addestramento di Modelli da Trilioni di Parametri
  2. arXiv (Ren et al.)ZeRO-Offload: Democratizzare l'Addestramento di Modelli su Scala di Miliardi
  3. arXiv (Rajbhandari et al.)ZeRO-Infinity: Superare il Limite di Memoria GPU per il Deep Learning su Scala Estrema
  4. arXiv (Wang et al.)ZeRO++: Comunicazione Collettiva Estremamente Efficiente per l'Addestramento di Modelli Giganti
  5. arXiv (Zhao et al.)PyTorch FSDP: Esperienze nella Scalabilità del Fully Sharded Data Parallel
  6. DeepSpeedTutorial Zero Redundancy Optimizer
  7. PyTorch documentationtorch.distributed.fsdp.fully_shard

Continua a esplorare

Newsletter gratuita

Ricevi il briefing quotidiano sull'IA

Tre storie verificate sull'IA ogni mattina nei giorni feriali, scritte in un inglese semplice. Gratuito per sempre, senza pubblicità.

Un'email ogni giorno feriale. Disiscriviti con un clic. Non vendiamo né condividiamo mai il tuo indirizzo.

Mettiti alla prova

Fai il quiz su ZeRO e Sharded Optimizers

Feedback immediato su ogni risposta e un certificato condivisibile con un ID verificabile una volta superato un corso.

Inizia il quiz

Sostieni l'istruzione gratuita sull'IA. AI Understanding è un'organizzazione non profit 501(c)(3) — nessun annuncio, nessun paywall, mai. Fai una donazione

Domande frequenti

Che cos'è ZeRO e Sharded Optimizers?

ZeRO (Zero Redundancy Optimizer) è una tecnica di risparmio di memoria per l'addestramento in data-parallel che divide gli stati dell'ottimizzatore, i gradienti e infine i pesi stessi tra le GPU invece di copiarli su ogni GPU. Introdotto da Microsoft nel 2019 e distribuito in DeepSpeed, è lui e il suo contropartita PyTorch FSDP che ora la maggior parte dei team utilizza per adattare modelli di più miliardi di parametri su cluster GPU ordinari.

Quale ridondanza elimina ZeRO rispetto al semplice parallelismo dei dati?

Il parallelismo dei dati standard memorizza una copia completa dello stato, dei gradienti e dei pesi dell'ottimizzatore su ogni GPU; ZeRO li suddivide in modo che ogni GPU ne contenga solo una fetta.

Perché lo stato dell'ottimizzatore è spesso il più grande divoratore di memoria con Adam?

Adam mantiene stime correnti come il primo e il secondo momento per parametro, che combinate con i pesi principali fp32 possono far impallidire le dimensioni del modello.

Cosa fa lo shard di ZeRO Stage 3 rispetto agli Stage 1 e 2?

La Fase 1 frammenta lo stato dell'ottimizzatore, la Fase 2 aggiunge gradienti e la Fase 3 va oltre suddividendo i parametri del modello anche tra le GPU.

In ZeRO Stage 3, come fa una GPU a ottenere tutti i parametri necessari per il passaggio in avanti di un livello?

Prima di calcolare un livello, un all-gather assembla i suoi parametri completi su ciascuna GPU; una volta terminato, le porzioni non di proprietà vengono liberate per recuperare memoria.

Quale funzionalità PyTorch implementa nativamente lo sharding in stile ZeRO?

FSDP (Fully Sharded Data Parallel) di PyTorch suddivide parametri, gradienti e stato dell'ottimizzatore, raccogliendoli ed effettuando il resharding al volo, rispecchiando ZeRO.