Pipeline Parallelism with AutoPipeline

View as Markdown

Introduction

As large language models continue to grow in size, training and fine-tuning them efficiently across multiple GPUs has become increasingly challenging. While data parallelism works well for smaller models, models with billions of parameters require more sophisticated parallelization strategies to overcome memory constraints and communication overhead.

Pipeline parallelism addresses these challenges by splitting a model’s layers across different devices and processing them in a pipelined fashion. Each device processes a different stage of the model, enabling training of models that wouldn’t fit on a single device while maintaining high GPU utilization through overlapped computation.

AutoPipeline is NeMo AutoModel’s high-level pipeline parallelism interface for Hugging Face-compatible models. Built on PyTorch’s native torch.distributed.pipelining, it expects an HF-style model with a config, a supported decoder-layer layout, and pipeline-compatible forwards. Recipe-driven pipeline parallelism also requires the selected model implementation to advertise a _pp_plan (or use the supported MoE path) and pass the repository’s pipeline validation; encoder-decoder models and models with actually tied input/output embedding weights are rejected.

The functional module at nemo_automodel.components.distributed.pipelining.functional exposes the same HF-specific pipeline_model() splitter plus lower-level stage and schedule helpers. Custom PyTorch architectures can reuse helpers such as stage_ids_this_rank(), calculate_virtual_stages(), and build_pipeline_schedule() after their own code constructs valid PipelineStage objects; pipeline_model() is not a generic nn.Module splitter.

This guide walks you through AutoPipeline for compatible Hugging Face models and the lower-level helpers for manually constructed stages. You’ll learn how to configure pipeline stages, integrate with existing training workflows, optimize performance, and combine pipeline parallelism with other parallelization strategies.

Prerequisites:

$# Install uv from https://docs.astral.sh/uv/getting-started/installation/
$# Initialize the virtual environment using uv
$uv venv
$
$# Install the latest stable release from PyPI
$uv pip install nemo-automodel
$
$# Or install from source for the latest features
$uv pip install git+https://github.com/NVIDIA-NeMo/Automodel.git

Before proceeding with this guide, please ensure that you have NeMo AutoModel installed on your machine. For a complete guide and additional options please consult the AutoModel Installation Guide.

Key Features

AutoPipeline provides the following capabilities:

  • Hugging Face-Compatible Model Support: Works with decoder-only causal language models and explicitly supported VLMs that satisfy the pipeline model contract
  • PyTorch Native Integration: Built on PyTorch’s torch.distributed.pipelining for optimal performance
  • Flexible Configuration: Multiple scheduling strategies, configurable microbatch sizes, and automatic or manual layer splitting
  • Mixed Parallelism Support: Combine pipeline parallelism with data parallelism, tensor parallelism, and FSDP
  • Modular Functional API: Lower-level stage and schedule helpers can be reused with manually constructed PipelineStage objects
  • Minimal Opinions: Easy to extend and integrate with existing training workflows

Quick Start with AutoPipeline (Hugging Face Models)

Here’s a minimal example to get started with AutoPipeline using 2 pipeline stages with a Hugging Face model:

