Generated banner for Nemo Mbridge Perf Memory Tuning
Generated logo for Nemo Mbridge Perf Memory Tuning

Nemo Mbridge Perf Memory Tuning

NVIDIAOfficialPublished by NVIDIA

  • Skill
  • Guidelines
  • Software development
  • Apache-2.0
  • Medium risk

From the author

Techniques for reducing peak GPU memory in Megatron Bridge — expandable segments, PEFT + SP input re-gather, parallelism resizing, activation recompute, CPU offloading constraints, and common OOM fixes.
— the description by NVIDIA

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a systematic approach to troubleshooting and resolving GPU memory issues in Megatron Bridge training environments. It distinguishes between memory fragmentation and genuine capacity limits, offering specific configuration adjustments to optimize memory usage. Key techniques include enabling expandable CUDA segments, configuring LoRA sequence-parallel input re-gathering, and understanding the constraints of parallelism resizing and CPU offloading.

What it does

  • Identifies memory fragmentation as a primary cause of OOM errors.
  • Provides environment variables to optimize the PyTorch CUDA allocator.
  • Details configuration changes for LoRA training to reduce activation memory.
  • Offers guidance on adjusting parallelism strategies to balance memory and throughput.
  • Includes a theoretical memory estimator for pre-launch configuration planning.
  • Documents compatibility constraints for CPU offloading and NCCL user-buffer registration.

When to use it

  • When encountering GPU out-of-memory (OOM) errors during training.
  • When attempting to reduce peak GPU memory usage for large model training.
  • When training LoRA models with sequence parallelism enabled.
  • When investigating OOM regressions following configuration changes.

Advantages

  • Reduces OOM errors caused by fragmentation without performance loss.
  • Provides memory-saving options for PEFT/LoRA workflows.
  • Offers clear decision-making criteria to avoid unnecessary throughput degradation.
  • Includes validation steps to ensure memory optimizations are correctly applied.

Usage examples

“How do I fix a persistent OOM error in my Megatron Bridge training job?”
The agent recommends setting the environment variable PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True as the first step to resolve potential memory fragmentation.
“I am training a LoRA model with sequence parallelism and running out of memory. What can I do?”
The agent suggests enabling sequence_parallel_input_regather=True in the LoRA configuration to reduce the retention of gathered inputs.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/nvidia/nemo-mbridge-perf-memory-tuning/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip nemo-mbridge-perf-memory-tuning.zip -d .agents/skills

Documentation by NVIDIA

Memory Tuning

Stable docs: @docs/parallelisms.md Card: @skills/nemo-mbridge-perf-memory-tuning/card.yaml

What It Is

GPU OOM failures during training often stem from memory fragmentation rather than raw capacity. PyTorch's default CUDA allocator can leave unusable gaps between allocations. The single most effective fix is:

export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True

This tells PyTorch to use expandable (non-fixed-size) memory segments, which dramatically reduces fragmentation and often eliminates borderline OOM without any model or parallelism changes.

Beyond fragmentation, actual peak memory is determined by:

  • Parameter + optimizer state memory — controlled by TP, PP, DP sharding (distributed optimizer, FSDP)

  • Activation memory — controlled by activation recompute, sequence length, micro-batch size, and PEFT-specific retention of gathered inputs

  • Temporary / workspace memory — CUDA kernels, NCCL buffers, CUDA graphs

For configuration planning, use the Bridge theoretical estimator before launching large jobs:

from megatron.bridge.training.utils.theoretical_memory_utils import estimate_training_memory

estimate = estimate_training_memory(cfg, num_microbatches=num_microbatches)

The estimator reports the most-loaded GPU shard and separates dense/embedding, routed MoE expert, and activation components. It does not include allocator fragmentation, CUDA/NCCL workspace, CUDA graph buffers, token imbalance, or dispatcher workspace, so validate final configs with runtime memory metrics.

Quick Decision

When a training run OOMs or is close to the memory limit:

  1. Set PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True first. This fixes fragmentation-induced OOM with zero performance cost. Most Slurm launch templates already include it.

  2. For LoRA with sequence parallelism, enable input re-gather (LoRA(sequence_parallel_input_regather=True)). This avoids retaining the full gathered LoRA-A input in every eligible layer; it has no effect when SP is disabled.

  3. Add selective activation recompute (recompute_modules=[core_attn]) if not already enabled. See @skills/nemo-mbridge-perf-activation-recompute/SKILL.md.

  4. Avoid increasing TP as a memory fix — doubling TP dramatically increases NVLink all-reduce volume and often kills throughput (-28% on Llama3 70B).

  5. Avoid increasing PP at the cost of DP — halving DP doubles gradient accumulation steps and hurts throughput (~6%).

  6. Consider mlp recompute if still OOM. Saves ~3 GB but costs ~16% GPU utilization on large dense models (Llama3 70B).

  7. CPU offloading is blocked when PP > 1.

