nemo-mbridge-perf-cpu-offloading
NVIDIA/skills
Konfigurieren und validieren Sie die CPU-Entlastung für das Training mit der Megatron Bridge, einschließlich der Entlastung bei der Aktivierung und der Entlastung des Optimiererstatus mit dem HybridDeviceOptimizer.
...Alle erweiternCPU-Entlastung
Referenzen
- Stabile Dokumentation: @docs/training/cpu-offloading.md
- Strukturierte Metadaten: @skills/nemo-mbridge-perf-cpu-offloading/card.yaml
Was ist das?
Zwei unabhängige Mechanismen, um Daten vom GPU- in den CPU-Speicher zu verschieben:
| Mechanismus | Konfigurations-Namespace | Was wird ausgelagert | PP-Beschränkung |
|---|---|---|---|
| Aktivierungs-Offloading | model.cpu_offloading* |
Aktivierungen (und optional Gewichte) pro Transformer-Schicht | PP muss 1 sein |
| Optimierer-Offloading | optimizer.optimizer_cpu_offload |
Adam-Optimierer-Zustände (Momentum + Varianz) über HybridDeviceOptimizer |
Keine |
Schnelle Entscheidung
| Situation | Empfehlung |
|---|---|
| Großes MoE-Modell (über 30 Milliarden), benötigt PP > 1 | Optimizer-Offloading – Aktivierungs-Offloading wird durch PP=1 blockiert |
| Kleines/mittleres Modell, PP=1 ist geeignet, Aktivierungsspeicher dominiert | Aktivierungs-Offloading |
| Gewünschter einstellbarer Kompromiss zwischen Speicher und Geschwindigkeit | Optimierer-Offloading mit dem Bruchwert „optimizer_offload_fraction“ |
| Durchsatz hat oberste Priorität | Nicht aktivieren – Offloading verursacht immer zusätzlichen Overhead |
| CUDA-Graphen sind erforderlich | Nur Optimierer-Offloading – Aktivierungs-Offloading ist nicht kompatibel |
| Der Speicherbedarf ist moderat | Optimierer-Offloading mit einem Anteil von 25–50 % für beste Effizienz |
Aktivierung
CPU-Offloading des Optimierers (empfohlen für große Modelle)
cfg.optimizer.optimizer_cpu_offload = True
cfg.optimizer.optimizer_offload_fraction = 1.0
cfg.optimizer.overlap_cpu_optimizer_d2h_h2d = True
Überschreibungen über die Befehlszeile:
optimizer.optimizer_cpu_offload=True \
optimizer.optimizer_offload_fraction=0.5 \
optimizer.overlap_cpu_optimizer_d2h_h2d=True
CPU-Auslagerung der Aktivierungen (nur kleine/mittlere Modelle)
cfg.model.cpu_offloading = True
cfg.model.cpu_offloading_num_layers = 16
cfg.model.cpu_offloading_activations = True
cfg.model.cpu_offloading_weights = False
cfg.model.pipeline_model_parallel_size = 1
cfg.model.recompute_granularity = None
cfg.model.cuda_graph_impl = "none"
Referenz zu den Konfigurationsparametern
Offloading des Optimierers
| Parameter | Standard | Beschreibung |
|---|---|---|
optimizer_cpu_offload |
Falsch |
Hauptschalter |
optimizer_offload_fraction |
0,0 |
Anteil der Optimierer-Zustände auf der CPU (0,0–1,0) |
overlap_cpu_optimizer_d2h_h2d |
Falsch |
Überlappung von GPU↔CPU-Übertragungen mit der Rechenverarbeitung |
use_torch_optimizer_for_cpu_offload |
Falsch |
Verwende torch.optim anstelle des Fused Optimizers für den CPU-Anteil |
Aktivierungs-Offloading
| Parameter | Standard | Beschreibung |
|---|---|---|
cpu_offloading |
Falsch |
Hauptschalter |
cpu_offloading_num_layers |
0 |
Anzahl der zu entlastenden Transformer-Schichten (0 bis num_layers-1) |
cpu_offloading_activations |
True |
Aktivierungen auslagern |
cpu_offloading_weights |
Falsch |
Offload-Gewichtungen |
cpu_offloading_double_buffering |
Falsch |
Doppelpufferung über Schichten hinweg beim Neuladen |
Kompatibilität und Einschränkungen
Aktivierungs-Offloading
pipeline_model_parallel_sizemuss 1 seinrecompute_granularitymussNonesein- Kann nicht mit
„fine_grained_activation_offloading“kombiniert werden - Kann nicht mit CUDA-Graphen kombiniert werden
„cpu_offloading_num_layers“muss im Bereich[0, num_layers-1)liegen
Auslagerung des Optimierers
- Erfordert `
use_distributed_optimizer = True` (Standard in den meisten Rezepten) - Keine Einschränkungen hinsichtlich PP, Neuberechnung oder CUDA-Graphen
„optimizer_offload_fraction“muss im Bereich[0,0; 1,0]liegen
Praxisbeispiel: große MoE-Modelle
Das Auslagern der Aktivierungen ist für Qwen3-30B-A3B und ähnliche große MoE-Modelle blockiert. Die Einschränkung „PP=1“ bedeutet, dass jede GPU alle 48 Schichten enthält; allein die Modellgewichte und Optimiererstände (~70 GB) überschreiten die 80-GB-Kapazität der H100.
Minimaler ausführbarer Befehl
uv run python scripts/training/run_recipe.py \
--recipe qwen3_30b_a3b_pretrain_config \
optimizer.optimizer_cpu_offload=True \
optimizer.optimizer_offload_fraction=0.5 \
train.train_iters=20 \
train.global_batch_size=8 \
train.micro_batch_size=1
Verifizierung
Einzeltests
uv run python -m pytest \
tests/unit_tests/models/test_gpt_full_te_layer_autocast_spec.py -k "cpu_offload" \
tests/unit_tests/peft/test_utils.py -k "cpu_offload" -q
Erfolgskriterien
- Die Konfigurationsvalidierung für den ausgewählten Offloading-Modus ist erfolgreich
- Das Training wird ohne OOM- oder NCCL-Fehler abgeschlossen
- Der Verlust entspricht der Basislinie ohne Offloading (max. Abweichung < 0,001)
- Der Speicherverbrauch sinkt proportional zum Offload-Anteil
Code-Anker
Einschränkungen für die MCore-Aktivierungsauslagerung
if self.cpu_offloading and (
self.cpu_offloading_num_layers < 0 or self.cpu_offloading_num_layers >=self.num_layers
):
raise ValueError(...)
if self.cpu_offloading and self.pipeline_model_parallel_size > 1:
raise ValueError(
"Derzeit wird keine Pipeline-Parallelität bei CPU-Offloading unterstützt"
)
if self.cpu_offloading and self.recompute_granularity is not None:
raise ValueError(
"CPU-Offloading funktioniert nicht, wenn die Neuberechnung der Aktivierungen aktiviert ist"
)
Inkompatibilität von MCore-CUDA-Graphen
if self.cpu_offloading:
raise ValueError("CUDA-Graphen werden bei CPU-Offloading nicht unterstützt.")
MCore: Gegenseitiger Ausschluss bei feinkörnigem Offloading
if self.fine_grained_activation_offloading:
assert (
not self.cpu_offloading
), "fine_grained_activation_offloading kann bei aktiviertem CPU-Offloading nicht aktiviert werden."
Instanziierung von MCore HybridDeviceOptimizer
if config.optimizer_cpu_offload:
# ... Einrichten der CPU-/GPU-Optimiererklassen ...
optimizer = HybridDeviceOptimizer(
param_groups,
offload_fraction=config.optimizer_offload_fraction,
cpu_optimizer_cls=cpu_optimizer_cls,
gpu_optimizer_cls=gpu_optimizer_cls,
overlap_cpu_optimizer_d2h_h2d=config.overlap_cpu_optimizer_d2h_h2d,
pin_cpu_grads=config.pin_cpu_grads,
pin_cpu_params=config.pin_cpu_params,
)
Bridge-CUDA-Graph-Guard
assert not config.cpu_offloading and config.recompute_granularity is None, "Cudagraphs werden nicht unterstützt"
Brücken-Aktivierungs-Offloading in PEFT
if self.config.cpu_offloading and self.config.cpu_offloading_activations:
x.activation_offloading = True
x, _ = self.linear_in(x)
x = self.activation(x)
if self.config.cpu_offloading and self.config.cpu_offloading_activations:
x.activation_offloading = True
x, _ = self.linear_out(x)
Fehlerdiagnose
| Symptom | Mögliche Ursache | So überprüfen Sie dies | Behebung |
|---|---|---|---|
Derzeit wird die Pipeline-Parallelität bei CPU-Offloading nicht unterstützt |
Aktivierungs-Offloading + PP > 1 | Überprüfen Sie „pipeline_model_parallel_size“ |
Setzen Sie PP=1 oder verwenden Sie die Auslagerung durch den Optimierer |
Die CPU-Auslagerung funktioniert nicht, wenn die Neuberechnung der Aktivierung aktiviert ist |
Aktivierungs-Offloading + Neuberechnung | Überprüfen Sie „recompute_granularity“ |
Setzen Sie ` recompute_granularity` auf `null` |
„fine_grained_activation_offloading“ kann nicht zusammen mit „cpu_offloading“ aktiviert werden |
Beide Offloading-Modi sind aktiviert | Beide Flags prüfen | Verwenden Sie entweder das eine oder das andere |
CUDA-Graphen werden bei CPU-Offloading nicht unterstützt |
CUDA-Graphs + Aktivierungs-Offloading | Überprüfen Sie „cuda_graph_impl“ |
Setzen Sie ` cuda_graph_impl="none"` |
| OOM bei Aktivierungs-Offloading | Modell zu groß für PP=1 | Zugewiesenen Speicher im Vergleich zu 80 GB überprüfen | Verwenden Sie das Offloading des Optimierers bei PP > 1 |
| Extreme Verlangsamung (>4-fach) | 100 % Optimierer-Offloading, CPU-Engpass bei Adam | Iterationszeit bei verschiedenen Anteilen vergleichen | Anteil reduzieren oder „overlap_cpu_optimizer_d2h_h2d“ aktivieren |
| OOM bei teilweiser Auslagerung des Optimierers | Unzureichende Auslagerung für diese Konfiguration | Speicher bei verschiedenen Anteilen prüfen | Erhöhen Sie den Anteil oder fügen Sie PP hinzu |
Bekannte Einschränkungen
- Die Auslagerung der Aktivierung erfordert PP=1, was sie für große Modelle (30B+ MoE), die Pipeline-Parallelität benötigen, unpraktisch macht.
- Der Durchsatzverlust durch die Auslagerung des Optimierers skaliert linear (~1,9-fach bei 25 %, ~4,2-fach bei 100 % für Qwen3-30B-A3B).
- Die D2H/H2D-Überlappung bietet nur eine Beschleunigung von ~7 %, da die CPU-Adam-Berechnung der dominierende Engpass ist.
„fine_grained_activation_offloading“ist ein separater Ansatz auf Modulebene, der bei PP > 1 funktioniert, sich jedoch nicht mitdem „cpu_offloading“auf Ebenenebene kombinieren lässt.
---
name: nemo-mbridge-perf-cpu-offloading
description: Configure and validate CPU offloading for Megatron Bridge training, including activation offloading and optimizer state offloading with HybridDeviceOptimizer.
license: Apache-2.0
---
# CPU Offloading
## References
- Stable docs: @docs/training/cpu-offloading.md
- Structured metadata: @skills/nemo-mbridge-perf-cpu-offloading/card.yaml
## What It Is
Two independent mechanisms to move data from GPU to CPU memory:
| Mechanism | Config namespace | What gets offloaded | PP restriction |
|---|---|---|---|
| Activation offloading | `model.cpu_offloading*` | Activations (and optionally weights) per transformer layer | PP must be 1 |
| Optimizer offloading | `optimizer.optimizer_cpu_offload` | Adam optimizer states (momentum + variance) via `HybridDeviceOptimizer` | None |
## Quick Decision
| Situation | Recommendation |
|---|---|
| Large MoE model (30B+), needs PP > 1 | Optimizer offloading — activation offloading is blocked by PP=1 |
| Small/medium model, PP=1 fits, activation memory dominates | Activation offloading |
| Want tunable memory-speed tradeoff | Optimizer offloading with fractional `optimizer_offload_fraction` |
| Throughput is top priority | Don't enable — offloading always adds overhead |
| CUDA graphs are needed | Only optimizer offloading — activation offloading is incompatible |
| Memory pressure is moderate | Optimizer offload at 25–50% fraction for best efficiency |
## Enablement
### Optimizer CPU offloading (recommended for large models)
```python
cfg.optimizer.optimizer_cpu_offload = True
cfg.optimizer.optimizer_offload_fraction = 1.0
cfg.optimizer.overlap_cpu_optimizer_d2h_h2d = True
```
CLI overrides:
```bash
optimizer.optimizer_cpu_offload=True \
optimizer.optimizer_offload_fraction=0.5 \
optimizer.overlap_cpu_optimizer_d2h_h2d=True
```
### Activation CPU offloading (small/medium models only)
```python
cfg.model.cpu_offloading = True
cfg.model.cpu_offloading_num_layers = 16
cfg.model.cpu_offloading_activations = True
cfg.model.cpu_offloading_weights = False
cfg.model.pipeline_model_parallel_size = 1
cfg.model.recompute_granularity = None
cfg.model.cuda_graph_impl = "none"
```
## Config Parameter Reference
### Optimizer offloading
| Parameter | Default | Description |
|-----------|---------|-------------|
| `optimizer_cpu_offload` | `False` | Master switch |
| `optimizer_offload_fraction` | `0.0` | Fraction of optimizer states on CPU (0.0–1.0) |
| `overlap_cpu_optimizer_d2h_h2d` | `False` | Overlap GPU↔CPU transfers with compute |
| `use_torch_optimizer_for_cpu_offload` | `False` | Use `torch.optim` instead of fused optimizer for CPU portion |
### Activation offloading
| Parameter | Default | Description |
|-----------|---------|-------------|
| `cpu_offloading` | `False` | Master switch |
| `cpu_offloading_num_layers` | `0` | Number of transformer layers to offload (0 to num_layers-1) |
| `cpu_offloading_activations` | `True` | Offload activations |
| `cpu_offloading_weights` | `False` | Offload weights |
| `cpu_offloading_double_buffering` | `False` | Double-buffer across layers while reloading |
## Compatibility And Constraints
### Activation offloading
- `pipeline_model_parallel_size` must be 1
- `recompute_granularity` must be `None`
- Cannot combine with `fine_grained_activation_offloading`
- Cannot combine with CUDA graphs
- `cpu_offloading_num_layers` must be in `[0, num_layers-1)`
### Optimizer offloading
- Requires `use_distributed_optimizer = True` (default in most recipes)
- No PP, recompute, or CUDA graph restrictions
- `optimizer_offload_fraction` must be in `[0.0, 1.0]`
### Practical: large MoE models
Activation offloading is blocked for Qwen3-30B-A3B and similar large MoE
models. The PP=1 constraint means each GPU holds all 48 layers; model
weights + optimizer states alone (~70 GB) exceed H100 80 GB capacity.
## Minimal Runnable Command
```bash
uv run python scripts/training/run_recipe.py \
--recipe qwen3_30b_a3b_pretrain_config \
optimizer.optimizer_cpu_offload=True \
optimizer.optimizer_offload_fraction=0.5 \
train.train_iters=20 \
train.global_batch_size=8 \
train.micro_batch_size=1
```
## Verification
### Unit tests
```bash
uv run python -m pytest \
tests/unit_tests/models/test_gpt_full_te_layer_autocast_spec.py -k "cpu_offload" \
tests/unit_tests/peft/test_utils.py -k "cpu_offload" -q
```
### Success criteria
- Config validation passes for the selected offloading mode
- Training completes without OOM or NCCL errors
- Loss matches the non-offloaded baseline (max delta < 0.001)
- Memory usage drops proportionally to offload fraction
## Code Anchors
### MCore activation offload constraints
```1296:1310:3rdparty/Megatron-LM/megatron/core/transformer/transformer_config.py
if self.cpu_offloading and (
self.cpu_offloading_num_layers < 0 or self.cpu_offloading_num_layers >= self.num_layers
):
raise ValueError(...)
if self.cpu_offloading and self.pipeline_model_parallel_size > 1:
raise ValueError(
"Currently there is no support for Pipeline parallelism with CPU offloading"
)
if self.cpu_offloading and self.recompute_granularity is not None:
raise ValueError(
"CPU offloading does not work when activation recomputation is enabled"
)
```
### MCore CUDA graph incompatibility
```1943:1944:3rdparty/Megatron-LM/megatron/core/transformer/transformer_config.py
if self.cpu_offloading:
raise ValueError("CUDA graphs not supported with CPU offloading.")
```
### MCore fine-grained offloading mutual exclusion
```1427:1430:3rdparty/Megatron-LM/megatron/core/transformer/transformer_config.py
if self.fine_grained_activation_offloading:
assert (
not self.cpu_offloading
), "fine_grained_activation_offloading cannot be enabled with cpu_offloading."
```
### MCore HybridDeviceOptimizer instantiation
```480:518:3rdparty/Megatron-LM/megatron/core/optimizer/__init__.py
if config.optimizer_cpu_offload:
# ... setup cpu/gpu optimizer classes ...
optimizer = HybridDeviceOptimizer(
param_groups,
offload_fraction=config.optimizer_offload_fraction,
cpu_optimizer_cls=cpu_optimizer_cls,
gpu_optimizer_cls=gpu_optimizer_cls,
overlap_cpu_optimizer_d2h_h2d=config.overlap_cpu_optimizer_d2h_h2d,
pin_cpu_grads=config.pin_cpu_grads,
pin_cpu_params=config.pin_cpu_params,
)
```
### Bridge CUDA graph guard
```232:234:src/megatron/bridge/models/gpt_full_te_layer_autocast_spec.py
assert not config.cpu_offloading and config.recompute_granularity is None, "Cudagraphs not supported"
```
### Bridge activation offloading in PEFT
```621:631:src/megatron/bridge/peft/utils.py
if self.config.cpu_offloading and self.config.cpu_offloading_activations:
x.activation_offloading = True
x, _ = self.linear_in(x)
x = self.activation(x)
if self.config.cpu_offloading and self.config.cpu_offloading_activations:
x.activation_offloading = True
x, _ = self.linear_out(x)
```
## Failure Diagnosis
| Symptom | Likely Cause | How To Confirm | Fix |
|---|---|---|---|
| `Currently there is no support for Pipeline parallelism with CPU offloading` | Activation offload + PP > 1 | Check `pipeline_model_parallel_size` | Set PP=1 or use optimizer offloading |
| `CPU offloading does not work when activation recomputation is enabled` | Activation offload + recompute | Check `recompute_granularity` | Set `recompute_granularity=null` |
| `fine_grained_activation_offloading cannot be enabled with cpu_offloading` | Both offloading modes enabled | Check both flags | Use one or the other |
| `CUDA graphs not supported with CPU offloading` | CUDA graphs + activation offload | Check `cuda_graph_impl` | Set `cuda_graph_impl="none"` |
| OOM with activation offloading | Model too large for PP=1 | Check allocated memory vs 80 GB | Use optimizer offloading with PP > 1 |
| Extreme slowdown (>4x) | 100% optimizer offload, CPU Adam bottleneck | Compare iter time at different fractions | Reduce fraction or enable `overlap_cpu_optimizer_d2h_h2d` |
| OOM at partial optimizer offload | Insufficient offload for this config | Check memory at different fractions | Increase fraction or add PP |
## Known Limitations
- Activation offloading requires PP=1, making it impractical for large models
(30B+ MoE) that need pipeline parallelism.
- Optimizer offloading throughput penalty scales linearly (~1.9x at 25%,
~4.2x at 100% for Qwen3-30B-A3B).
- D2H/H2D overlap provides only ~7% speedup because CPU Adam compute is
the dominant bottleneck.
- `fine_grained_activation_offloading` is a separate module-level approach
that works with PP > 1 but cannot be combined with layer-level
`cpu_offloading`.
Alle Dateien
6 Dateiennemo-mbridge-perf-cpu-offloading installieren
Laden Sie die Skill-Dateien herunter und entpacken Sie sie in Ihr Verzeichnis „.claude/skills/“.
ZIP herunterladenKlonen Sie das Repository und kopieren Sie die Skill-Dateien in Ihr Projekt.
git clone https://github.com/NVIDIA/skills/tree/main/skills/nemo-mbridge-perf-cpu-offloading # Copy SKILL.md to your .claude/skills/ directory
Kopieren





Heim
