This document is relevant for: Trn2, Trn3

Tutorial: Train Llama 3 with pipeline parallelism on TorchTitan#

This tutorial walks you through pipeline-parallel (PP) training with TorchTitan on AWS Trainium using TorchNeuron. When you have completed it, you will have split a 16-layer Llama 3 70B model into four pipeline stages across four Trainium nodes, trained it with the 1F1B and Interleaved 1F1B schedules, and balanced the work across the stages.

Overview#

FSDP and tensor parallelism split every layer of the model across ranks. Pipeline parallelism splits the model by depth instead: each stage owns a run of consecutive layers on its own group of ranks. TorchTitan divides each batch into microbatches. A stage runs the forward pass on a microbatch and sends the activation to the next stage. In the backward pass, it sends the gradient back to the previous stage. A stage communicates only with its neighbors, once for each microbatch. This traffic is much lighter than a collective across all ranks, so PP is the dimension to put across nodes, where bandwidth is lowest.

The cost is the pipeline bubble. At the start of each step, the later stages wait for the first microbatch to reach them. At the end, the earlier stages wait for the last gradients to come back. For p stages, m microbatches, and v stages on each rank, the idle fraction of the step is about:

bubble = (p - 1) / (v * m + p - 1)

There are two ways to shrink the bubble: more microbatches (a larger m), and an interleaved schedule that puts more than one stage on each rank (a larger v). This tutorial uses both.

Best practices for TorchTitan Neuron recommends that you add PP last, after FSDP and tensor parallelism. This tutorial uses a 16-layer truncation of Llama 3 70B, so that each run compiles and starts quickly. The layers keep their 70B shapes, so the per-stage compute and the stage-to-stage transfers are those of the full model.

How pipeline parallelism works on Neuron#

TorchTitan builds its stages and schedules with the standard torch.distributed.pipelining API. No Neuron-specific code exists in the model or the schedule. At each stage boundary, the schedule calls send and recv (batched with batch_isend_irecv) on the pipeline process group. The neuron distributed backend implements these calls as follows:

  • RDMA over EFA. The backend registers device memory (HBM) with the EFA network device that is attached to each NeuronCore. It then writes the boundary tensor directly from the HBM of the sender into the HBM of the receiver, with no copy through host memory. Ranks on the same node use the same EFA path, so a single-node pipeline also needs EFA. When a schedule places both ends of a boundary on one rank, the transfer is a local device copy.

  • Receiver-driven handshake. Each receive writes a small descriptor of its destination buffer into a mailbox on the sender, and the sender then writes the data. The backend creates one channel for each peer and tag on first use, and it keeps the channel for the rest of the run. Only the first step pays for the setup.

  • Non-blocking transfers. A send or recv posts its transfer and returns at once. A host worker thread advances every transfer in flight and completes it from the completion queue of the network device. With streams enabled (the default), transfers run on a dedicated point-to-point (P2P) stream. work.wait() makes only the consuming stream wait for the transfer, without blocking the CPU, so the host keeps queuing compute. The pipeline schedules post receives early and wait for them late, so a transfer usually overlaps the compute between them.

  • Failure detection. A transfer that does not complete within its deadline fails with an error that names the peer and the tag it is waiting for. The deadline is the smaller of the process group timeout and TORCH_NEURONX_STALL_TIMEOUT. Without this deadline, a failed neighbor would hang its pipeline.

TorchTitan makes PP the outermost dimension of its device mesh. When the PP degree equals the number of nodes, each stage fills one node. Tensor parallelism and FSDP collectives then stay inside a node, and only the stage-to-stage transfers cross the network. Each rank exchanges data with the rank that has the same TP and FSDP position on the neighboring node, 64 ranks away:

4 nodes, 256 ranks, PP=4 x FSDP=16 x TP=4 (default layer split)

node 0 (r0-63)       node 1 (r64-127)     node 2 (r128-191)    node 3 (r192-255)
┌────────────────┐   ┌────────────────┐   ┌────────────────┐   ┌────────────────┐
│ stage 0        │──►│ stage 1        │──►│ stage 2        │──►│ stage 3        │
│ embedding      │   │ layers 4-8     │   │ layers 9-12    │   │ layers 13-15   │
│ layers 0-3     │◄──│                │◄──│                │◄──│ output, loss   │
│ TP4 x FSDP16   │   │ TP4 x FSDP16   │   │ TP4 x FSDP16   │   │ TP4 x FSDP16   │
└────────────────┘   └────────────────┘   └────────────────┘   └────────────────┘
         activations ──►  (RDMA over EFA)  ◄── activation gradients