Enablement

Set in the job's environment before launching:

export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True

In Slurm scripts this is typically placed alongside other env vars:

export CUDA_DEVICE_MAX_CONNECTIONS=1
export NVTE_ALLOW_NONDETERMINISTIC_ALGO=1
export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True

No model config changes needed. Zero throughput cost.

Parallelism resizing

If the model genuinely does not fit (not fragmentation), adjust parallelism:

StrategyMemory effectThroughput costNotes
Increase PP (keeping DP)Fewer layers per stageModerate (~6% if DP halved)Only if GPU count allows
Increase TPFewer params per GPUSevere (-28% on 70B)Last resort
Distributed optimizerShards optimizer state across DP ranks~1-2%Recommended for large models
FSDPShards params + grads + optimizerVariesSee @skills/nemo-mbridge-perf-megatron-fsdp/SKILL.md
Activation recompute

See @skills/nemo-mbridge-perf-activation-recompute/SKILL.md for full details.

PEFT + sequence-parallel input re-gather

For LoRA training with sequence parallelism, eligible column-parallel linear_qkv and linear_fc1 adapters consume a gathered LayerNorm output. Because LoRA-A is trainable, the default path retains that full gathered input until backward for the LoRA-A weight gradient.

Enable input re-gather when constructing the PEFT config:

from megatron.bridge.peft.lora import LoRA

cfg.peft = LoRA(
    # Keep the recipe's existing LoRA settings here.
    sequence_parallel_input_regather=True,
)

With this option, forward still materializes the full input temporarily for the LoRA-A GEMM, but MCore autograd retains only its sequence-local shard. Backward asynchronously gathers the full input again, overlaps the collective with dgrad when possible, computes the LoRA-A weight gradient, and then reuses the temporary communication buffer.

This is a memory-for-communication tradeoff, not conventional activation checkpointing: no LayerNorm, attention, MLP, or LoRA GEMM is rerun. Some throughput degradation is expected, and the benefit grows with the amount of eligible LoRA-A activation retained. The option has no effect when sequence parallelism is disabled.

CPU offloading
cfg.model.cpu_offloading = True

Incompatible with PP > 1. Only usable when pipeline_model_parallel_size = 1.

A Note on VPP

Virtual pipeline parallelism (VPP) is primarily a throughput optimization that reduces pipeline bubble overhead by interleaving smaller model chunks. Its effect on peak memory is minimal — changing VPP does not meaningfully change the total activation, parameter, or optimizer memory on a GPU.

In earlier experiments we incorrectly attributed an OOM fix to VPP tuning (VPP 5→10). The actual fix was PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True which eliminated memory fragmentation. The VPP=10 run actually used slightly more peak memory (60.2 GB vs 58.8 GB) but did not OOM because expandable segments prevented fragmentation.

VPP should be tuned for pipeline bubble reduction (see @docs/parallelisms.md), not as a memory fix.

Compatibility and Constraints

  • expandable_segments:True is incompatible with --use-nccl-ub (NCCL user-buffer registration). See Megatron-FSDP docs.

  • When using CUDA graphs with expandable_segments:True, set NCCL_GRAPH_REGISTER=0 (required on pre-Blackwell GPUs, enforced by MCore CudaGraphManager).

  • CPU offloading requires pipeline_model_parallel_size = 1.

  • Distributed optimizer requires use_distributed_optimizer = True in the optimizer config.

  • sequence_parallel_input_regather applies only to eligible non-expert column-parallel LoRA-A projections. Row-parallel adapters, expert adapters, TP=1, CUDA graphs, CPU activation offload, and overlapping full-layer or selective MLP activation recompute fall back to the existing path.

Measured Results

Llama3 70B SFT on 32x H100 80GB, FP8 (Current Scaling):

  • Baseline: TP=4, PP=4, VPP=5, DP=2, MBS=1, GBS=32, seq_len=4096

  • Golden GPU utilization: 709.93 TFLOP/s/GPU

  • Regression threshold: 5%

Strategy comparison: parallelism changes for memory reduction
ExperimentTPPPVPPDPTFLOP/s/GPUvs GoldenPeak Mem (GB)Result
Baseline4452~704-0.8%58.8OOM (fragmentation)
More PP4851668.0-5.9%53.2Borderline perf
More TP8451508.7-28.4%50.2Severe regression
Baseline + expandable_segments4452~704-0.8%~59Passed

Key takeaways:

  • expandable_segments:True is the winner. The baseline OOM was caused by memory fragmentation, not insufficient capacity. Setting this env var eliminated the OOM with zero throughput cost and no parallelism changes.

  • PP=8 works for memory but loses DP (2→1), meaning 32 gradient accumulation steps per batch, which hurts throughput by ~6%.

  • TP=8 is catastrophic (-28%) because doubling TP increases all-reduce communication volume proportionally across NVLink, and DP=1 means no micro-batch overlap.

