Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions training/rdsp/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
__pycache__/
*.pyc
.venv/
.pytest_cache/
.ruff_cache/
.cache/
.DS_Store
*.egg-info/
dist/
build/

# raw run logs and profiles
bench/results/

# bench_oct10: the working folder of the October-November benchmark rounds
# (plans, queues, notes, raw logs, profiles).
bench_oct10/

# what the bench/ scripts write when they run stays local...
bench/**/logs*/*
bench/**/profiles*/
bench/**/prep/
bench/mimo_vs_rdsp/sweep/
bench/mimo_vs_rdsp/convert.log
*.sqlite
*.nsys-rep
*.qdrep
*.pt.trace.json
*.dmon

# benchmark logs and raw results stay local: docs/REPRODUCE.md names the log
# each run writes; the write-ups (*.md) are kept
bench/published/
bench/blog_round/logs27b/
bench/encoder_test/results/**
!bench/encoder_test/results/**/
!bench/encoder_test/results/**/*.md
bench/torchtitan/results/data_check.txt

# nCompass profiling plugin's working files
ncompass/
167 changes: 167 additions & 0 deletions training/rdsp/CONTEXT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
# rdsp

Pipeline-parallel training in which one CPU process hands each GPU its work and every GPU trains its share of the model with DeepSpeed. This glossary fixes the words we use for rdsp and for comparing it with Megatron-Bridge and MegatronMIMO.

## Language

### Processes

**Driver**:
The single CPU process that plans each training step and gives every GPU its work. It holds no model weights and no activations.
_Avoid_: controller, master, launcher

**Stage worker**:
The Ray actor that owns one GPU and trains that GPU's part of one stage.
_Avoid_: worker, actor, rank (a rank is a number in a group, not the process)

### Pipeline layout

**Stage**:
A consecutive slice of the model, together with the GPUs that train it. The first stage can also hold the vision encoder, and the last stage holds the loss.
_Avoid_: partition, pipeline rank, module (MegatronMIMO uses "module" for a whole sub-model)

**Stage world**:
The `torch.distributed` group of one stage's GPUs. Tensor and data parallelism happen inside it, and it does not know that other stages exist.
_Avoid_: process group, mesh

**Cross-stage groups**:
The two NCCL groups, `fwd` and `bwd`, that span every GPU and carry only boundary tensors.
_Avoid_: P2P world, pipeline group

**Boundary tensor**:
The activation sent forward to the next stage, or its gradient sent back, for one microbatch.
_Avoid_: message, payload

**Cut**:
The number of decoder layers each stage holds, written in stage order, e.g. 13 | 19.
_Avoid_: split, partition, boundary

**Balanced cut**:
rdsp's default cut. It gives each stage an equal share of the estimated compute, and that estimate includes the vision encoder.
_Avoid_: auto cut, smart cut

**Measured cut**:
A balanced cut redone from what a few profiled steps measured: each stage's time per step, and its memory as a limit on how many layers it may gain.
_Avoid_: calibrated cut, tuned cut

**Even cut**:
A cut with the same number of decoder layers on every stage. Megatron uses it by default, and it does not count the vision encoder.
_Avoid_: uniform split, default split

### Vision placement

**Shared first stage**:
The vision encoder runs on the first stage's GPUs, ahead of that stage's decoder layers.
_Avoid_: colocated, encoder on stage 0

**Vision-only stage**:
The vision encoder is a stage of its own and holds no decoder layers.
_Avoid_: non-colocated, separate encoder

**Replicated encoder**:
Every GPU holds a copy of the vision encoder outside the pipeline. Each copy encodes a share of the images and sends the features to the first stage.
_Avoid_: colocated vision, colocated

### Parallelism inside a stage

**DP copy**:
One of a stage's data-parallel replicas. It holds the stage's full slice of the model (split across its TP GPUs) and trains on different rows from the other copies.
_Avoid_: replica, DP rank

### Training step

**Row**:
One training sample (an image, its prompt and its answer) as a single token sequence.
_Avoid_: sample, example, sequence