Sequence parallelism is on by default with tensor parallelism, so the activation between two blocks is sharded across the TP group, and each rank sends only its slice. Here a slice is 1 × 8192 tokens × 8192 hidden × 2 bytes ÷ 4 TP ranks = 32 MiB per microbatch.

Before you start#

This tutorial assumes that you have experience in the following areas:

  • Running TorchTitan on Neuron, on one node and on several nodes, verified by Tutorial: Run a basic TorchTitan training on Neuron. This tutorial reuses its MPI launch without explaining it again.

  • FSDP and tensor parallelism, and how each one splits a model.

  • The basic idea of a pipeline schedule: microbatches, forward and backward passes, and why a pipeline has a bubble. The PyTorch pipelining documentation covers it.

Model details#

This tutorial trains a 16-layer truncation of Llama 3 70B:

  • Module: torchtitan_neuron.models.llama3

  • Config: llama3_70b_16layers_fullac_compile

  • Model: the first 16 decoder layers of Llama 3 70B (hidden size 8192), with the full-size token embedding and output projection

  • Execution: torch.compile with the Neuron backend, compiled per transformer block, with full activation checkpointing

  • Batch: local batch size 8, sequence length 8192, on the bundled c4_test split

The recipe sets no pipeline parallelism. You add it on the command line:

Override

Value

Effect

--parallelism.pipeline_parallel_degree

4

Four pipeline ranks, so one stage on each node for 1F1B.

--parallelism.tensor_parallel_degree

4

The recipe inherits TP8 from upstream llama3_70b. TP4 matches the four logical NeuronCores of one Trainium2 device.

--parallelism.pipeline_parallel_schedule

1F1B, then Interleaved1F1B

The pipeline schedule.

FSDP takes the remaining ranks: 256 ÷ (4 × 4) = 16. Each rank processes a local batch of 8 sequences, split into 8 microbatches of one sequence each (local_batch_size ÷ pipeline_parallel_microbatch_size). The global batch is 8 × 16 = 128 sequences.

Limitations:

  • PyTorch 2.14 does not support the zero-bubble schedules (ZBVZeroBubble, InterleavedZeroBubble, and DualPipeV) with torch.compile. Use 1F1B or Interleaved1F1B.

  • PP is not available with the SimpleFSDP (GraphTrainer) recipes in this release. GraphTrainer’s pipeline path needs the aot_fx_trace compile mode, and on Neuron SimpleFSDP supports only the jit mode. Use the torchtitan_neuron.models recipes for PP.

Note

The attention backend these recipes use applies causal attention but does not consume TorchTitan’s packed-document boundaries. A sequence that holds more than one document therefore lets tokens attend across the boundary into earlier, unrelated documents. The Neuron recipes do not currently offer a backend that masks this, and the backend is fixed by the recipe rather than settable on the command line. If strict cross-document isolation matters for your workload, confirm that this limitation is acceptable before you build on this path.

Prerequisites#


Prepare your environment#

Work from the torchtitan-neuron directory that you installed in How to set up TorchTitan Neuron. Every node must have the same environment: torch-neuronx, the torchtitan-neuron directory at the same path, and a hostfile that lists each node with one slot. These are the requirements of the multi-node launch in Multi-node with MPI.

The training steps use the run_train.sh wrapper and the NGPU, MODULE, and CONFIG environment variables from the basic tutorial. Extra arguments pass through to torchtitan.train, which is how you add pipeline parallelism.

Important

Steps 2 to 4 run ten steps each on c4_test, a small split bundled with the repository, with a bundled tokenizer. They confirm that the pipeline is wired correctly, so they need no network access and no Hugging Face token. A loss curve from a run like that tells you little about the model.

Step 1: Check point-to-point transfers#

In this step, you will confirm that two NeuronCores can exchange tensors over RDMA, first on one node and then across all four nodes. A pipeline that cannot transfer data between stages fails or hangs on its first step, so this check saves a long launch.

Save this script as p2p_check.py on every node, at the same path:

import os

import torch
import torch.distributed as dist
import torch_neuronx  # Registers the Neuron device and distributed backend.