CPU offloading: blocked
Experimentoffload_layersResult
Exp 42Incompatible (PP > 1)
Exp 54Incompatible (PP > 1)
Exp 66Incompatible (PP > 1)

ValueError: Currently there is no support for Pipeline parallelism with CPU offloading. This approach is blocked for any model using PP > 1.

Activation recompute: expensive alternative

Selective activation recompute with mlp saved ~3 GB peak memory but cost ~16% GPU utilization on this workload. See @skills/nemo-mbridge-perf-activation-recompute/SKILL.md for full results.

LoRA + SP input re-gather

Real-checkpoint H100 training with SQuAD showed lower peak memory in all tested configurations, with workload-dependent throughput cost:

Model/configBaseline peakInput re-gather peakMemory savedThroughput change
Qwen3-8B, TP2, seq 819247.545 GB42.814 GB4.731 GB (10.0%)-6.74%
Qwen3-30B-A3B, TP4/EP429.890 GB28.321 GB1.569 GB (5.2%)-2.89%
GPT-OSS-120B, TP2/EP852.185 GB51.371 GB0.814 GB (1.6%)-0.34%

All runs had finite losses with zero skipped or NaN iterations. Two-rank BF16 and FP32 checks matched the baseline for outputs, input gradients, LoRA-A and LoRA-B gradients, and two-microbatch fused main_grad accumulation.

Code Anchors

LoRA sequence-parallel input re-gather
src/megatron/bridge/peft/lora.py
    LoRA.sequence_parallel_input_regather

src/megatron/bridge/peft/utils.py
    ParallelLinearAdapter._sequence_parallel_input_regather_eligibility()
    ParallelLinearAdapter.forward()
CPU offloading PP incompatibility (MCore)
        if self.cpu_offloading and self.pipeline_model_parallel_size > 1:
            raise ValueError(
                "Currently there is no support for Pipeline parallelism with CPU offloading"
            )
VPP config and layer divisibility validation (MCore)
            if pipeline_parallel_size and self.virtual_pipeline_model_parallel_size is not None:
                num_layers_per_middle_pipeline_rank = num_layers // pipeline_parallel_size
                if (
                    not num_layers_per_middle_pipeline_rank
                    % self.virtual_pipeline_model_parallel_size
                    == 0
                ):
                    raise ValueError(
                        f"number of layers on each middle pipeline rank:"
                        f"{num_layers_per_middle_pipeline_rank} must be divisible by virtual"
                        f"pipeline parallel degree {self.virtual_pipeline_model_parallel_size}"
                    )
Parallelism docs on interleaved pipeline schedule
To minimize the pipeline bubble, the computation on each GPU can be divided into multiple subsets of layers (referred to as model chunks), rather than a single contiguous block. Enable this by setting `virtual_pipeline_model_parallel_size`:

model_config = GPTModelProvider(
    pipeline_model_parallel_size=4,
    virtual_pipeline_model_parallel_size=2,  # 2 model chunks per pipeline stage
    # ... other model parameters
)

Failure Diagnosis

SymptomCauseConfirmFix
OOM on a single rank despite headroom on othersMemory fragmentationcheck if expandable_segments:True is setset PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
OOM with expandable_segments already setGenuine capacity limitcheck nvidia-smi for param/optimizer memoryincrease PP, use distributed optimizer, or add recompute
Estimated memory exceeds GPU capacity before launchmodel state or activations genuinely too largerun estimate_training_memory and inspect the largest componentadjust PP/TP/CP/EP, distributed optimizer, or recompute before launching
LoRA + SP retains unexpectedly high activation memoryfull gathered LoRA-A inputs are retained until backwardcheck whether cfg.peft.sequence_parallel_input_regather is enabled and the target is eligibleset LoRA(sequence_parallel_input_regather=True); verify fallback constraints
ValueError: PP + CPU offloadingusing cpu_offloading with PP > 1check PP configdisable CPU offloading or set PP=1
RuntimeError with --use-nccl-ub + expandable segmentsNCCL UB incompatible with expandable allocatorcheck env varsremove expandable_segments:True or disable --use-nccl-ub

Known Limitations

  • CPU offloading is blocked when PP > 1

  • Parallelism resizing (TP/PP) often has significant throughput costs

  • The theoretical estimator is formula-based and does not replace runtime profiling or CUDA memory reports

  • LoRA input re-gather does not cover row-parallel or expert adapters and may have negligible benefit when few eligible LoRA-A activations dominate memory

Verification

Quick check that expandable_segments:True is active:

import os
assert "expandable_segments:True" in os.environ.get("PYTORCH_CUDA_ALLOC_CONF", "")