**Step**:
One optimizer update, covering every row of the batch.
_Avoid_: iteration

**Microbatch**:
The group of rows that moves through the pipeline as one unit.
_Avoid_: chunk, minibatch

**Microbatch count**:
How many microbatches make up one step. It sets the size of the bubble.
_Avoid_: accumulation steps, number of microbatches

**Microbatch size**:
The number of rows in one microbatch, counted across all DP copies of a stage.
_Avoid_: batch size, micro batch size per GPU

**Job list**:
The ordered forwards and backwards that one stage runs in one step, delivered to it in a single call.
_Avoid_: op list, command list, schedule

**1F1B**:
The job-list order in which a stage runs its warm-up forwards and then alternates one forward with one backward.
_Avoid_: interleaved schedule, PipeDream

**Bubble**:
The share of a step during which a stage sits idle, waiting for a neighbouring stage.
_Avoid_: pipeline stall, idle time

**Apply**:
The optimizer update at the end of a step. It starts on any stage only after every stage has finished all its backwards.
_Avoid_: optimizer step, update

### Model

**GDN layer**:
A Gated DeltaNet decoder layer: Qwen3.5's linear-attention layer type. Qwen3.5-4B has 24 of them next to 8 full-attention layers.
_Avoid_: linear layer, DeltaNet, SSM layer

**Remainder master**:
Exact fp32 master weights kept as the bf16 weights plus the 16 bits the rounding dropped, 2 bytes per parameter instead of 4.
_Avoid_: bf16 master (that one is not exact), compressed master

**Untied output layer**:
The last stage's own copy of the output-layer weight, which the original model shares with the input embedding on stage 0.
_Avoid_: lm head copy, duplicated embedding

### Failure

**Rebuild**:
Recovery that replaces every stage worker and reloads the last checkpoint, while the driver and the Ray cluster keep running.
_Avoid_: restart, failover, elastic recovery

### Data and loss

**Replayed data**:
The rows that Megatron-Bridge exported, given to rdsp in the same order and the same microbatch groups, so that both systems train on identical input.
_Avoid_: shared dataset, same data

**Real token**:
A position that holds an actual token of the row: an image, prompt or answer token.
_Avoid_: valid token, non-pad token

**Answer token**:
A real token from the row's answer. It is the only kind of token with a label, so it is the only kind that counts in the loss.
_Avoid_: caption token, supervised token, label token

**Padding**:
Positions added after a row's last real token so that the rows in a microbatch share one length. They are computed, but they never count in the loss.
_Avoid_: pad tokens, filler

**Positions per real token**:
The number of positions computed, divided by the number of real tokens. It measures how much compute goes to padding.
_Avoid_: padding ratio, efficiency

**Token-mean loss**:
A step's loss taken as the plain average over every answer token in the step, whichever microbatch or GPU holds the token.
_Avoid_: per-token loss, global mean

**Microbatch-mean loss**:
A step's training loss taken as the average of each rank-microbatch's own answer-token average: each data-parallel rank's share of a microbatch is averaged on its own. Tokens in rank-microbatches with fewer answer tokens count for more. The reported loss is still the token mean.
_Avoid_: per-microbatch loss, mean of means

### Comparison

**Recipe comparison**:
A benchmark with the same layout, data, batch, microbatch count, optimizer and loss on both systems. Each system keeps its own padding, cut and kernels.
_Avoid_: same settings, apples-to-apples, fair comparison

**Equal-work comparison**:
A recipe comparison in which both systems also compute the same token positions.
_Avoid_: same settings, apples-to-apples
117 changes: 117 additions & 0 deletions training/rdsp/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
# rdsp: pipeline parallelism on Ray + DeepSpeed

rdsp (`ray_deepspeed_pipeline`) splits a model into pipeline stages and gives each stage its own GPU count and parallel layout. You can split a Hugging Face vision-language model so the vision encoder gets its own stage, and train it from the HF checkpoint without converting it.