rank = int(os.environ["RANK"])
world_size = int(os.environ["WORLD_SIZE"])
dist.init_process_group(
    backend="neuron", init_method="env://", rank=rank, world_size=world_size,
)
try:
    device = torch.device("neuron")
    numel = 16 * 1024 * 1024  # 32 MiB of bfloat16, one stage-boundary slice
    next_rank = (rank + 1) % world_size
    prev_rank = (rank - 1) % world_size

    send_buf = torch.full((numel,), float(rank), dtype=torch.bfloat16, device=device)
    recv_buf = torch.empty(numel, dtype=torch.bfloat16, device=device)
    ops = [
        dist.P2POp(dist.isend, send_buf, next_rank),
        dist.P2POp(dist.irecv, recv_buf, prev_rank),
    ]
    for work in dist.batch_isend_irecv(ops):
        work.wait()

    received = recv_buf.cpu()
    assert bool((received == prev_rank).all()), f"rank {rank}: bad data from {prev_rank}"
    print(f"rank={rank}: received {numel} elements from rank {prev_rank}", flush=True)
finally:
    dist.destroy_process_group()

Each rank sends a tensor to the next rank in a ring and receives one from the previous rank, in one batched exchange. This is the pattern a pipeline stage uses. The receiving rank checks every element, so a corrupted or misrouted transfer fails the check.

Run it with two workers on one node:

torchrun --standalone --nproc-per-node=2 p2p_check.py

Both workers print a line, for example rank=1: received 16777216 elements from rank 0. Then run it with one worker on each of the four nodes, so that every transfer crosses the network as a stage boundary does:

mpirun --allow-run-as-root -np 4 --hostfile <hostfile> \
  -x PATH=<venv-path>/bin:$PATH -x CCOM_SOCKET_IFNAME=eth0 \
  bash -c 'torchrun --nnodes=4 --nproc-per-node=1 \
    --rdzv-backend=c10d --rdzv-endpoint=<node-0 address>:29500 \
    /path/to/p2p_check.py'

All four ranks print a line. If a run fails or hangs, see Common issues before you continue.

Step 2: Launch a four-stage pipeline with 1F1B#

In this step, you will train with four pipeline stages, one on each node, with the 1F1B schedule. In steady state, 1F1B alternates one forward and one backward pass on each stage. This keeps at most p microbatches of activations in flight on a stage.

Run this command on the launcher:

mpirun --allow-run-as-root -np 4 --hostfile <hostfile> --tag-output \
  -x PATH=<venv-path>/bin:$PATH -x CCOM_SOCKET_IFNAME=eth0 \
  -x NEURON_LOGICAL_NC_CONFIG=2 -x NEURON_RT_NUM_CORES=64 \
  -x TORCH_NEURONX_STALL_TIMEOUT=1800 \
  bash -c 'cd /path/to/torchtitan-neuron && \
  NGPU=64 NNODES=4 RDZV_ENDPOINT=<node-0 address>:29500 LOG_RANK=0,192 \
  MODULE=torchtitan_neuron.models.llama3 \
  CONFIG=llama3_70b_16layers_fullac_compile \
  ./run_train.sh \
    --training.steps 10 \
    --hf_assets_path ./tests/assets/tokenizer \
    --parallelism.tensor_parallel_degree 4 \
    --parallelism.pipeline_parallel_degree 4 \
    --parallelism.pipeline_parallel_schedule 1F1B \
    --comm.init_timeout_seconds 1800'

Most of the command is the multi-node launch from the basic tutorial. The parts that are specific to PP are:

  • --parallelism.pipeline_parallel_degree 4 and --parallelism.pipeline_parallel_schedule 1F1B turn on the pipeline. The TP override and the FSDP degree are described in Model details.

  • --tag-output makes mpirun tag each output line with the index of the node that printed it. Only the last stage computes the loss, so you need to tell the nodes apart.

  • LOG_RANK=0,192: run_train.sh uses LOG_RANK for two things. torchrun shows the console output only of the listed local ranks on each node, so 0 shows the first rank of every node. Each node holds one stage, so this is also the first rank of every stage. TorchTitan checks that the global rank that reports the loss is listed, and warns if it is not. That rank is the first rank of the last stage: (256 ÷ 4) × 3 = 192.

  • TORCH_NEURONX_STALL_TIMEOUT=1800 and --comm.init_timeout_seconds 1800 give the first step room to compile. With a cold compile cache, the stages compile one after another: a stage compiles its forward pass only when the activation from the previous stage arrives. So the last stages wait on the compiles of the earlier ones, and the backward pass waits in the other direction. A transfer that waits longer than the stall timeout (600 seconds by default) fails. You can drop both settings once the compile cache is warm.

The first step takes much longer than the steps after it. Each stage compiles its own graphs: the first stage also compiles the embedding, and the last stage also compiles the output projection and the loss. The compiled graphs are cached on disk, so later runs with the same configuration start faster.

Watch the log for the line that confirms the schedule:

Using pipeline schedule 1F1B with 8 microbatches and 4 stages.

Then read the per-step lines from the node that holds the last stage (index 3), which report the training loss. The other nodes print a constant negative placeholder in the loss field (-16.0 with this layout), because they have no loss to report. That placeholder is expected. The grad_norm field is computed across all stages, so every node prints the same value. The memory field differs by node, because each stage holds different layers.

Note

1F1B needs at least as many microbatches as stages. A local batch size smaller than pipeline_parallel_degree fails when the schedule is built. With this recipe, 8 microbatches over 4 stages is well above that limit.

Neuron settings for pipeline parallelism#

The defaults are right for pipeline training. These are the settings that change how stage-to-stage transfers behave:

Variable

Default

Effect on PP

TORCH_NEURONX_STALL_TIMEOUT

600

Seconds. Also caps the deadline of a P2P transfer. Raise it for a first run with a cold compile cache. 0 turns off stall detection.

TORCH_NEURONX_ENABLE_STREAMS

1

With 1, transfers run on a dedicated P2P stream and wait() does not block the CPU. With 0, wait() blocks the CPU until the transfer lands. Keep the default.

TORCH_NEURONX_LOG_LEVEL

1

Set to 2 to log transport setup and, every 60 seconds, each transfer that is still waiting and what it is waiting for. Use it to find which neighbor a stalled stage waits on.

NEURON_RT_MAP_HBM

1

torch-neuronx sets this at import. The RDMA path needs it to register device memory. Do not set it to 0.

For the full list, see TorchNeuron environment variables.

Step 3: Switch to the Interleaved 1F1B schedule#

In this step, you will put two stages on each rank to shrink the bubble.

Interleaved1F1B cuts the model into 8 stages of about two layers each, and assigns stages r and r + 4 to pipeline rank r. Each microbatch passes through every node twice. The bubble shrinks because a node can work on its second stage while the next node works on its first. With 4 pipeline ranks and 8 microbatches, the bubble is about 27% of the step for 1F1B and about 16% for Interleaved 1F1B.

Run the command from Step 2 with one change:

--parallelism.pipeline_parallel_schedule Interleaved1F1B

You do not change the pipeline degree: pipeline_parallel_degree counts ranks, not stages. TorchTitan gives multi-stage schedules two stages on each rank by default. The log confirms the new layout:

Using pipeline schedule Interleaved1F1B with 8 microbatches and 8 stages.

The last stage is still on pipeline rank 3, so the loss is again on node 3 and LOG_RANK=0,192 still applies. Compare the tps and mfu fields of this run with those of Step 2.

Interleaving has two costs. Each microbatch crosses twice as many stage boundaries, which the non-blocking transport overlaps with compute. Each rank also keeps more microbatches in flight, which raises peak memory. Check the memory field against the 1F1B run.

Step 4: Balance the stages and tune the pipeline#

In this step, you will even out the work across the stages, and learn the other settings that matter for a pipeline.

Balance the stages#

A pipeline runs at the pace of its slowest stage. By default, TorchTitan counts the token embedding as one layer of work for the first stage, and the output projection as one layer for the last stage. It then splits the rest of the layers evenly. For this model that gives four ranks with 4, 5, 4, and 3 decoder layers. The embedding is only a table lookup, so the second rank, with five layers, is the slowest.

Set both weights to zero to give every rank four layers:

--parallelism.pipeline_parallel_first_stage_less_layers 0 \
--parallelism.pipeline_parallel_last_stage_less_layers 0

Add these two lines to the command of Step 2 or Step 3. With 1F1B, the stages become: the embedding and layers 0-3, layers 4-7, layers 8-11, and layers 12-15 with the output projection. With Interleaved 1F1B, every one of the 8 stages gets two layers. The last rank is still a little heavier, because it also runs the output projection and the loss. With whole layers, this is as even as this model gets.

For a split that the two weights cannot express, list the modules of each stage in parallelism.module_fqns_per_model_part in your config. The module names are tok_embeddings, layers.<n>, norm, and lm_head.

Use more microbatches, not gradient accumulation#

The number of microbatches is local_batch_size ÷ pipeline_parallel_microbatch_size. More microbatches shrink the bubble: with --training.local_batch_size 16, the bubble falls to about 16% of the step for 1F1B and about 9% for Interleaved 1F1B. This also doubles the global batch to 256 sequences, so choose a value that fits your training recipe. Peak memory can grow with the number of microbatches, so check the memory field as you raise it.