For Slurm jobs, verify the env var is exported before the training command in the launch script.

For LoRA + SP input re-gather, run the focused configuration tests and the real two-rank MCore backward-parity test:

uv run python -m pytest \
  tests/unit_tests/peft/test_utils.py -k "sequence_parallel_input_regather" \
  tests/unit_tests/peft/test_lora.py -k "sequence_parallel_input_regather"

uv run python -m torch.distributed.run --nproc_per_node=2 -m pytest \
  tests/unit_tests/peft/test_lora_sp_input_regather_distributed.py

Files

BENCHMARK.md

Evaluation Report

Evaluation of the nemo-mbridge-perf-memory-tuning skill before publication through NVSkills-Eval.

This benchmark summarizes 3-Tier Evaluation from NVSkills-Eval results for the skill. The goal is to document whether the skill is safe, discoverable, effective, and useful for agents before it is published for broader workflow use.

Evaluation Summary

  • Skill: nemo-mbridge-perf-memory-tuning

  • Evaluation date: 2026-06-30

  • NVSkills-Eval profile: external

  • Environment: astra-sandbox

  • Dataset: 1 evaluation tasks

  • Attempts per task: 1

  • Pass threshold: 50%

  • Overall verdict: PASS

Agents Used

  • claude-code

  • codex

Metrics Used

Reported benchmark dimensions:

  • Security: checks whether skill-assisted execution avoids unsafe behavior such as secret leakage, destructive commands, or unauthorized access.

  • Correctness: checks whether the agent follows the expected workflow and produces the correct final output.

  • Discoverability: checks whether the agent loads the skill when relevant and avoids using it when irrelevant.

  • Effectiveness: checks whether the agent performs measurably better with the skill than without it.

  • Efficiency: checks whether the agent uses fewer tokens and avoids redundant work.

Underlying evaluation signals used in this run:

  • security (Security): checks for unsafe operations, secret leakage, and unauthorized access.

  • skill_execution (Skill Execution): verifies that the agent loaded the expected skill and workflow.

  • skill_efficiency (Efficiency): checks routing quality, decoy avoidance, and redundant tool usage.

  • accuracy (Accuracy): grades final-answer correctness against the reference answer.

  • goal_accuracy (Goal Accuracy): checks whether the overall user task completed successfully.

  • behavior_check (Behavior Check): verifies expected behavior steps, including safety expectations.

  • token_efficiency (Token Efficiency): compares token usage with and without the skill.

Test Tasks

The benchmark dataset contained 1 evaluation tasks:

  • Positive tasks: 1 tasks where the skill was expected to activate.

  • Negative tasks: 0 tasks where no skill was expected.

  • Unlabeled tasks: 0 tasks where positive/negative intent could not be inferred.

Task composition is derived from the evaluation dataset when possible. Entries with expected_skill set are treated as positive skill-activation cases, while entries with expected_skill: null are treated as negative activation cases.

Results

DimensionNumclaude-codecodex
Security1100% (+0%)100% (+0%)
Correctness1100% (+100%)97% (+72%)
Discoverability1100% (+100%)97% (+47%)
Effectiveness198% (+86%)100% (+90%)
Efficiency194% (+67%)96% (+35%)

Score values show skill-assisted performance. Values in parentheses show uplift versus the no-skill baseline when baseline data is available.

Tier 1: Static Validation Summary

Tier 1 validation passed with observations. NVSkills-Eval ran 1 checks and found 4 total findings.

Top findings:

  • MEDIUM SCHEMA/body_recommended_section: Missing recommended section: '## Instructions' (skills/nemo-mbridge-perf-memory-tuning/SKILL.md)

  • MEDIUM SCHEMA/body_recommended_section: Missing recommended section: '## Examples' (skills/nemo-mbridge-perf-memory-tuning/SKILL.md)

  • MEDIUM SCHEMA/author_missing: Author not specified in metadata (skills/nemo-mbridge-perf-memory-tuning/SKILL.md)

  • LOW SCHEMA/unexpected_file: Unexpected 'card.yaml' in skill root (skills/nemo-mbridge-perf-memory-tuning/card.yaml)

Tier 2: Deduplication Summary

This tier was not run or did not produce findings in this report.

Publication Recommendation

The skill is suitable to proceed toward NVSkills-Eval publication based on this benchmark. Skill owners should keep this file with the skill and refresh it when the evaluation dataset, skill behavior, or target agents materially change.

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs Python

Security

What our scanner noticed· Medium risk

  • Large base64-encoded blobs

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
NVIDIA
Publisher
NVIDIA (Official)
Source
NVIDIA/skills · skills/nemo-mbridge-perf-memory-tuning · commit fce3cca
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE-APACHE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by NVIDIA or NVIDIA.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download nemo-mbridge-perf-memory-tuning.zip