![rdsp architecture. The driver cuts the model into stages and sends every GPU its schedule and batch. Each stage has its own group of GPUs, and every GPU is a Ray actor running a DeepSpeed engine. Activations go forward and gradients come back directly between the GPUs of neighbouring stages.](docs/images/architecture.png)

Every stage is a group of Ray actors, one per GPU, each running a stock DeepSpeed engine. Stages pass activations and gradients to each other directly over NCCL; the driver only plans and schedules.

## Results

Qwen3.5 vision-language models on H100 GPUs, trained on CORD-v2. Median time per training step; lower is better.

| Model | GPUs | rdsp | Megatron-Bridge | TorchTitan |
|---|---|---|---|---|
| Qwen3.5-35B-A3B (mixture of experts) | 16, two nodes | **6.38 s** | 8.67 s | 9.11 s |
| Qwen3.5-27B (dense) | 8, one node | **10.66 s** | 15.13 s | 13.16 s |

- On the 35B that is 1.36× Megatron-Bridge's throughput and 1.43× TorchTitan's; on the 27B, 1.42× and 1.23×. With two rows per microbatch, the fastest setting for both pipelines on the 27B, rdsp is 1.05× Megatron-Bridge.
- On MegatronMIMO's own layouts, with one GPU for the vision encoder, rdsp runs at 0.99–1.09× MIMO's throughput.
- rdsp ran the 35B with the vision encoder on its own 4-GPU stage and six 2-GPU language stages, and the 27B as eight 1-GPU stages, each choosing how many of its layers to recompute. Megatron-Bridge used the layout of NVIDIA's H100 recipe on the 35B and rdsp's eight-stage split on the 27B. TorchTitan sharded over all GPUs, with expert parallelism on the 35B.

One run per configuration. Settings and commands for each number: [docs/REPRODUCE.md](docs/REPRODUCE.md). Earlier Qwen3.5-2B and 4B results on 8 GPUs: [docs/BENCHMARK_RESULTS.md](docs/BENCHMARK_RESULTS.md).

## Install

Linux, CUDA GPUs, Python 3.12. On a fresh node:

```bash
bash bench/setup_node.sh
```