Do not reach a larger global batch through gradient accumulation (a --training.global_batch_size above local_batch_size × the FSDP degree). Under PP, each accumulation step drains and refills the pipeline, so you pay the bubble once for each accumulation step. A larger local_batch_size reaches the same global batch with one bubble per step.

Trade throughput for memory#

With PP, TorchTitan keeps the parameters of each stage unsharded from the first forward pass of a step until its gradient reduction. This saves an FSDP all-gather for every microbatch, but every rank holds its stage’s full parameters for the whole step. If a run is out of memory, reshard after every forward pass instead:

--parallelism.fsdp_reshard_after_forward always

This lowers peak memory noticeably, at a throughput cost for the extra all-gathers. The recipe already uses full activation checkpointing, so this setting is the next lever before you lower the batch size.

Confirmation#

The runs succeeded if all of the following hold, for each schedule that you ran:

  • The log reports the schedule, the number of microbatches, and the number of stages that you expect.

  • Node 3 prints per-step loss lines, and the loss values are finite (never nan) and lower by the tenth step than at the first.

  • The other nodes print the constant placeholder loss and the same grad_norm as node 3.

  • neuron-top shows the NeuronCores in use on every node.

  • The second step completes much faster than the first, because only the first step pays the one-time compile cost.

Congratulations! You have now trained a model with pipeline parallelism across four Trainium nodes. If you encountered any issues, see the Common issues section below.


Common issues#

  • The run fails at startup with Number of microbatches (N) must be greater than or equal to the number of stages: 1F1B needs at least one microbatch for each stage. Raise --training.local_batch_size to at least pipeline_parallel_degree.

  • The run fails at startup with Interleaved 1F1B requires the number of microbatches to be a multiple of the number of rounds: use a number of microbatches that is a multiple of pipeline_parallel_degree.

  • A stage fails with RDMA P2P timeout after ... ms; unfinished [...]: a neighbor stage did not send or receive in time. The bracketed list names each transfer that is still waiting, with its peer rank and tag. First, look in the log of that peer: it might have failed, or still be compiling. On a first run with a cold compile cache, raise TORCH_NEURONX_STALL_TIMEOUT and --comm.init_timeout_seconds as in Step 2. To see what a stage waits for while it waits, set TORCH_NEURONX_LOG_LEVEL=2.

  • The first transfer fails with libfabric.so.1 not available: EFA is not installed, or its libraries are not on the library path of the process. Install EFA as in Prerequisites. In a container, add the EFA library directory, for example /opt/amazon/efa/lib, to LD_LIBRARY_PATH, and pass it with -x to mpirun.

  • The first transfer fails with nrt_get_attached_efa_bdf failed: the process cannot see the EFA device that is attached to its NeuronCore. In a container, make the EFA devices of the host visible to the container.

  • TorchTitan warns Pipeline Parallel loss is not visible: the global rank that reports the loss is not in LOG_RANK. Add it, as in Step 2. The warning does not change the training.

  • Loss lines show a negative constant: you are reading a node that does not hold the last stage. Read the lines from the last node.

  • Out of memory: the recipe already uses full activation checkpointing. Set --parallelism.fsdp_reshard_after_forward always. If the run is on Interleaved 1F1B, try 1F1B, which keeps fewer microbatches in flight. Lower the local batch size last, because it grows the bubble. See Best practices for TorchTitan Neuron.

  • The run hangs at startup: NGPU must match the NeuronCores on each node (64 on a trn2.48xlarge), and NNODES and -np must match the number of nodes. Confirm with neuron-ls on each node.

  • “Config function not found”: MODULE needs the path to the Neuron recipe module, torchtitan_neuron.models.llama3. llama3 resolves to the upstream registry, which has no Neuron recipes.

Clean up#

Stop the training processes with Ctrl-C on the launcher. mpirun forwards the interrupt to the per-node processes and tears down the job on every node. Remove the output that TorchTitan wrote under ./outputs and the p2p_check.py script if you no longer need them. Stop or terminate the instances, because they bill while they run.

Note

Running on Trn3: The instance-dependent values on this page, such as the number of ranks per node, the device memory (HBM) per rank, NEURON_RT_NUM_CORES, and the device mesh shapes, are for Trn2 (trn2.48xlarge). Trn3 servers have a different number of Trainium chips, so these values do not apply to Trn3 without change. Before you run on Trn3, calculate them again from the Amazon EC2 Trn3 architecture and Trainium3 architecture specifications. For the effect of the LNC setting on the number of visible cores, see Logical NeuronCore configuration.

Next steps#

Further reading#

This document is relevant for: Trn2, Trn3