1import torch
2from torch.distributed.device_mesh import init_device_mesh
3from nemo_automodel.components.distributed.pipelining import AutoPipeline
4from nemo_automodel.components.utils.model_utils import init_empty_weights
5from transformers import AutoModelForCausalLM
6from transformers.initialization import no_init_weights
7from transformers.utils import ContextManagers
8
9def loss_fn(logits: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
10 """Define loss function for pipeline training."""
11 return torch.nn.functional.cross_entropy(
12 logits.float().view(-1, logits.size(-1)),
13 targets.view(-1),
14 ignore_index=-100
15 )
16
17if __name__ == "__main__":
18 # 1) Initialize device mesh with 2 pipeline stages
19 world_mesh = init_device_mesh("cuda", mesh_shape=(2,), mesh_dim_names=("pp",))
20
21 # 2) Load model on meta device to avoid OOM with large models
22 init_ctx = ContextManagers([no_init_weights(), init_empty_weights()])
23 with init_ctx:
24 model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.1-8B")
25
26 # 3) Configure and build pipeline
27 ap = AutoPipeline(
28 world_mesh=world_mesh,
29 pp_axis_name="pp",
30 pp_schedule="1f1b",
31 pp_microbatch_size=1,
32 pp_batch_size=8, # Local batch size consumed by the pipeline schedule
33 device=torch.cuda.current_device(),
34 dtype=torch.bfloat16,
35 ).build(model, loss_fn=loss_fn)
36
37 # 4) Access pipeline components
38 print(ap.debug_summary())
39 print(ap.pretty_print_stages())

Run the Quick Start Example

Save the above code as pipeline_example.py and run with:

$# Run with 2 GPUs for 2 pipeline stages
$uv run torchrun --nproc-per-node=2 pipeline_example.py

For a complete training example:

$# Run fine-tuning with 2-way pipeline parallelism using Llama 3.1 8B
$automodel --nproc-per-node=2 examples/llm_finetune/llama3_1/llama3_1_8b_hellaswag_pp.yaml

Configuration Options

Basic Configuration

AutoPipeline provides comprehensive control over pipeline behavior:

1ap = AutoPipeline(
2 # Device mesh configuration
3 world_mesh=world_mesh, # DeviceMesh with pipeline axis
4 pp_axis_name="pp", # Name of pipeline axis (default: "pp")
5
6 # Schedule configuration
7 pp_schedule="1f1b", # Pipeline schedule ("1f1b", "LoopedBFS", etc.)
8 pp_microbatch_size=1, # Microbatch size per stage
9 pp_batch_size=8, # Local schedule batch, split into microbatches
10 # Recipe flows set this from step_scheduler.local_batch_size
11
12 # Stage configuration
13 layers_per_stage=None, # Layers per stage (None for auto)
14 module_fqns_per_model_part=None, # Manual module assignment
15
16 # Model patching (HF-specific)
17 patch_inner_model=True, # Make decoder forward stage-friendly
18 patch_causal_lm_model=True, # Make CausalLM wrapper return tensors (hidden/logits)
19).build(model, loss_fn=loss_fn)

Model Patching (patch_inner_model, patch_causal_lm_model)

AutoPipeline splits a model by deep-copying it per stage and pruning away modules that don’t belong to that stage. Many Hugging Face models assume the full module tree is present and return ModelOutput objects; after pruning, their original forward() often breaks (or returns objects that are awkward to pipeline).

These two flags switch AutoPipeline to lightweight, pipeline-friendly forward() implementations that return tensors (see nemo_automodel.components.distributed.pipelining.hf_utils.patch_hf_model_for_pp):

  • patch_inner_model: patches the decoder module (model.model for ...ForCausalLM, otherwise the module itself) so each stage can run even after pruning.

    • Stage 0 (has embed_tokens): takes token IDs and produces hidden states.
    • Middle stages (no embed_tokens): take hidden states from the previous stage (using inputs_embeds, or a float tensor passed through input_ids) and produce hidden states.
    • Handles sliced layer containers (e.g., layers becoming dict-like after stage pruning) and returns a tensor of hidden states so stages can be chained.

    For compilation/performance, this patched forward prefers a precomputed causal_mask_mapping dict (it will fall back to computing masks and warn if you don’t provide it).

  • patch_causal_lm_model: patches the ...ForCausalLM wrapper forward (the module that owns lm_head) so pipeline stages return tensors:

    • Returns hidden states when lm_head is absent on that stage.
    • Returns logits when lm_head is present (typically only the last stage).
    • Supports logits_to_keep to compute logits for only the last k tokens.

    Note: this is only used when the module you pipeline is a ...ForCausalLM-style wrapper (i.e., it has a .model attribute). If you pass a base decoder module directly, patch_causal_lm_model typically has no effect.

When Should I Change These?

  • Leave both True (default) for standard Hugging Face AutoModelForCausalLM / ...ForCausalLM models. This is the common case and gives the expected behavior: token IDs -> hidden states -> logits across stages.
  • Set both False when your model already has a pipeline-friendly forward (returns tensors and can accept hidden states when embeddings are absent) or it needs custom kwargs/paths that the HF patch doesn’t preserve (common for NeMo AutoModel-native model implementations, packed-sequence/thd paths, extra args like padding_mask, etc.). Many benchmark configs for NeMo-native models do this (for example examples/llm_benchmark/qwen/qwen3_moe_30b_torch.yaml).
  • Set patch_inner_model=False, patch_causal_lm_model=True when your inner model is already stage-friendly, but the wrapper forward still returns a ModelOutput and you only want the wrapper simplified to “hidden states or logits”.

If you disable patch_causal_lm_model, your last stage will typically output hidden states instead of logits; in that case, make sure your loss_fn (or your last-stage module) applies the LM head explicitly.

Automatic vs. Manual Layer Distribution

AutoPipeline offers flexible control over how your model is split across pipeline stages:

Automatic Distribution

Let AutoPipeline automatically balance layers across stages:

1ap = AutoPipeline(
2 world_mesh=world_mesh,
3 pp_schedule="1f1b",
4 layers_per_stage=8, # Each stage gets ~8 transformer layers
5).build(model, loss_fn=loss_fn)

Manual Distribution

Specify exactly which modules go to each stage:

1from nemo_automodel.components.distributed.pipelining.functional import (
2 generate_hf_model_fqn_per_model_part
3)
4
5# Generate balanced assignments
6module_fqns = generate_hf_model_fqn_per_model_part(
7 num_stages=4,
8 num_layers=32,
9 include_embeddings=True,
10 include_lm_head=True,
11 include_rotary_emb=True,
12 fqn_prefix="model."
13)
14
15# Or define custom assignments
16custom_module_fqns = [
17 # Stage 0: Embeddings + first 8 layers
18 ["model.embed_tokens", "model.rotary_emb"] +
19 [f"model.layers.{i}" for i in range(8)],
20
21 # Stage 1: Next 8 layers
22 ["model.rotary_emb"] + [f"model.layers.{i}" for i in range(8, 16)],
23
24 # Stage 2: Next 8 layers
25 ["model.rotary_emb"] + [f"model.layers.{i}" for i in range(16, 24)],
26
27 # Stage 3: Final 8 layers + output
28 ["model.rotary_emb"] + [f"model.layers.{i}" for i in range(24, 32)] +
29 ["model.norm", "lm_head"]
30]
31
32ap = AutoPipeline(
33 world_mesh=world_mesh,
34 module_fqns_per_model_part=custom_module_fqns,
35).build(model, loss_fn=loss_fn)

Understand Model Splitting

When AutoPipeline splits your model, it intelligently distributes components across pipeline stages. Here’s how a typical model gets split:

Example: 32-Layer Model Across 2 Stages

1# Stage 0 (Rank 0): Input processing + first half
2stage_0_modules = [
3 "model.embed_tokens", # Token embeddings
4 "model.layers.0-15", # First 16 transformer layers
5 "model.rotary_emb" # Position embeddings (shared)
6]
7
8# Stage 1 (Rank 1): Second half + output processing
9stage_1_modules = [
10 "model.layers.16-31", # Last 16 transformer layers
11 "model.norm", # Final layer norm
12 "lm_head", # Language modeling head
13 "model.rotary_emb" # Position embeddings (shared)
14]

Example: 32-Layer Model Across 4 Stages

1# Stage 0 (Rank 0): Input processing
2stage_0_modules = [
3 "model.embed_tokens", # Token embeddings
4 "model.layers.0-7", # First 8 transformer layers
5 "model.rotary_emb" # Position embeddings (shared)
6]
7
8# Stage 1 (Rank 1): Early layers
9stage_1_modules = [
10 "model.layers.8-15", # Next 8 transformer layers
11 "model.rotary_emb"
12]
13
14# Stage 2 (Rank 2): Middle layers
15stage_2_modules = [
16 "model.layers.16-23", # Next 8 transformer layers
17 "model.rotary_emb"
18]
19
20# Stage 3 (Rank 3): Output processing
21stage_3_modules = [
22 "model.layers.24-31", # Final 8 transformer layers
23 "model.norm", # Final layer norm
24 "lm_head", # Language modeling head
25 "model.rotary_emb"
26]

Key observations:

  • Embeddings only exist on the first stage
  • Language modeling head only exists on the last stage
  • Rotary embeddings are shared across all stages (for position encoding)
  • Transformer layers are evenly distributed

Use Lower-Level Functional Helpers

AutoPipeline and the functional pipeline_model() convenience path both use Hugging Face-specific model splitting. For a custom architecture, construct the stage modules and PyTorch PipelineStage objects in model-owned code, then reuse the lower-level scheduling helpers. The examples below illustrate those lower-level pieces; they do not make pipeline_model() a generic model splitter.

Key Functional API Components

The functional API provides several utilities for building custom pipeline parallel systems:

Stage ID Calculation

1from nemo_automodel.components.distributed.pipelining.functional import stage_ids_this_rank
2
3# Calculate which stages run on this rank
4# For a "loop" style schedule (default)
5stage_ids = stage_ids_this_rank(pp_rank=0, pp_size=4, num_stages=8, style="loop")
6# Returns: (0, 4) - rank 0 gets stages 0 and 4
7
8# For a "v" style schedule (for zero-bubble schedules)
9stage_ids = stage_ids_this_rank(pp_rank=0, pp_size=4, num_stages=8, style="v")
10# Returns: (0, 7) - rank 0 gets stages 0 and 7

Module Name Generation

1from nemo_automodel.components.distributed.pipelining.functional import (
2 generate_hf_model_fqn_per_model_part
3)
4
5# Generate balanced module assignments for an HF-style decoder layout
6module_names = generate_hf_model_fqn_per_model_part(
7 num_stages=4,
8 num_layers=32,
9 include_embeddings=True,
10 include_lm_head=True,
11 include_rotary_emb=False, # Set based on your model
12 fqn_prefix="" # Use "model." for nested models
13)

Virtual Stage Calculation

1from nemo_automodel.components.distributed.pipelining.functional import calculate_virtual_stages
2
3# Calculate virtual stages for interleaved schedules
4num_virtual_stages, stages_per_rank = calculate_virtual_stages(
5 num_layers=32,
6 layers_per_stage=4, # Each virtual stage has 4 layers
7 pp_size=4,
8 is_single_stage_schedule=False,
9 round_to_pp_multiple="up" # Round up to nearest multiple of pp_size
10)

Pipeline Schedule Build

1from nemo_automodel.components.distributed.pipelining.functional import build_pipeline_schedule
2
3# Build a schedule for your stages
4schedule = build_pipeline_schedule(
5 pipeline_parallel_schedule_csv=None, # Optional CSV schedule
6 pipeline_parallel_schedule="1f1b",
7 microbatch_size=1,
8 local_batch_size=8,
9 stages=stages, # List of PipelineStage objects
10 loss_fn=loss_fn,
11 scale_grads=False
12)

Pseudocode: Pipeline Parallelism for Custom Models

The following fence is intentionally non-runnable pseudocode. A real custom model must provide model-owned create_stage_model splitting, a dataloader, pipeline-compatible stage input/output contracts, and process-group setup before reusing these scheduling helpers. It is an architectural outline, not a script to run unchanged.

1# NON-RUNNABLE PSEUDOCODE
2import torch
3import torch.nn as nn
4from torch.distributed.device_mesh import init_device_mesh
5from torch.distributed.pipelining import PipelineStage
6from nemo_automodel.components.distributed.pipelining.functional import (
7 stage_ids_this_rank,
8 build_pipeline_schedule,
9 calculate_virtual_stages
10)
11
12class CustomTransformerBlock(nn.Module):
13 def __init__(self, hidden_size):
14 super().__init__()
15 self.attention = nn.MultiheadAttention(hidden_size, num_heads=8)
16 self.mlp = nn.Sequential(
17 nn.Linear(hidden_size, hidden_size * 4),
18 nn.GELU(),
19 nn.Linear(hidden_size * 4, hidden_size)
20 )
21 self.norm1 = nn.LayerNorm(hidden_size)
22 self.norm2 = nn.LayerNorm(hidden_size)
23
24 def forward(self, x):
25 # Simplified transformer block
26 attn_out, _ = self.attention(x, x, x)
27 x = self.norm1(x + attn_out)
28 x = self.norm2(x + self.mlp(x))
29 return x
30
31class CustomModel(nn.Module):
32 def __init__(self, vocab_size, hidden_size, num_layers):
33 super().__init__()
34 self.embedding = nn.Embedding(vocab_size, hidden_size)
35 self.layers = nn.ModuleList([
36 CustomTransformerBlock(hidden_size) for _ in range(num_layers)
37 ])
38 self.output_proj = nn.Linear(hidden_size, vocab_size)
39
40 def forward(self, input_ids):
41 x = self.embedding(input_ids)
42 for layer in self.layers:
43 x = layer(x)
44 return self.output_proj(x)
45
46def split_custom_model_for_pipeline(model, pp_rank, pp_size, num_stages):
47 """Split a custom model into pipeline stages."""
48
49 # Determine which stages this rank handles
50 stage_indices = stage_ids_this_rank(pp_rank, pp_size, num_stages, style="loop")
51
52 stages = []
53 for stage_idx in stage_indices:
54 # Create a stage-specific version of the model
55 # This is a simplified example - you'd need to implement proper splitting
56 stage_model = create_stage_model(model, stage_idx, num_stages)
57
58 # Create PipelineStage
59 stage = PipelineStage(
60 stage_model,
61 stage_idx,
62 num_stages,
63 device=torch.cuda.current_device(),
64 group=None # Set your process group here
65 )
66 stages.append(stage)
67
68 return stages
69
70# Sketch of model-owned orchestration
71def main():
72 # Initialize device mesh
73 world_mesh = init_device_mesh("cuda", mesh_shape=(4,), mesh_dim_names=("pp",))
74 pp_rank = world_mesh["pp"].get_local_rank()
75 pp_size = world_mesh["pp"].size()
76
77 # Create model
78 model = CustomModel(vocab_size=50000, hidden_size=768, num_layers=24)
79
80 # Calculate virtual stages
81 num_virtual_stages, stages_per_rank = calculate_virtual_stages(
82 num_layers=24,
83 layers_per_stage=3, # 8 virtual stages total
84 pp_size=4,
85 is_single_stage_schedule=False
86 )
87
88 # Split model into stages
89 stages = split_custom_model_for_pipeline(model, pp_rank, pp_size, num_virtual_stages)
90
91 # Define loss function
92 def loss_fn(logits, targets):
93 return nn.functional.cross_entropy(
94 logits.view(-1, logits.size(-1)),
95 targets.view(-1)
96 )
97
98 # Build pipeline schedule
99 schedule = build_pipeline_schedule(
100 pipeline_parallel_schedule_csv=None,
101 pipeline_parallel_schedule="interleaved1f1b", # Multi-stage schedule registered by PyTorch
102 microbatch_size=1,
103 local_batch_size=8,
104 stages=stages,
105 loss_fn=loss_fn,
106 scale_grads=True
107 )
108
109 # Training loop
110 for batch in dataloader:
111 # Use schedule.step() for training
112 losses = []
113 schedule.step(batch["input_ids"], target=batch["labels"], losses=losses)
114
115 # losses will contain the loss values from the last stage
116 if losses:
117 print(f"Loss: {sum(losses) / len(losses)}")

Add a Parallelization Callback to HF-Compatible Splitting

When using the HF-compatible pipeline_model() path, a callback can apply additional parallelism to each model part. Its signature must match ParallelizeFnProtocol:

1from nemo_automodel.components.distributed.pipelining.functional import pipeline_model
2
3def custom_parallelize_fn(
4 model, world_mesh, moe_mesh, *,
5 dp_axis_names,
6 cp_axis_name=None,
7 tp_axis_name=None,
8 ep_axis_name=None,
9 ep_shard_axis_names=None,
10):
11 """Custom parallelization function for each local model part."""
12 # Apply your custom parallelization logic here
13 # This is called for each local model part
14 if dp_axis_names:
15 # Apply data parallelism
16 pass
17 # Add any other parallelization strategies
18 pass
19
20# Use pipeline_model only with an HF-compatible model.
21schedule, model_parts, has_first, has_last, stages = pipeline_model(
22 model=hf_compatible_model,
23 world_mesh=world_mesh,
24 moe_mesh=None,
25 pp_axis_name="pp",
26 dp_axis_names=("dp",),
27 layers_per_stage=4,
28 pipeline_parallel_schedule="1f1b",
29 pipeline_parallel_schedule_csv=None,
30 microbatch_size=1,
31 local_batch_size=8,
32 device=torch.cuda.current_device(),
33 loss_fn=loss_fn,
34 parallelize_fn=custom_parallelize_fn,
35 module_fqns_per_model_part=None, # Or provide an explicit HF module assignment
36 patch_inner_model=False, # Use only when the model's inner forward is already stage-friendly
37 patch_causal_lm_model=False, # Use only when the wrapper already returns stage tensors
38)

Tips for Manually Staged Custom Models

The lower-level helpers can support a custom model after its model-owned splitting code has created the stage modules:

  1. Module Naming: Ensure your model has consistent module naming that can be mapped to stages
  2. State Management: Handle model state (embeddings, buffers) carefully across stages
  3. Communication: First and last stages need special handling for inputs/outputs
  4. Splitting Ownership: Keep custom model splitting in the model implementation; do not pass an arbitrary nn.Module to pipeline_model()
  5. Testing: Start with a small model and verify correct splitting before scaling up

The schedule helpers are reusable, but the repository’s automatic splitting path retains Hugging Face-specific assumptions.

Mixed Parallelism

AutoPipeline can be combined with other parallelization strategies for optimal performance:

1def parallelize_fn(
2 model, world_mesh, moe_mesh, *,
3 dp_axis_names,
4 cp_axis_name=None,
5 tp_axis_name=None,
6 ep_axis_name=None,
7 ep_shard_axis_names=None,
8):
9 """Apply additional parallelization to each local model part."""
10 # Example: Apply FSDP to each local model part
11 if dp_axis_names:
12 from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
13 # Wrap model with FSDP (simplified example)
14 # In practice, you'd configure FSDP parameters
15 pass
16
17 # Example: Apply tensor parallelism
18 if tp_axis_name:
19 # Apply tensor parallelism to attention/MLP layers
20 pass
21
22# Build pipeline with custom parallelization
23ap = AutoPipeline(world_mesh=world_mesh).build(
24 model,
25 loss_fn=loss_fn,
26 parallelize_fn=parallelize_fn
27)

Monitor and Debug

AutoPipeline provides comprehensive tools for understanding your pipeline configuration:

Pipeline Information

1# Get pipeline info
2info = ap.info
3print(f"Pipeline enabled: {info.enabled}")
4print(f"Has first stage: {info.has_first_stage}")
5print(f"Has last stage: {info.has_last_stage}")
6
7# Access model parts and runtime pipeline stages
8model_parts = ap.parts # List of local model-part nn.Module objects
9pipeline_stages = info.stages # List of local PipelineStage objects used by the schedule
10stage_modules = ap.list_stage_modules() # Module names within each local model part

Analysis

1# Parameter distribution
2stage_param_counts = ap.get_stage_param_counts()
3total_params = ap.get_total_param_count()
4trainable_params = ap.get_total_param_count(trainable_only=True)
5
6for i, params in enumerate(stage_param_counts):
7 percentage = (params / total_params) * 100
8 print(f"Stage {i}: {params:,} parameters ({percentage:.1f}%)")
9
10# Debug summary
11print(ap.debug_summary())
12print(ap.pretty_print_stages(max_modules_per_stage=10))
13
14# Visualize schedule
15ap.visualize_current_schedule("pipeline_schedule.png")

Gradient Management

1from nemo_automodel.components.distributed.pipelining.functional import scale_grads_by_divisor
2from nemo_automodel.components.training.utils import clip_grad_norm
3
4# Call these after backward on every pipeline rank.
5scale_grads_by_divisor(ap.info.stages, divisor=8)
6
7# Use the PP-aware clipping helper across the local model parts.
8grad_norm = clip_grad_norm(
9 1.0,
10 ap.parts,
11 norm_type=2.0,
12 pp_enabled=True,
13 device_mesh=world_mesh,
14 pp_axis_name="pp",
15)

Add Pipeline Parallelism to Supported Configurations

Pipeline parallelism can be added to an FSDP2 training configuration only when the model satisfies the repository’s PP contract and the PP, TP, CP, and inferred DP sizes compose to the total worker count. DDP and Megatron FSDP do not support PP. For recipe-driven model implementations, use a model with a _pp_plan or the explicitly supported MoE path.

Command-Line Override Method

For an FSDP2 config whose model supports PP, use command-line overrides such as:

$uv run automodel examples/llm_finetune/llama3_2/llama3_2_1b_squad.yaml \
> --nproc-per-node 2 \
> --step_scheduler.local_batch_size 8 \
> --distributed.strategy fsdp2 \
> --distributed.pp_size 2 \
> --distributed.pipeline.pp_schedule 1f1b \
> --distributed.pipeline.pp_microbatch_size 1 \
> --distributed.pipeline.round_virtual_stages_to_pp_multiple up \
> --distributed.pipeline.scale_grads_in_schedule false

Key parameters to override:

  • --distributed.pp_size: Number of pipeline ranks; PP, TP, CP, and inferred DP sizes must compose to the total worker count
  • --step_scheduler.local_batch_size: Runtime batch size used for both the pipeline schedule and dataloader
  • --distributed.pipeline.pp_schedule: Pipeline schedule (1f1b, interleaved1f1b, LoopedBFS, etc.)

YAML Configuration Method

Add these sections to a compatible FSDP2 YAML config:

1step_scheduler:
2 local_batch_size: 8 # Also sets the runtime pipeline batch size
3
4distributed:
5 strategy: fsdp2
6 dp_size: 1
7 tp_size: 1
8 cp_size: 1
9 pp_size: 4 # Enable 4-way pipeline parallelism
10 sequence_parallel: false
11 pipeline:
12 pp_schedule: 1f1b
13 pp_microbatch_size: 1
14 round_virtual_stages_to_pp_multiple: up
15 scale_grads_in_schedule: false
16 layers_per_stage: null # Auto-compute, or specify number

Mixed Parallelism Examples

Pipeline + Data Parallelism (4 GPUs Total)

$uv run automodel your_config.yaml \
> --nproc-per-node 4 \
> --distributed.pp_size 2 \
> --distributed.dp_size 2 \
> --step_scheduler.local_batch_size 16

Pipeline + Tensor Parallelism (4 GPUs Total)

$uv run automodel your_config.yaml \
> --nproc-per-node 4 \
> --distributed.pp_size 2 \
> --distributed.tp_size 2 \
> --step_scheduler.local_batch_size 8

Full Hybrid: PP + DP + TP (8 GPUs Total)

$uv run automodel your_config.yaml \
> --nproc-per-node 8 \
> --distributed.pp_size 2 \
> --distributed.dp_size 2 \
> --distributed.tp_size 2 \
> --step_scheduler.local_batch_size 32

Integrate with Training Recipes

AutoPipeline seamlessly integrates with NeMo AutoModel’s recipe system. Here’s a complete example YAML configuration:

1# config.yaml
2recipe: TrainFinetuneRecipeForNextTokenPrediction
3
4step_scheduler:
5 global_batch_size: 8
6 local_batch_size: 8
7 max_steps: 10
8 ckpt_every_steps: 10
9 val_every_steps: 10
10
11dist_env:
12 backend: nccl
13 timeout_minutes: 1
14
15seed: 1111
16
17model:
18 _target_: nemo_automodel.NeMoAutoModelForCausalLM.from_pretrained
19 pretrained_model_name_or_path: meta-llama/Llama-3.2-1B
20
21checkpoint:
22 enabled: false
23
24clip_grad_norm:
25 max_norm: 1.0
26
27distributed:
28 strategy: fsdp2
29 dp_size: none
30 dp_replicate_size: none
31 tp_size: 1
32 cp_size: 1
33 pp_size: 2 # 2-way pipeline parallelism
34 ep_size: 1
35 sequence_parallel: false
36 pipeline:
37 pp_schedule: 1f1b
38 pp_microbatch_size: 1
39 layers_per_stage: null # Auto-compute layer distribution
40 round_virtual_stages_to_pp_multiple: up
41 scale_grads_in_schedule: false
42
43loss_fn:
44 _target_: nemo_automodel.components.loss.masked_ce.MaskedCrossEntropy
45
46dataset:
47 _target_: nemo_automodel.components.datasets.llm.squad.make_squad_dataset
48 dataset_name: rajpurkar/squad
49 split: train
50
51packed_sequence:
52 packed_sequence_size: 0
53
54dataloader:
55 _target_: torchdata.stateful_dataloader.StatefulDataLoader
56 collate_fn:
57 _target_: nemo_automodel.components.datasets.utils.default_collater
58 shuffle: false
59
60validation_dataset:
61 _target_: nemo_automodel.components.datasets.llm.squad.make_squad_dataset
62 dataset_name: rajpurkar/squad
63 split: validation
64 limit_dataset_samples: 64
65
66validation_dataloader:
67 _target_: torchdata.stateful_dataloader.StatefulDataLoader
68 collate_fn:
69 _target_: nemo_automodel.components.datasets.utils.default_collater
70
71optimizer:
72 _target_: torch.optim.Adam
73 betas: [0.9, 0.999]
74 eps: 1e-8
75 lr: 1.0e-5
76 weight_decay: 0
77
78lr_scheduler:
79 lr_decay_style: cosine
80 min_lr: 1.0e-6

Run training with:

$# Run with 2 GPUs for 2-way pipeline parallelism
$uv run automodel config.yaml --nproc-per-node 2

Troubleshooting

Common Issues

Model doesn’t fit in memory:

  • Increase number of pipeline stages
  • Reduce microbatch size
  • Enable gradient checkpointing

Pipeline bubbles reducing efficiency:

  • Increase step_scheduler.local_batch_size to have more microbatches
  • Try different schedules (e.g., interleaved1f1b)
  • Adjust virtual stages configuration

Uneven stage distribution:

  • Use manual module assignment for fine control
  • Adjust layers_per_stage parameter
  • Check parameter counts with get_stage_param_counts()

Conclusion

AutoPipeline and pipeline_model() provide the repository’s HF-compatible splitting path, while lower-level functional helpers can be reused after custom code constructs its own pipeline stages.

Key takeaways:

  • Pipeline parallelism enables training of models too large for a single GPU
  • AutoPipeline provides a simple API for Hugging Face-compatible models with powerful customization options
  • Lower-level functional helpers can schedule manually constructed stages for custom models
  • Both can be combined with other parallelization strategies for optimal performance
  • Use built-in monitoring tools to understand and optimize your pipeline