This builds `~/venv` with torch, DeepSpeed at the commit every result was measured with, and rdsp, and pulls the container the Megatron comparisons run in. To install by hand, or without the container: [docs/GETTING_STARTED.md](docs/GETTING_STARTED.md#install).

Importing `ray_deepspeed_pipeline` doesn't import Ray or DeepSpeed; only the stage actors do.

## Quickstart

```bash
./recipes/qwen35-2b-tp2pp2dp2.sh # Qwen3.5-2B on CORD-v2, 8 GPUs
./recipes/qwen35-2b-tp2pp2dp2.sh --steps 200 # extra flags override the recipe
```

`recipes/` has one script per benchmarked layout, plus a text-only Qwen3 recipe. [docs/GETTING_STARTED.md](docs/GETTING_STARTED.md) covers the flags, your own data, and common failures.

## Python API

```python
import ray, ray_deepspeed_pipeline as rdsp

def count_tokens(labels): # tokens the loss is computed on
return int((labels[:, 1:] != -100).sum())

ray.init()
engine, _, _, _ = rdsp.initialize(
model=model, # HF model, built under accelerate.init_empty_weights()
weights="/path/to/hf/checkpoint", # each stage loads only its own tensors
config=ds_config, # DeepSpeed config dict
loss_fn=rdsp.TokenMeanLoss(rdsp.next_token_loss_sum, count_tokens), # mean over the step's tokens
pipeline_config=rdsp.PipelineConfig(
stages=2,
partition=rdsp.BalancedTransformerBlocks(vision_token_ratio=ratio),
stage_overrides=(rdsp.StageOverride(stage=0, num_gpus=4, tp=2, zero_stage=1),
rdsp.StageOverride(stage=1, num_gpus=4, tp=2, zero_stage=1)),
),
)
loss = engine.train_batch(data_iter) # consumes exactly M (inputs, labels) entries
engine.save_checkpoint("ckpt/", tag="step100")
```

If the input embedding and output layer share a weight and land on different stages, untie them first (`train_vl.py --untie-embeddings`); on one stage they stay tied. Every public name, what it guarantees and what it raises are listed in [docs/CONTRACTS.md](docs/CONTRACTS.md). `train_vl.py` is a complete training script.

## How it works

- **Planning.** `rdsp.initialize` lowers the config into an immutable plan: where the model is cut, each stage's GPUs and DeepSpeed config, and a hash that binds checkpoints. Every check, including the cluster's GPU count, runs before any actor starts.
- **Stages.** Each stage runs the HF model's own `forward`. Blocks outside the stage pass their input through, and a hook injects what arrived from upstream. No per-architecture code is needed.
- **Step.** The driver hands each stage its 1F1B schedule, which interleaves forward and backward microbatches. Each stage applies its optimizer step only after every stage reports its backward done.
- **Failures.** A failure before any update raises `StepFailed`: weights are unchanged and a retry is exact. A failure during the update raises `PipelinePoisoned` until a checkpoint is loaded.

Vision encoder placement, how the cuts are chosen, memory, and the reasoning behind the design: [docs/ENGINEERING.md](docs/ENGINEERING.md).

## Model coverage

| Builder | Models | Validation |
|---|---|---|
| `HFModelStage` | Any HF model with a `config`: Llama, Mistral, Qwen2/3/3.5, Qwen3-MoE, Mixtral, Gemma 1–3, Phi-3, OLMo2, Granite, Cohere, StarCoder2, StableLM, DeepSeek-V3, GLM-4/4-MoE/5.3, GPT-2, GPT-NeoX, Falcon, Bloom, Mamba, Qwen3-VL, Qwen3.5-VL | Pipeline loss equals the unsplit model's on CPU (`tests/integration/test_hf_families.py`). Qwen3, Qwen3-MoE and Qwen3.5-VL validated on GPU. |
| `CausalLMStage` | Llama, Qwen3, Qwen3-MoE | GPU-validated in every layout in CONTRACTS.md |
| `GenericSequentialStage` | Plain sequential models | CPU |

TP inside a stage uses the model's AutoTP plan. Configs without one get a plan for the standard projection names. Qwen3-VL injects vision features into its first decoder blocks, so its encoder can't be colocated and the first cut must come after them.

## Tests

```bash
pytest -q # CPU: full runtime on Ray with a stub engine (~500 tests); GPU tests skip
ruff check .
```

The GPU tests (parity against the unsplit model, checkpoint round trip, rank-kill recovery) run on Modal: `scripts/modal_tests.py`.

## Docs

| | |
|---|---|
| [GETTING_STARTED](docs/GETTING_STARTED.md) | Install, terms, recipes, flags, your own data, common failures |
| [REPRODUCE](docs/REPRODUCE.md) | Rerun the benchmarks |
| [BENCHMARK_RESULTS](docs/BENCHMARK_RESULTS.md) | Qwen3.5-2B and 4B results, per-layout settings, what moved the numbers |
| [CONTRACTS](docs/CONTRACTS.md) | Public API guarantees, errors, supported layouts |
| [ENGINEERING](docs/ENGINEERING.md) | Design |

## Limitations

- **Scale.** Benchmarked on one 8-GPU node and on two 8× H100 nodes. Two nodes is the most it has run on.
- **Schedule.** 1F1B only, no interleaved stages. No global-norm gradient clipping: a nonzero `gradient_clipping` is rejected.
- **Weights.** No parameters tied across stages.
- **Colocated vision.** It matches the unsplit model. On 32 GB GPUs it needs encoder recompute and is slower; on 80 GB H100s it was the fastest Qwen3.5-4B layout.
- **Balanced cuts.** The cost model ignores communication and counts MoE experts in full, not by the active fraction. `ExplicitCuts` overrides it.
- **Checkpoints.** Node-local: they survive actor loss, not node loss. A stage that spans nodes needs shared storage.
Loading