diff --git a/training/rdsp/.gitignore b/training/rdsp/.gitignore
index fc99446af..d27302bf5 100644
--- a/training/rdsp/.gitignore
+++ b/training/rdsp/.gitignore
@@ -9,51 +9,12 @@ __pycache__/
dist/
build/
-# raw results of the old Modal Qwen3-0.6B grid
-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: each experiment's logs/ folder (logs,
-# profiles, prep output, the result notes kept beside them)
-bench/*/logs/
+# what the bench/ scripts write when they run stays local: logs, profiles, prep output
+bench/**/logs*/
+*.log
+*.out
*.sqlite
*.nsys-rep
*.qdrep
*.pt.trace.json
*.dmon
-
-# kept on disk, not in the repository: the old Modal Qwen3-0.6B grid, one-off checks and tools
-bench/modal_bench.py
-bench/modal_smoke.py
-bench/analyze.py
-bench/megatron_hf_loop.py
-bench/megatron_pretrain.sh
-bench/rdsp_bench.py
-bench/bench_hooks.py
-bench/torchtitan/checks/
-bench/cluster/three.sh
-bench/cluster/ray_cluster3.sh
-bench/mimo/nsys_breakdown.py
-tests/unit/test_nsys_breakdown.py
-bench/encoder/summarize.py
-bench/encoder/sync_stacks.py
-
-# kept on disk, not in the repository: internal notes, slides, the Modal runners, recipes without
-# a published result
-CONTEXT.md
-docs/CODING_STANDARDS.md
-docs/CONTRACTS.md
-docs/P0.md
-docs/REPRODUCE.md
-docs/presentation/
-docs/research/
-scripts/
-recipes/qwen35-4b-vision1-tp2pp2.sh
-recipes/qwen35-4b-vision1-tp4.sh
-recipes/qwen35-4b-vision2-tp2dp2.sh
-
-# nCompass profiling plugin's working files
-ncompass/
diff --git a/training/rdsp/README.md b/training/rdsp/README.md
index 157004811..3e1d24546 100644
--- a/training/rdsp/README.md
+++ b/training/rdsp/README.md
@@ -4,7 +4,7 @@ rdsp (`ray_deepspeed_pipeline`) splits a model into pipeline stages and gives ea

-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.
+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
@@ -12,104 +12,66 @@ Qwen3.5 vision-language models on H100 GPUs, trained on CORD-v2. Median time per
| 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 |
+| Qwen3.5-35B-A3B (mixture of experts) | 16, two nodes | **5.41 s** | 7.93 s | 8.93 s |
+| Qwen3.5-27B (dense) | 16, two nodes | **11.52 s** | 13.39 s | 13.36 s |
+| Qwen3.5-9B (dense) | 16, two nodes | **3.17 s** | 3.23 s | 4.93 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 recomputing its own number of layers. Both measured their own cuts. 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.
+That is 1.47× Megatron-Bridge's throughput and 1.65× TorchTitan's on the 35B, 1.16× and 1.16× on the 27B, and 1.02× and 1.56× on the 9B, where 1.02× is a tie. Against MegatronMIMO on MIMO's own layouts, rdsp's throughput is 1.04× on the 9B (16 GPUs) and 1.05× on the 27B (9 GPUs, two rows per microbatch). MIMO cannot train the 35B.
-One run per configuration. Settings and commands for each number: [docs/GETTING_STARTED.md](docs/GETTING_STARTED.md#reproducing-the-blogs-results). Earlier Qwen3.5-2B and 4B results on 8 GPUs: [docs/BENCHMARK_RESULTS.md](docs/BENCHMARK_RESULTS.md).
+rdsp's 35B and 27B numbers, and its MIMO comparisons, are three runs averaged (MIMO's are two); every other number is one run. Layouts and caveats: [docs/BENCHMARK_RESULTS.md](docs/BENCHMARK_RESULTS.md). Settings and commands: [bench/compare/README.md](bench/compare/README.md).
## Install
-Linux, CUDA GPUs, Python 3.12. On a fresh node:
+Linux with CUDA GPUs and Python 3.12. On every node:
```bash
-bash bench/setup_node.sh
+bash install.sh && source .venv/bin/activate
```
-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 ([docs/GETTING_STARTED.md](docs/GETTING_STARTED.md#install)).
-
-Importing `ray_deepspeed_pipeline` doesn't import Ray or DeepSpeed; only the stage actors do.
+On a Mac it installs everything except the Linux-only GPU kernels. There, `rdsp train MODEL --cpu` trains a small text model on the CPU to try rdsp out; real training needs NVIDIA GPUs.
## 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
+rdsp setup # first node: starts a Ray cluster and prints the join command
+rdsp setup --join
# every other node: the command the first node printed
+rdsp train Qwen/Qwen3.5-9B # every GPU in the cluster
```
-`recipes/` has one script per Qwen3.5-2B and 4B layout in [docs/BENCHMARK_RESULTS.md](docs/BENCHMARK_RESULTS.md), plus a text-only Qwen3 recipe; the 9B to 35B runs are scripts in `bench/`. [docs/GETTING_STARTED.md](docs/GETTING_STARTED.md) covers the flags, your own data and the environment variables.
+`rdsp train` decides what you don't set: pipeline stages (`-pp`, the fewest that fit in memory, each inside one node), tensor parallelism (`-tp`, 1) and data-parallel copies of each stage (`-dp`, the remaining GPUs). It prints the layout and the command before it runs. `--tune` times the stages first and re-cuts them by the times; a vision-language model's vision encoder also gets a stage of its own, sized by the timing. Flags after `--` go to the training script. On one machine, skip `rdsp setup`. More: [docs/GETTING_STARTED.md](docs/GETTING_STARTED.md).
## 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())
+import ray
+import ray_deepspeed_pipeline as rdsp
ray.init()
engine, _, _, _ = rdsp.initialize(
- model=model, # HF model, built under accelerate.init_empty_weights()
+ 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
+ config=ds_config, # an ordinary DeepSpeed config
+ loss_fn=rdsp.TokenMeanLoss(), # next-token loss, averaged 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)),
+ partition=rdsp.BalancedTransformerBlocks(),
+ stage_overrides=(
+ rdsp.StageOverride(stage=0, num_gpus=4, tp=2),
+ rdsp.StageOverride(stage=1, num_gpus=4, tp=2),
+ ),
),
)
-loss = engine.train_batch(data_iter) # consumes exactly M (inputs, labels) entries
+loss = engine.train_batch(data_iter) # one optimizer step
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. The docstrings in `src/ray_deepspeed_pipeline/` give each public name's guarantees and errors. `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`, `tests/integration/test_vl_pipeline.py`). Qwen3, Qwen3-MoE and Qwen3.5-VL validated on GPU. |
-| `CausalLMStage` | Llama, Qwen3, Qwen3-MoE | GPU-validated in every layout in `src/ray_deepspeed_pipeline/support_matrix.py` |
-| `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 (about 630 tests); GPU tests skip
-ruff check .
-```
-
-On a node with GPUs and DeepSpeed (`bench/setup_node.sh`), the same command also runs the GPU tests: parity against the unsplit model, checkpoint round trip and rank-kill recovery.
+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. The docstrings in `src/ray_deepspeed_pipeline/` give each public name's guarantees and errors. `train_vl.py` is a complete training script, and [examples/](examples) trains Qwen3.5-9B, 27B and 35B-A3B with the Python API on 16 GPUs.
## Docs
| | |
|---|---|
-| [GETTING_STARTED](docs/GETTING_STARTED.md) | Install, recipes, flags, environment variables, rerunning the benchmarks |
-| [BENCHMARK_RESULTS](docs/BENCHMARK_RESULTS.md) | Qwen3.5-2B and 4B results, per-layout settings, what moved the numbers |
-| [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.
+| [GETTING_STARTED](docs/GETTING_STARTED.md) | Install, recipes, flags, environment variables, reproducing every result |
+| [BENCHMARK_RESULTS](docs/BENCHMARK_RESULTS.md) | Every result with its layout and caveats, and the validated layouts |
+| [ENGINEERING](docs/ENGINEERING.md) | How it works, model coverage, tests, limitations |
+| [bench](bench/README.md) | The benchmark scripts |
diff --git a/training/rdsp/bench/README.md b/training/rdsp/bench/README.md
index b7b31f67b..70c06c345 100644
--- a/training/rdsp/bench/README.md
+++ b/training/rdsp/bench/README.md
@@ -1,27 +1,34 @@
-# bench
-
-The benchmark scripts: rdsp against Megatron-Bridge, MegatronMIMO and TorchTitan on Qwen3.5. How to run each one, the settings held equal and the numbers: [docs/GETTING_STARTED.md](../docs/GETTING_STARTED.md#reproducing-the-blogs-results). Every script writes into a `logs/` folder next to it, which stays out of git.
-
-| Experiment | Script | What it writes |
-|---|---|---|
-| Set up a fresh GPU node | `setup_node.sh` | `~/venv`, the NeMo container |
-| Qwen3.5-2B and 4B, one node, against MIMO and Bridge | `qwen35_small/bench.sh` | `~/bench//r/.log`, `summary.txt` |
-| Qwen3.5-35B-A3B, two nodes: prepare both nodes | `qwen35_35b/prep.sh` (runs `node_prep.sh` on each) | `qwen35_35b/logs/prep/` |
-| 35B: rdsp, vision encoder on its own stage | `qwen35_35b/rdsp_vision_stage.sh` | `qwen35_35b/logs/vision_stage/rdsp-k*.log` |
-| 35B: rdsp, TP1 × PP8 × DP2 | `qwen35_35b/rdsp_pp8dp2.sh` | `qwen35_35b/logs/pp8dp2/rdsp*.log` |
-| 35B: Bridge, TP1 × PP8 × DP2 | `qwen35_35b/bridge_pp8dp2.sh` | `qwen35_35b/logs/pp8dp2/bridge*.log` |
-| 35B: Bridge, TP1 × PP2 × EP8 (NVIDIA's layout) | `common/runs.sh custom-megatron` through `cluster/both.sh` (the command is in GETTING_STARTED) | `qwen35_35b/logs/pp2ep8/bridge-pp2ep8-nv.log` |
-| 35B: TorchTitan, FSDP over 16 GPUs | `qwen35_35b/torchtitan.sh` | `qwen35_35b/logs/fsdp16/--node.log` |
-| 35B: rdsp, ZeRO-3 over 16 GPUs | `qwen35_35b/rdsp_zero3.sh` | `qwen35_35b/logs/fsdp16/rdsp-zero3*.log` |
-| Qwen3.5-27B: prepare both nodes (35B prep, then the 27B) | `qwen35_27b/prep.sh` | `qwen35_27b/logs/prep/` |
-| 27B, one node, TP1 × PP8: Bridge or rdsp | `qwen35_27b/pp8.sh` (rdsp side: `rdsp_pp8.sh`) | `qwen35_27b/logs/pp8/` |
-| 27B: rdsp with recompute set per stage | `qwen35_27b/rdsp_tune.sh` | its output (GETTING_STARTED's commands save it in `qwen35_27b/logs/pp8/`) |
-| 27B: one node's whole queue | `qwen35_27b/one_node.sh` | `qwen35_27b/logs/pp8/`, `torchtitan/logs/` |
-| 9B against MIMO, one node | `mimo/mimo_9b.sh` | `mimo/logs//`, `mimo/logs/sweep/` |
-| 9B: Bridge against rdsp, TP4 × PP2, and the 9B prep | `mimo/bridge_9b.sh` (rdsp side: `rdsp_9b_tp4pp2.sh`) | `mimo/logs/9b_tp4pp2dp1/` |
-| 27B against MIMO, two nodes: rdsp's side | `mimo/rdsp_27b.sh` | `mimo/logs/27b_v1_tp4pp2dp1/rdsp-9gpu.log` |
-| 27B against MIMO: MIMO with Bridge's memory settings | `mimo/patch_mimo.py` (`patch.diff`: the result) | a patched copy of MIMO's launcher in `/tmp` |
-| TorchTitan on Bridge's rows | `torchtitan/run.sh` (one node), `torchtitan/run_two_node.sh`, `torchtitan/setup_box.sh` | `torchtitan/logs/` |
-| Vision encoder alone | `encoder/enc_bench.py`, `encoder/grids.py` | the JSON given with `--out` |
-| Two-node helpers | `cluster/both.sh`, `ray_cluster.sh`, `efa_env.sh`, `nccl_check.sh` | `~/both-.log` on node 2 |
-| Shared by the scripts above | `common/runs.sh` (Bridge, MIMO and rdsp cases in the NeMo container), `two_node.sh`, `meg_extra_bf16.txt`, `export_bridge_batches.py`, `medians.py`, `summarize.py`, `layout_from_log.py` | `$LOGS/.log` |
+# Benchmarks
+
+Run rdsp on every GPU of one or more nodes, and time it.
+
+## Run
+
+On every node:
+
+```bash
+bash install.sh && source .venv/bin/activate
+```
+
+Then start the cluster and train:
+
+```bash
+rdsp setup # node 0: starts the cluster and prints the join command
+rdsp setup --join # every other node: the command node 0 printed
+rdsp nodes # check that every GPU is there
+rdsp train Qwen/Qwen3.5-9B --steps 15 --tune
+```
+
+`rdsp train` picks the layout for the GPUs it finds and prints the command before it runs it. `--tune` times the stages first and re-cuts them; the vision encoder gets its own stage.
+
+## Time it
+
+```bash
+python bench/results.py train.log
+```
+
+It prints the median time of steps 6–15 and tokens/s per GPU (`--gpus` for the GPU count, default 16). Save the run's output with `rdsp train ... | tee train.log`.
+
+## The published results
+
+The published rdsp numbers ([docs/BENCHMARK_RESULTS.md](../docs/BENCHMARK_RESULTS.md)) trained on rows exported from Megatron-Bridge's CORD-v2 loader, so that every system saw the same data. rdsp's published layouts are recipes: `recipes/qwen35-9b-vision4-pp6dp2.sh`, `qwen35-27b-vision2-pp7dp2.sh` and `qwen35-35b-a3b-vision4-pp6dp2.sh`. [compare/](compare/README.md) holds the scripts that export those rows and run the recipes against Megatron-Bridge, TorchTitan and MegatronMIMO.
diff --git a/training/rdsp/bench/cluster/both.sh b/training/rdsp/bench/cluster/both.sh
deleted file mode 100755
index 08154ca37..000000000
--- a/training/rdsp/bench/cluster/both.sh
+++ /dev/null
@@ -1,40 +0,0 @@
-#!/bin/bash
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-# both.sh , on node 1 from ~/rdsp: the same command on both nodes at once, for
-# launchers that start one torchrun per node (Bridge and MIMO through bench/common/runs.sh,
-# TorchTitan). It runs with NNODES=2, NODE_RANK (0 here, 1 on node 2) and MASTER_ADDR (node 1)
-# in its environment; pass any other setting inside the command (env MODEL=... bash ...), since
-# node 2 gets only the command. Node 2 runs it from ~/rdsp too, its output in ~/both-.log
-# there. Exits with node 1's code, or 1 if node 1 passed and node 2 failed.
-# Fail fast: once either node's command ends, the other gets GRACE seconds (default 120) to end
-# too, then its containers and torchrun are killed (otherwise a crash on one node leaves the other
-# waiting in NCCL or the rendezvous until the run's own timeout).
-# both.sh --cleanup: kill every container and torchrun on both nodes.
-set -uo pipefail
-. ~/env2.sh
-SSH2="ssh -i $HOME/key2.pem -o StrictHostKeyChecking=no -o BatchMode=yes ubuntu@$PRIV2"
-KILL="sudo docker ps -q | xargs -r sudo docker kill >/dev/null 2>&1; pkill -f '[t]orch.distributed.run' ; pkill -f '[t]orchrun' ; true"
-if [ "${1:-}" = --cleanup ]; then
- $SSH2 "$KILL" < /dev/null; bash -c "$KILL"; exit 0
-fi
-LOG2=both-$(date -u +%H%M%S).log
-$SSH2 "cd ~/rdsp && NNODES=2 NODE_RANK=1 MASTER_ADDR=$PRIV1 $(printf '%q ' "$@") > ~/$LOG2 2>&1" < /dev/null &
-PEER=$!
-NNODES=2 NODE_RANK=0 MASTER_ADDR=$PRIV1 "$@" &
-HERE=$!
-while kill -0 $HERE 2>/dev/null && kill -0 $PEER 2>/dev/null; do sleep 5; done
-for _ in $(seq 1 $(( ${GRACE:-120} / 5 ))); do
- kill -0 $HERE 2>/dev/null || kill -0 $PEER 2>/dev/null || break
- sleep 5
-done
-if kill -0 $HERE 2>/dev/null || kill -0 $PEER 2>/dev/null; then
- echo "both.sh: one node ended, the other still running after ${GRACE:-120} s: killing it"
- $SSH2 "$KILL" < /dev/null; bash -c "$KILL"
- sleep 10; kill $HERE $PEER 2>/dev/null # whatever the kill above did not end
-fi
-wait $HERE; rc=$?
-wait $PEER; rc2=$?
-echo "both.sh: node 1 exit $rc, node 2 exit $rc2 (node 2 log ~/$LOG2)"
-[ $rc = 0 ] && [ $rc2 != 0 ] && rc=1
-exit $rc
diff --git a/training/rdsp/bench/cluster/efa_env.sh b/training/rdsp/bench/cluster/efa_env.sh
deleted file mode 100644
index f5a439b58..000000000
--- a/training/rdsp/bench/cluster/efa_env.sh
+++ /dev/null
@@ -1,9 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-# Sourced on each node before anything that runs NCCL across nodes (Ray's raylets, so every
-# actor inherits it; torchrun). NCCL reaches the other node over EFA through the aws-ofi-nccl
-# plugin on the AMI. LD_LIBRARY_PATH holds only the plugin and libfabric: the AMI's CUDA
-# libraries break torch's cuDNN (bench/setup_node.sh).
-export LD_LIBRARY_PATH=/opt/amazon/ofi-nccl/lib:/opt/amazon/efa/lib
-export FI_PROVIDER=efa FI_EFA_USE_DEVICE_RDMA=1
-export NCCL_SOCKET_IFNAME=^lo,docker
diff --git a/training/rdsp/bench/cluster/nccl_check.py b/training/rdsp/bench/cluster/nccl_check.py
deleted file mode 100644
index b781be8a5..000000000
--- a/training/rdsp/bench/cluster/nccl_check.py
+++ /dev/null
@@ -1,59 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-
-"""All-reduce and all-to-all bandwidth over every GPU of both nodes, with NCCL set up as the
-runs use it (EFA through the aws-ofi-nccl plugin, bench/cluster/efa_env.sh). Start on both
-nodes at once:
-
- bash bench/cluster/both.sh bash bench/cluster/nccl_check.sh
-
-Rank 0 prints each size's time and bus bandwidth (2 (n-1)/n x bytes / time). Over TCP instead of
-EFA the large sizes come out an order of magnitude lower."""
-
-import os
-import time
-
-import torch
-import torch.distributed as dist
-
-dist.init_process_group("nccl")
-rank, world = dist.get_rank(), dist.get_world_size()
-torch.cuda.set_device(int(os.environ["LOCAL_RANK"]))
-for mib in (16, 256, 1024):
- x = torch.ones(mib * 2**20 // 2, dtype=torch.bfloat16, device="cuda")
- for _ in range(5):
- dist.all_reduce(x)
- torch.cuda.synchronize()
- start, n = time.perf_counter(), 20
- for _ in range(n):
- dist.all_reduce(x)
- torch.cuda.synchronize()
- seconds = (time.perf_counter() - start) / n
- bus = 2 * (world - 1) / world * x.numel() * x.element_size() / seconds / 1e9
- if rank == 0:
- print(
- f"all_reduce {mib} MiB over {world} GPUs: {seconds * 1e3:.2f} ms, "
- f"bus bandwidth {bus:.1f} GB/s",
- flush=True,
- )
-# all-to-all, as expert parallelism sends tokens: each rank sends 1/world of the buffer to every
-# rank. Bus bandwidth (n-1)/n x bytes / time, as nccl-tests reports it.
-for mib in (16, 256, 1024):
- x = torch.ones(mib * 2**20 // 2, dtype=torch.bfloat16, device="cuda")
- y = torch.empty_like(x)
- for _ in range(5):
- dist.all_to_all_single(y, x)
- torch.cuda.synchronize()
- start, n = time.perf_counter(), 20
- for _ in range(n):
- dist.all_to_all_single(y, x)
- torch.cuda.synchronize()
- seconds = (time.perf_counter() - start) / n
- bus = (world - 1) / world * x.numel() * x.element_size() / seconds / 1e9
- if rank == 0:
- print(
- f"all_to_all {mib} MiB per GPU over {world} GPUs: {seconds * 1e3:.2f} ms, "
- f"bus bandwidth {bus:.1f} GB/s",
- flush=True,
- )
-dist.destroy_process_group()
diff --git a/training/rdsp/bench/cluster/nccl_check.sh b/training/rdsp/bench/cluster/nccl_check.sh
deleted file mode 100755
index 61c747f67..000000000
--- a/training/rdsp/bench/cluster/nccl_check.sh
+++ /dev/null
@@ -1,13 +0,0 @@
-#!/bin/bash
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-# nccl_check.sh: nccl_check.py with torchrun on this node (8 GPUs), in the rdsp venv with
-# efa_env.sh; run on both nodes by both.sh (NNODES, NODE_RANK, MASTER_ADDR). NCCL_DEBUG=INFO
-# records which network NCCL picked ("NET/OFI ... efa" or "NET/Socket").
-set -uo pipefail
-HERE=$(cd "$(dirname "$0")" && pwd)
-unset LD_LIBRARY_PATH
-. ~/venv/bin/activate
-. "$HERE/efa_env.sh"
-NCCL_DEBUG=INFO NCCL_DEBUG_SUBSYS=INIT,NET torchrun --nnodes "$NNODES" --node_rank "$NODE_RANK" \
- --master_addr "$MASTER_ADDR" --master_port 29414 --nproc_per_node 8 "$HERE/nccl_check.py"
diff --git a/training/rdsp/bench/cluster/ray_cluster.sh b/training/rdsp/bench/cluster/ray_cluster.sh
deleted file mode 100755
index 9b6cd7486..000000000
--- a/training/rdsp/bench/cluster/ray_cluster.sh
+++ /dev/null
@@ -1,32 +0,0 @@
-#!/bin/bash
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-# ray_cluster.sh , on node 1: the 2-node Ray
-# cluster, head on node 1 and a worker on node 2, both raylets started with efa_env.sh so
-# every rdsp actor's NCCL uses EFA. A driver on node 1 joins it with RAY_ADDRESS=auto.
-# Node 2 is reached with ~/key2.pem.
-set -euo pipefail
-HERE=$(cd "$(dirname "$0")" && pwd)
-ACTION=$1 PRIV1=$2 PRIV2=$3
-SSH2="ssh -i $HOME/key2.pem -o StrictHostKeyChecking=no ubuntu@$PRIV2"
-START=". ~/venv/bin/activate; . $HERE/efa_env.sh; ray start --disable-usage-stats --num-gpus 8"
-stop() {
- $SSH2 ". ~/venv/bin/activate; ray stop --force" < /dev/null > /dev/null 2>&1 || true
- bash -c ". ~/venv/bin/activate; ray stop --force" > /dev/null 2>&1 || true
-}
-case $ACTION in
- up)
- stop # a cluster left running (an earlier run, by hand) would refuse a new head
- bash -c "$START --head --port 6379 --node-ip-address $PRIV1" > ~/ray_head.log 2>&1
- $SSH2 "$START --address $PRIV1:6379 --node-ip-address $PRIV2 > ~/ray_worker.log 2>&1" < /dev/null
- for _ in $(seq 1 30); do # wait until both nodes' GPUs are in the cluster
- n=$(bash -c ". ~/venv/bin/activate; python -c \"import ray; ray.init(address='auto', \
-log_to_driver=False); print(int(ray.cluster_resources().get('GPU', 0)))\"" 2>/dev/null | tail -1)
- [ "$n" = 16 ] && { echo "ray cluster up: 16 GPUs"; exit 0; }
- sleep 2
- done
- echo "ray cluster has ${n:-0} GPUs, not 16" >&2; exit 1 ;;
- down)
- stop ;;
- *) echo "usage: $0 " >&2; exit 2 ;;
-esac
diff --git a/training/rdsp/bench/common/medians.py b/training/rdsp/bench/common/medians.py
deleted file mode 100644
index 9a802d85d..000000000
--- a/training/rdsp/bench/common/medians.py
+++ /dev/null
@@ -1,75 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-
-"""medians.py ...: median seconds per step over steps 6-50 of each log
-(one line per log: " ", or nothing when fewer than 40 steps ran), and with --best
-only the log with the lowest median. MEDIAN_FIRST (default 6) and MEDIAN_MIN (default 40): the
-first step counted and the fewest steps a median needs (the 10-step receipt control: 4 and 5).
-
- bridge Megatron-Bridge: "iteration N/ M | ... elapsed time per iteration (ms): X"
- titan TorchTitan: the time between consecutive "step: N" lines of one rank
- rdsp rdsp: "step N loss L T ms" lines
-"""
-
-import os
-import re
-import statistics
-import sys
-
-
-def bridge(text: str) -> dict[int, float]:
- pattern = r"iteration +(\d+)/ *\d+ \|.*?elapsed time per iteration \(ms\): ([\d.]+)"
- times = {int(m.group(1)): float(m.group(2)) / 1000 for m in re.finditer(pattern, text)}
- if (
- not times
- ): # two-node logs of node 1 print only "Step Time : X s", one line per step from step 1
- times = {
- i: float(t) for i, t in enumerate(re.findall(r"^Step Time : ([\d.]+)s", text, re.M), 1)
- }
- return times
-
-
-def titan(text: str) -> dict[int, float]:
- stamps: dict[int, float] = {}
- pattern = (
- r"\[rank0\].*?(\d\d):(\d\d):(\d\d),(\d+) - torchtitan\.observability\.metrics - INFO - "
- r".*?step: +(\d+) "
- )
- for m in re.finditer(pattern, re.sub(r"\x1b\[[0-9;]*m", "", text)):
- h, mi, s, ms, step = m.groups()
- stamps[int(step)] = int(h) * 3600 + int(mi) * 60 + int(s) + int(ms) / 1000
- return {k: stamps[k] - stamps[k - 1] for k in stamps if k - 1 in stamps}
-
-
-def rdsp(text: str) -> dict[int, float]:
- return {
- int(m.group(1)): float(m.group(2)) / 1000
- for m in re.finditer(r"^step (\d+) loss \S+ +(\d+) ms", text, re.M)
- }
-
-
-def median(kind: str, path: str) -> float | None:
- try:
- text = open(path, errors="ignore").read()
- except OSError:
- return None
- times = globals()[kind](text)
- first = int(os.environ.get("MEDIAN_FIRST", "6"))
- window = [times[i] for i in range(first, 51) if i in times]
- return (
- statistics.median(window)
- if len(window) >= int(os.environ.get("MEDIAN_MIN", "40"))
- else None
- )
-
-
-if __name__ == "__main__":
- args = sys.argv[1:]
- best = "--best" in args
- args = [a for a in args if a != "--best"]
- kind, logs = args[0], args[1:]
- found = [(m, log) for log in logs if (m := median(kind, log)) is not None]
- if best and found:
- found = [min(found)]
- for m, log in found:
- print(f"{m:.2f} {log}")
diff --git a/training/rdsp/bench/common/meg_extra_bf16.txt b/training/rdsp/bench/common/meg_extra_bf16.txt
deleted file mode 100644
index b10398aaf..000000000
--- a/training/rdsp/bench/common/meg_extra_bf16.txt
+++ /dev/null
@@ -1 +0,0 @@
-mixed_precision=null model.bf16=true model.fp16=false model.params_dtype=bf16 model.pipeline_dtype=bf16 optimizer.bf16=true optimizer.fp16=false optimizer.params_dtype=bf16 optimizer.use_precision_aware_optimizer=true optimizer.main_grads_dtype=bf16 optimizer.main_params_dtype=fp32 optimizer.store_param_remainders=true optimizer.exp_avg_dtype=fp32 optimizer.exp_avg_sq_dtype=fp32
diff --git a/training/rdsp/bench/common/runs.sh b/training/rdsp/bench/common/runs.sh
deleted file mode 100755
index 7d5560e0a..000000000
--- a/training/rdsp/bench/common/runs.sh
+++ /dev/null
@@ -1,209 +0,0 @@
-#!/bin/bash
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-# rdsp vs Megatron (MegatronMIMO and Megatron-Bridge) on one 8-GPU node,
-# Qwen3.5 on CORD-v2. Run on the node after bench/setup_node.sh:
-#
-# MODEL=Qwen3.5-2B runs.sh convert # HF -> Megatron checkpoints
-# MODEL=Qwen3.5-2B runs.sh export # Bridge's samples, replayed by rdsp
-# MODEL=Qwen3.5-2B runs.sh noncoloc-mimo | noncoloc-rdsp # vision 1 GPU + language TP2xDP2
-# MODEL=Qwen3.5-2B runs.sh shared-megatron | shared-rdsp # TP2xPP2xDP2
-# MODEL=Qwen3.5-4B runs.sh tp4pp2-megatron | tp4pp2-rdsp # TP4xPP2xDP1
-# MODEL=Qwen3.5-4B runs.sh coloc-rdsp # rdsp only: colocated vision
-# python summarize.py ~/runs # the results table
-#
-# Case names are the same for both models: set LOGS=~/runs-4b for the 4B runs.
-#
-# GBS: rows per step (default 64; the two-node runs use 128). EXPORT_NAME: the export's folder in
-# ~/mimo (default cord_steps-$MODEL).
-# Settings held equal: seq 2048, 64 rows per step, one row per GPU per
-# microbatch, AdamW lr 1e-5 constant, betas 0.9/0.95, eps 1e-8, no weight
-# decay, no clipping, no warm-up, bf16 with fp32 gradients and optimizer
-# state split over data parallel, no recompute, 50 steps. Megatron's
-# defaults that differ are overridden here (clipping, warm-up, cosine decay,
-# the MTP head, the shuffling sampler). Loss: the Bridge runs train on the
-# token mean (calculate_per_token_loss); MegatronMIMO trains on per-
-# microbatch means and the rdsp run against it does the same. rdsp runs the
-# recipes in ../../recipes with DATA=exported:.
-set -euo pipefail
-MODEL=${MODEL:-Qwen3.5-2B}
-export STEPS=${STEPS:-50}
-WORK=$HOME/mimo # /workspace inside the container
-IMAGE=nvcr.io/nvidia/nemo:26.08
-LOGS=${LOGS:-$HOME/runs}; mkdir -p "$LOGS"
-if [ -n "${NSYS_DELAY:-}" ]; then mkdir -p "$WORK/nsys"; fi
-RDSP=$(cd "$(dirname "$0")/../.." && pwd)
-SIZE=$(echo "${MODEL#Qwen3.5-}" | tr '[:upper:]' '[:lower:]') # 2b, 4b
-case $SIZE in
- 2b) RECIPE=${RECIPE:-qwen35_vl_2b_sft_1gpu_h100_bf16_config} ;;
- *) RECIPE=${RECIPE:-qwen35_vl_${SIZE}_sft_2gpu_h100_bf16_config} ;;
-esac
-
-# Two nodes (NNODES=2, NODE_RANK, MASTER_ADDR): host networking and every device (EFA), NCCL
-# over EFA through the container's own aws-ofi-nccl plugin (its ld.so.conf lists it; replacing
-# the container's LD_LIBRARY_PATH would also drop its CUDA forward-compatibility library, which
-# its CUDA 13.3 needs on a 13.2 driver); NET=socket forces TCP instead.
-NNODES=${NNODES:-1}
-MULTI=""
-if [ "$NNODES" -gt 1 ]; then
- MULTI="--network host --privileged -e FI_PROVIDER=efa -e FI_EFA_USE_DEVICE_RDMA=1 \
- -e NCCL_SOCKET_IFNAME=^lo,docker"
- [ "${NET:-efa}" = socket ] && MULTI="$MULTI -e NCCL_NET=Socket"
- # HOST_OFI=1: the host's aws-ofi-nccl (1.21.1, with its Libfabric) mounted over the container's
- # (1.17.3, built for NCCL 2.28, beside the container's NCCL 2.30.7). NCCL_P2P_PXN_LEVEL: passed
- # through (0: each rank's send/recv on its own NIC, not through another GPU's process). Both for
- # Bridge's pipeline across the nodes, which deadlocks in batched send/recv.
- [ -n "${HOST_OFI:-}" ] && MULTI="$MULTI -v /opt/amazon/ofi-nccl:/opt/amazon/ofi-nccl:ro \
- -v /opt/amazon/efa:/opt/amazon/efa:ro"
- [ -n "${NCCL_P2P_PXN_LEVEL:-}" ] && MULTI="$MULTI -e NCCL_P2P_PXN_LEVEL=$NCCL_P2P_PXN_LEVEL"
-fi
-# Compiled Triton and TorchInductor kernels persist in $WORK/.cache across containers: a run's
-# first step compiles for many minutes (35B on two nodes: 30+), the next run reuses them. Steps
-# after the first, which the results use, are unchanged.
-container() { # container
- sudo docker run --gpus all --rm --ipc=host --shm-size=64g --ulimit memlock=-1 $MULTI \
- -v "$HOME/hf:/root/.cache/huggingface" -v "$WORK:/workspace" -v "$RDSP:/rdsp" \
- -e HF_HOME=/root/.cache/huggingface -e PYTHONUNBUFFERED=1 -w /opt/Megatron-Bridge \
- -e TRITON_CACHE_DIR=/workspace/.cache/triton -e TORCHINDUCTOR_CACHE_DIR=/workspace/.cache/inductor \
- ${NCCL_DEBUG:+-e NCCL_DEBUG=$NCCL_DEBUG} \
- "$IMAGE" bash -c "$*"
- sudo chown -R "$(id -u):$(id -g)" "$HOME/hf" "$WORK" # the container writes as root
-}
-
-# SEQ (default 2048) and DATASET (a Bridge preset, default cord_v2): NVIDIA's published SFT run
-# uses DATASET=medpix SEQ=4096 GBS=32
-STD_DATA="model.seq_length=${SEQ:-2048} dataset.seq_length=${SEQ:-2048} dataset.source.dataset_name=${DATASET:-cord_v2} \
- dataset.dataloader_type=single train.global_batch_size=${GBS:-64}"
-STD_TRAIN="$STD_DATA train.micro_batch_size=1 train.train_iters=$STEPS \
- checkpoint.pretrained_checkpoint=/workspace/std/$MODEL checkpoint.save=null \
- model.mtp_num_layers=null model.calculate_per_token_loss=true \
- model.recompute_granularity=null \
- optimizer.lr=1e-5 optimizer.min_lr=1e-5 optimizer.adam_beta1=0.9 optimizer.adam_beta2=0.95 \
- optimizer.adam_eps=1e-8 optimizer.weight_decay=0.0 optimizer.clip_grad=0.0 \
- scheduler.lr_warmup_iters=0 scheduler.lr_decay_style=constant \
- scheduler.start_weight_decay=0.0 scheduler.end_weight_decay=0.0 \
- ddp.grad_reduce_in_fp32=${GRAD_REDUCE_FP32:-true} ddp.use_distributed_optimizer=true ddp.average_in_collective=false \
- validation.eval_iters=0 logger.log_interval=1"
-# Diagnosis only, never for published runs: MIMO_EXTRA (e.g. "--pad-to-seq-length
-# false"), MEGATRON_EXTRA (Bridge overrides, e.g. "logger.timing_log_level=2"),
-# RDSP_EXTRA (train_vl.py flags, e.g. "--profile"), NCCL_DEBUG=INFO.
-# GRAD_REDUCE_FP32=false: Bridge's gradient buffer in bf16 (only with mixed_precision=null
-# in MEGATRON_EXTRA; Bridge's bf16_mixed resets it to true).
-# NSYS_DELAY + NSYS_DURATION (seconds): Nsight Systems on that window of the
-# run, every process, report in ~/mimo/nsys/.nsys-rep. NSYS_FLAGS replaces the
-# default "-s none --cpuctxsw=none" (e.g. call stacks for every sync).
-MIMO_TRAIN="--hf-model Qwen/$MODEL --dataset-name cord_v2 --seq-length 2048 \
- --global-batch-size ${GBS:-64} --train-iters $STEPS --dataloader-type single \
- --pretrained-checkpoint /workspace/$MODEL-mimo \
- --lr 1e-5 --min-lr 1e-5 --adam-beta1 0.9 --adam-beta2 0.95 --weight-decay 0.0 \
- --start-weight-decay 0.0 --end-weight-decay 0.0 --clip-grad 0.0 --lr-warmup-iters 0 \
- --log-interval 1 --experiment-root /workspace/runs ${MIMO_EXTRA:-}"
-
-nsys_prefix() { # nsys_prefix : a profiler prefix when NSYS_DELAY and NSYS_DURATION are set
- [ -n "${NSYS_DELAY:-}" ] && [ -n "${NSYS_DURATION:-}" ] || return 0
- echo "nsys profile -t cuda,nvtx ${NSYS_FLAGS:--s none --cpuctxsw=none} --delay $NSYS_DELAY" \
- "--duration $NSYS_DURATION --force-overwrite true -o $1"
-}
-
-megatron() { # megatron : the standard Bridge recipe
- container "$(nsys_prefix "/workspace/nsys/$1") python -m torch.distributed.run --nproc_per_node=8 \
- --nnodes $NNODES --node_rank ${NODE_RANK:-0} --master_addr ${MASTER_ADDR:-127.0.0.1} --master_port 29411 \
- scripts/training/run_recipe.py \
- --recipe $RECIPE --step_func qwen3_vl_step $STD_TRAIN \
- model.tensor_model_parallel_size=$2 model.pipeline_model_parallel_size=$3 ${MEGATRON_EXTRA:-}" \
- 2>&1 | tee "$LOGS/$1.log"
-}
-
-mimo() { # mimo
- # MIMO_PATCH=1: a /tmp copy of MIMO's launcher with Bridge's memory settings
- # (bench/mimo/patch_mimo.py; the container's own file stays as shipped);
- # MIMO_RECOMPUTE=1 then also recomputes every language layer
- local script=examples/megatron_mimo/qwen35_vl/finetune_qwen35_vl.py prep=""
- if [ -n "${MIMO_PATCH:-}" ]; then
- prep="cp $script /tmp/mimo_mem.py && python /rdsp/bench/mimo/patch_mimo.py /tmp/mimo_mem.py &&"
- script=/tmp/mimo_mem.py
- fi
- # MIMO_NPROC0 / 1 / 2: processes on node 1 / node 2 / a third box when they differ (e.g. language on node
- # 1's 8 GPUs, the vision encoder alone on 1 GPU of node 2: 8 and 1); default GPUs / NNODES each
- local nproc=$(( $2 / NNODES ))
- [ "${NODE_RANK:-0}" = 0 ] && nproc=${MIMO_NPROC0:-$nproc}
- [ "${NODE_RANK:-0}" = 1 ] && nproc=${MIMO_NPROC1:-$nproc}
- [ "${NODE_RANK:-0}" = 2 ] && nproc=${MIMO_NPROC2:-$nproc}
- container "$prep MIMO_RECOMPUTE=${MIMO_RECOMPUTE:-0} $(nsys_prefix "/workspace/nsys/$1") python -m torch.distributed.run --nproc_per_node=$nproc \
- --nnodes $NNODES --node_rank ${NODE_RANK:-0} --master_addr ${MASTER_ADDR:-127.0.0.1} --master_port 29412 \
- $script $MIMO_TRAIN --micro-batch-size $3 \
- --run-name $1 --component language=$4 --component images=$5" 2>&1 | tee "$LOGS/$1.log"
-}
-
-rdsp() { # rdsp [train_vl flags]
- local name=$1 recipe=$RDSP/recipes/$2; shift 2
- [ -f "$recipe" ] || { echo "no recipe $recipe for $MODEL" >&2; exit 1; }
- (unset LD_LIBRARY_PATH && . "$HOME/venv/bin/activate" && . "$HOME/cuda_env.sh" && \
- DS_BUILD_OPS=0 HF_HOME=$HOME/hf PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
- DATA=exported:$WORK/cord_steps-$MODEL $(nsys_prefix "$WORK/nsys/$name") \
- bash "$recipe" --steps "$STEPS" "$@" ${RDSP_EXTRA:-}) \
- 2>&1 | tee "$LOGS/$name.log"
-}
-
-case "${1:-}" in
- convert)
- container "python scripts/conversion/setup_conversion.py import --hf-model Qwen/$MODEL \
- --megatron-path /workspace/std/$MODEL && \
- python -m torch.distributed.run --nproc_per_node=2 examples/conversion/convert_megatron_mimo.py \
- import --hf-model Qwen/$MODEL --megatron-path /workspace/$MODEL-mimo \
- --component language=tp=1,dp=1,rank_offset=0 --component images=tp=1,dp=1,rank_offset=1 \
- --torch-dtype bfloat16" 2>&1 | tee "$LOGS/convert.log" ;;
- export)
- container "python /rdsp/bench/common/export_bridge_batches.py --out /workspace/${EXPORT_NAME:-cord_steps-$MODEL} \
- --steps $STEPS --recipe $RECIPE $STD_DATA dataset.pad_to_max_length=true" \
- 2>&1 | tee "$LOGS/export.log" ;;
- # MegatronMIMO's microbatch is global over language DP: 1 row per language rank
- noncoloc-mimo) # language TP2 x DP2 on ranks 0-3, images on rank 4
- mimo noncoloc-mimo 5 2 tp=2,pp=1,dp=2,rank_offset=0 tp=1,pp=1,dp=1,rank_offset=4 ;;
- noncoloc-rdsp)
- rdsp noncoloc-rdsp "qwen35-$SIZE-vision1-tp2dp2.sh" ;;
- mimo-layout) # any grid: MIMO_NAME MIMO_GPUS MIMO_MBS MIMO_LANGUAGE MIMO_IMAGES from the caller
- mimo "${MIMO_NAME:?}" "${MIMO_GPUS:?}" "${MIMO_MBS:?}" "${MIMO_LANGUAGE:?}" "${MIMO_IMAGES:?}" ;;
- shared-megatron)
- megatron shared-megatron 2 2 ;;
- shared-rdsp)
- rdsp shared-rdsp "qwen35-$SIZE-tp2pp2dp2.sh" ;;
- tp4pp2-megatron)
- megatron tp4pp2-megatron 4 2 ;;
- tp2dp4-megatron) # TP2 x DP4, no pipeline
- megatron tp2dp4-megatron 2 1 ;;
- tp4dp2-megatron) # TP4 x DP2, no pipeline
- megatron tp4dp2-megatron 4 1 ;;
- tp2pp4-megatron) # TP2 x PP4, no data parallelism
- megatron tp2pp4-megatron 2 4 ;;
- tp1pp8-megatron) # TP1 x PP8: one GPU per pipeline stage
- megatron tp1pp8-megatron 1 8 ;;
- dp8-megatron) # data parallel 8, no TP or PP (with Megatron FSDP overrides: fully sharded)
- megatron dp8-megatron 1 1 ;;
- twonode-mimo) # two nodes: language TP4 x PP2 on node 1 (ranks 0-7), images DP8 on node 2
- mimo twonode-mimo 16 8 tp=4,pp=2,dp=1,rank_offset=0 tp=1,pp=1,dp=8,rank_offset=8 ;;
- convert-mimo) # only the MegatronMIMO checkpoint: language on GPUs 0..CONVERT_TP-1 (TP
- # CONVERT_TP, default 1; the 27B needs 4: on one GPU its conversion runs out of memory), images
- # on the next GPU. Training reshards it on load.
- ctp=${CONVERT_TP:-1}
- container "python -m torch.distributed.run --nproc_per_node=$((ctp + 1)) examples/conversion/convert_megatron_mimo.py \
- import --hf-model Qwen/$MODEL --megatron-path /workspace/$MODEL-mimo \
- --component language=tp=$ctp,dp=1,rank_offset=0 --component images=tp=1,dp=1,rank_offset=$ctp \
- --torch-dtype bfloat16" 2>&1 | tee "$LOGS/convert-mimo.log" ;;
- tp2ep16-megatron) # two nodes: TP2 x DP8, no pipeline; the experts' split comes with the
- megatron tp2ep16-megatron 2 1 ;; # overrides (model.expert_model_parallel_size=16)
- custom-megatron) # any TP x PP (DP from the GPU count), log $LOGS/.log; experts,
- # layout and the rest come with MEGATRON_EXTRA
- megatron "${CUSTOM_NAME:?}" "${CUSTOM_TP:?}" "${CUSTOM_PP:?}" ;;
- nccl-check) # bench/cluster/nccl_check.py inside the container (its NCCL and EFA plugin),
- # every GPU of NNODES nodes; NCCL_DEBUG=INFO shows the network it picked
- container "NCCL_DEBUG=INFO NCCL_DEBUG_SUBSYS=INIT,NET python -m torch.distributed.run \
- --nproc_per_node=8 --nnodes $NNODES --node_rank ${NODE_RANK:-0} \
- --master_addr ${MASTER_ADDR:-127.0.0.1} --master_port 29415 /rdsp/bench/cluster/nccl_check.py" \
- 2>&1 | tee "$LOGS/nccl-check-container.log" ;;
- tp4pp2-rdsp)
- rdsp tp4pp2-rdsp "qwen35-$SIZE-tp4pp2dp1.sh" ;;
- coloc-rdsp) # rdsp only: vision encoder on every GPU, language TP2 x PP2 x DP2
- rdsp coloc-rdsp "qwen35-$SIZE-coloc-tp2pp2dp2.sh" ;;
- *) sed -n 2,15p "$0"; exit 1 ;;
-esac
diff --git a/training/rdsp/bench/common/summarize.py b/training/rdsp/bench/common/summarize.py
deleted file mode 100644
index 8afa9627f..000000000
--- a/training/rdsp/bench/common/summarize.py
+++ /dev/null
@@ -1,78 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-
-"""Results table from bench/common/runs.sh logs: one row per Megatron / rdsp
-pair, median step time over steps 6-50 (the first five compile and warm up).
-
-Tokens/s is rows x sequence length / median step time (64 x 2048 in every
-bench/qwen35_small run); per GPU divides by the layout's GPU count.
-
- python summarize.py ~/runs --price 5.32
-"""
-
-import argparse
-import re
-import statistics
-from pathlib import Path
-
-PAIRS = ( # (layout, GPUs, Megatron run or None for rdsp only, rdsp run)
- ("vision 1 GPU + language TP2xDP2", 5, "noncoloc-mimo", "noncoloc-rdsp"),
- ("TP2xPP2xDP2", 8, "shared-megatron", "shared-rdsp"),
- ("TP4xPP2xDP1", 8, "tp4pp2-megatron", "tp4pp2-rdsp"),
- ("colocated vision + TP2xPP2xDP2", 8, None, "coloc-rdsp"),
-)
-_MEGATRON = re.compile(r"iteration\s+(\d+)/\s*\d+ .*?elapsed time per iteration \(ms\): ([\d.]+)")
-_RDSP = re.compile(r"^step (\d+) loss \S+ +(\d+) ms", re.M)
-
-
-def parse(path: Path) -> dict:
- """{step: ms}, steps counted from 0 (Megatron's iteration 1 is step 0, as in rdsp)."""
- text = path.read_text(errors="replace")
- ms = {int(m[1]) - 1: float(m[2]) for m in _MEGATRON.finditer(text)}
- ms.update({int(m[1]): float(m[2]) for m in _RDSP.finditer(text)})
- return ms
-
-
-def main(argv=None) -> None:
- p = argparse.ArgumentParser()
- p.add_argument("logs")
- p.add_argument("--price", type=float, default=5.32, help="8-GPU node, $/hour")
- p.add_argument("--first", type=int, default=5, help="warm-up steps left out")
- p.add_argument("--rows", type=int, default=64, help="rows per step")
- p.add_argument("--seq", type=int, default=2048, help="sequence length")
- args = p.parse_args(argv)
- logs = Path(args.logs)
- print(
- f"{'layout':34} {'GPUs':>4} {'Megatron s':>10} {'rdsp s':>7} {'step':>6} "
- f"{'Megatron tok/s':>14} {'rdsp tok/s':>10} {'rdsp $/M tok':>12} "
- f"{'Megatron tok/s/GPU':>18} {'rdsp tok/s/GPU':>14}"
- )
- for layout, gpus, megatron, rdsp in PAIRS:
- if not (logs / f"{rdsp}.log").exists() or (
- megatron and not (logs / f"{megatron}.log").exists()
- ):
- continue
- r_ms = parse(logs / f"{rdsp}.log")
- m_ms = parse(logs / f"{megatron}.log") if megatron else None
- timed = [s for s in sorted(r_ms) if s >= args.first and (m_ms is None or s in m_ms)]
- if not timed:
- continue
- tokens = args.rows * args.seq
- r_s = statistics.median(r_ms[s] for s in timed) / 1e3
- r_tok = tokens / r_s
- cost = args.price * gpus / 8 / 3600 / r_tok * 1e6
- if m_ms is None:
- m_col, step, m_tok, m_gpu = "-", "-", "-", "-"
- else:
- m_s = statistics.median(m_ms[s] for s in timed) / 1e3
- m_col, step = f"{m_s:.2f}", f"{r_s / m_s - 1:+.0%}"
- tok = tokens / m_s
- m_tok, m_gpu = f"{tok:.0f}", f"{tok / gpus:.0f}"
- print(
- f"{layout:34} {gpus:>4} {m_col:>10} {r_s:>7.2f} {step:>6} "
- f"{m_tok:>14} {r_tok:>10.0f} {cost:>12.3f} {m_gpu:>18} {r_tok / gpus:>14.0f}"
- )
-
-
-if __name__ == "__main__":
- main()
diff --git a/training/rdsp/bench/common/two_node.sh b/training/rdsp/bench/common/two_node.sh
deleted file mode 100644
index e345b4eaa..000000000
--- a/training/rdsp/bench/common/two_node.sh
+++ /dev/null
@@ -1,80 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-# Sourced by the two-node scripts on node 1 (bench/qwen35_35b/*.sh, bench/mimo/rdsp_27b.sh), after
-# bench/qwen35_35b/prep.sh: Qwen3.5-35B-A3B on two p5.48xlarge (16 H100, EFA), the settings every
-# run shares. Bridge and TorchTitan start on both nodes through bench/cluster/both.sh; rdsp's
-# driver runs here, its actors on the Ray cluster bench/cluster/ray_cluster.sh runs over both nodes.
-COMMON=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
-RDSP=$(cd "$COMMON/../.." && pwd)
-# MODEL=Qwen3.5-27B: the dense 27B on the same layouts (its logs in logs/-27b/)
-export MODEL=${MODEL:-Qwen3.5-35B-A3B} GBS=${GBS:-128}
-case $MODEL in
- Qwen3.5-27B) export RECIPE=qwen35_vl_27b_sft_16gpu_h100_bf16_config LOGS_SUFFIX=-27b ;;
- *) export RECIPE=qwen35_vl_35b_a3b_sft_16gpu_h100_bf16_config LOGS_SUFFIX="" ;;
-esac
-export STEPS=${STEPS:-50}
-RUNS=$COMMON/runs.sh
-BOTH=$RDSP/bench/cluster/both.sh
-DATA=exported:$HOME/mimo/${EXPORT_NAME:-cord_steps-$MODEL} # EXPORT_NAME: other rows
-# Bridge: bf16 gradients with the fp32 master as 2-byte remainders (the 27B runs' settings), no
-# router load-balancing loss, every row padded to 2048 (pipelines pad on their own anyway), and
-# a 60-minute NCCL timeout: Bridge's first step compiles for 10-18 minutes.
-MEG_COMMON="$(cat "$COMMON/meg_extra_bf16.txt") \
-model.moe_router_load_balancing_type=none model.moe_aux_loss_coeff=0.0 \
-dataset.pad_to_max_length=true dist.distributed_timeout_minutes=60"
-# Megatron refuses sequence parallelism (the recipe's, for its TP2) without tensor parallelism
-MEG_TP1="model.sequence_parallel=false"
-MEG_RC="model.recompute_granularity=full model.recompute_method=uniform model.recompute_num_layers=1"
-# rdsp: the 27B runs' flags (bench/qwen35_27b/rdsp_pp8.sh) with the 2-byte
-# master. MOE_EXPERTS=hf (default): Hugging Face's grouped matmuls for the experts. Liger's fused
-# kernel (liger) took 350 s for the first step against 24 s (2026-10-18, PP8xDP2), compiling and
-# benchmarking its kernels; a stage waiting that long hits NCCL's 5-minute timeout.
-RDSP_COMMON="--seq ${SEQ:-2048} --pad-multiple 0 --lr 1e-5 --betas 0.9,0.95 --eps 1e-8 --weight-decay 0.0 \
---grad-dtype bf16 --master-dtype remainder --fused-adam --optimizer-group-numel 250000000 \
---loss token-mean --liger \
---moe-experts ${MOE_EXPERTS:-hf} --prefetch --sharded-loss --drop-padding-mask"
-# RECOMPUTE=1: every block recomputed, on whichever system runs (a run that does not fit without)
-RECOMPUTE=${RECOMPUTE:-0}
-# NET=socket: NCCL between the nodes over TCP instead of EFA (NCCL_NET=Socket; NVLink inside a
-# node as before), as on a cluster without EFA or InfiniBand. Logs get "-tcp" after NAME.
-export NET=${NET:-efa}
-[ "$NET" = socket ] && export NAME="${NAME:-}-tcp"
-# ~/no_tcp: TCP runs switched off (a script already running skips them when it gets there)
-if [ "$NET" = socket ] && [ -f "$HOME/no_tcp" ]; then echo "TCP runs off (~/no_tcp)"; exit 0; fi
-
-bridge() { # bridge [Bridge overrides...]: Bridge on both nodes
- local case=$1 name=$2 rc=0; shift 2
- local rc_flags=""; [ "$RECOMPUTE" = 1 ] && rc_flags=$MEG_RC
- bash "$BOTH" env MODEL=$MODEL RECIPE=$RECIPE GBS=$GBS STEPS=$STEPS LOGS=$LOGS NET=$NET \
- NCCL_DEBUG=${NCCL_DEBUG:-} HOST_OFI=${HOST_OFI:-} NCCL_P2P_PXN_LEVEL=${NCCL_P2P_PXN_LEVEL:-} \
- GRAD_REDUCE_FP32=false MEGATRON_EXTRA="$MEG_COMMON $rc_flags $*" bash "$RUNS" "$case" || rc=$?
- mv "$LOGS/$case.log" "$LOGS/$name.log" 2>/dev/null || true
- return $rc
-}
-
-rdsp() { # rdsp [train_vl.py layout flags...]: rdsp, actors on both nodes
- local name=$1; shift
- (unset LD_LIBRARY_PATH && . "$HOME/venv/bin/activate" && . "$HOME/cuda_env.sh" && \
- . "$RDSP/bench/cluster/efa_env.sh" && \
- { [ "$NET" != socket ] || export NCCL_NET=Socket; } && \
- env DS_BUILD_OPS=0 HF_HOME=$HOME/hf PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
- RAY_ADDRESS=auto python "$RDSP/train_vl.py" --model "Qwen/$MODEL" --dataset "$DATA" \
- --steps "$STEPS" $RDSP_COMMON "$@" ${RDSP_ARGS:-}) 2>&1 | tee "$LOGS/$name.log"
- return "${PIPESTATUS[0]}"
-}
-
-vision_first() { # vision_first : stage 0's --stage flag where it holds the vision encoder.
- # Its encoder is recomputed (recompute_blocks=0: the encoder's blocks, none of the decoder's):
- # without, stage 0 ran out of memory when Adam's state appeared at step 1 (PP8xDP2, 76 GB of
- # 79 in use). VISION_RC=0 keeps the activations; RECOMPUTE=1 recomputes every block anyway.
- local rc=",recompute_blocks=0"
- [ "${VISION_RC:-1}" = 0 ] && rc=""
- [ "$RECOMPUTE" = 1 ] && rc=",recompute=1"
- echo "--stage 0:gpus=$1,tp=1,zero=1$rc"
-}
-
-stage_flags() { # stage_flags [extra]: --stage flags
- local s out="" rc=""; [ "$RECOMPUTE" = 1 ] && rc=",recompute=1"
- for ((s = $1; s < $1 + $2; s++)); do out="$out --stage $s:gpus=$3,tp=1,zero=1$rc${4:-}"; done
- echo "$out"
-}
diff --git a/training/rdsp/bench/compare/README.md b/training/rdsp/bench/compare/README.md
new file mode 100644
index 000000000..2ba1fda1e
--- /dev/null
+++ b/training/rdsp/bench/compare/README.md
@@ -0,0 +1,57 @@
+# Comparisons
+
+Megatron-Bridge, TorchTitan and MegatronMIMO against rdsp, with the settings of the PyTorch blog post "Ray-based Pipeline Parallelism in DeepSpeed": Qwen3.5 on CORD-v2, two nodes of 8 H100 GPUs. Results: [docs/BENCHMARK_RESULTS.md](../../docs/BENCHMARK_RESULTS.md).
+
+| Script | What it runs |
+|---|---|
+| `qwen35_35b.sh` | Table 1 and Figure 2: Qwen3.5-35B-A3B |
+| `qwen35_27b.sh` | Table 2: Qwen3.5-27B |
+| `qwen35_9b.sh` | Table 3: Qwen3.5-9B |
+| `mimo.sh` | Table 4: rdsp on MegatronMIMO's layouts |
+| `setup.sh` | sets up a node |
+| `prepare.sh` | downloads the weights, converts the Megatron checkpoints, exports the training rows |
+| `../results.py` | step time and tokens/s per GPU from the logs |
+
+## Setup
+
+On every node:
+
+```bash
+bash bench/compare/setup.sh # rdsp and the NeMo container
+bash bench/compare/setup.sh torchtitan # TorchTitan, for its runs
+bash bench/compare/prepare.sh 35B-A3B 27B 9B # into ~/rdsp-bench (DATA_DIR)
+```
+
+rdsp runs on a Ray cluster across the nodes: `rdsp setup` on node 0, then `rdsp setup --join ` on the others ([../README.md](../README.md)).
+
+## Run
+
+Each script takes the system to run. rdsp runs from node 0 only; its main rows run the 16-GPU recipes in [recipes/](../../recipes) on the exported rows. Megatron-Bridge, MegatronMIMO and TorchTitan run on every node at the same time, with torchrun's variables:
+
+```bash
+bash bench/compare/qwen35_35b.sh rdsp
+
+NNODES=2 NODE_RANK=0 MASTER_ADDR= bash bench/compare/qwen35_35b.sh bridge # node 0
+NNODES=2 NODE_RANK=1 MASTER_ADDR= bash bench/compare/qwen35_35b.sh bridge # node 1
+
+python bench/results.py bench/compare/logs/qwen35_35b/*.log
+```
+
+Run a script without arguments to list its systems. Each run is 15 steps; `results.py` reports the median of steps 6–15. Logs go to `bench/compare/logs/`. `DRY=1` prints a run's command without running it.
+
+Network settings (`NCCL_*`, `FI_*`) in your environment reach every system, including the Megatron container.
+
+## Settings
+
+Every system trains the same weights on the same rows: 128 rows a step, every row padded to 2,048 tokens. rdsp and TorchTitan replay the rows Megatron-Bridge's loader exported, in the same order.
+
+| | rdsp | Megatron-Bridge | TorchTitan | MegatronMIMO |
+|---|---|---|---|---|
+| Optimizer | AdamW, lr 1e-5 constant, betas 0.9/0.95, eps 1e-8, no weight decay, clipping or warm-up | the same | the same | the same |
+| Precision | BF16 compute and gradients | the same | BF16, FP32 gradient accumulation | the same (patched launcher) |
+| Master weights | BF16 weight + 16-bit remainder, FP32 Adam state | the same | FP32 | the same (patched launcher) |
+| Loss | mean over the step's tokens | the same | the same | mean per microbatch |
+| Kernels | Hugging Face model, Liger-Kernel | Transformer Engine | its own | Transformer Engine |
+| Layout | best of up to 6 tried per model | the same | the same | MIMO's own layouts |
+
+Software: DeepSpeed 53a2ac4, Megatron-Bridge v0.6.0 and MegatronMIMO in NeMo 26.08, TorchTitan 3c36a77, Transformers 5.17.0.
diff --git a/training/rdsp/bench/compare/lib/bridge_replay.py b/training/rdsp/bench/compare/lib/bridge_replay.py
new file mode 100644
index 000000000..d60e145b5
--- /dev/null
+++ b/training/rdsp/bench/compare/lib/bridge_replay.py
@@ -0,0 +1,74 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+
+"""bridge_replay.py , from Megatron-Bridge's folder in its container:
+runs Bridge's own launcher, scripts/training/run_recipe.py, with one change. Its own train loader
+builds every batch of the run (BRIDGE_REPLAY_STEPS steps) before step 1 and training reads them
+from memory, as rdsp and TorchTitan replay prepared rows. Without it Bridge prepares images while
+it trains. Bridge's files are unchanged: its loaders module gets the wrapped loader when it is
+imported, after the launcher has set its environment."""
+
+import importlib.machinery
+import itertools
+import os
+import runpy
+import sys
+
+LOADERS = "megatron.bridge.data.loaders"
+LAUNCHER = os.path.join("scripts", "training", "run_recipe.py")
+
+
+class Replay:
+ """A loader whose iterator has every batch ready; anything else asks the loader itself."""
+
+ def __init__(self, loader, count):
+ self._loader, self._count = loader, count
+
+ def __getattr__(self, name):
+ return getattr(self._loader, name)
+
+ def __iter__(self):
+ batches = list(itertools.islice(iter(self._loader), self._count))
+ if len(batches) != self._count:
+ raise RuntimeError(f"BRIDGE_REPLAY: {len(batches)} of {self._count} batches")
+ print(f"BRIDGE_REPLAY: {self._count} batches ready before step 1", flush=True)
+ return iter(batches)
+
+
+def replay(build, steps):
+ def wrapped(dataset, consumed, kind, micro_batch_size, *args, **kwargs):
+ loader = build(dataset, consumed, kind, micro_batch_size, *args, **kwargs)
+ rows = steps * kwargs["global_batch_size"] // kwargs["data_parallel_size"]
+ return Replay(loader, rows // micro_batch_size)
+
+ return wrapped
+
+
+class Finder:
+ """Wraps build_pretraining_data_loader in Bridge's loaders module as it is imported."""
+
+ def __init__(self, steps):
+ self.steps = steps
+
+ def find_spec(self, name, path, target=None):
+ if name != LOADERS:
+ return None
+ spec = importlib.machinery.PathFinder.find_spec(name, path, target)
+ if spec is None:
+ return None
+ run, steps = spec.loader.exec_module, self.steps
+
+ def exec_module(module):
+ run(module)
+ module.build_pretraining_data_loader = replay(
+ module.build_pretraining_data_loader, steps
+ )
+
+ spec.loader.exec_module = exec_module
+ return spec
+
+
+if __name__ == "__main__":
+ sys.meta_path.insert(0, Finder(int(os.environ["BRIDGE_REPLAY_STEPS"])))
+ sys.argv[0] = LAUNCHER
+ runpy.run_path(LAUNCHER, run_name="__main__")
diff --git a/training/rdsp/bench/compare/lib/common.sh b/training/rdsp/bench/compare/lib/common.sh
new file mode 100644
index 000000000..45ae37197
--- /dev/null
+++ b/training/rdsp/bench/compare/lib/common.sh
@@ -0,0 +1,147 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+# Sourced by the table scripts after they set MODEL: the settings every run shares and one
+# launcher per system. DRY=1 prints each command instead of running it.
+#
+# recipe [flags...] an rdsp recipe, from one node of the Ray cluster
+# rdsp rdsp on another layout, the same way
+# bridge [overrides...] Megatron-Bridge, on every node
+# mimo
+# MegatronMIMO, on every node
+# titan TorchTitan, on every node
+
+BENCH=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
+RDSP=$(cd "$BENCH/../.." && pwd)
+DATA_DIR=${DATA_DIR:-$HOME/rdsp-bench} # weights, checkpoints and rows (prepare.sh)
+LOGS=${LOGS:-$BENCH/logs}
+RDSP_VENV=${RDSP_VENV:-$HOME/venv} # setup.sh
+TITAN_DIR=${TITAN_DIR:-$HOME/torchtitan} TITAN_VENV=${TITAN_VENV:-$HOME/tt_venv}
+NEMO=nvcr.io/nvidia/nemo:26.08
+NNODES=${NNODES:-1} NODE_RANK=${NODE_RANK:-0} MASTER_ADDR=${MASTER_ADDR:-127.0.0.1}
+GPUS_PER_NODE=${GPUS_PER_NODE:-8}
+STEPS=${STEPS:-15} # results.py reports the median of steps 6-15
+GBS=128 SEQ=2048 # rows a step, tokens a row
+
+case ${MODEL:?set MODEL} in
+ Qwen3.5-9B) RECIPE=qwen35_vl_9b_sft_4gpu_h100_bf16_config ;;
+ Qwen3.5-27B) RECIPE=qwen35_vl_27b_sft_16gpu_h100_bf16_config ;;
+ Qwen3.5-35B-A3B) RECIPE=qwen35_vl_35b_a3b_sft_16gpu_h100_bf16_config ;;
+ *) echo "unknown MODEL $MODEL" >&2; exit 1 ;;
+esac
+
+# rdsp: every run trains with these
+RDSP_FLAGS="--seq $SEQ --pad-multiple 0 --lr 1e-5 --betas 0.9,0.95 --eps 1e-8 --weight-decay 0.0 \
+--grad-dtype bf16 --master-dtype remainder --fused-adam --optimizer-group-numel 250000000 \
+--loss token-mean --liger --prefetch --sharded-loss --drop-padding-mask"
+
+# Megatron-Bridge: the same optimizer and data, Megatron's other defaults (warm-up, decay,
+# clipping, the MTP head) off; BF16 gradients with the 16-bit-remainder master; no router
+# load-balancing loss; NaN checks off; 8 data workers; a 60-minute timeout for the first step
+BRIDGE_DATA="model.seq_length=$SEQ dataset.seq_length=$SEQ dataset.source.dataset_name=cord_v2 \
+dataset.dataloader_type=single train.global_batch_size=$GBS dataset.pad_to_max_length=true"
+BRIDGE_TRAIN="$BRIDGE_DATA train.micro_batch_size=1 checkpoint.pretrained_checkpoint=/workspace/megatron/$MODEL \
+checkpoint.save=null model.mtp_num_layers=null model.calculate_per_token_loss=true model.recompute_granularity=null \
+optimizer.lr=1e-5 optimizer.min_lr=1e-5 optimizer.adam_beta1=0.9 optimizer.adam_beta2=0.95 optimizer.adam_eps=1e-8 \
+optimizer.weight_decay=0.0 optimizer.clip_grad=0.0 scheduler.lr_warmup_iters=0 scheduler.lr_decay_style=constant \
+scheduler.start_weight_decay=0.0 scheduler.end_weight_decay=0.0 ddp.grad_reduce_in_fp32=false \
+ddp.use_distributed_optimizer=true ddp.average_in_collective=false validation.eval_iters=0 logger.log_interval=1"
+BRIDGE_COMMON="mixed_precision=null model.bf16=true model.fp16=false model.params_dtype=bf16 \
+model.pipeline_dtype=bf16 optimizer.bf16=true optimizer.fp16=false optimizer.params_dtype=bf16 \
+optimizer.use_precision_aware_optimizer=true optimizer.main_grads_dtype=bf16 optimizer.main_params_dtype=fp32 \
+optimizer.store_param_remainders=true optimizer.exp_avg_dtype=fp32 optimizer.exp_avg_sq_dtype=fp32 \
+model.moe_router_load_balancing_type=none model.moe_aux_loss_coeff=0.0 dist.distributed_timeout_minutes=60 \
+rerun_state_machine.check_for_nan_in_loss=false ddp.check_for_nan_in_grad=false dataset.num_workers=8 \
+model.cross_entropy_fusion_impl=te"
+BRIDGE_RECOMPUTE="model.recompute_granularity=full model.recompute_method=uniform model.recompute_num_layers=1"
+
+# MegatronMIMO: the same optimizer and data; its launcher is patched for BF16 gradients and the
+# remainder master (patch_mimo.py)
+MIMO_TRAIN="--hf-model Qwen/$MODEL --dataset-name cord_v2 --seq-length $SEQ --global-batch-size $GBS \
+--dataloader-type single --pretrained-checkpoint /workspace/mimo/$MODEL --lr 1e-5 --min-lr 1e-5 \
+--adam-beta1 0.9 --adam-beta2 0.95 --weight-decay 0.0 --start-weight-decay 0.0 --end-weight-decay 0.0 \
+--clip-grad 0.0 --lr-warmup-iters 0 --log-interval 1 --experiment-root /workspace/runs --num-workers 8"
+
+run() { # run : the command, its output also written to
+ local log=$1; shift
+ if [ -n "${DRY:-}" ]; then echo "$*"; return 0; fi
+ mkdir -p "$(dirname "$log")"
+ "$@" 2>&1 | tee "$log"
+ return "${PIPESTATUS[0]}"
+}
+
+in_venv() { # in_venv
+ (unset LD_LIBRARY_PATH && . "$1/bin/activate" && cd "$2" && shift 2 && exec "$@")
+}
+
+container() { # container : in the NeMo container, with the host's NCCL_* and FI_* settings
+ local opts="" kv
+ [ "$NNODES" -gt 1 ] && opts="--network host --privileged"
+ for kv in $(env | grep -oE '^(NCCL|FI)_[A-Za-z0-9_]+'); do opts="$opts -e $kv"; done
+ for kv in ${CONTAINER_ENV:-}; do opts="$opts -e $kv"; done
+ ${DOCKER:-sudo docker} run --gpus all --rm --ipc=host --shm-size=64g --ulimit memlock=-1 $opts \
+ -v "$DATA_DIR:/workspace" -v "$DATA_DIR/hf:/root/.cache/huggingface" -v "$RDSP:/rdsp" \
+ -e HF_HOME=/root/.cache/huggingface -e PYTHONUNBUFFERED=1 -w /opt/Megatron-Bridge \
+ -e TRITON_CACHE_DIR=/workspace/.cache/triton -e TORCHINDUCTOR_CACHE_DIR=/workspace/.cache/inductor \
+ "$NEMO" bash -c "$*"
+}
+
+torchrun_args() { # torchrun_args [processes on this node]
+ echo "--nnodes $NNODES --node_rank $NODE_RANK --master_addr $MASTER_ADDR --master_port $1 \
+--nproc_per_node ${2:-$GPUS_PER_NODE}"
+}
+
+stages() { # stages [extra keys]: --stage flags, TP1, ZeRO-1
+ local s
+ for ((s = $1; s < $1 + $2; s++)); do printf -- '--stage %s:gpus=%s,tp=1,zero=1%s ' "$s" "$3" "${4:+,$4}"; done
+}
+
+rdsp() {
+ local name=$1; shift
+ run "$LOGS/$name.log" in_venv "$RDSP_VENV" "$RDSP" env HF_HOME="$DATA_DIR/hf" DS_BUILD_OPS=0 \
+ PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True RAY_ADDRESS="${RAY_ADDRESS:-auto}" \
+ python train_vl.py --model "Qwen/$MODEL" --dataset "exported:$DATA_DIR/rows/$MODEL" \
+ --steps "$STEPS" $RDSP_FLAGS --moe-experts "${MOE_EXPERTS:-hf}" "$@"
+}
+
+recipe() { # the recipe on the exported rows, for $STEPS steps
+ local name=$1 file=$2; shift 2
+ run "$LOGS/$name.log" in_venv "$RDSP_VENV" "$RDSP" env HF_HOME="$DATA_DIR/hf" DS_BUILD_OPS=0 \
+ RAY_ADDRESS="${RAY_ADDRESS:-auto}" DATA="exported:$DATA_DIR/rows/$MODEL" \
+ bash "recipes/$file" --steps "$STEPS" "$@"
+}
+
+bridge() {
+ local name=$1 tp=$2 pp=$3; shift 3
+ local launcher=scripts/training/run_recipe.py prefix="" extra=""
+ if [ "${BRIDGE_REPLAY:-0}" = 1 ]; then # every batch built before step 1
+ launcher=/rdsp/bench/compare/lib/bridge_replay.py prefix="BRIDGE_REPLAY_STEPS=$STEPS"
+ fi
+ [ "$tp" = 1 ] && extra="model.sequence_parallel=false"
+ [ "${RECOMPUTE:-0}" = 1 ] && extra="$extra $BRIDGE_RECOMPUTE"
+ run "$LOGS/$name-node$NODE_RANK.log" container "$prefix python -m torch.distributed.run \
+$(torchrun_args 29411) $launcher --recipe $RECIPE --step_func qwen3_vl_step $BRIDGE_TRAIN \
+train.train_iters=$STEPS model.tensor_model_parallel_size=$tp model.pipeline_model_parallel_size=$pp \
+$BRIDGE_COMMON $extra $*"
+}
+
+mimo() {
+ local name=$1 images=$2 language=$3 rows=$4 procs=$5
+ [ "$NODE_RANK" = 1 ] && procs=$6
+ local launcher=examples/megatron_mimo/qwen35_vl/finetune_qwen35_vl.py
+ run "$LOGS/$name-node$NODE_RANK.log" container "cp $launcher /tmp/mimo.py && \
+python /rdsp/bench/compare/lib/patch_mimo.py /tmp/mimo.py && MIMO_RECOMPUTE=0 MIMO_REPLAY=1 \
+MIMO_PIN=${MIMO_PIN:-1} python -m torch.distributed.run $(torchrun_args 29412 "$procs") /tmp/mimo.py \
+$MIMO_TRAIN --train-iters $STEPS --micro-batch-size $rows --run-name $name \
+--component language=$language --component images=$images"
+}
+
+titan() {
+ local name=$1 config=$2 assets
+ assets=$(ls -d "$DATA_DIR"/hf/hub/models--Qwen--"$MODEL"/snapshots/* 2>/dev/null | head -1 || true)
+ run "$LOGS/$name-node$NODE_RANK.log" in_venv "$TITAN_VENV" "$TITAN_DIR" env \
+ PYTHONPATH="$BENCH/torchtitan" HF_ASSETS="$assets" EXPORTED="$DATA_DIR/rows/$MODEL" \
+ ROWS=$GBS SEQ=$SEQ STEPS="$STEPS" MB_ROWS="${MB_ROWS:-1}" LOG_RANK=0 \
+ PYTORCH_ALLOC_CONF=expandable_segments:True \
+ torchrun $(torchrun_args 29413) --local-ranks-filter 0 --role rank --tee 3 \
+ -m torchtitan.train --module cord_qwen35 --config "$config"
+}
diff --git a/training/rdsp/bench/common/export_bridge_batches.py b/training/rdsp/bench/compare/lib/export_bridge_batches.py
similarity index 100%
rename from training/rdsp/bench/common/export_bridge_batches.py
rename to training/rdsp/bench/compare/lib/export_bridge_batches.py
diff --git a/training/rdsp/bench/common/layout_from_log.py b/training/rdsp/bench/compare/lib/layout_from_log.py
similarity index 83%
rename from training/rdsp/bench/common/layout_from_log.py
rename to training/rdsp/bench/compare/lib/layout_from_log.py
index a594f0918..7a2762ac5 100644
--- a/training/rdsp/bench/common/layout_from_log.py
+++ b/training/rdsp/bench/compare/lib/layout_from_log.py
@@ -1,18 +1,21 @@
# SPDX-License-Identifier: Apache-2.0
# DeepSpeed Team
-"""Layout choices for later two-node runs, read from rdsp's run 1 log (TP1 x PP8 x DP2, --cuts
-measured), so neither is picked by hand:
+"""Layout choices read from an rdsp run's log (TP1 x PP8 x DP2, --cuts measured), so neither is
+picked by hand:
python3 layout_from_log.py megatron-cut
"F L": layers on Megatron's first and last pipeline stage
(model.num_layers_in_first/last_pipeline_stage), the middle stages equal, nearest to
the cut rdsp measured and chose (fewest layers moved).
+ python3 layout_from_log.py megatron-layout
+ rdsp's measured cut exactly, as Megatron's model.pipeline_model_parallel_layout
+ ("Et*a|t*b|...|t*zL": E the embedding and vision encoder, L the loss).
python3 layout_from_log.py vision-width [language GPUs per stage]
k: GPUs for a vision-only first stage (--cuts 0,measured), from {2, 4, 8}, the language
on the other GPUs as pipeline stages of 2 (or the given size, which must divide both
GPUs - k and k); the k that minimizes the slower of vision time / k and language time /
- (GPUs - k), both in GPU-seconds per step as run 1 measured.
+ (GPUs - k), both in GPU-seconds per step as that run measured.
The log lines read: "stages (blocks): ((0, 3), (3, 9), ...)" (the last one is the measured
cut's pipeline) and "measured: MeasuredStages(cuts=(...), seconds=(...), ...)" (the
@@ -63,6 +66,14 @@ def megatron_cut(blocks: list[int], layers: int) -> tuple[int, int]:
return best[1]
+def megatron_layout(blocks: list[int]) -> str:
+ """rdsp's cut (decoder layers per stage) as Megatron's pipeline layout string."""
+ stages = ["t" if n == 1 else f"t*{n}" if n else "" for n in blocks]
+ stages[0] = "E" + stages[0]
+ stages[-1] += "L"
+ return "|".join(stages)
+
+
def vision_width(
cuts: tuple,
seconds: tuple,
@@ -96,6 +107,8 @@ def main(argv):
if what == "megatron-cut":
blocks = [b - a for a, b in last_stage_blocks(text)]
print(*megatron_cut(blocks, int(argv[3])))
+ elif what == "megatron-layout":
+ print(megatron_layout([b - a for a, b in last_stage_blocks(text)]))
elif what == "vision-width":
m = measured_stages(text)
layers = last_stage_blocks(text)[-1][1]
diff --git a/training/rdsp/bench/mimo/patch_mimo.py b/training/rdsp/bench/compare/lib/patch_mimo.py
similarity index 56%
rename from training/rdsp/bench/mimo/patch_mimo.py
rename to training/rdsp/bench/compare/lib/patch_mimo.py
index 77247e268..d90809648 100644
--- a/training/rdsp/bench/mimo/patch_mimo.py
+++ b/training/rdsp/bench/compare/lib/patch_mimo.py
@@ -11,6 +11,11 @@
2. gradients reduced in bf16 (ddp and the mixed-precision preset both set fp32)
3. MIMO_RECOMPUTE=1 in the environment: every language-model layer recomputed (full, uniform,
1 layer); the launcher has no recompute option
+ 4. MIMO_REPLAY=1 in the environment: MIMO's own loader builds every batch of the run before step
+ 1 and training reads them from memory, as rdsp and TorchTitan replay prepared rows. Without
+ it every MIMO rank prepares images while it trains, each vision rank all of them
+ 5. MIMO_PIN=1 in the environment: every rank runs on the CPUs of its GPU's socket (GPUs 0-3 on
+ NUMA node 0, 4-7 on node 1 of a p5.48xlarge), as NVIDIA's recipes do with numactl
The stock file in the container is untouched: runs.sh copies it to /tmp, patches the copy and runs
that, in a container removed after the run.
"""
@@ -45,11 +50,38 @@
" standard_provider.recompute_num_layers = 1\n"
' if hasattr(standard_provider, "mtp_num_layers"):\n',
),
+ (
+ " loader_iter: Iterator[dict[str, Any]] = iter(train_loader)\n",
+ " loader_iter: Iterator[dict[str, Any]] = iter(train_loader)\n"
+ ' if os.environ.get("MIMO_REPLAY") == "1":\n'
+ " from itertools import islice\n"
+ " _n = cfg.train.train_iters * (\n"
+ " cfg.train.global_batch_size // cfg.train.micro_batch_size\n"
+ " )\n"
+ " _batches = list(islice(loader_iter, _n))\n"
+ " if len(_batches) != _n:\n"
+ ' raise RuntimeError(f"MIMO_REPLAY: {len(_batches)} of {_n} batches")\n'
+ ' print(f"MIMO_REPLAY: {_n} batches ready before step 1", flush=True)\n'
+ " loader_iter = iter(_batches)\n",
+ ),
]
+PIN = """
+if os.environ.get("MIMO_PIN") == "1":
+ _node = int(os.environ["LOCAL_RANK"]) // 4
+ _cpus = set()
+ for _part in open(f"/sys/devices/system/node/node{_node}/cpulist").read().strip().split(","):
+ _first, _, _last = _part.partition("-")
+ _cpus.update(range(int(_first), int(_last or _first) + 1))
+ os.sched_setaffinity(0, _cpus)
+ print(f"MIMO_PIN: rank {os.environ['LOCAL_RANK']} on NUMA node {_node}", flush=True)
+"""
+if src.count("import os\n") < 1:
+ sys.exit("patch_mimo: no 'import os' line")
+src = src.replace("import os\n", "import os\n" + PIN, 1)
for old, new in EDITS:
n = src.count(old)
if n != 1:
sys.exit(f"patch_mimo: expected 1 match, found {n}: {old.strip()[:70]!r}")
src = src.replace(old, new)
open(path, "w").write(src)
-print("patch_mimo: 4 edits applied to", path)
+print(f"patch_mimo: {len(EDITS) + 1} edits applied to {path}")
diff --git a/training/rdsp/bench/compare/mimo.sh b/training/rdsp/bench/compare/mimo.sh
new file mode 100755
index 000000000..ee9a86562
--- /dev/null
+++ b/training/rdsp/bench/compare/mimo.sh
@@ -0,0 +1,35 @@
+#!/bin/bash
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+# Table 4: rdsp against MegatronMIMO on MIMO's own layouts. Usage: bash bench/mimo.sh
+# layout 9b Qwen3.5-9B: 8 vision GPUs + language DP8, 16 GPUs
+# 27b Qwen3.5-27B: 1 vision GPU + language TP4 x PP2, 9 GPUs
+# 9b-10gpu Qwen3.5-9B: 2 vision GPUs + language DP8, 10 GPUs
+# system rdsp from one node of the Ray cluster
+# mimo on every node; MIMO_PIN=0 runs it unpinned
+set -euo pipefail
+case "${1:-}" in
+ 9b | 9b-10gpu) MODEL=Qwen3.5-9B ;;
+ 27b) MODEL=Qwen3.5-27B ;;
+ *) sed -n 4,9p "$0"; exit 1 ;;
+esac
+. "$(dirname "$0")/lib/common.sh"
+LOGS=$LOGS/mimo
+DP8=tp=1,pp=1,dp=8,rank_offset=0
+
+case "$1-${2:-}" in
+ 9b-rdsp)
+ rdsp 9b-rdsp --stages 2 --cuts 0 --stage 0:gpus=8,tp=1,zero=1 --stage 1:gpus=8,tp=1,zero=1 \
+ --rows 8 --microbatches 16 ;;
+ 9b-mimo) mimo 9b-mimo tp=1,pp=1,dp=8,rank_offset=8 $DP8 8 8 8 ;;
+ 27b-rdsp)
+ rdsp 27b-rdsp --stages 3 --cuts 0,33 --stage 0:gpus=1,tp=1,zero=1 \
+ --stage 1:gpus=4,tp=4,zero=1,recompute_blocks=1 --stage 2:gpus=4,tp=4,zero=1 \
+ --rows 2 --microbatches 64 ;;
+ 27b-mimo) mimo 27b-mimo tp=1,pp=1,dp=1,rank_offset=8 tp=4,pp=2,dp=1,rank_offset=0 2 8 1 ;;
+ 9b-10gpu-rdsp)
+ rdsp 9b-10gpu-rdsp --stages 2 --cuts 0 --stage 0:gpus=2,tp=1,zero=1 --stage 1:gpus=8,tp=1,zero=1 \
+ --rows 8 --microbatches 16 ;;
+ 9b-10gpu-mimo) MIMO_PIN=${MIMO_PIN:-0} mimo 9b-10gpu-mimo tp=1,pp=1,dp=2,rank_offset=8 $DP8 8 8 2 ;;
+ *) sed -n 4,9p "$0"; exit 1 ;;
+esac
diff --git a/training/rdsp/bench/compare/prepare.sh b/training/rdsp/bench/compare/prepare.sh
new file mode 100755
index 000000000..7af10ba85
--- /dev/null
+++ b/training/rdsp/bench/compare/prepare.sh
@@ -0,0 +1,33 @@
+#!/bin/bash
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+# Weights, Megatron checkpoints and training rows for the models named, in $DATA_DIR (default
+# ~/rdsp-bench). Run it on every node, or once if DATA_DIR is on storage the nodes share.
+# bash bench/prepare.sh 35B-A3B 27B 9B
+# For each model: the Hugging Face weights; Megatron-Bridge's checkpoint; MegatronMIMO's (9B, 27B);
+# and 50 steps of 128 rows exported from Bridge's CORD-v2 loader, which rdsp and TorchTitan replay.
+# Finished steps are skipped on a rerun.
+set -euo pipefail
+for size in "$@"; do
+ MODEL=Qwen3.5-$size
+ . "$(dirname "$0")/lib/common.sh"
+ LOGS=$BENCH/logs/prepare/$size
+ mkdir -p "$DATA_DIR/hf" "$LOGS"
+
+ run "$LOGS/download.log" in_venv "$RDSP_VENV" . env HF_HOME="$DATA_DIR/hf" python -c \
+ "import huggingface_hub as h; h.snapshot_download('Qwen/$MODEL', allow_patterns=['*.json', '*.safetensors', '*.txt', '*.jinja'])"
+
+ [ -d "$DATA_DIR/megatron/$MODEL" ] || run "$LOGS/convert.log" container \
+ "python scripts/conversion/setup_conversion.py import --hf-model Qwen/$MODEL --megatron-path /workspace/megatron/$MODEL"
+
+ if [ "$size" != 35B-A3B ] && [ ! -d "$DATA_DIR/mimo/$MODEL" ]; then
+ tp=1; [ "$size" = 27B ] && tp=4 # the 27B runs out of memory converting on one GPU
+ run "$LOGS/convert-mimo.log" container "python -m torch.distributed.run --nproc_per_node=$((tp + 1)) \
+examples/conversion/convert_megatron_mimo.py import --hf-model Qwen/$MODEL --megatron-path /workspace/mimo/$MODEL \
+--component language=tp=$tp,dp=1,rank_offset=0 --component images=tp=1,dp=1,rank_offset=$tp --torch-dtype bfloat16"
+ fi
+
+ [ -f "$DATA_DIR/rows/$MODEL/stats.json" ] || run "$LOGS/export.log" container \
+ "python /rdsp/bench/compare/lib/export_bridge_batches.py --out /workspace/rows/$MODEL --steps 50 --recipe $RECIPE $BRIDGE_DATA"
+ [ -n "${DRY:-}" ] || sudo chown -R "$(id -u):$(id -g)" "$DATA_DIR" # the container writes as root
+done
diff --git a/training/rdsp/bench/compare/qwen35_27b.sh b/training/rdsp/bench/compare/qwen35_27b.sh
new file mode 100755
index 000000000..b59306039
--- /dev/null
+++ b/training/rdsp/bench/compare/qwen35_27b.sh
@@ -0,0 +1,37 @@
+#!/bin/bash
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+# Table 2: Qwen3.5-27B on 16 GPUs. Usage: bash bench/qwen35_27b.sh
+# rdsp vision encoder on a 2-GPU stage, 7 language stages of 2 GPUs
+# rdsp-fp32 the same with FP32 gradients and master weights
+# rdsp-pp8 8 stages of 2 GPUs, every layer recomputed
+# rdsp-pp8-cut 8 stages of 2 GPUs at 4 rows a microbatch: the cut bridge uses
+# bridge Megatron-Bridge, PP8 x DP2 at rdsp-pp8-cut's cut (on every node)
+# torchtitan FSDP inside each node, DP2 across the nodes (on every node)
+set -euo pipefail
+MODEL=Qwen3.5-27B
+. "$(dirname "$0")/lib/common.sh"
+LOGS=$LOGS/qwen35_27b
+RECIPE_27B=qwen35-27b-vision2-pp7dp2.sh
+
+case "${1:-}" in
+ rdsp) recipe rdsp $RECIPE_27B ;;
+ rdsp-fp32) recipe rdsp-fp32 $RECIPE_27B --grad-dtype fp32 --master-dtype fp32 ;;
+ rdsp-pp8)
+ rdsp rdsp-pp8 --stages 8 --cuts measured --stage 0:gpus=2,tp=1,zero=1,recompute=1 \
+ $(stages 1 7 2 recompute=1) --rows 2 --microbatches 64 ;;
+ rdsp-pp8-cut)
+ rdsp rdsp-pp8-cut --stages 8 --cuts measured --stage 0:gpus=2,tp=1,zero=1,recompute_blocks=0 \
+ $(stages 1 7 2) --rows 4 --microbatches 32 ;;
+ bridge) # LAYOUT: the cut rdsp-pp8-cut printed, on nodes that do not have its log
+ if [ -z "${LAYOUT:-}" ] && [ ! -f "$LOGS/rdsp-pp8-cut.log" ]; then
+ echo "run 'bash bench/qwen35_27b.sh rdsp-pp8-cut' first, or set LAYOUT" >&2; exit 1
+ fi
+ layout=${LAYOUT:-$(python3 "$BENCH/lib/layout_from_log.py" megatron-layout "$LOGS/rdsp-pp8-cut.log")}
+ echo "LAYOUT=$layout"
+ RECOMPUTE=1 bridge bridge 1 8 "\"model.pipeline_model_parallel_layout='$layout'\"" \
+ dist.use_tp_pp_dp_mapping=true model.batch_p2p_sync=false ddp.overlap_grad_reduce=true \
+ ddp.overlap_param_gather=true train.micro_batch_size=2 ;;
+ torchtitan) titan torchtitan qwen35_27b_cord_hsdp2x8_rc_bf16 ;;
+ *) sed -n 4,10p "$0"; exit 1 ;;
+esac
diff --git a/training/rdsp/bench/compare/qwen35_35b.sh b/training/rdsp/bench/compare/qwen35_35b.sh
new file mode 100755
index 000000000..18050f433
--- /dev/null
+++ b/training/rdsp/bench/compare/qwen35_35b.sh
@@ -0,0 +1,35 @@
+#!/bin/bash
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+# Table 1 and Figure 2: Qwen3.5-35B-A3B on 16 GPUs. Usage: bash bench/qwen35_35b.sh
+# rdsp vision encoder on a 4-GPU stage, 6 language stages of 2 GPUs, Liger's expert kernel
+# rdsp-hf the same with Hugging Face's experts
+# bridge Megatron-Bridge: NVIDIA's TP1 x PP2 x EP8 with HybridEP (on every node)
+# torchtitan FSDP over 16 GPUs + EP8 (on every node)
+# figure2-vision 50 steps, vision encoder on a 4-GPU stage, Hugging Face's experts
+# figure2-pp8 50 steps, 8 stages of 2 GPUs
+set -euo pipefail
+MODEL=Qwen3.5-35B-A3B
+. "$(dirname "$0")/lib/common.sh"
+LOGS=$LOGS/qwen35_35b
+
+case "${1:-}" in
+ rdsp) recipe rdsp qwen35-35b-a3b-vision4-pp6dp2.sh ;;
+ rdsp-hf) recipe rdsp-hf qwen35-35b-a3b-vision4-pp6dp2.sh --moe-experts hf ;;
+ bridge)
+ export CONTAINER_ENV="CUDA_DEVICE_MAX_CONNECTIONS=32 NUM_OF_HYBRID_EP_RANKS_PER_NVLINK_DOMAIN=8 \
+NVLINK_DOMAIN_SIZE=8 USE_MNNVL=0"
+ bridge bridge 1 2 model.expert_model_parallel_size=8 model.batch_p2p_comm=false \
+ model.batch_p2p_sync=false "\"model.pipeline_model_parallel_layout='Et*17|t*23L'\"" \
+ model.moe_token_dispatcher_type=flex model.moe_flex_dispatcher_backend=hybridep \
+ model.moe_hybridep_num_sms=16 model.moe_permute_fusion_into_hybridep=true ;;
+ torchtitan)
+ titan torchtitan qwen35_35b_a3b_cord_fsdp16_ep8_bf16 ;;
+ figure2-vision)
+ STEPS=50 rdsp figure2-vision --stages 7 --cuts 0,measured \
+ --stage 0:gpus=4,tp=1,zero=1,recompute=1 $(stages 1 6 2 recompute=1) --rows 4 --microbatches 32 ;;
+ figure2-pp8)
+ STEPS=50 rdsp figure2-pp8 --stages 8 --cuts measured \
+ --stage 0:gpus=2,tp=1,zero=1,recompute_blocks=0 $(stages 1 7 2) --rows 2 --microbatches 64 ;;
+ *) sed -n 4,10p "$0"; exit 1 ;;
+esac
diff --git a/training/rdsp/bench/compare/qwen35_9b.sh b/training/rdsp/bench/compare/qwen35_9b.sh
new file mode 100755
index 000000000..4280be1e2
--- /dev/null
+++ b/training/rdsp/bench/compare/qwen35_9b.sh
@@ -0,0 +1,20 @@
+#!/bin/bash
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+# Table 3: Qwen3.5-9B on 16 GPUs. Usage: bash bench/qwen35_9b.sh
+# rdsp vision encoder on a 4-GPU stage, 6 language stages of 2 GPUs
+# bridge Megatron-Bridge, DP16, images prepared before step 1 (on every node)
+# torchtitan FSDP inside each node, DP2 across the nodes (on every node)
+set -euo pipefail
+MODEL=Qwen3.5-9B
+. "$(dirname "$0")/lib/common.sh"
+LOGS=$LOGS/qwen35_9b
+
+case "${1:-}" in
+ rdsp) recipe rdsp qwen35-9b-vision4-pp6dp2.sh ;;
+ bridge)
+ BRIDGE_REPLAY=1 bridge bridge 1 1 train.micro_batch_size=1 ddp.overlap_grad_reduce=true \
+ ddp.overlap_param_gather=true ;;
+ torchtitan) titan torchtitan qwen35_9b_cord_hsdp2x8_bf16 ;;
+ *) sed -n 4,7p "$0"; exit 1 ;;
+esac
diff --git a/training/rdsp/bench/compare/setup.sh b/training/rdsp/bench/compare/setup.sh
new file mode 100755
index 000000000..6b110855d
--- /dev/null
+++ b/training/rdsp/bench/compare/setup.sh
@@ -0,0 +1,36 @@
+#!/bin/bash
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+# Set up one GPU node with the versions the results were measured with.
+# bash bench/setup.sh rdsp in $RDSP_VENV (default ~/venv) and the NeMo container
+# bash bench/setup.sh torchtitan TorchTitan 3c36a77 in ~/torchtitan, its own venv ~/tt_venv
+# Needs NVIDIA drivers, CUDA, Docker with the NVIDIA runtime, and uv (astral.sh/uv).
+set -euxo pipefail
+RDSP=$(cd "$(dirname "$0")/../.." && pwd)
+VENV=${RDSP_VENV:-$HOME/venv}
+unset LD_LIBRARY_PATH # some images' CUDA libraries break torch's cuDNN
+
+if [ "${1:-}" = torchtitan ]; then
+ [ -d ~/torchtitan ] || git clone https://github.com/pytorch/torchtitan ~/torchtitan
+ git -C ~/torchtitan checkout 3c36a7767cf2222aa4e0d494463f486363c8df99
+ uv venv -p 3.12 ~/tt_venv && . ~/tt_venv/bin/activate
+ uv pip install --pre "torch==2.16.0.dev20261012" "torchvision==0.30.0.dev20261012" \
+ --index-url https://download.pytorch.org/whl/nightly/cu130
+ uv pip install -r ~/torchtitan/requirements.txt -r ~/torchtitan/.ci/docker/requirements-vlm.txt
+ uv pip install --no-deps -e ~/torchtitan
+ exit 0
+fi
+
+uv venv -p 3.12 "$VENV" && . "$VENV/bin/activate"
+uv pip install "torch==2.13.0" "torchvision==0.28.0" "transformers==5.17.0" "ray==2.59.0" \
+ "accelerate==1.15.0" cloudpickle safetensors datasets pillow ninja packaging numpy pytest
+CUDA_HOME=/usr/local/cuda-$(python -c "import torch; print(torch.version.cuda)")
+[ -d "$CUDA_HOME" ] || CUDA_HOME=/usr/local/cuda
+echo "export CUDA_HOME=$CUDA_HOME" >> "$VENV/bin/activate"
+export CUDA_HOME DS_BUILD_OPS=0
+uv pip install --no-build-isolation \
+ "git+https://github.com/deepspeedai/DeepSpeed.git@53a2ac44fb664bea838df3981ba4366b91643070"
+uv pip install -e "$RDSP"
+uv pip install "flash-linear-attention==0.5.2" "liger-kernel==0.8.4"
+uv pip install --no-build-isolation "causal-conv1d==1.7.0"
+${DOCKER:-sudo docker} pull nvcr.io/nvidia/nemo:26.08
diff --git a/training/rdsp/bench/torchtitan/cord_data.py b/training/rdsp/bench/compare/torchtitan/cord_data.py
similarity index 100%
rename from training/rdsp/bench/torchtitan/cord_data.py
rename to training/rdsp/bench/compare/torchtitan/cord_data.py
diff --git a/training/rdsp/bench/torchtitan/cord_qwen35.py b/training/rdsp/bench/compare/torchtitan/cord_qwen35.py
similarity index 62%
rename from training/rdsp/bench/torchtitan/cord_qwen35.py
rename to training/rdsp/bench/compare/torchtitan/cord_qwen35.py
index 95d56a1de..34781a7c5 100644
--- a/training/rdsp/bench/torchtitan/cord_qwen35.py
+++ b/training/rdsp/bench/compare/torchtitan/cord_qwen35.py
@@ -3,7 +3,7 @@
"""TorchTitan on the rows Megatron-Bridge exported: Qwen3.5 on CORD-v2.
-Bridge's SFT rows, exported by bench/common/export_bridge_batches.py (the files rdsp
+Bridge's SFT rows, exported by bench/compare/lib/export_bridge_batches.py (the files rdsp
replays), are fed to TorchTitan unchanged: same rows in the same order, same token
ids, same answer-only loss mask, same image patches, every row padded to 2048. Only
the conventions change:
@@ -26,10 +26,7 @@
PYTHONPATH= EXPORTED= HF_ASSETS= MODULE=cord_qwen35 CONFIG=qwen35_27b_cord_tp4pp2 ./run_train.sh
-STEPS (default 50). CONFIG=qwen35_27b_cord_tp4pp2_rc: the same with full recompute.
-CONFIG=qwen35_27b_cord_tp4dp2 (no pipeline: TP4 x FSDP over 2) and qwen35_27b_cord_tp4dp2_rc;
-qwen35_27b_cord_tp2pp2dp2 (TP2 x PP2 x FSDP 2) and qwen35_27b_cord_tp2pp4 (TP2 x PP4), each also
-_rc.
+STEPS (default 50). The configs below are the ones bench/compare/qwen35_*.sh run.
"""
import os
@@ -39,7 +36,7 @@
from torchtitan.components.loss import ChunkedLossWrapper, CrossEntropyLoss
from torchtitan.components.optim import AdamW, LRSchedulersContainer, Optim, OptimizersContainer
from torchtitan.components.tokenizer import MultiModalTokenizer
-from torchtitan.config import TrainingConfig
+from torchtitan.config import CommConfig, DebugConfig, TrainingConfig
from torchtitan.config.parallelism import ParallelismConfig
from torchtitan.distributed.activation_checkpoint import FullAC, RegionAC
from torchtitan.models.common.config_utils import decoder_vocab_size
@@ -117,34 +114,6 @@ def qwen35_27b_cord_tp4pp2_rc() -> Trainer.Config:
return config
-def qwen35_27b_cord_tp4dp2() -> Trainer.Config:
- """No pipeline: TP4 x data parallel 2 on 8 GPUs, the layout Bridge and rdsp run
- as TP4 x DP2. TorchTitan's data parallelism is FSDP (dp_shard 2): weights,
- gradients and Adam are split over the two copies, where Bridge's distributed
- optimizer and DeepSpeed's ZeRO-1 split only the optimizer state. 32 microbatches
- of 2 rows (one per copy) per step, the same rows as Bridge's; everything else as
- qwen35_27b_cord_tp4pp2."""
- config = qwen35_27b_cord_tp4pp2()
- parallelism = ParallelismConfig(
- data_parallel_shard_degree=2,
- tensor_parallel_degree=4,
- enable_sequence_parallel=True,
- )
- config.parallelism = parallelism
- config.model = build_model_config("27B", seq_len=SEQ, parallelism=parallelism)
- config.dataloader = exported_dataloader(os.environ["EXPORTED"], data_parallel=2)
- # 64 rows of 2048 tokens a step: 32 accumulation steps of one row per copy
- config.training.num_tokens_per_train_step = ROWS_PER_STEP * SEQ
- return config
-
-
-def qwen35_27b_cord_tp4dp2_rc() -> Trainer.Config:
- """qwen35_27b_cord_tp4dp2 with every block recomputed (FullAC)."""
- config = qwen35_27b_cord_tp4dp2()
- config.activation_checkpoint = FullAC.Config()
- return config
-
-
def _with_layout(
config: Trainer.Config, parallelism: ParallelismConfig, data_parallel: int, flavor: str = "27B"
) -> Trainer.Config:
@@ -158,80 +127,14 @@ def _with_layout(
)
config.dataloader = exported_dataloader(os.environ["EXPORTED"], data_parallel=data_parallel)
config.training.num_tokens_per_train_step = ROWS_PER_STEP * SEQ
- return config
-
-
-def qwen35_27b_cord_tp2pp2dp2() -> Trainer.Config:
- """TP2 x PP2 x data parallel 2 (FSDP over the 2 copies), as Bridge and rdsp ran this
- layout: 32 pipeline microbatches of one row per copy, the vision encoder on stage 0,
- layers 32 | 32 (TorchTitan's default split). No recompute: a fit check."""
- return _with_layout(
- qwen35_27b_cord_tp4pp2(),
- ParallelismConfig(
- data_parallel_shard_degree=2,
- tensor_parallel_degree=2,
- enable_sequence_parallel=True,
- pipeline_parallel_degree=2,
- pipeline_parallel_schedule="1F1B",
- num_pp_microbatches=ROWS_PER_STEP // 2,
- ),
- data_parallel=2,
+ # MB_ROWS (default 1): rows each GPU runs per microbatch, so fewer accumulation steps
+ config.training.num_tokens_per_microbatch_per_dp_rank = SEQ * int(
+ os.environ.get("MB_ROWS", "1")
)
-
-
-def qwen35_27b_cord_tp2pp2dp2_rc() -> Trainer.Config:
- """qwen35_27b_cord_tp2pp2dp2 with every block recomputed (FullAC)."""
- config = qwen35_27b_cord_tp2pp2dp2()
- config.activation_checkpoint = FullAC.Config()
- return config
-
-
-def qwen35_27b_cord_tp2pp4() -> Trainer.Config:
- """TP2 x PP4, no data parallelism, as Bridge and rdsp ran this layout: 64 pipeline
- microbatches of one row, the vision encoder on stage 0, layers 16 | 17 | 16 | 15
- (TorchTitan's default split: the embedding and the output layer each count as one
- layer). No recompute: a fit check."""
- return _with_layout(
- qwen35_27b_cord_tp4pp2(),
- ParallelismConfig(
- data_parallel_shard_degree=1,
- tensor_parallel_degree=2,
- enable_sequence_parallel=True,
- pipeline_parallel_degree=4,
- pipeline_parallel_schedule="1F1B",
- num_pp_microbatches=ROWS_PER_STEP,
- ),
- data_parallel=1,
- )
-
-
-def qwen35_27b_cord_tp2pp4_rc() -> Trainer.Config:
- """qwen35_27b_cord_tp2pp4 with every block recomputed (FullAC)."""
- config = qwen35_27b_cord_tp2pp4()
- config.activation_checkpoint = FullAC.Config()
- return config
-
-
-def qwen35_27b_cord_fsdp8() -> Trainer.Config:
- """TorchTitan's own regime: FSDP over all 8 GPUs (dp_shard 8), no tensor or pipeline
- parallelism. Weights, gradients and Adam are split eight ways, and each layer is
- gathered whole just before it runs. 8 accumulation steps of one row per GPU per step:
- 64 rows, Bridge's rows dealt to the 8 copies as Megatron deals them. No recompute: a
- fit check."""
- return _with_layout(
- qwen35_27b_cord_tp4pp2(),
- ParallelismConfig(
- data_parallel_shard_degree=8,
- tensor_parallel_degree=1,
- ),
- data_parallel=8,
- )
-
-
-def qwen35_27b_cord_fsdp8_rc() -> Trainer.Config:
- """qwen35_27b_cord_fsdp8 with every block recomputed (FullAC)."""
- config = qwen35_27b_cord_fsdp8()
- config.activation_checkpoint = FullAC.Config()
+ # no NCCL flight recorder and no structured logging: debugging aids, off for timing (as
+ # Megatron-Bridge runs without its NaN checks)
+ config.comm = CommConfig(trace_buf_size=0)
+ config.debug = DebugConfig(enable_structured_logging=False)
return config
@@ -280,13 +183,6 @@ def qwen35_35b_a3b_cord_fsdp16() -> Trainer.Config:
)
-def qwen35_35b_a3b_cord_fsdp16_rc() -> Trainer.Config:
- """qwen35_35b_a3b_cord_fsdp16 with every block recomputed (FullAC)."""
- config = qwen35_35b_a3b_cord_fsdp16()
- config.activation_checkpoint = FullAC.Config()
- return config
-
-
def qwen35_35b_a3b_cord_fsdp16_ep8() -> Trainer.Config:
"""qwen35_35b_a3b_cord_fsdp16 with expert parallelism 8: each node's 8 GPUs split the
256 experts (32 each) and send tokens to them with all-to-all inside the node; the expert
@@ -323,22 +219,6 @@ def _bf16_reduce(config: Trainer.Config) -> Trainer.Config:
return config
-def qwen35_27b_cord_fsdp8_rc_bf16() -> Trainer.Config:
- """qwen35_27b_cord_fsdp8_rc with gradients reduced in bf16."""
- return _bf16_reduce(qwen35_27b_cord_fsdp8_rc())
-
-
-def qwen35_27b_cord_fsdp8_ffnrc_bf16() -> Trainer.Config:
- """qwen35_27b_cord_fsdp8 with only each block's MLP recomputed (RegionAC: every declared
- region kept except feed_forward.*) and gradients reduced in bf16. Between no recompute
- (out of memory at 73 GiB) and FullAC."""
- config = _bf16_reduce(qwen35_27b_cord_fsdp8())
- config.activation_checkpoint = RegionAC.Config(
- save_regions=["*"], recompute_regions=["feed_forward.*"]
- )
- return config
-
-
def qwen35_35b_a3b_cord_fsdp16_ep8_bf16() -> Trainer.Config:
"""qwen35_35b_a3b_cord_fsdp16_ep8 with gradients reduced in bf16."""
return _bf16_reduce(qwen35_35b_a3b_cord_fsdp16_ep8())
@@ -373,27 +253,6 @@ def qwen35_27b_cord_fsdp16_rc_bf16() -> Trainer.Config:
return _bf16_reduce(qwen35_27b_cord_fsdp16_rc())
-def qwen35_35b_a3b_cord_fsdp8_ep8_rc_bf16() -> Trainer.Config:
- """Qwen3.5-35B-A3B on one node: FSDP over 8 GPUs with expert parallelism 8 (32 experts per
- GPU), every block recomputed, gradients reduced in bf16, no router load-balancing loss
- (ROWS=64). TorchTitan keeps fp32 weights and Adam moments: ~16 bytes a parameter, about
- 70 GB a GPU before activations, so this is a fit check."""
- config = _without_router_balancing_loss(
- _with_layout(
- qwen35_27b_cord_tp4pp2(),
- ParallelismConfig(
- data_parallel_shard_degree=8,
- tensor_parallel_degree=1,
- expert_parallel_degree=8,
- ),
- data_parallel=8,
- flavor="35B-A3B",
- )
- )
- config.activation_checkpoint = FullAC.Config()
- return _bf16_reduce(config)
-
-
# rdsp's measured cut of the 27B over 8 pipeline stages (decoder layers per stage), given to
# TorchTitan and Megatron-Bridge alike
PP8_CUT_27B = (1, 9, 10, 9, 9, 9, 10, 7)
@@ -428,45 +287,108 @@ def _from_dcp(config: Trainer.Config) -> Trainer.Config:
return config
-def qwen35_27b_cord_pp8_rc() -> Trainer.Config:
- """TP1 x PP8 on one node, 1F1B, 64 microbatches of one row, at rdsp's measured cut
- (PP8_CUT_27B), every block recomputed (FullAC), gradients reduced in bf16 (no data
- parallel here, so no reduce), weights from DCP."""
- config = _with_layout(
- qwen35_27b_cord_tp4pp2(),
- ParallelismConfig(
- data_parallel_shard_degree=1,
- tensor_parallel_degree=1,
- pipeline_parallel_degree=8,
- pipeline_parallel_schedule="1F1B",
- num_pp_microbatches=ROWS_PER_STEP,
- pipeline_parallel_module_fqns_per_model_part=_module_split(PP8_CUT_27B),
- ),
- data_parallel=1,
+def _qwen35_9b_16gpu(shard: int, tp: int, replicate: int = 1, **parallel) -> Trainer.Config:
+ """Qwen3.5-9B on two nodes (ROWS=128, HF_ASSETS at the 9B snapshot): TP `tp` inside a
+ node times FSDP over `shard` copies, those `replicate` times (tp * shard * replicate =
+ 16), gradients reduced in bf16, no recompute. `parallel`: other ParallelismConfig
+ fields."""
+ return _bf16_reduce(
+ _with_layout(
+ qwen35_27b_cord_tp4pp2(),
+ ParallelismConfig(
+ data_parallel_replicate_degree=replicate,
+ data_parallel_shard_degree=shard,
+ tensor_parallel_degree=tp,
+ **parallel,
+ ),
+ data_parallel=shard * replicate,
+ flavor="9B",
+ )
)
+
+
+def qwen35_9b_cord_fsdp16_bf16() -> Trainer.Config:
+ """Qwen3.5-9B, FSDP over all 16 GPUs, no tensor parallelism."""
+ return _qwen35_9b_16gpu(shard=16, tp=1)
+
+
+def qwen35_9b_cord_fsdp16_rc_bf16() -> Trainer.Config:
+ """qwen35_9b_cord_fsdp16_bf16 with every block recomputed (FullAC)."""
+ config = qwen35_9b_cord_fsdp16_bf16()
config.activation_checkpoint = FullAC.Config()
- return _from_dcp(_bf16_reduce(config))
+ return config
+
+
+def qwen35_9b_cord_tp2fsdp8_bf16() -> Trainer.Config:
+ """Qwen3.5-9B, TP2 inside a node times FSDP over 8 copies."""
+ return _qwen35_9b_16gpu(shard=8, tp=2)
+
+
+def qwen35_9b_cord_tp4fsdp4_bf16() -> Trainer.Config:
+ """Qwen3.5-9B, TP4 inside a node (Bridge's recipe layout) times FSDP over 4 copies."""
+ return _qwen35_9b_16gpu(shard=4, tp=4)
+
+
+def qwen35_9b_cord_hsdp2x8_bf16() -> Trainer.Config:
+ """Qwen3.5-9B, HSDP: FSDP over each node's 8 GPUs, the two nodes replicas of each other.
+ A microbatch's weight gathers and gradient reduce-scatters stay on NVLink; the nodes
+ all-reduce the gradients once a step."""
+ return _qwen35_9b_16gpu(shard=8, tp=1, replicate=2)
+
+def qwen35_9b_cord_fsdp16_noreshard_bf16() -> Trainer.Config:
+ """qwen35_9b_cord_fsdp16_bf16 keeping the weights gathered for the forward pass until
+ the backward pass (fsdp_reshard_after_forward="never"): one gather per microbatch
+ instead of two, the 9B's bf16 weights resident on every GPU."""
+ return _qwen35_9b_16gpu(shard=16, tp=1, fsdp_reshard_after_forward="never")
-def qwen35_27b_cord_pp8dp2_rc() -> Trainer.Config:
- """Two nodes (ROWS=128): PP8 x FSDP over 2 copies, 64 microbatches of one row per copy,
- otherwise as qwen35_27b_cord_pp8_rc."""
+
+def qwen35_27b_cord_hsdp2x8_rc_bf16() -> Trainer.Config:
+ """Qwen3.5-27B, HSDP: FSDP over each node's 8 GPUs (each GPU the shard and work of the
+ one-node FSDP8 run), the nodes replicas, every block recomputed, gradients reduced in
+ bf16 (ROWS=128)."""
config = _with_layout(
qwen35_27b_cord_tp4pp2(),
ParallelismConfig(
- data_parallel_shard_degree=2,
+ data_parallel_replicate_degree=2,
+ data_parallel_shard_degree=8,
tensor_parallel_degree=1,
- pipeline_parallel_degree=8,
- pipeline_parallel_schedule="1F1B",
- num_pp_microbatches=ROWS_PER_STEP // 2,
- pipeline_parallel_module_fqns_per_model_part=_module_split(PP8_CUT_27B),
),
- data_parallel=2,
+ data_parallel=16,
)
config.activation_checkpoint = FullAC.Config()
- return _from_dcp(_bf16_reduce(config))
+ return _bf16_reduce(config)
-def qwen35_35b_a3b_cord_fsdp16_bf16() -> Trainer.Config:
- """qwen35_35b_a3b_cord_fsdp16 with gradients reduced in bf16."""
- return _bf16_reduce(qwen35_35b_a3b_cord_fsdp16())
+def qwen35_35b_a3b_cord_fsdp16_ep8_rc_bf16() -> Trainer.Config:
+ """qwen35_35b_a3b_cord_fsdp16_ep8_rc with gradients reduced in bf16. With MB_ROWS=8 each
+ GPU runs its 8 rows of the step in one microbatch, so FSDP gathers the expert weights
+ across the nodes once a step instead of eight times."""
+ return _bf16_reduce(qwen35_35b_a3b_cord_fsdp16_ep8_rc())
+
+
+def qwen35_35b_a3b_cord_fsdp16_ep16_bf16() -> Trainer.Config:
+ """Qwen3.5-35B-A3B with expert parallelism 16: each GPU holds 16 of the 256 experts
+ whole, so expert weights are never gathered; the all-to-all crosses the nodes. FSDP over
+ 16 for the rest, no router load-balancing loss, gradients reduced in bf16."""
+ return _bf16_reduce(
+ _without_router_balancing_loss(
+ _with_layout(
+ qwen35_27b_cord_tp4pp2(),
+ ParallelismConfig(
+ data_parallel_shard_degree=16,
+ tensor_parallel_degree=1,
+ expert_parallel_degree=16,
+ ),
+ data_parallel=16,
+ flavor="35B-A3B",
+ )
+ )
+ )
+
+
+def qwen35_35b_a3b_cord_fsdp16_ep16_rc_bf16() -> Trainer.Config:
+ """qwen35_35b_a3b_cord_fsdp16_ep16_bf16 with every block recomputed (FullAC)."""
+ config = qwen35_35b_a3b_cord_fsdp16_ep16_bf16()
+ config.activation_checkpoint = FullAC.Config()
+ return config
diff --git a/training/rdsp/bench/encoder/enc_bench.py b/training/rdsp/bench/encoder/enc_bench.py
deleted file mode 100644
index 3f0fa3052..000000000
--- a/training/rdsp/bench/encoder/enc_bench.py
+++ /dev/null
@@ -1,681 +0,0 @@
-#!/usr/bin/env python
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-
-"""Time one Qwen3.5 vision encoder alone on one GPU: Megatron-Bridge's (Transformer Engine
-modules) or Hugging Face's, built from the same config with random weights, on the same images.
-
-For each number of images per call (--images) and each mode (forward; forward + backward):
- timing pass no hooks, no profiler: median over --passes of the time per image
- profile pass torch.profiler over --profile-images images, with labels on the encoder's parts
- (record_function from module hooks and wrappers around the rotary and attention
- functions; the encoders' code is not changed). From the trace: GPU kernels per
- image, GPU busy time per image, CPU time per part, kernels per part, GPU syncs.
-
- python enc_bench.py --impl bridge|hf [--hf-attn sdpa|varlen] --config
- --grids grids.json --images 1,2,4,8 --out result.json [--trace-dir DIR]
-
-Bridge runs inside the NeMo container (Megatron-Bridge v0.6.0 there); Hugging Face runs in the
-container (same torch as Bridge) or in rdsp's venv (the stack the blog's rdsp runs used).
-"""
-
-import argparse
-import bisect
-import collections
-import gzip
-import json
-import os
-import platform
-import statistics
-import time
-import types
-
-import torch
-
-PARTS = (
- "rotary",
- "core_attn",
- "linear",
- "norm",
- "attn_other",
- "mlp_other",
- "layer_other",
- "outside",
- "backward",
-)
-
-
-# ---------------------------------------------------------------- building the encoders
-
-
-def build_bridge(config_dir, recompute=False, cuda_graph_len=0):
- """Megatron-Bridge's Qwen3VLVisionModel exactly as Qwen3VLModel builds it
- (modelling_qwen3_vl/model.py, v0.6.0): TE layer spec with Qwen3VLSelfAttention, TE merger,
- get_vision_model_config from the HF vision config; bf16 as Float16Module makes it.
- recompute: the language config's full/uniform/1, as our 27B Bridge runs (the vision config
- copies it). cuda_graph_len: vision CUDA graphs (vision_cuda_graph_impl="transformer_engine",
- every call padded to this many patches), captured by capture_bridge_graphs()."""
- os.environ.setdefault("MASTER_ADDR", "127.0.0.1")
- os.environ.setdefault("MASTER_PORT", "29511")
- torch.distributed.init_process_group("nccl", rank=0, world_size=1)
- from megatron.core import parallel_state
- from megatron.core.tensor_parallel.random import model_parallel_cuda_manual_seed
-
- parallel_state.initialize_model_parallel(1, 1)
- # Bridge's initialize.py: use_cudagraphable_rng when CUDA graphs are on (TE's tracker with them)
- model_parallel_cuda_manual_seed(
- 0, te_rng_tracker=bool(cuda_graph_len), use_cudagraphable_rng=bool(cuda_graph_len)
- )
- from megatron.bridge.models.qwen_vl.modelling_qwen3_vl.attention import Qwen3VLSelfAttention
- from megatron.bridge.models.qwen_vl.modelling_qwen3_vl.transformer_config import (
- get_vision_model_config,
- )
- from megatron.bridge.models.qwen_vl.modelling_qwen3_vl.utils import PatchMergerSubmodules
- from megatron.bridge.models.qwen_vl.modelling_qwen3_vl.vision_model import Qwen3VLVisionModel
- from megatron.core.extensions.transformer_engine import (
- TEColumnParallelLinear,
- TENorm,
- TERowParallelLinear,
- )
- from megatron.core.models.vision.vit_layer_specs import (
- get_vit_layer_with_transformer_engine_spec,
- )
- from transformers import AutoConfig
-
- hf_vision = AutoConfig.from_pretrained(config_dir).vision_config
- # the language config's fields get_vision_model_config copies: our Bridge runs' values
- # (no vision CUDA graphs; recompute off here: it repeats the forward, not a per-call cost)
- lang = types.SimpleNamespace(
- recompute_granularity="full" if recompute else None,
- recompute_method="uniform" if recompute else None,
- recompute_num_layers=1 if recompute else None,
- tensor_model_parallel_size=1,
- enable_cuda_graph=False,
- cuda_graph_use_single_mempool=False,
- cuda_graph_retain_backward_graph=False,
- cuda_graph_warmup_steps=3,
- external_cuda_graph=False,
- vision_cuda_graph_impl="transformer_engine" if cuda_graph_len else "none",
- vision_cuda_graph_scope=None,
- )
- if cuda_graph_len:
- lang.max_vision_cuda_graph_seq_length = cuda_graph_len
- cfg = get_vision_model_config(hf_vision, megatron_config=lang)
- cfg.pipeline_model_parallel_size = 1
- cfg.first_pipeline_num_layers = None
- cfg.bf16 = True
- cfg.params_dtype = torch.bfloat16
- spec = get_vit_layer_with_transformer_engine_spec()
- spec.submodules.self_attention.module = Qwen3VLSelfAttention
- merger = PatchMergerSubmodules(
- patch_norm=TENorm, linear_fc1=TEColumnParallelLinear, linear_fc2=TERowParallelLinear
- )
- from megatron.core.process_groups_config import ProcessGroupCollection
-
- # Qwen3VLModel passes its pg_collection; the vision model reads self.pg_collection.tp
- enc = Qwen3VLVisionModel(
- cfg,
- spec,
- merger,
- pre_process=True,
- post_process=True,
- pg_collection=ProcessGroupCollection.use_mpu_process_groups(),
- )
- if os.environ.get("ENC_INT_MAX_SEQLEN") == "1":
- # experiment, not Bridge's behaviour: hand TE the longest image as a Python int instead of
- # Bridge's GPU tensor (seqlens.max()), to measure what the per-layer GPU reads cost
- build = enc.build_packed_seq_params
-
- def build_int(grid_thw):
- p = build(grid_thw)
- p.max_seqlen_q = p.max_seqlen_kv = int(p.max_seqlen_q)
- return p
-
- enc.build_packed_seq_params = build_int
- return enc.cuda().to(torch.bfloat16).train(), hf_vision
-
-
-def capture_bridge_graphs(enc):
- """Capture the vision layers' CUDA graphs as Bridge's training loop does after its warmup
- steps (training/train.py: VisionTECudaGraphHelper, create_cudagraphs, manual hooks)."""
- from megatron.core import num_microbatches_calculator as nmc
- from megatron.core.transformer.cuda_graphs import (
- VisionTECudaGraphHelper,
- get_vision_cuda_graph_seq_length,
- )
-
- if nmc._GLOBAL_NUM_MICROBATCHES_CALCULATOR is None: # training's setup does this
- nmc.init_num_microbatches_calculator(
- rank=0,
- rampup_batch_size=None,
- global_batch_size=1,
- micro_batch_size=1,
- data_parallel_size=1,
- )
- holder = torch.nn.Module()
- holder.vision_model = enc
- helper = VisionTECudaGraphHelper(
- model=[holder],
- vision_config=enc.config,
- vision_seq_length=get_vision_cuda_graph_seq_length(enc.config),
- micro_batch_size=1,
- num_microbatches=1,
- )
- helper.create_cudagraphs()
- helper.cuda_graph_set_manual_hooks()
- assert helper.graphs_created(), "vision CUDA graphs not created"
- return helper
-
-
-def build_hf(config_dir, attn, device, recompute=False):
- from transformers import AutoConfig
- from transformers.models.qwen3_5 import modeling_qwen3_5
-
- hf_vision = AutoConfig.from_pretrained(config_dir).vision_config
- hf_vision._attn_implementation = "sdpa"
- torch.manual_seed(0)
- enc = modeling_qwen3_5.Qwen3_5VisionModel(hf_vision)
- if attn == "varlen":
- # rdsp's --vision-attn varlen (coded 2026-10-17, not in the blog's runs): set after the
- # model is built, as rdsp's use_varlen_vision_attention does
- from ray_deepspeed_pipeline import varlen_attention
-
- varlen_attention.register()
- for m in enc.modules():
- cfg = getattr(m, "config", None)
- if cfg is not None and hasattr(cfg, "_attn_implementation"):
- cfg._attn_implementation = varlen_attention.NAME
- elif attn != "sdpa":
- raise ValueError(attn)
- if recompute:
- # rdsp's recompute_blocks (partition.py): each block's forward under
- # torch.utils.checkpoint(use_reentrant=False)
- import functools
-
- from torch.utils import checkpoint as torch_checkpoint
-
- def checkpointed(forward, *a, **k):
- return torch_checkpoint.checkpoint(forward, *a, use_reentrant=False, **k)
-
- for blk in enc.blocks:
- blk.forward = functools.partial(checkpointed, blk.forward)
- return enc.to(device=device, dtype=torch.bfloat16).train(), hf_vision
-
-
-class _BlockCall(torch.nn.Module):
- """One HF vision block with positional tensor inputs (what make_graphed_callables takes)."""
-
- def __init__(self, blk, length, recompute):
- super().__init__()
- self.blk, self.length, self.recompute = blk, length, recompute
-
- def _run(self, h, cu, cos, sin):
- return self.blk(h, cu_seqlens=cu, max_seqlen=self.length, position_embeddings=(cos, sin))
-
- def forward(self, h, cu, cos, sin):
- if self.recompute:
- from torch.utils import checkpoint as torch_checkpoint
-
- return torch_checkpoint.checkpoint(self._run, h, cu, cos, sin, use_reentrant=False)
- return self._run(h, cu, cos, sin)
-
-
-class HFGraphed(torch.nn.Module):
- """Hugging Face's encoder with CUDA graphs, the way Bridge graphs its encoder: each layer's
- forward and backward captured once (torch.cuda.make_graphed_callables) at a fixed length,
- every call padded to it. Unlike Bridge's, the padding is an attention segment of its own, so
- images never attend to it or to each other (varlen attention, cu_seqlens with the padding
- appended). Patch embedding, position embeddings, rotary tables and merger run eagerly, as in
- Bridge. A prototype for rdsp, not code rdsp ships."""
-
- def __init__(self, enc, length, recompute):
- super().__init__()
- self.enc, self.length, self.recompute = enc, length, recompute
- self.graphed = None
-
- def _prepare(self, pixels, grid_thw):
- from transformers.vision_utils import (
- get_vision_cu_seqlens,
- get_vision_interpolation_indices_and_weights,
- get_vision_position_ids,
- )
-
- enc = self.enc
- idx, w = get_vision_interpolation_indices_and_weights(
- grid_thw,
- num_grid_per_side=enc.num_grid_per_side,
- mode=enc.interpolation_mode,
- align_corners=enc.interpolation_align_corners,
- spatial_merge_size=enc.config.spatial_merge_size,
- kwargs={},
- )
- pos_ids = get_vision_position_ids(grid_thw, enc.spatial_merge_size, kwargs={})
- cu = get_vision_cu_seqlens(grid_thw, kwargs={})
- h = enc.patch_embed(pixels)
- h = h + (enc.pos_embed(idx) * w[:, :, None]).sum(1).to(h.dtype)
- cos, sin = enc.rotary_pos_emb(h, pos_ids)
- s = h.shape[0]
- assert s < self.length, (s, self.length)
- pad = self.length - s
- h = torch.nn.functional.pad(h, (0, 0, 0, pad))
- cos = torch.nn.functional.pad(cos, (0, 0, 0, pad))
- sin = torch.nn.functional.pad(sin, (0, 0, 0, pad))
- cu = torch.cat([cu.to(torch.int32), cu.new_tensor([self.length], dtype=torch.int32)])
- return h, cu, cos, sin, s
-
- def forward(self, pixels, grid_thw):
- h, cu, cos, sin, s = self._prepare(pixels, grid_thw)
- if self.graphed is None:
- torch.set_grad_enabled(
- True
- ) # capture records backward too, even on a no_grad first call
- calls = tuple(_BlockCall(b, self.length, self.recompute) for b in self.enc.blocks)
- sample = []
- x = h.detach()
- for _ in calls:
- sample.append(
- (
- x.clone().requires_grad_(True),
- cu.clone(),
- cos.detach().clone(),
- sin.detach().clone(),
- )
- )
- self.graphed = torch.cuda.make_graphed_callables(calls, tuple(sample))
- print(f"captured HF vision CUDA graphs, length {self.length}", flush=True)
- for g in self.graphed:
- h = g(h, cu, cos, sin)
- return types.SimpleNamespace(pooler_output=self.enc.merger(h[:s]))
-
-
-def encoder_output(impl, out):
- """The merged image embeddings each encoder hands to the language model."""
- return out[0] if impl == "bridge" else out.pooler_output
-
-
-# ---------------------------------------------------------------- labels for the profile pass
-
-
-class Labels:
- """record_function ranges around the encoder's parts, for the profile pass only."""
-
- def __init__(self):
- self.handles = []
- self.undo = []
-
- def module(self, mod, name):
- stack = []
-
- def pre(_m, _args, *_rest):
- r = torch.autograd.profiler.record_function(name)
- r.__enter__()
- stack.append(r)
-
- def post(_m, _args, *_rest):
- stack.pop().__exit__(None, None, None)
-
- self.handles.append(mod.register_forward_pre_hook(pre, with_kwargs=True))
- self.handles.append(mod.register_forward_hook(post, with_kwargs=True))
-
- def function(self, owner, attr, name):
- fn = getattr(owner, attr)
-
- def wrapped(*a, **k):
- with torch.autograd.profiler.record_function(name):
- return fn(*a, **k)
-
- setattr(owner, attr, wrapped)
- self.undo.append(lambda: setattr(owner, attr, fn))
-
- def remove(self):
- for h in self.handles:
- h.remove()
- for undo in self.undo:
- undo()
- self.handles, self.undo = [], []
-
-
-def label_bridge(enc, labels):
- from megatron.bridge.models.qwen_vl.modelling_qwen3_vl import attention as bridge_attention
-
- labels.module(enc, "P:encoder")
- for layer in enc.decoder.layers:
- labels.module(layer, "P:layer")
- sa = layer.self_attention
- labels.module(sa, "P:attn")
- labels.module(sa.linear_qkv, "P:linear") # TE fuses the layer norm into this linear
- labels.module(sa.core_attention, "P:core_attn")
- labels.module(sa.linear_proj, "P:linear")
- labels.module(layer.mlp, "P:mlp")
- labels.module(layer.mlp.linear_fc1, "P:linear") # with the pre-MLP layer norm fused
- labels.module(layer.mlp.linear_fc2, "P:linear")
- labels.function(bridge_attention, "apply_rotary_pos_emb_absolute", "P:rotary")
-
-
-def label_hf(enc, labels):
- from transformers import AttentionInterface
- from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS
- from transformers.models.qwen3_5 import modeling_qwen3_5
-
- labels.module(enc, "P:encoder")
- for blk in enc.blocks:
- labels.module(blk, "P:layer")
- labels.module(blk.attn, "P:attn")
- labels.module(blk.attn.qkv, "P:linear")
- labels.module(blk.attn.proj, "P:linear")
- labels.module(blk.norm1, "P:norm")
- labels.module(blk.norm2, "P:norm")
- labels.module(blk.mlp, "P:mlp")
- for child in blk.mlp.children():
- if isinstance(child, torch.nn.Linear):
- labels.module(child, "P:linear")
- labels.function(modeling_qwen3_5, "apply_rotary_pos_emb_vision", "P:rotary")
- name = enc.config._attn_implementation
- fn = ALL_ATTENTION_FUNCTIONS[name]
-
- def core(*a, **k):
- with torch.autograd.profiler.record_function("P:core_attn"):
- return fn(*a, **k)
-
- AttentionInterface.register(name, core)
- labels.undo.append(lambda: AttentionInterface.register(name, fn))
-
-
-# ---------------------------------------------------------------- reading the trace
-
-SYNC_NAMES = ("cudaStreamSynchronize", "cudaDeviceSynchronize", "cudaEventSynchronize")
-
-
-def analyse_trace(path):
- """Kernels, GPU busy time, syncs, and CPU time and kernels per labelled part."""
- opener = gzip.open if path.endswith(".gz") else open
- with opener(path, "rt") as f:
- events = json.load(f)["traceEvents"]
- ranges = collections.defaultdict(list) # tid -> [(start, end, part)]
- launch_at = {} # correlation -> (tid, ts)
- kernels, syncs, memcpy_d2h = [], 0, 0
- for e in events:
- if e.get("ph") != "X":
- continue
- cat, name = e.get("cat", ""), e.get("name", "")
- if cat == "user_annotation" and name.startswith("P:"):
- ranges[e["tid"]].append((e["ts"], e["ts"] + e["dur"], name[2:]))
- elif cat == "cuda_runtime" or cat == "cuda_driver":
- corr = e.get("args", {}).get("correlation")
- if corr is not None:
- launch_at[corr] = (e["tid"], e["ts"])
- if name in SYNC_NAMES:
- syncs += 1
- elif cat == "kernel":
- kernels.append(e)
- elif cat == "gpu_memcpy" and "DtoH" in name:
- memcpy_d2h += 1
-
- # innermost range containing a time, per thread
- index = {}
- for tid, rs in ranges.items():
- rs.sort()
- index[tid] = ([r[0] for r in rs], rs)
-
- def part_at(tid, ts):
- if tid not in index:
- return "backward" # autograd's thread: no labels there
- starts, rs = index[tid]
- # ranges nest: of those containing ts, the one starting last is the innermost
- i = bisect.bisect_right(starts, ts) - 1
- while i >= 0:
- s, end, part = rs[i]
- if ts <= end:
- return part
- i -= 1
- return "outside_encoder"
-
- def category(part):
- return {
- "encoder": "outside",
- "layer": "layer_other",
- "attn": "attn_other",
- "mlp": "mlp_other",
- }.get(part, part)
-
- k_count = collections.Counter()
- k_time = collections.Counter()
- busy = 0.0
- for k in kernels:
- tid_ts = launch_at.get(k.get("args", {}).get("correlation"))
- part = category(part_at(*tid_ts)) if tid_ts else "unknown"
- k_count[part] += 1
- k_time[part] += k["dur"]
- busy += k["dur"]
-
- # CPU time per part, exclusive of nested labelled ranges (forward thread)
- cpu = collections.Counter()
- for rs in ranges.values():
- rs = sorted(rs, key=lambda r: (r[0], -r[1]))
- stack = []
- child = collections.defaultdict(float)
- for s, e, part in rs:
- while stack and stack[-1][1] <= s:
- stack.pop()
- if stack:
- child[stack[-1]] += e - s
- stack.append((s, e, part))
- for r in rs:
- cpu[category(r[2])] += (r[1] - r[0]) - child[r]
- return {
- "kernels": len(kernels),
- "gpu_busy_us": busy,
- "syncs": syncs,
- "memcpy_d2h": memcpy_d2h,
- "kernels_by_part": dict(k_count),
- "gpu_us_by_part": dict(k_time),
- "cpu_us_by_part": dict(cpu),
- }
-
-
-# ---------------------------------------------------------------- running
-
-
-def make_calls(impl, enc, hf_vision, grids, n, device):
- """Groups of n consecutive images: (pixel_values, grid_thw, output grad) per call."""
- patch_dim = hf_vision.in_channels * hf_vision.temporal_patch_size * hf_vision.patch_size**2
- g = torch.Generator().manual_seed(0)
- calls = []
- for i in range(0, len(grids) - n + 1, n):
- thw = torch.tensor(grids[i : i + n], dtype=torch.long)
- patches = int(thw.prod(-1).sum())
- pixels = torch.randn(patches, patch_dim, generator=g).to(device, torch.bfloat16)
- thw = thw.to(device)
- with torch.no_grad():
- out = encoder_output(
- impl, enc(pixels, grid_thw=thw) if impl == "hf" else enc(pixels, thw)
- )
- grad = torch.randn(out.shape, generator=g).to(device, out.dtype)
- calls.append((pixels, thw, grad))
- return calls
-
-
-def run_call(impl, enc, call, backward):
- pixels, thw, grad = call
- out = enc(pixels, grid_thw=thw) if impl == "hf" else enc(pixels, thw)
- out = encoder_output(impl, out)
- if backward:
- out.backward(grad)
-
-
-def sync(device):
- if device == "cuda":
- torch.cuda.synchronize()
-
-
-def main():
- ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
- ap.add_argument("--impl", choices=("bridge", "hf"), required=True)
- ap.add_argument("--hf-attn", default="sdpa", help="sdpa (the blog's rdsp runs) or varlen")
- ap.add_argument("--config", default="Qwen/Qwen3.5-27B")
- ap.add_argument("--grids", required=True, help="JSON list of [t, h, w] per image")
- ap.add_argument("--images", default="1,2,4,8")
- ap.add_argument("--modes", default="fwd,fwdbwd")
- ap.add_argument("--passes", type=int, default=3)
- ap.add_argument("--profile-images", type=int, default=16)
- ap.add_argument("--device", default="cuda")
- ap.add_argument("--trace-dir", default="traces")
- ap.add_argument(
- "--recompute",
- action="store_true",
- help="recompute every layer in backward, as both systems' 27B runs",
- )
- ap.add_argument(
- "--cuda-graphs",
- action="store_true",
- help="Bridge's vision CUDA graphs; one --images value; each call padded to "
- "the longest call's patches (rounded up to 256)",
- )
- ap.add_argument(
- "--hf-cuda-graphs",
- action="store_true",
- help="HFGraphed: Hugging Face's encoder with per-layer CUDA graphs (a prototype; "
- "needs --hf-attn varlen and one --images value)",
- )
- ap.add_argument("--label", default="")
- ap.add_argument("--out", required=True)
- args = ap.parse_args()
-
- grids = json.load(open(args.grids))
- device = args.device
- graph_len = 0
- if args.cuda_graphs or args.hf_cuda_graphs:
- assert "," not in args.images, "CUDA graphs: one --images value"
- assert args.impl == ("bridge" if args.cuda_graphs else "hf")
- n = int(args.images)
- longest = max(
- sum(t * h * w for t, h, w in grids[i : i + n]) for i in range(0, len(grids) - n + 1, n)
- )
- # HF's padding is a segment of its own: at least one patch longer than the longest call
- graph_len = -(-(longest + (1 if args.hf_cuda_graphs else 0)) // 256) * 256
- if args.impl == "bridge":
- enc, hf_vision = build_bridge(args.config, args.recompute, graph_len)
- elif args.hf_cuda_graphs:
- assert args.hf_attn == "varlen", "--hf-cuda-graphs needs --hf-attn varlen (no host sync)"
- enc, hf_vision = build_hf(args.config, args.hf_attn, device, recompute=False)
- enc = HFGraphed(enc, graph_len, args.recompute)
- else:
- enc, hf_vision = build_hf(args.config, args.hf_attn, device, args.recompute)
- label = args.label or (args.impl if args.impl == "bridge" else f"hf-{args.hf_attn}")
- graphs_captured = False
- os.makedirs(args.trace_dir, exist_ok=True)
- import transformers
-
- env = {
- "torch": torch.__version__,
- "transformers": transformers.__version__,
- "python": platform.python_version(),
- "gpu": torch.cuda.get_device_name() if device == "cuda" else "cpu",
- "params": sum(p.numel() for p in enc.parameters()),
- }
- try:
- import transformer_engine
-
- env["transformer_engine"] = transformer_engine.__version__
- except ImportError:
- pass
- print(json.dumps(env), flush=True)
-
- results = []
- for n in [int(x) for x in args.images.split(",")]:
- calls = make_calls(args.impl, enc, hf_vision, grids, n, device)
- images = len(calls) * n
- for mode in args.modes.split(","):
- bwd = mode == "fwdbwd"
- for call in calls[:3]: # warm up: autotuning, allocator, first-call setup
- run_call(args.impl, enc, call, bwd)
- sync(device)
- if args.cuda_graphs and not graphs_captured:
- # Bridge captures after cuda_graph_warmup_steps (3) training steps
- t = time.perf_counter()
- capture_bridge_graphs(enc)
- print(
- f"captured vision CUDA graphs, length {graph_len}, in "
- f"{time.perf_counter() - t:.1f} s",
- flush=True,
- )
- graphs_captured = True
- for call in calls[:3]:
- run_call(args.impl, enc, call, bwd)
- sync(device)
- per_pass = []
- for _ in range(args.passes):
- t = time.perf_counter()
- for call in calls:
- run_call(args.impl, enc, call, bwd)
- sync(device)
- per_pass.append((time.perf_counter() - t) / images * 1e3)
- row = {
- "label": label,
- "impl": args.impl,
- "images_per_call": n,
- "mode": mode,
- "recompute": args.recompute,
- "cuda_graph_len": graph_len,
- "images_timed": images,
- "ms_per_image_passes": per_pass,
- "ms_per_image": statistics.median(per_pass),
- }
- if args.profile_images > 0:
- labels = Labels()
- if not args.hf_cuda_graphs: # graph replay runs no Python inside the layers
- (label_bridge if args.impl == "bridge" else label_hf)(enc, labels)
- pcalls = calls[: max(1, args.profile_images // n)]
- acts = [torch.profiler.ProfilerActivity.CPU]
- if device == "cuda":
- acts.append(torch.profiler.ProfilerActivity.CUDA)
- with torch.profiler.profile(activities=acts) as prof:
- t = time.perf_counter()
- for call in pcalls:
- run_call(args.impl, enc, call, bwd)
- sync(device)
- traced_ms = (time.perf_counter() - t) * 1e3
- labels.remove()
- path = os.path.join(args.trace_dir, f"{label}-n{n}-{mode}.json.gz")
- prof.export_chrome_trace(path)
- pimages = len(pcalls) * n
- a = analyse_trace(path)
- row.update(
- {
- "profiled_images": pimages,
- "traced_ms_per_image": traced_ms / pimages,
- "kernels_per_image": a["kernels"] / pimages,
- "gpu_busy_ms_per_image": a["gpu_busy_us"] / pimages / 1e3,
- "syncs_per_image": a["syncs"] / pimages,
- "d2h_copies_per_image": a["memcpy_d2h"] / pimages,
- "kernels_by_part_per_image": {
- k: v / pimages for k, v in a["kernels_by_part"].items()
- },
- "gpu_ms_by_part_per_image": {
- k: v / pimages / 1e3 for k, v in a["gpu_us_by_part"].items()
- },
- "cpu_ms_by_part_per_image": {
- k: v / pimages / 1e3 for k, v in a["cpu_us_by_part"].items()
- },
- }
- )
- print(
- json.dumps(
- {
- k: (round(v, 3) if isinstance(v, float) else v)
- for k, v in row.items()
- if not isinstance(v, dict)
- }
- ),
- flush=True,
- )
- results.append(row)
- del calls
- if device == "cuda":
- torch.cuda.empty_cache()
- json.dump({"env": env, "args": vars(args), "results": results}, open(args.out, "w"), indent=1)
- print("=== DONE", label, flush=True)
-
-
-if __name__ == "__main__":
- main()
diff --git a/training/rdsp/bench/encoder/grids.py b/training/rdsp/bench/encoder/grids.py
deleted file mode 100644
index b2c3dfc79..000000000
--- a/training/rdsp/bench/encoder/grids.py
+++ /dev/null
@@ -1,40 +0,0 @@
-#!/usr/bin/env python
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-
-"""grids.py [count]: [t, h, w] patch grids of real CORD-v2 receipts after the Qwen3.5
-image processor, with the pixel cap whose mean is closest to our training rows: 800.7 merged
-tokens (3,203 patches) per image in Megatron-Bridge's export, 2,562,208 vision tokens over 3,200
-rows (bench/mimo/logs/9b_tp4pp2dp1/export.log). The processor's default cap gives about
-7,800 patches per image, which those 2,048-token rows (none full) cannot have held."""
-
-import json
-import sys
-
-import datasets
-from transformers import AutoProcessor
-
-TARGET = 2562208 / 3200 * 4 # patches per image in training
-out, count = sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 64
-proc = AutoProcessor.from_pretrained("Qwen/Qwen3.5-27B")
-data = datasets.load_dataset("naver-clova-ix/cord-v2", split="train").shuffle(seed=0)
-images = [row["image"].convert("RGB") for row in data.select(range(count))]
-best = None
-for cap in (2_000_000, 1_500_000, 1_200_000, 1_000_000, 900_000, 800_000, 700_000, 600_000):
- grids = []
- for im in images:
- thw = proc.image_processor(
- images=im, return_tensors="pt", size={"longest_edge": cap, "shortest_edge": 56 * 56}
- )["image_grid_thw"]
- grids.append([int(x) for x in thw[0]])
- mean = sum(t * h * w for t, h, w in grids) / len(grids)
- print(f"cap {cap:,} pixels: patches per image mean {mean:.0f}")
- if best is None or abs(mean - TARGET) < abs(best[1] - TARGET):
- best = (cap, mean, grids)
-cap, mean, grids = best
-json.dump(grids, open(out, "w"))
-patches = [t * h * w for t, h, w in grids]
-print(
- f"chosen cap {cap:,}: {len(grids)} images, patches per image mean {mean:.0f} (training "
- f"{TARGET:.0f}), min {min(patches)}, max {max(patches)}; merged tokens mean {mean / 4:.0f}"
-)
diff --git a/training/rdsp/bench/mimo/bridge_9b.sh b/training/rdsp/bench/mimo/bridge_9b.sh
deleted file mode 100755
index a38c1f3d3..000000000
--- a/training/rdsp/bench/mimo/bridge_9b.sh
+++ /dev/null
@@ -1,125 +0,0 @@
-#!/bin/bash
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-# bridge_9b.sh : one step of the 9B Megatron-Bridge vs rdsp TP4xPP2xDP1 comparison, on the
-# H100 box, after bench/setup_node.sh; its prep step is also the MIMO 9B runs' (mimo_9b.sh).
-# Logs go to logs/9b_tp4pp2dp1/ (and ~/mimo for the container).
-#
-# prep HF -> Megatron checkpoint, then export Bridge's samples (pad 2048)
-# preflight 3 steps of each system: fits in memory? (peak memory in the logs)
-# bridge Megatron-Bridge, 50 steps
-# rdsp rdsp, equal work (every row padded to 2048), 50 steps
-# timers 15 steps each, per-phase timers (Megatron timing_log_level=2, rdsp
-# --profile) and per-second GPU utilization (nvidia-smi dmon)
-# nsys 15 steps each under Nsight Systems: NSYS_DELAY_BRIDGE / NSYS_DELAY_RDSP
-# seconds from launch, NSYS_DURATION seconds; reports in logs/9b_tp4pp2dp1/profiles
-# backtrace like nsys, plus the Python call stack of every CPU-GPU sync
-# (reports logs/9b_tp4pp2dp1/profiles/{bridge,rdsp}-bt.nsys-rep)
-# pyspy (or pyspy-bridge / pyspy-rdsp) 15 steps each, untraced; 40 s of
-# wall-clock Python stacks from every GPU process once steady (py-spy,
-# 25 Hz): logs/9b_tp4pp2dp1/profiles/pyspy--.txt
-# Profiled runs are diagnosis: their step times are not the results.
-#
-# RECOMPUTE (default 0) recomputes every layer on BOTH systems (Megatron: full,
-# uniform, 1 layer per chunk; rdsp: recompute=1 on both stages). COMPILE_VISION
-# (default 0) is rdsp's torch.compile of the vision encoder.
-set -euo pipefail
-HERE=$(cd "$(dirname "$0")" && pwd)
-RDSP=$(cd "$HERE/../.." && pwd)
-export MODEL=Qwen3.5-9B RECIPE=qwen35_vl_9b_sft_4gpu_h100_bf16_config
-export LOGS=$HERE/logs/9b_tp4pp2dp1; mkdir -p "$LOGS"
-RUNS=$RDSP/bench/common/runs.sh
-DATA=exported:$HOME/mimo/cord_steps-$MODEL
-# 9B fits without recompute. Its vision encoder is 27B's (MLP 4304 wide): compiled
-# under TP4 it crashed on 27B ("misaligned address"), so it runs eager here too.
-export RECOMPUTE=${RECOMPUTE:-0} COMPILE_VISION=${COMPILE_VISION:-0}
-MEG_RC=""
-[ "${RECOMPUTE:-0}" = 1 ] && MEG_RC="model.recompute_granularity=full model.recompute_method=uniform model.recompute_num_layers=1"
-TAG=""; [ "${RECOMPUTE:-0}" = 1 ] && TAG=-rc
-
-container() { # the same NeMo container runs.sh uses
- sudo docker run --gpus all --rm --ipc=host --shm-size=64g --ulimit memlock=-1 \
- -v "$HOME/hf:/root/.cache/huggingface" -v "$HOME/mimo:/workspace" -v "$RDSP:/rdsp" \
- -e HF_HOME=/root/.cache/huggingface -e PYTHONUNBUFFERED=1 -w /opt/Megatron-Bridge \
- nvcr.io/nvidia/nemo:26.08 bash -c "$*"
- sudo chown -R "$(id -u):$(id -g)" "$HOME/hf" "$HOME/mimo"
-}
-PROF=$LOGS/profiles; mkdir -p "$PROF"
-nsys_cmd() { # nsys_cmd : a profiler prefix when NSYS_DELAY is set
- [ -n "${NSYS_DELAY:-}" ] || return 0
- echo "nsys profile -t cuda,nvtx ${NSYS_FLAGS:--s none --cpuctxsw=none} --delay $NSYS_DELAY --duration ${NSYS_DURATION:-60} --force-overwrite true -o $PROF/$1"
-}
-dmon() { nvidia-smi dmon -s u -d 1 -o T > "$LOGS/$1.dmon" 2>&1 & DMON=$!; }
-sample() { # sample : 40 s of wall-clock Python stacks per process, at once
- local sys=$1; shift
- local jobs=()
- for p in "$@"; do
- sudo "$HOME/venv/bin/py-spy" record --pid "$p" --rate 25 --duration 40 --idle --format raw \
- -o "$PROF/pyspy-$sys-$p.txt" > "$PROF/pyspy-$sys-$p.log" 2>&1 &
- jobs+=($!)
- done
- wait "${jobs[@]}" # only the samplers: the training run keeps going
-}
-rdsp() { # rdsp [env...]
- local name=$1; shift
- (unset LD_LIBRARY_PATH && . "$HOME/venv/bin/activate" && . "$HOME/cuda_env.sh" && \
- env DS_BUILD_OPS=0 HF_HOME=$HOME/hf PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
- DATA=$DATA "$@" $(nsys_cmd "$name") bash "$HERE/rdsp_9b_tp4pp2.sh" ${RDSP_ARGS:-}) 2>&1 | tee "$LOGS/$name.log"
-}
-
-case "${1:-}" in
- prep) # Bridge's checkpoint only: this layout has no MegatronMIMO run
- container "python scripts/conversion/setup_conversion.py import --hf-model Qwen/$MODEL \
- --megatron-path /workspace/std/$MODEL" 2>&1 | tee "$LOGS/convert.log"
- bash "$RUNS" export ;;
- preflight)
- STEPS=3 MEGATRON_EXTRA="$MEG_RC" bash "$RUNS" tp4pp2-megatron || true
- mv "$LOGS/tp4pp2-megatron.log" "$LOGS/preflight-bridge$TAG.log"
- # --profile: per-phase timers and peak memory per GPU (a 3-step memory check, not timing)
- RDSP_ARGS=--profile rdsp "preflight-rdsp$TAG" STEPS=3 RECOMPUTE="${RECOMPUTE:-0}" || true ;;
- preflight-rdsp) # rdsp only; NAME suffixes the log, e.g. -nocompile
- RDSP_ARGS=--profile rdsp "preflight-rdsp$TAG${NAME:-}" STEPS=3 RECOMPUTE="${RECOMPUTE:-0}" \
- COMPILE_VISION="${COMPILE_VISION:-1}" || true ;;
- bridge)
- MEGATRON_EXTRA="$MEG_RC" bash "$RUNS" tp4pp2-megatron
- mv "$LOGS/tp4pp2-megatron.log" "$LOGS/bridge$TAG.log" ;;
- rdsp) rdsp "rdsp-equal$TAG" PAD=equal RECOMPUTE="${RECOMPUTE:-0}" ;;
- timers)
- dmon timers-bridge; STEPS=15 MEGATRON_EXTRA="$MEG_RC logger.timing_log_level=2" bash "$RUNS" tp4pp2-megatron || true
- kill $DMON; mv "$LOGS/tp4pp2-megatron.log" "$LOGS/timers-bridge.log"
- dmon timers-rdsp; RDSP_ARGS=--profile rdsp timers-rdsp STEPS=15 || true; kill $DMON ;;
- nsys)
- STEPS=15 NSYS_DELAY=$NSYS_DELAY_BRIDGE NSYS_DURATION=${NSYS_DURATION:-60} MEGATRON_EXTRA="$MEG_RC" \
- bash "$RUNS" tp4pp2-megatron || true
- mv "$LOGS/tp4pp2-megatron.log" "$LOGS/nsys-bridge.log"
- mv "$HOME/mimo/nsys/tp4pp2-megatron.nsys-rep" "$PROF/bridge.nsys-rep" || true
- NSYS_DELAY=$NSYS_DELAY_RDSP rdsp nsys-rdsp STEPS=15 || true
- mv "$PROF/nsys-rdsp.nsys-rep" "$PROF/rdsp.nsys-rep" || true ;;
- backtrace)
- export NSYS_FLAGS="--sample=process-tree --cpuctxsw=none --cudabacktrace=sync --python-backtrace=cuda"
- STEPS=15 NSYS_DELAY=$NSYS_DELAY_BRIDGE NSYS_DURATION=${NSYS_DURATION:-45} MEGATRON_EXTRA="$MEG_RC" \
- bash "$RUNS" tp4pp2-megatron || true
- mv "$LOGS/tp4pp2-megatron.log" "$LOGS/bt-bridge.log"
- mv "$HOME/mimo/nsys/tp4pp2-megatron.nsys-rep" "$PROF/bridge-bt.nsys-rep" || true
- NSYS_DELAY=$NSYS_DELAY_RDSP rdsp bt-rdsp STEPS=15 || true
- mv "$PROF/bt-rdsp.nsys-rep" "$PROF/rdsp-bt.nsys-rep" || true ;;
- pyspy) bash "$0" pyspy-bridge && bash "$0" pyspy-rdsp ;;
- pyspy-bridge)
- STEPS=15 MEGATRON_EXTRA="$MEG_RC" bash "$RUNS" tp4pp2-megatron > /dev/null 2>&1 &
- RUN=$!
- until grep -q "iteration 6/" "$LOGS/tp4pp2-megatron.log" 2>/dev/null; do sleep 5; done
- workers=$(for p in $(pgrep -f "[r]un_recipe.py"); do
- tr '\0' ' ' < /proc/$p/cmdline | grep -q torch.distributed.run || echo "$p"; done)
- echo "bridge processes:" $workers
- sample bridge $workers
- wait $RUN; mv "$LOGS/tp4pp2-megatron.log" "$LOGS/pyspy-bridge.log" ;;
- pyspy-rdsp)
- rdsp pyspy-rdsp STEPS=15 > /dev/null &
- RUN=$!
- until grep -q "^step 5 loss" "$LOGS/pyspy-rdsp.log" 2>/dev/null; do sleep 5; done
- actors=$(pgrep -f "[r]ay::StageWorkerActor")
- echo "rdsp actors:" $actors
- sample rdsp $actors
- wait $RUN ;;
- *) sed -n 4,21p "$0"; exit 1 ;;
-esac
diff --git a/training/rdsp/bench/mimo/mimo_9b.sh b/training/rdsp/bench/mimo/mimo_9b.sh
deleted file mode 100755
index 900f914f4..000000000
--- a/training/rdsp/bench/mimo/mimo_9b.sh
+++ /dev/null
@@ -1,167 +0,0 @@
-#!/bin/bash
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-# mimo_9b.sh [layout] [steps]: MegatronMIMO vs rdsp on Qwen3.5-9B, 8x H100, on the box
-# after bench/setup_node.sh and the 9B export (bridge_9b.sh prep). Logs in logs//.
-#
-# convert HF -> MegatronMIMO checkpoint for 9B (once)
-# mimo [n] MegatronMIMO, n steps (50) -> logs//mimo.log
-# rdsp [n] rdsp, the same grids, n steps -> logs//rdsp.log
-# sweep MegatronMIMO, 15 steps -> logs/sweep/.log
-# best the fastest vision layout for that language grid (median of
-# steps 6-15, MIMO), counting the 1-GPU vision run from its 50-step log
-# pyspy 20 steps each, untraced; 40 s of wall-clock Python stacks from every
-# GPU process once steady (py-spy, 25 Hz) -> logs//profiles/pyspy-*.txt;
-# also records each system's launch-to-steady time for nsys
-# nsys 20 steps each under Nsight Systems, a window from that steady time
-# -> logs//profiles/{mimo,rdsp}.nsys-rep and .sqlite
-# backtrace rdsp only, 12 steps under Nsight Systems with the call stack of every
-# kernel launch (names the autograd node or Python line behind each GPU
-# operation); needs the pyspy step's steady time
-# -> logs//profiles/rdsp-bt.nsys-rep and .sqlite
-# Profiled runs are diagnosis: their step times are not the results. TAG (e.g. -nov11) suffixes
-# the profiles directory and the profiled runs' logs, so a later run keeps the earlier files.
-#
-# Layout name: 9b__. Language on ranks 0-3, the vision encoder after it.
-# vision: v1 (1 GPU), vtp2, vtp4, vdp2, vtp2dp2
-# language: tp2pp2dp1 (1 row per microbatch, 64 microbatches)
-# tp2pp1dp2 (2 rows per microbatch, 1 per DP copy, 32 microbatches)
-# Both systems: every row padded to 2048 (MIMO's default; rdsp --pad-multiple 0), MIMO's
-# per-microbatch loss mean (rdsp --loss microbatch-mean), no recompute, rdsp's vision
-# encoder eager (no torch.compile), 64 rows per step.
-set -euo pipefail
-HERE=$(cd "$(dirname "$0")" && pwd)
-RDSP=$(cd "$HERE/../.." && pwd)
-L=$HERE/logs
-export MODEL=Qwen3.5-9B
-RUNS=$RDSP/bench/common/runs.sh
-DATA=exported:$HOME/mimo/cord_steps-$MODEL
-
-spec() { # spec : sets IMG, VGPUS, VSTAGE, LANG, MBS, ROWS, MICRO, STAGES
- local v=${1#9b_}; local l=${v#*_}; v=${v%%_*}
- case $v in
- v1) IMG=tp=1,pp=1,dp=1; VGPUS=1; VSTAGE=0:gpus=1,zero=1 ;;
- vtp2) IMG=tp=2,pp=1,dp=1; VGPUS=2; VSTAGE=0:gpus=2,tp=2,zero=1 ;;
- vtp4) IMG=tp=4,pp=1,dp=1; VGPUS=4; VSTAGE=0:gpus=4,tp=4,zero=1 ;;
- vdp2) IMG=tp=1,pp=1,dp=2; VGPUS=2; VSTAGE=0:gpus=2,zero=1 ;;
- vtp2dp2) IMG=tp=2,pp=1,dp=2; VGPUS=4; VSTAGE=0:gpus=4,tp=2,zero=1 ;;
- *) echo "unknown vision layout $v" >&2; exit 1 ;;
- esac
- case $l in
- tp2pp2dp1) LANG=tp=2,pp=2,dp=1; MBS=1; ROWS=1; MICRO=64
- STAGES="--stages 3 --cuts 0,balanced --stage $VSTAGE --stage 1:gpus=2,tp=2,zero=1 --stage 2:gpus=2,tp=2,zero=1" ;;
- tp2pp1dp2) LANG=tp=2,pp=1,dp=2; MBS=2; ROWS=2; MICRO=32
- STAGES="--stages 2 --cuts 0 --stage $VSTAGE --stage 1:gpus=4,tp=2,zero=1" ;;
- *) echo "unknown language layout $l" >&2; exit 1 ;;
- esac
-}
-
-mimo_run() { # mimo_run ; NSYS_DELAY/NSYS_DURATION trace it
- spec "$1"
- mkdir -p "$3"
- env LOGS="$3" STEPS="$2" MIMO_NAME="$4" MIMO_GPUS=$((4 + VGPUS)) MIMO_MBS=$MBS \
- MIMO_LANGUAGE="$LANG,rank_offset=0" MIMO_IMAGES="$IMG,rank_offset=4" bash "$RUNS" mimo-layout
-}
-
-rdsp_run() { # rdsp_run [profiler prefix...]
- local layout=$1 steps=$2 name=$3; shift 3
- spec "$layout"; mkdir -p "$L/$layout"
- (unset LD_LIBRARY_PATH && . "$HOME/venv/bin/activate" && . "$HOME/cuda_env.sh" && \
- env DS_BUILD_OPS=0 HF_HOME=$HOME/hf PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
- "$@" python "$RDSP/train_vl.py" --model "Qwen/$MODEL" --dataset "$DATA" $STAGES \
- --rows $ROWS --microbatches $MICRO --seq 2048 --pad-multiple 0 \
- --steps "$steps" --lr 1e-5 --betas 0.9,0.95 --eps 1e-8 --weight-decay 0.0 \
- --grad-dtype fp32 --loss microbatch-mean --liger \
- --prefetch --sharded-loss --drop-padding-mask) 2>&1 | tee "$L/$layout/$name.log"
-}
-
-sample() { # sample : 40 s of wall-clock Python stacks per process, at once
- local out=$1 sys=$2; shift 2
- local jobs=()
- for p in "$@"; do
- sudo "$HOME/venv/bin/py-spy" record --pid "$p" --rate 25 --duration 40 --idle --format raw \
- -o "$out/pyspy-$sys-$p.txt" > "$out/pyspy-$sys-$p.log" 2>&1 &
- jobs+=($!)
- done
- wait "${jobs[@]}" # only the samplers: the training run keeps going
-}
-
-steady() { # steady : wait for the line, print seconds since start
- until grep -qE "$2" "$1" 2>/dev/null; do kill -0 "$4" 2>/dev/null || return 1; sleep 2; done
- echo $(( $(date +%s) - $3 ))
-}
-
-case "${1:-}" in
- convert)
- mkdir -p "$L"
- sudo docker run --gpus all --rm --ipc=host --shm-size=64g --ulimit memlock=-1 \
- -v "$HOME/hf:/root/.cache/huggingface" -v "$HOME/mimo:/workspace" \
- -e HF_HOME=/root/.cache/huggingface -w /opt/Megatron-Bridge nvcr.io/nvidia/nemo:26.08 bash -c \
- "python -m torch.distributed.run --nproc_per_node=2 examples/conversion/convert_megatron_mimo.py \
- import --hf-model Qwen/$MODEL --megatron-path /workspace/$MODEL-mimo \
- --component language=tp=1,dp=1,rank_offset=0 --component images=tp=1,dp=1,rank_offset=1 \
- --torch-dtype bfloat16" 2>&1 | tee "$L/convert.log"
- sudo chown -R "$(id -u):$(id -g)" "$HOME/hf" "$HOME/mimo" ;;
- mimo) mimo_run "$2" "${3:-50}" "$L/$2" mimo ;;
- sweep) mimo_run "$2" 15 "$L/sweep" "$2" || true ;;
- rdsp) rdsp_run "$2" "${3:-50}" rdsp ;;
- pyspy)
- T=${TAG:-}; P=$L/$2/profiles$T; D=$L/$2; mkdir -p "$P" "$D"; rm -f "$D/pyspy-mimo$T.log" "$D/pyspy-rdsp$T.log"
- t0=$(date +%s); mimo_run "$2" 20 "$D" "pyspy-mimo$T" > /dev/null 2>&1 &
- RUN=$!
- steady "$D/pyspy-mimo$T.log" "iteration +6/" "$t0" $RUN > "$P/steady-mimo.s"
- # the workers: the launcher and the docker/bash wrappers also name torch.distributed.run
- workers=$(for p in $(pgrep -f "[f]inetune_qwen35_vl.py"); do
- tr '\0' ' ' < /proc/$p/cmdline | grep -q torch.distributed.run || echo "$p"; done)
- echo "mimo processes:" $workers "(steady after $(cat "$P/steady-mimo.s") s)"
- sample "$P" mimo $workers
- wait $RUN || true
- t0=$(date +%s); rdsp_run "$2" 20 "pyspy-rdsp$T" > /dev/null 2>&1 &
- RUN=$!
- steady "$D/pyspy-rdsp$T.log" "^step 5 loss" "$t0" $RUN > "$P/steady-rdsp.s"
- actors=$(pgrep -f "[r]ay::StageWorkerActor")
- echo "rdsp actors:" $actors "(steady after $(cat "$P/steady-rdsp.s") s)"
- sample "$P" rdsp $actors
- wait $RUN || true ;;
- nsys) # a window from each system's steady time (pyspy step), NSYS_DURATION seconds (75)
- T=${TAG:-}; P=$L/$2/profiles$T; D=$L/$2; mkdir -p "$HOME/mimo/nsys"
- NSYS_DELAY=$(cat "$P/steady-mimo.s") NSYS_DURATION=${NSYS_DURATION:-75} \
- mimo_run "$2" 20 "$D" "nsys-mimo$T" || true
- mv "$HOME/mimo/nsys/nsys-mimo$T.nsys-rep" "$P/mimo.nsys-rep" || true
- rdsp_run "$2" 20 "nsys-rdsp$T" nsys profile -t cuda,nvtx -s none --cpuctxsw=none \
- --delay "$(cat "$P/steady-rdsp.s")" --duration "${NSYS_DURATION:-75}" --force-overwrite true \
- -o "$P/rdsp" || true
- # the container's nsys is newer than the host's: export both reports there
- sudo docker run --gpus all --ipc=host -v "$P:/p" nvcr.io/nvidia/nemo:26.08 bash -c \
- "for r in mimo rdsp; do nsys export --type sqlite --force-overwrite true -o /p/\$r.sqlite /p/\$r.nsys-rep; done"
- sudo chown -R "$(id -u):$(id -g)" "$P" ;;
- backtrace)
- T=${TAG:-}; P=$L/$2/profiles$T; mkdir -p "$P"
- # --kill none: the run ends by itself after the window, so no process loses its last records
- rdsp_run "$2" 12 "bt-rdsp$T" nsys profile -t cuda,nvtx --sample=process-tree --cpuctxsw=none \
- --cudabacktrace=kernel --kill none --delay "$(cat "$P/steady-rdsp.s")" \
- --duration "${NSYS_DURATION:-40}" --force-overwrite true -o "$P/rdsp-bt" || true
- # the host's nsys made the report; the container's may be older (2026-11-11) or newer (October)
- nsys export --type sqlite --force-overwrite true -o "$P/rdsp-bt.sqlite" "$P/rdsp-bt.nsys-rep" || {
- sudo docker run --rm --gpus all --ipc=host -v "$P:/p" nvcr.io/nvidia/nemo:26.08 bash -c \
- "nsys export --type sqlite --force-overwrite true -o /p/rdsp-bt.sqlite /p/rdsp-bt.nsys-rep"
- sudo chown -R "$(id -u):$(id -g)" "$P"; } ;;
- best)
- python3 - "$L" "$2" <<'PY'
-import glob, os, re, statistics, sys
-logs_dir, lang = sys.argv[1], sys.argv[2]
-logs = {f"9b_v1_{lang}": f"{logs_dir}/9b_v1_{lang}/mimo.log"}
-logs.update({os.path.basename(p)[:-4]: p for p in glob.glob(f"{logs_dir}/sweep/9b_*_{lang}.log")})
-med = {}
-for name, path in logs.items():
- t = [float(m[2]) for m in re.finditer(r"iteration +(\d+)/ +\d+ .*?per iteration \(ms\): ([\d.]+)",
- open(path).read()) if 6 <= int(m[1]) <= 15]
- if len(t) >= 5:
- med[name] = statistics.median(t) / 1e3
-for name, s in sorted(med.items(), key=lambda kv: kv[1]):
- print(f"{name} {s:.2f}", file=sys.stderr)
-print(min(med, key=med.get))
-PY
- ;;
- *) sed -n 2,26p "$0"; exit 1 ;;
-esac
diff --git a/training/rdsp/bench/mimo/patch.diff b/training/rdsp/bench/mimo/patch.diff
deleted file mode 100644
index 21054e334..000000000
--- a/training/rdsp/bench/mimo/patch.diff
+++ /dev/null
@@ -1,24 +0,0 @@
-343a344,347
-> if os.environ.get("MIMO_RECOMPUTE") == "1":
-> standard_provider.recompute_granularity = "full"
-> standard_provider.recompute_method = "uniform"
-> standard_provider.recompute_num_layers = 1
-1009,1010c1013,1014
-< optimizer_cfg.use_precision_aware_optimizer = False
-< optimizer_cfg.main_grads_dtype = torch.float32
----
-> optimizer_cfg.use_precision_aware_optimizer = True
-> optimizer_cfg.main_grads_dtype = torch.bfloat16
-1011a1016
-> optimizer_cfg.store_param_remainders = True
-1056c1061
-< grad_reduce_in_fp32=True,
----
-> grad_reduce_in_fp32=False,
-1066c1071,1074
-< cfg.mixed_precision = "bf16_mixed" if not args.fp32 else None
----
-> from megatron.bridge.training.mixed_precision import bf16_mixed as _bf16_mixed
-> _mp = _bf16_mixed()
-> _mp.grad_reduce_in_fp32 = False
-> cfg.mixed_precision = _mp if not args.fp32 else None
diff --git a/training/rdsp/bench/mimo/rdsp_27b.sh b/training/rdsp/bench/mimo/rdsp_27b.sh
deleted file mode 100644
index 95bda6f1e..000000000
--- a/training/rdsp/bench/mimo/rdsp_27b.sh
+++ /dev/null
@@ -1,24 +0,0 @@
-#!/bin/bash
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-# rdsp_27b.sh, on node 1 with the two-node Ray cluster up (bench/cluster/ray_cluster.sh): the dense
-# 27B on Megatron-MIMO's 9-GPU layout, beside MIMO's own run of it: the vision encoder alone on
-# 1 GPU (stage 0, --cuts 0,measured), the language model as 2 stages of TP4. Receipt rows, 128 x
-# 2048 a step, 1 row a microbatch, MIMO's per-microbatch loss mean, no recompute; the memory
-# settings MIMO runs with here (bf16 gradients, 2-byte master). Stages fill the driver's node
-# first: the encoder and stage 1 on node 1, stage 2 on node 2. STEPS (default 10). Log:
-# logs/27b_v1_tp4pp2dp1/rdsp-9gpu.log. Last, the median from step 4 (6 when STEPS >= 50) to the
-# last step, as rdsp numbers them (from 0); the script fails if any step of that window is missing.
-set -euo pipefail
-export MODEL=Qwen3.5-27B EXPORT_NAME=cord_steps-Qwen3.5-27B-128 GBS=128 STEPS=${STEPS:-10}
-. ~/rdsp/bench/common/two_node.sh # RDSP_COMMON, rdsp
-export LOGS=~/rdsp/bench/mimo/logs/27b_v1_tp4pp2dp1; mkdir -p "$LOGS"
-rdsp rdsp-9gpu --stages 3 --cuts 0,measured --stage 0:gpus=1,tp=1,zero=1 \
- --stage 1:gpus=4,tp=4,zero=1 --stage 2:gpus=4,tp=4,zero=1 \
- --rows 1 --microbatches 128 --loss microbatch-mean
-first=4; [ "$STEPS" -ge 50 ] && first=6
-last=$(( STEPS - 1 < 50 ? STEPS - 1 : 50 ))
-median=$(MEDIAN_FIRST=$first MEDIAN_MIN=$((last - first + 1)) \
- python3 "$RDSP/bench/common/medians.py" rdsp "$LOGS/rdsp-9gpu.log")
-[ -n "$median" ] || { echo "steps $first-$last incomplete in $LOGS/rdsp-9gpu.log" >&2; exit 1; }
-echo "median over steps $first-$last: $median"
diff --git a/training/rdsp/bench/mimo/rdsp_9b_tp4pp2.sh b/training/rdsp/bench/mimo/rdsp_9b_tp4pp2.sh
deleted file mode 100755
index 0010e10c1..000000000
--- a/training/rdsp/bench/mimo/rdsp_9b_tp4pp2.sh
+++ /dev/null
@@ -1,31 +0,0 @@
-#!/usr/bin/env bash
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-# rdsp_9b_tp4pp2.sh: rdsp, Qwen3.5-9B, 2 pipeline stages of TP4 (no data parallelism) on 8x H100.
-# One row per microbatch, 64 microbatches per step, as Megatron runs this layout.
-#
-# PAD=equal (default): every row padded to 2048, as Megatron-Bridge pads under PP
-# PAD=own: each microbatch padded to its longest row (rdsp's recipe)
-# RECOMPUTE=1: recompute every block on both stages (not used: 9B fits)
-# COMPILE_VISION=0: no torch.compile on the vision encoder's blocks
-# STEPS (50), DATA (exported:). Extra arguments go to train_vl.py.
-set -euo pipefail
-RDSP=$(cd "$(dirname "$0")/../.." && pwd)
-case ${PAD:-equal} in
- equal) PAD_FLAGS="--pad-multiple 0" ;;
- own) PAD_FLAGS="--pad-multiple 128 --pad-per-microbatch" ;;
- *) echo "PAD must be equal or own" >&2; exit 1 ;;
-esac
-RC=""; [ "${RECOMPUTE:-0}" = 1 ] && RC=",recompute=1"
-CV=",compile_vision=1"; [ "${COMPILE_VISION:-1}" = 0 ] && CV=""
-# 9B's checkpoint has its own output layer (tie_word_embeddings false): no untying needed
-exec python "$RDSP/train_vl.py" \
- --model Qwen/Qwen3.5-9B --dataset "${DATA:?set DATA=exported:}" \
- --stages 2 --cuts balanced \
- --stage "0:gpus=4,tp=4,zero=1$CV$RC" \
- --stage "1:gpus=4,tp=4,zero=1$RC" \
- --rows 1 --microbatches 64 --seq 2048 $PAD_FLAGS \
- --steps "${STEPS:-50}" --lr 1e-5 --betas 0.9,0.95 --eps 1e-8 --weight-decay 0.0 \
- --grad-dtype fp32 --loss token-mean --liger \
- --prefetch --sharded-loss --drop-padding-mask \
- "$@"
diff --git a/training/rdsp/bench/qwen35_27b/one_node.sh b/training/rdsp/bench/qwen35_27b/one_node.sh
deleted file mode 100755
index 72284506e..000000000
--- a/training/rdsp/bench/qwen35_27b/one_node.sh
+++ /dev/null
@@ -1,74 +0,0 @@
-#!/bin/bash
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-# one_node.sh : this node's one-node runs on the dense 27B (8 GPUs). "bridge"
-# runs on node 1 while "others" runs on node 2, so the cleanup here touches this node only.
-# Each run prints a "=== " line when it starts and when it ends.
-# bridge Megatron-Bridge TP1 x PP8, every layer recomputed, at three per-stage cuts given
-# with model.pipeline_model_parallel_layout
-# others TorchTitan FSDP8 (FullAC fp32 reduce, FullAC bf16 reduce, MLP-only recompute
-# bf16 reduce); TorchTitan TP1 x PP8 at rdsp's cut (weights converted to DCP);
-# then rdsp TP1 x PP8 with its measured cut
-set -uo pipefail
-cd ~/rdsp
-B=~/rdsp/bench
-P8=$B/qwen35_27b
-L8=$P8/logs/pp8
-TL=$B/torchtitan/logs
-SMI="nvidia-smi --query-gpu=timestamp,index,memory.used --format=csv,noheader,nounits -lms 500"
-mark() { echo "=== $* $(date -u +%H:%M:%S)"; }
-cleanup() {
- sudo docker ps -q | xargs -r sudo docker kill > /dev/null 2>&1
- pkill -f "[t]orch.distributed.run"; pkill -f "[t]orchrun"; pkill -f "[t]rain_vl.py"
- bash -c ". ~/venv/bin/activate; ray stop --force" > /dev/null 2>&1
- sleep 10
-}
-run() { # run
- local name=$1 minutes=$2 csv=$3; shift 3
- mark "START $name"
- $SMI > "$csv" &
- local smi=$!
- timeout $((minutes * 60)) "$@"; local rc=$?
- kill $smi
- cleanup
- mark "END $name exit $rc"
-}
-# Bridge: every layer recomputed (27B does not fit TP1 x PP8 without); NVIDIA's perf recipes'
-# check flags off; 8 data workers (Bridge decodes the images while it trains)
-RC_ALL="model.recompute_granularity=full model.recompute_method=uniform model.recompute_num_layers=1"
-FAST="rerun_state_machine.check_for_nan_in_loss=false ddp.check_for_nan_in_grad=false dataset.num_workers=8"
-# The layout reaches Hydra as a quoted string through runs.sh's bash -c
-layout() { echo "\"model.pipeline_model_parallel_layout='$1'\""; }
-bridge() { # bridge [overrides...]
- local name=$1 lay=$2; shift 2
- run "bridge-27b-$name" 60 "$L8/nvsmi-bridge-gap-$name.csv" env NAME="-gap-$name" \
- MEG_RC="$RC_ALL $(layout "$lay") $FAST $*" bash "$P8/pp8.sh" bridge
-}
-titan() { # titan
- run "titan-27b-$1" 40 "$TL/nvsmi-gap-$1.csv" env NAME=-gap bash "$B/torchtitan/run.sh" run "$1"
-}
-mkdir -p "$L8" "$TL"
-case "${1:-}" in
- bridge)
- bridge cut1 "Et|t*9|t*10|t*9|t*9|t*9|t*10|t*7L" model.batch_p2p_sync=false
- bridge cut0 "E|t*9|t*10|t*10|t*10|t*9|t*9|t*7L" model.batch_p2p_sync=false
- bridge vp2 "E|t*5|t*5|t*5|t*5|t*5|t*5|t*4|t|t*4|t*5|t*4|t*4|t*4|t*5|t*3L" \
- model.overlap_p2p_comm=true model.batch_p2p_comm=false ;;
- others)
- titan qwen35_27b_cord_fsdp8_rc
- titan qwen35_27b_cord_fsdp8_rc_bf16
- titan qwen35_27b_cord_fsdp8_ffnrc_bf16
- # TorchTitan 8 stages at rdsp's cut: weights converted to DCP first (its HF loader rejects
- # middle pipeline stages)
- HF27=$(ls -d ~/hf/hub/models--Qwen--Qwen3.5-27B/snapshots/* | head -1)
- [ -f ~/tt_dcp/Qwen3.5-27B/.metadata ] || run titan-27b-dcp 40 "$TL/nvsmi-gap-dcp.csv" bash -c \
- "unset LD_LIBRARY_PATH; . ~/tt_venv/bin/activate; cd ~/torchtitan && python \
- scripts/checkpoint_conversion/convert_from_hf.py $HF27 ~/tt_dcp/Qwen3.5-27B \
- --model_name qwen3_5 --model_flavor 27B > $TL/convert-dcp-27b-gap.log 2>&1"
- run titan-27b-pp8 50 "$TL/nvsmi-gap-pp8.csv" env NAME=-gap TT_DCP="$HOME/tt_dcp/Qwen3.5-27B" \
- LOG_RANK=0,7 bash "$B/torchtitan/run.sh" run qwen35_27b_cord_pp8_rc
- run rdsp-27b-pp8 40 "$L8/nvsmi-rdsp-gap.csv" env NAME=-gap \
- RDSP_ARGS="--master-dtype remainder --cuts measured" bash "$P8/pp8.sh" rdsp ;;
- *) sed -n 2,9p "$0"; exit 1 ;;
-esac
-mark "ONE NODE DONE $1"
diff --git a/training/rdsp/bench/qwen35_27b/pp8.sh b/training/rdsp/bench/qwen35_27b/pp8.sh
deleted file mode 100755
index a799c2e9a..000000000
--- a/training/rdsp/bench/qwen35_27b/pp8.sh
+++ /dev/null
@@ -1,79 +0,0 @@
-#!/bin/bash
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-# pp8.sh : 27B TP1 x PP8 x DP1 (8 pipeline stages of one GPU) on the H100 box, after
-# bench/setup_node.sh and the 27B checkpoint + export (bench/qwen35_27b/prep.sh makes both).
-# Logs in logs/pp8/.
-#
-# bridge Megatron-Bridge, 50 steps
-# rdsp rdsp, 50 steps
-# timers Megatron-Bridge, 15 steps with its own per-rank timers (logger.timing_log_level=2,
-# every rank printed) -> logs/pp8/timers-bridge.log
-# pyspy Megatron-Bridge, 15 steps untraced; PYSPY_SECONDS (60) of wall-clock Python stacks
-# from every stage process once steady (py-spy, 25 Hz)
-# -> logs/pp8/profiles/pyspy-bridge-.txt, and the stage of each pid in
-# logs/pp8/profiles/pyspy-bridge-ranks.txt
-# timers and pyspy are diagnosis: their step times are not results.
-#
-# Both recompute every layer and accumulate gradients in bf16 (fp32 master weights and Adam), as
-# in the TP4xPP2 runs. Under a pipeline Megatron-Bridge pads every row to 2048 on its own.
-# STEPS (default 50).
-set -euo pipefail
-HERE=$(cd "$(dirname "$0")" && pwd)
-RDSP=$(cd "$HERE/../.." && pwd)
-export MODEL=Qwen3.5-27B RECIPE=qwen35_vl_27b_sft_16gpu_h100_bf16_config
-export LOGS=$HERE/logs/pp8; mkdir -p "$LOGS"
-RUNS=$RDSP/bench/common/runs.sh
-DATA=${DATA:-exported:$HOME/mimo/cord_steps-$MODEL} # DATA: other rows (e.g. MedPix)
-# MEG_RC: Bridge's recompute overrides (default: every layer); RECOMPUTE=0: none
-MEG_RC=${MEG_RC:-"model.recompute_granularity=full model.recompute_method=uniform model.recompute_num_layers=1"}
-[ "${RECOMPUTE:-1}" = 0 ] && MEG_RC=""
-MEG_BF16=$(cat "$RDSP/bench/common/meg_extra_bf16.txt")
-
-case "${1:-}" in
- bridge)
- GRAD_REDUCE_FP32=false MEGATRON_EXTRA="$MEG_RC $MEG_BF16" bash "$RUNS" tp1pp8-megatron || rc=$?
- mv "$LOGS/tp1pp8-megatron.log" "$LOGS/bridge${NAME:-}.log" # kept when the run fails
- exit "${rc:-0}" ;;
- timers)
- STEPS=${STEPS:-15} GRAD_REDUCE_FP32=false \
- MEGATRON_EXTRA="$MEG_RC $MEG_BF16 logger.timing_log_level=2 logger.timing_log_option=all" \
- bash "$RUNS" tp1pp8-megatron || rc=$?
- mv "$LOGS/tp1pp8-megatron.log" "$LOGS/timers-bridge${NAME:-}.log"
- exit "${rc:-0}" ;;
- pyspy)
- PROF=$LOGS/profiles; mkdir -p "$PROF"; rm -f "$LOGS/tp1pp8-megatron.log"
- STEPS=${STEPS:-15} GRAD_REDUCE_FP32=false MEGATRON_EXTRA="$MEG_RC $MEG_BF16" \
- bash "$RUNS" tp1pp8-megatron > /dev/null 2>&1 &
- RUN=$!
- until grep -q "iteration 6/" "$LOGS/tp1pp8-megatron.log" 2>/dev/null; do
- kill -0 $RUN 2>/dev/null || { echo "the Bridge run ended before step 6"; break; }
- sleep 5
- done
- # the workers: the launcher and the docker/bash wrappers also name torch.distributed.run
- # (the 8 data workers of each rank are its children and share its command line)
- # `if`, not `&&`: a false last test would fail the assignment and, under set -e, end the script
- workers=$(for p in $(pgrep -f "[r]un_recipe.py"); do
- if tr '\0' ' ' < /proc/$p/cmdline | grep -q torch.distributed.run; then continue; fi
- pp=$(ps -o ppid= -p "$p" | tr -d ' ')
- if tr '\0' ' ' < "/proc/$pp/cmdline" 2>/dev/null | grep -q torch.distributed.run; then echo "$p"; fi
- done)
- for p in $workers; do # RANK = pipeline stage (TP1, DP1)
- echo "$p $(sudo cat /proc/$p/environ | tr '\0' '\n' | grep -E '^(RANK|LOCAL_RANK)=' | tr '\n' ' ')"
- done | tee "$PROF/pyspy-bridge${NAME:-}-ranks.txt"
- jobs=()
- for p in $workers; do
- sudo "$HOME/venv/bin/py-spy" record --pid "$p" --rate 25 --duration "${PYSPY_SECONDS:-60}" --idle \
- --format raw -o "$PROF/pyspy-bridge${NAME:-}-$p.txt" > "$PROF/pyspy-bridge${NAME:-}-$p.log" 2>&1 &
- jobs+=($!)
- done
- [ ${#jobs[@]} -gt 0 ] && wait "${jobs[@]}" # only the samplers: the training run keeps going
- wait $RUN || rc=$?
- mv "$LOGS/tp1pp8-megatron.log" "$LOGS/pyspy-bridge${NAME:-}.log"
- exit "${rc:-0}" ;;
- rdsp)
- (unset LD_LIBRARY_PATH && . "$HOME/venv/bin/activate" && . "$HOME/cuda_env.sh" && \
- env DS_BUILD_OPS=0 HF_HOME=$HOME/hf PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
- DATA=$DATA bash "$HERE/rdsp_pp8.sh" ${RDSP_ARGS:-}) 2>&1 | tee "$LOGS/rdsp${NAME:-}.log" ;;
- *) sed -n 4,20p "$0"; exit 1 ;;
-esac
diff --git a/training/rdsp/bench/qwen35_27b/prep.sh b/training/rdsp/bench/qwen35_27b/prep.sh
deleted file mode 100755
index f74dd0ff9..000000000
--- a/training/rdsp/bench/qwen35_27b/prep.sh
+++ /dev/null
@@ -1,57 +0,0 @@
-#!/bin/bash
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-# prep.sh, on node 1 (docs/GETTING_STARTED.md lists what must be in place): both nodes ready.
-# 1. bench/qwen35_35b/prep.sh: environments, NeMo container, 35B weights, Bridge's 35B
-# checkpoint, the 35B rows at 128 a step on both nodes, NCCL check, Ray cluster
-# 2. the dense 27B: weights on both nodes, Bridge's checkpoint on node 1 (its one-node runs),
-# Bridge's rows at 64 a step (the one-node runs' rows) on both nodes
-# Idempotent like the 35B prep. Logs in logs/prep/.
-set -uo pipefail # no -e: each step checks its own exit code and reports which one failed
-RDSP=~/rdsp
-. ~/env2.sh
-LOGS=$RDSP/bench/qwen35_27b/logs/prep; mkdir -p "$LOGS"
-SSH2="ssh -i $HOME/key2.pem -o StrictHostKeyChecking=no -o BatchMode=yes ubuntu@$PRIV2"
-mark() { echo "=== $* $(date -u +%H:%M:%S)"; }
-step() { echo "--- $* $(date -u +%H:%M:%S)"; }
-
-step "START 35B prep"
-bash "$RDSP/bench/qwen35_35b/prep.sh" > "$LOGS/prep35.log" 2>&1
-grep -q "^=== PREP DONE" "$LOGS/prep35.log" || { mark "PREP FAILED 35B (logs/prep/prep35.log)"; exit 1; }
-grep -E "bus bandwidth|Selected|network" "$LOGS/prep35.log" | head -5
-step "END 35B prep"
-
-step "START 27B weights"
-DL="unset LD_LIBRARY_PATH; . ~/venv/bin/activate; HF_HOME=~/hf python -c \"import huggingface_hub as h; \
-h.snapshot_download('Qwen/Qwen3.5-27B', allow_patterns=['*.json', '*.safetensors', '*.txt', '*.jinja'])\""
-$SSH2 "$DL" < /dev/null > "$LOGS/download27b-node2.log" 2>&1 &
-D2=$!
-bash -c "$DL" > "$LOGS/download27b-node1.log" 2>&1; rc1=$?
-wait $D2; rc2=$?
-[ $rc1 = 0 ] && [ $rc2 = 0 ] || { mark "PREP FAILED 27B download: node 1 exit $rc1, node 2 exit $rc2"; exit 1; }
-step "END 27B weights"
-
-step "START 27B convert and export"
-MODEL=Qwen3.5-27B
-CONTAINER="sudo docker run --gpus all --rm --ipc=host --shm-size=64g --ulimit memlock=-1 \
- -v $HOME/hf:/root/.cache/huggingface -v $HOME/mimo:/workspace -v $RDSP:/rdsp \
- -e HF_HOME=/root/.cache/huggingface -e PYTHONUNBUFFERED=1 -w /opt/Megatron-Bridge nvcr.io/nvidia/nemo:26.08"
-if [ ! -f "$HOME/mimo/std/$MODEL.done" ]; then
- $CONTAINER bash -c "python scripts/conversion/setup_conversion.py import --hf-model Qwen/$MODEL \
- --megatron-path /workspace/std/$MODEL" > "$LOGS/convert27b.log" 2>&1; rc=$?
- sudo chown -R "$(id -u):$(id -g)" "$HOME/hf" "$HOME/mimo"
- [ $rc = 0 ] || { mark "PREP FAILED 27B convert exit $rc"; exit 1; }
- touch "$HOME/mimo/std/$MODEL.done"
-fi
-if [ ! -f "$HOME/mimo/cord_steps-$MODEL/stats.json" ]; then
- env MODEL=$MODEL RECIPE=qwen35_vl_27b_sft_16gpu_h100_bf16_config GBS=64 STEPS=50 LOGS="$LOGS" \
- bash "$RDSP/bench/common/runs.sh" export > /dev/null 2>&1; rc=$?
- mv "$LOGS/export.log" "$LOGS/export27b.log" 2>/dev/null
- [ $rc = 0 ] && [ -f "$HOME/mimo/cord_steps-$MODEL/stats.json" ] || { mark "PREP FAILED 27B export exit $rc"; exit 1; }
-fi
-cat "$HOME/mimo/cord_steps-$MODEL/stats.json"; echo # 65,003 real tokens a step on 2026-10-17
-$SSH2 "mkdir -p ~/mimo" < /dev/null
-rsync -a -e "ssh -i $HOME/key2.pem -o StrictHostKeyChecking=no" "$HOME/mimo/cord_steps-$MODEL/" \
- "ubuntu@$PRIV2:mimo/cord_steps-$MODEL/" || { mark "PREP FAILED copy 27B rows to node 2"; exit 1; }
-step "END 27B convert and export"
-mark "PREP DONE"
diff --git a/training/rdsp/bench/qwen35_27b/rdsp_pp8.sh b/training/rdsp/bench/qwen35_27b/rdsp_pp8.sh
deleted file mode 100755
index 1034a8fef..000000000
--- a/training/rdsp/bench/qwen35_27b/rdsp_pp8.sh
+++ /dev/null
@@ -1,22 +0,0 @@
-#!/usr/bin/env bash
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-# rdsp_pp8.sh: rdsp, Qwen3.5-27B, TP1 x PP8 x DP1 (8 pipeline stages of one GPU) on 8x H100. 1 row(s) per microbatch (one per DP copy), 64
-# microbatches per step, as Megatron runs this layout. Every row padded to 2048. Recompute every
-# block (27B does not fit this layout without), bf16 gradient accumulation,
-# fused AdamW, optimizer groups of 250M. Vision encoder eager. Extra arguments go to train_vl.py.
-set -euo pipefail
-RDSP=$(cd "$(dirname "$0")/../.." && pwd)
-# RECOMPUTE=0: no recompute (a fit check); ZERO: ZeRO stage (default 1); PROFILER: a command
-# prefix such as an nsys profile call
-RC=",recompute=1"; [ "${RECOMPUTE:-1}" = 0 ] && RC=""
-# RC_BLOCKS=N: recompute only each stage's first N decoder layers (and the vision encoder)
-[ -n "${RC_BLOCKS:-}" ] && RC=",recompute_blocks=$RC_BLOCKS"
-exec ${PROFILER:-} python "$RDSP/train_vl.py" \
- --model Qwen/Qwen3.5-27B --dataset "${DATA:?set DATA=exported:}" \
- --stages 8 --cuts balanced --stage 0:gpus=1,tp=1,zero=${ZERO:-1}$RC --stage 1:gpus=1,tp=1,zero=${ZERO:-1}$RC --stage 2:gpus=1,tp=1,zero=${ZERO:-1}$RC --stage 3:gpus=1,tp=1,zero=${ZERO:-1}$RC --stage 4:gpus=1,tp=1,zero=${ZERO:-1}$RC --stage 5:gpus=1,tp=1,zero=${ZERO:-1}$RC --stage 6:gpus=1,tp=1,zero=${ZERO:-1}$RC --stage 7:gpus=1,tp=1,zero=${ZERO:-1}$RC \
- --rows 1 --microbatches 64 --seq 2048 --pad-multiple 0 \
- --steps "${STEPS:-50}" --lr 1e-5 --betas 0.9,0.95 --eps 1e-8 --weight-decay 0.0 \
- --grad-dtype bf16 --fused-adam --optimizer-group-numel 250000000 \
- --loss token-mean --liger --prefetch --sharded-loss --drop-padding-mask \
- "$@"
diff --git a/training/rdsp/bench/qwen35_27b/rdsp_tune.sh b/training/rdsp/bench/qwen35_27b/rdsp_tune.sh
deleted file mode 100644
index d2108ebca..000000000
--- a/training/rdsp/bench/qwen35_27b/rdsp_tune.sh
+++ /dev/null
@@ -1,41 +0,0 @@
-#!/usr/bin/env bash
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-# rdsp_tune.sh: rdsp_pp8.sh's 27B run (TP1 x PP8 x DP1, 8 x H100) with extra knobs, everything else as
-# rdsp_pp8.sh with --master-dtype remainder --cuts measured (the blog's 27B runs):
-# ROWS (default 1) images (rows) per microbatch; 64 / ROWS microbatches a step
-# RC_BLOCKS=N recompute only the first N decoder blocks of each stage (and stage 0's vision
-# encoder) instead of every block; N counts at the calibration cut and moves
-# with the measured cut, so each stage keeps the same number of blocks' activations
-# COMPILE=1 torch.compile each stage's decoder blocks; turns Liger's RMSNorm/SwiGLU off
-# (the two crash together; the loss is rdsp's sharded loss either way)
-# LIGER=0 Liger off without compiling
-# STEPS (default 50); extra arguments go to train_vl.py
-set -euo pipefail
-RDSP=$(cd "$(dirname "$0")/../.." && pwd)
-ROWS=${ROWS:-1}
-RC=",recompute=1"
-[ -n "${RC_BLOCKS:-}" ] && RC=",recompute_blocks=$RC_BLOCKS"
-CP=""
-LIGER_FLAG="--liger"
-[ "${LIGER:-1}" = 0 ] && LIGER_FLAG=""
-if [ "${COMPILE:-0}" = 1 ]; then CP=",compile=1"; LIGER_FLAG=""; fi
-# RC_PER="n0,n1,...,n7": recompute_blocks per stage instead (early stages hold more microbatches in
-# flight under 1F1B, so they can keep fewer blocks' activations than late ones)
-IFS=, read -r -a PER <<< "${RC_PER:-}"
-STAGES=()
-for s in 0 1 2 3 4 5 6 7; do
- rc=$RC
- [ -n "${RC_PER:-}" ] && rc=",recompute_blocks=${PER[$s]}"
- STAGES+=(--stage "$s:gpus=1,tp=1,zero=1$rc$CP")
-done
-echo "rdsp_tune: ROWS=$ROWS RC_BLOCKS=${RC_BLOCKS:-all} RC_PER=${RC_PER:-} COMPILE=${COMPILE:-0} liger=${LIGER_FLAG:-off}"
-exec python "$RDSP/train_vl.py" \
- --model Qwen/Qwen3.5-27B --dataset "${DATA:?set DATA=exported:}" \
- --stages 8 --cuts measured "${STAGES[@]}" \
- --rows "$ROWS" --microbatches $((64 / ROWS)) --seq 2048 --pad-multiple 0 \
- --steps "${STEPS:-50}" --lr 1e-5 --betas 0.9,0.95 --eps 1e-8 --weight-decay 0.0 \
- --grad-dtype bf16 --fused-adam --optimizer-group-numel 250000000 \
- --loss token-mean $LIGER_FLAG --prefetch --sharded-loss --drop-padding-mask \
- --master-dtype remainder \
- ${RDSP_EXTRA:-} "$@"
diff --git a/training/rdsp/bench/qwen35_35b/bridge_pp8dp2.sh b/training/rdsp/bench/qwen35_35b/bridge_pp8dp2.sh
deleted file mode 100755
index bf3d464c5..000000000
--- a/training/rdsp/bench/qwen35_35b/bridge_pp8dp2.sh
+++ /dev/null
@@ -1,23 +0,0 @@
-#!/bin/bash
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-# bridge_pp8dp2.sh: Megatron-Bridge on Qwen3.5-35B-A3B, TP1 x PP8 x DP2 on two nodes, the layout
-# of rdsp_pp8dp2.sh: no expert parallelism, 64 microbatches of 2 rows. On node 1, after prep.sh.
-# CUT="F L": layers on the first and last stage (Megatron's middle stages are equal); unset, 5
-# per stage. ../common/layout_from_log.py megatron-cut gives the cut nearest rdsp's.
-# BRIDGE_EXTRA: more Bridge overrides, e.g. dist.use_tp_pp_dp_mapping=true (each pipeline inside
-# one node, DP across the nodes: the default order, pipeline across the nodes, deadlocked twice
-# in batched send/recv).
-# STEPS (default 50), RECOMPUTE=1 (every layer), NAME (log suffix). Logs in logs/pp8dp2/.
-set -euo pipefail
-HERE=$(cd "$(dirname "$0")" && pwd)
-. "$HERE/../common/two_node.sh"
-export LOGS=$HERE/logs/pp8dp2$LOGS_SUFFIX; mkdir -p "$LOGS"
-TAG=""; [ "$RECOMPUTE" = 1 ] && TAG=-rc
-cut=""
-if [ -n "${CUT:-}" ]; then
- read -r first last <<< "$CUT"
- cut="model.num_layers_in_first_pipeline_stage=$first model.num_layers_in_last_pipeline_stage=$last"
-fi
-bridge tp1pp8-megatron "bridge$TAG${NAME:-}" $MEG_TP1 model.expert_model_parallel_size=1 $cut \
- ${BRIDGE_EXTRA:-}
diff --git a/training/rdsp/bench/qwen35_35b/node_prep.sh b/training/rdsp/bench/qwen35_35b/node_prep.sh
deleted file mode 100755
index 1a9c2b3a7..000000000
--- a/training/rdsp/bench/qwen35_35b/node_prep.sh
+++ /dev/null
@@ -1,22 +0,0 @@
-#!/bin/bash
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-# node_prep.sh: one node ready for the 35B runs (prep.sh runs it on both nodes at once): the rdsp
-# environment and NeMo container (bench/setup_node.sh), TorchTitan's environment
-# (bench/torchtitan/setup_box.sh) and the Qwen3.5-35B-A3B weights (~72 GB) side by side, then a
-# record of the node's GPUs and EFA devices in ~/hardware.txt. Logs in ~/.
-set -uo pipefail # no -e: each step checks its own exit code and reports which one failed
-RDSP=$(cd "$(dirname "$0")/../.." && pwd)
-bash "$RDSP/bench/setup_node.sh" > ~/setup.log 2>&1 || { echo "SETUP FAILED"; exit 1; }
-bash "$RDSP/bench/torchtitan/setup_box.sh" > ~/tt_setup.log 2>&1 &
-TT=$!
-(unset LD_LIBRARY_PATH; . ~/venv/bin/activate; HF_HOME=~/hf python -c "import huggingface_hub as h; \
- h.snapshot_download('Qwen/Qwen3.5-35B-A3B', allow_patterns=['*.json', '*.safetensors', '*.txt', '*.jinja'])") \
- > ~/download.log 2>&1 || { echo "DOWNLOAD FAILED"; exit 1; }
-wait $TT || { echo "TORCHTITAN SETUP FAILED"; exit 1; }
-{ hostname; nvidia-smi --query-gpu=name,memory.total,driver_version --format=csv; nvidia-smi topo -m
- echo "EFA devices: $(ls /sys/class/infiniband 2>/dev/null | wc -l)"
- /opt/amazon/efa/bin/fi_info -p efa 2>/dev/null | grep -m3 -E "provider|fabric|domain"
- ls /opt/amazon/ofi-nccl/lib 2>/dev/null | head -3; lscpu | head -20; } > ~/hardware.txt 2>&1
-touch ~/.rdsp_node_prep_done # prep.sh skips this node next time
-echo "NODE PREP DONE"
diff --git a/training/rdsp/bench/qwen35_35b/prep.sh b/training/rdsp/bench/qwen35_35b/prep.sh
deleted file mode 100755
index 402f582ac..000000000
--- a/training/rdsp/bench/qwen35_35b/prep.sh
+++ /dev/null
@@ -1,63 +0,0 @@
-#!/bin/bash
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-# prep.sh, on node 1 with ~/env2.sh and ~/key2.pem in place (docs/GETTING_STARTED.md): both
-# nodes ready for the 35B runs. Logs in logs/prep/.
-# 1. node_prep.sh on both nodes at once: environments, NeMo container, 35B weights, hardware
-# 2. node 1: Bridge's checkpoint (HF -> Megatron, the standard path; MIMO is not run) and
-# Bridge's rows exported at 128 per step, 50 steps; both copied to node 2
-# 3. NCCL all-reduce over both nodes (EFA) and the network NCCL picked
-# 4. the Ray cluster over both nodes, for rdsp
-# SKIP_CONVERT=1: no Bridge checkpoint (rdsp-only rounds; the rows export needs only the container).
-# Steps already done (their outputs in place) are skipped, so a failed prep restarts where it
-# stopped: ~/.rdsp_node_prep_done on each node, ~/mimo/std/$MODEL.done, the export's stats.json.
-set -uo pipefail # no -e: each step checks its own exit code and reports which one failed
-HERE=$(cd "$(dirname "$0")" && pwd)
-. "$HERE/../common/two_node.sh"
-. ~/env2.sh
-LOGS=$HERE/logs/prep; mkdir -p "$LOGS"
-SSH2="ssh -i $HOME/key2.pem -o StrictHostKeyChecking=no -o BatchMode=yes ubuntu@$PRIV2"
-mark() { echo "=== $* $(date -u +%H:%M:%S)"; } # "=== " lines are the outcome: DONE, FAILED
-step() { echo "--- $* $(date -u +%H:%M:%S)"; } # progress only: GPUs idle during prep by design
-
-step "START node prep"
-NODE_PREP="[ -f ~/.rdsp_node_prep_done ] || bash ~/rdsp/bench/qwen35_35b/node_prep.sh"
-$SSH2 "$NODE_PREP" < /dev/null >> "$LOGS/node2_prep.log" 2>&1 &
-N2=$!
-bash -c "$NODE_PREP" >> "$LOGS/node1_prep.log" 2>&1; rc1=$?
-wait $N2; rc2=$?
-cp ~/hardware.txt "$LOGS/hardware-node1.txt"; $SSH2 "cat ~/hardware.txt" < /dev/null > "$LOGS/hardware-node2.txt"
-[ $rc1 = 0 ] && [ $rc2 = 0 ] || { mark "PREP FAILED node prep: node 1 exit $rc1, node 2 exit $rc2"; exit 1; }
-step "END node prep"
-
-step "START convert and export"
-CONTAINER="sudo docker run --gpus all --rm --ipc=host --shm-size=64g --ulimit memlock=-1 \
- -v $HOME/hf:/root/.cache/huggingface -v $HOME/mimo:/workspace -v $RDSP:/rdsp \
- -e HF_HOME=/root/.cache/huggingface -e PYTHONUNBUFFERED=1 -w /opt/Megatron-Bridge nvcr.io/nvidia/nemo:26.08"
-if [ -z "${SKIP_CONVERT:-}" ] && [ ! -f "$HOME/mimo/std/$MODEL.done" ]; then
- $CONTAINER bash -c "python scripts/conversion/setup_conversion.py import --hf-model Qwen/$MODEL \
- --megatron-path /workspace/std/$MODEL" > "$LOGS/convert.log" 2>&1; rc=$?
- sudo chown -R "$(id -u):$(id -g)" "$HOME/hf" "$HOME/mimo"
- [ $rc = 0 ] || { mark "PREP FAILED convert exit $rc"; exit 1; }
- touch "$HOME/mimo/std/$MODEL.done"
-fi
-if [ ! -f "$HOME/mimo/cord_steps-$MODEL/stats.json" ]; then
- env LOGS="$LOGS" bash "$RUNS" export > /dev/null 2>&1; rc=$? # GBS=128, STEPS=50 from two_node.sh
- [ $rc = 0 ] && [ -f "$HOME/mimo/cord_steps-$MODEL/stats.json" ] || { mark "PREP FAILED export exit $rc"; exit 1; }
-fi
-$SSH2 "mkdir -p ~/mimo/std" < /dev/null # rsync makes only the last directory of a path
-for d in $([ -d "$HOME/mimo/std/$MODEL" ] && echo "std/$MODEL") "cord_steps-$MODEL"; do
- rsync -a -e "ssh -i $HOME/key2.pem -o StrictHostKeyChecking=no" "$HOME/mimo/$d/" "ubuntu@$PRIV2:mimo/$d/" \
- || { mark "PREP FAILED copy $d to node 2"; exit 1; }
-done
-step "END convert and export"
-
-step "START nccl check"
-bash "$BOTH" bash "$RDSP/bench/cluster/nccl_check.sh" > "$LOGS/nccl_check.log" 2>&1
-grep -E "bus bandwidth" "$LOGS/nccl_check.log"
-grep -m2 -oE "NET/OFI Selected [^ ]+ [^ ]+|Using network [A-Za-z]+|NET/Socket" "$LOGS/nccl_check.log" | sort -u
-step "END nccl check"
-
-bash "$RDSP/bench/cluster/ray_cluster.sh" up "$PRIV1" "$PRIV2" > "$LOGS/ray_up.log" 2>&1 \
- || { mark "PREP FAILED ray cluster"; cat "$LOGS/ray_up.log"; exit 1; }
-mark "PREP DONE"
diff --git a/training/rdsp/bench/qwen35_35b/rdsp_pp8dp2.sh b/training/rdsp/bench/qwen35_35b/rdsp_pp8dp2.sh
deleted file mode 100755
index 3068bccf4..000000000
--- a/training/rdsp/bench/qwen35_35b/rdsp_pp8dp2.sh
+++ /dev/null
@@ -1,21 +0,0 @@
-#!/bin/bash
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-# rdsp_pp8dp2.sh: rdsp on Qwen3.5-35B-A3B, TP1 x PP8 x DP2 on two nodes, each of the 8 pipeline
-# stages on 2 GPUs of one node (stages 0-3 on node 1, 4-7 on node 2), no expert parallelism (each
-# stage's 2 copies hold all its experts). 64 microbatches of 2 rows (one per copy). On node 1,
-# after prep.sh, with the Ray cluster up. --cuts measured: rdsp times its stages on 3 steps and
-# re-cuts by what it measured.
-# Stage 0's vision encoder is recomputed (../common/two_node.sh vision_first; VISION_RC=0: not).
-# LANG_EP=2: every stage splits its experts over its 2 GPUs (DeepSpeed AutoEP, NVLink inside the
-# node), about half the expert weights and optimizer state per GPU; logs get "-ep2".
-# STEPS (default 50), RECOMPUTE=1 (every block), NAME (log suffix). Logs in logs/pp8dp2/.
-set -euo pipefail
-HERE=$(cd "$(dirname "$0")" && pwd)
-. "$HERE/../common/two_node.sh"
-export LOGS=$HERE/logs/pp8dp2$LOGS_SUFFIX; mkdir -p "$LOGS"
-TAG=""; [ "$RECOMPUTE" = 1 ] && TAG=-rc
-EP=${LANG_EP:+,ep=$LANG_EP}
-rdsp "rdsp${LANG_EP:+-ep$LANG_EP}$TAG${NAME:-}" --stages 8 --cuts measured $(vision_first 2)$EP \
- $(stage_flags 1 7 2 "$EP") \
- --rows 2 --microbatches $((GBS / 2))
diff --git a/training/rdsp/bench/qwen35_35b/rdsp_vision_stage.sh b/training/rdsp/bench/qwen35_35b/rdsp_vision_stage.sh
deleted file mode 100755
index 5b67ae6ff..000000000
--- a/training/rdsp/bench/qwen35_35b/rdsp_vision_stage.sh
+++ /dev/null
@@ -1,32 +0,0 @@
-#!/bin/bash
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-# rdsp_vision_stage.sh: rdsp on Qwen3.5-35B-A3B with the vision encoder on a stage of its own: K
-# GPUs encode the step's images (one image row per GPU per microbatch), the language model runs as
-# (16 - K) / 2 pipeline stages of 2 GPUs. K comes from rdsp_pp8dp2.sh's measured stage times
-# (../common/layout_from_log.py vision-width logs/pp8dp2/rdsp.log 16), not by hand. 128 / K
-# microbatches of K rows. --cuts 0,measured: the language stages re-cut by their measured times.
-# On node 1, after prep.sh, with the Ray cluster up.
-# The vision stage's encoder is recomputed (../common/two_node.sh vision_first; VISION_RC=0: not).
-# LANG_EP=2: each language stage splits its experts over its 2 GPUs (DeepSpeed AutoEP, NVLink
-# inside the node): about half the weights and optimizer state per GPU.
-# STAGE_GPUS=4: language stages of 4 GPUs instead of 2 ((16 - K) / 4 of them; K a multiple of 4),
-# logs get "-s4"; with LANG_EP=4 each splits its experts over its 4 GPUs.
-# K (required: 2, 4 or 8), STEPS (default 50), RECOMPUTE=1 (every block), NAME (log suffix).
-# Logs in logs/vision_stage/.
-set -euo pipefail
-HERE=$(cd "$(dirname "$0")" && pwd)
-. "$HERE/../common/two_node.sh"
-export LOGS=$HERE/logs/vision_stage$LOGS_SUFFIX; mkdir -p "$LOGS"
-TAG=""; [ "$RECOMPUTE" = 1 ] && TAG=-rc
-K=${K:?set K, the vision stage GPUs}
-SG=${STAGE_GPUS:-2}
-if [ $(( (16 - K) % SG )) != 0 ] || [ $(( K % SG )) != 0 ]; then
- echo "K=$K does not split into language stages of $SG GPUs (each microbatch's K rows over $SG)" >&2
- exit 1
-fi
-P=$(( (16 - K) / SG ))
-S=""; [ "$SG" != 2 ] && S=-s$SG
-rdsp "rdsp-k$K$S${LANG_EP:+-ep$LANG_EP}$TAG${NAME:-}" --stages $((P + 1)) --cuts 0,measured \
- $(vision_first "$K") $(stage_flags 1 $P "$SG" "${LANG_EP:+,ep=$LANG_EP}") \
- --rows "$K" --microbatches $((GBS / K))
diff --git a/training/rdsp/bench/qwen35_35b/rdsp_zero3.sh b/training/rdsp/bench/qwen35_35b/rdsp_zero3.sh
deleted file mode 100755
index 3457b5c68..000000000
--- a/training/rdsp/bench/qwen35_35b/rdsp_zero3.sh
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/bin/bash
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-# rdsp_zero3.sh: rdsp on Qwen3.5-35B-A3B as one stage of all 16 GPUs under DeepSpeed ZeRO-3, the
-# fully sharded layout of torchtitan.sh: weights, gradients and Adam split 16 ways, one row per GPU
-# per microbatch, 8 microbatches. fp32 master (4 bytes): the 2-byte master works with ZeRO 1 and 2
-# only; TorchTitan's master is fp32 too. On node 1, after prep.sh, with the Ray cluster up.
-# STEPS (default 50), RECOMPUTE=1 (every block), NAME (log suffix). Logs in logs/fsdp16/.
-set -euo pipefail
-HERE=$(cd "$(dirname "$0")" && pwd)
-. "$HERE/../common/two_node.sh"
-export LOGS=$HERE/logs/fsdp16$LOGS_SUFFIX; mkdir -p "$LOGS"
-TAG=""; RC=""; [ "$RECOMPUTE" = 1 ] && TAG=-rc RC=",recompute=1"
-rdsp "rdsp-zero3$TAG${NAME:-}" --stages 1 --stage "0:gpus=16,zero=3$RC" \
- --rows 16 --microbatches 8 --master-dtype fp32
diff --git a/training/rdsp/bench/qwen35_35b/torchtitan.sh b/training/rdsp/bench/qwen35_35b/torchtitan.sh
deleted file mode 100755
index 84852a3f9..000000000
--- a/training/rdsp/bench/qwen35_35b/torchtitan.sh
+++ /dev/null
@@ -1,28 +0,0 @@
-#!/bin/bash
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-# torchtitan.sh : TorchTitan on Qwen3.5-35B-A3B, fully sharded
-# over all 16 GPUs: weights, gradients and Adam split 16 ways, each layer gathered whole just
-# before it runs; one row per GPU per microbatch, 8 microbatches. On node 1, after prep.sh.
-# fsdp16 FSDP over 16, every expert gathered like the rest
-# fsdp16-ep8 FSDP16 + expert parallelism 8 (each node's 8 GPUs split the experts)
-# fsdp16-ep8-bf16 the same with gradients reduced in bf16, as Bridge and rdsp send theirs
-# STEPS (default 50; 3 for a fit check), RECOMPUTE=1 (every block), NAME (log suffix).
-# Logs in logs/fsdp16/--node.log.
-set -euo pipefail
-HERE=$(cd "$(dirname "$0")" && pwd)
-. "$HERE/../common/two_node.sh"
-export LOGS=$HERE/logs/fsdp16$LOGS_SUFFIX; mkdir -p "$LOGS"
-SUFFIX=""; [ "$RECOMPUTE" = 1 ] && SUFFIX=_rc
-STEP=run; [ "$STEPS" = 3 ] && STEP=fit
-titan() { # titan
- bash "$BOTH" env LOGS="$LOGS" STEPS="$STEPS" NET="$NET" NAME="${NAME:-}" \
- NSYS_DELAY="${NSYS_DELAY:-}" NSYS_DURATION="${NSYS_DURATION:-}" \
- bash "$RDSP/bench/torchtitan/run_two_node.sh" "$STEP" "$1$SUFFIX"
-}
-case "${1:-}" in
- fsdp16) titan qwen35_35b_a3b_cord_fsdp16 ;;
- fsdp16-ep8) titan qwen35_35b_a3b_cord_fsdp16_ep8 ;;
- fsdp16-ep8-bf16) titan qwen35_35b_a3b_cord_fsdp16_ep8_bf16 ;; # gradients reduced in bf16
- *) sed -n 4,11p "$0"; exit 1 ;;
-esac
diff --git a/training/rdsp/bench/qwen35_small/bench.sh b/training/rdsp/bench/qwen35_small/bench.sh
deleted file mode 100755
index 6629b5dbc..000000000
--- a/training/rdsp/bench/qwen35_small/bench.sh
+++ /dev/null
@@ -1,85 +0,0 @@
-#!/bin/bash
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-# bench.sh ...: rdsp against Megatron on one 8-GPU node, then the table.
-#
-# noncoloc MegatronMIMO vs rdsp: vision encoder on 1 GPU, language TP2xDP2 (5 GPUs)
-# tp2 Megatron-Bridge vs rdsp: TP2xPP2xDP2
-# tp4 Megatron-Bridge vs rdsp: TP4xPP2xDP1
-# coloc rdsp only: vision encoder on every GPU, language TP2xPP2xDP2
-# all the four above
-#
-# Env: MODEL (Qwen3.5-4B), STEPS (50), ROUNDS (1), PRICE (node $/h for the cost
-# column, 5.32), LOGS (~/bench/$MODEL; round r writes $LOGS/r), DRY_RUN=1
-# prints the plan. Converts the checkpoints and exports the samples first when
-# they are missing. Each pair runs back to back, Megatron first; a layout with
-# no rdsp recipe for MODEL is skipped. NSYS_DELAY + NSYS_DURATION profile every
-# run with Nsight Systems (see bench/common/runs.sh). Run after bench/setup_node.sh.
-set -uo pipefail
-HERE=$(cd "$(dirname "$0")" && pwd)
-RDSP=$(cd "$HERE/../.." && pwd)
-export MODEL=${MODEL:-Qwen3.5-4B} STEPS=${STEPS:-50}
-ROUNDS=${ROUNDS:-1}; PRICE=${PRICE:-5.32}
-BASE=${LOGS:-$HOME/bench/$MODEL}
-WORK=$HOME/mimo
-SIZE=$(echo "${MODEL#Qwen3.5-}" | tr '[:upper:]' '[:lower:]')
-
-usage() { sed -n 2,17p "$0"; exit 1; }
-[ $# -gt 0 ] || usage
-layouts=()
-for arg in "$@"; do
- case $arg in
- all) layouts+=(noncoloc tp2 tp4 coloc) ;;
- noncoloc|tp2|tp4|coloc) layouts+=("$arg") ;;
- *) echo "unknown layout: $arg"; usage ;;
- esac
-done
-
-cases_of() { # cases_of : runs.sh cases, Megatron first
- case $1 in
- noncoloc) echo noncoloc-mimo noncoloc-rdsp ;;
- tp2) echo shared-megatron shared-rdsp ;;
- tp4) echo tp4pp2-megatron tp4pp2-rdsp ;;
- coloc) echo coloc-rdsp ;;
- esac
-}
-recipe_of() {
- case $1 in
- noncoloc) echo "qwen35-$SIZE-vision1-tp2dp2.sh" ;;
- tp2) echo "qwen35-$SIZE-tp2pp2dp2.sh" ;;
- tp4) echo "qwen35-$SIZE-tp4pp2dp1.sh" ;;
- coloc) echo "qwen35-$SIZE-coloc-tp2pp2dp2.sh" ;;
- esac
-}
-
-failed=0
-run() { # run
- echo "run LOGS=$1 $2"
- [ -n "${DRY_RUN:-}" ] && return 0
- LOGS=$1 bash "$RDSP/bench/common/runs.sh" "$2" || { echo "FAILED: $2"; failed=1; }
-}
-
-if [ ! -d "$WORK/std/$MODEL" ] || [ ! -d "$WORK/$MODEL-mimo" ]; then
- run "$BASE" convert
-fi
-exported=$(ls "$WORK/cord_steps-$MODEL"/step_*.pt 2>/dev/null | wc -l)
-if [ "$exported" -lt "$STEPS" ]; then
- run "$BASE" export
-fi
-
-for round in $(seq 1 "$ROUNDS"); do
- logs=$BASE/r$round
- for layout in "${layouts[@]}"; do
- recipe=$(recipe_of "$layout")
- if [ ! -f "$RDSP/recipes/$recipe" ]; then
- echo "skip $layout: no recipes/$recipe"
- continue
- fi
- for c in $(cases_of "$layout"); do run "$logs" "$c"; done
- done
- if [ -z "${DRY_RUN:-}" ]; then
- mkdir -p "$logs"
- python3 "$RDSP/bench/common/summarize.py" "$logs" --price "$PRICE" | tee "$logs/summary.txt"
- fi
-done
-exit $failed
diff --git a/training/rdsp/bench/results.py b/training/rdsp/bench/results.py
new file mode 100644
index 000000000..9e4cc6da7
--- /dev/null
+++ b/training/rdsp/bench/results.py
@@ -0,0 +1,80 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+
+"""Step time and throughput from benchmark logs.
+
+ python bench/results.py bench/logs/qwen35_35b/*.log [--gpus 16]
+
+For each log: the median time of training steps 6-15 (the first five compile and warm up) and
+tokens/s per GPU at 128 rows of 2,048 tokens a step. rdsp, Megatron (Bridge and MIMO) and
+TorchTitan logs are told apart by their step lines.
+"""
+
+import argparse
+import re
+import statistics
+
+ROWS, SEQ = 128, 2048
+FIRST, LAST = 6, 15 # training steps counted, numbered from 1
+
+
+def rdsp_times(text: str) -> dict[int, float]:
+ """ "step N loss L T ms" lines; rdsp numbers its steps from 0."""
+ found = re.finditer(r"^step (\d+) loss \S+ +(\d+) ms", text, re.M)
+ return {int(m.group(1)) + 1: float(m.group(2)) / 1000 for m in found}
+
+
+def megatron_times(text: str) -> dict[int, float]:
+ """ "iteration N/ M | ... elapsed time per iteration (ms): X" lines."""
+ pattern = r"iteration +(\d+)/ *\d+ \|.*?elapsed time per iteration \(ms\): ([\d.]+)"
+ times = {int(m.group(1)): float(m.group(2)) / 1000 for m in re.finditer(pattern, text)}
+ if not times: # the other node of a two-node run: "Step Time : X s", one line per step
+ found = re.findall(r"^Step Time : ([\d.]+)s", text, re.M)
+ times = {i: float(t) for i, t in enumerate(found, 1)}
+ return times
+
+
+def titan_times(text: str) -> dict[int, float]:
+ """The time between rank 0's consecutive "step: N" metric lines."""
+ pattern = (
+ r"\[rank0\].*?(\d\d):(\d\d):(\d\d),(\d+) - torchtitan\.observability\.metrics - INFO - "
+ r".*?step: +(\d+) "
+ )
+ stamps = {}
+ for m in re.finditer(pattern, re.sub(r"\x1b\[[0-9;]*m", "", text)):
+ h, mi, s, ms, step = m.groups()
+ stamps[int(step)] = int(h) * 3600 + int(mi) * 60 + int(s) + int(ms) / 1000
+ return {k: stamps[k] - stamps[k - 1] for k in stamps if k - 1 in stamps}
+
+
+PARSERS = {"rdsp": rdsp_times, "megatron": megatron_times, "torchtitan": titan_times}
+
+
+def measure(text: str) -> tuple[str | None, float | None]:
+ """(framework, median seconds a step over steps 6-15), or None where the log has none."""
+ for name, parse in PARSERS.items():
+ times = parse(text)
+ if times:
+ window = [times[i] for i in range(FIRST, LAST + 1) if i in times]
+ return name, statistics.median(window) if len(window) == LAST - FIRST + 1 else None
+ return None, None
+
+
+def main(argv=None) -> None:
+ parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ parser.add_argument("logs", nargs="+")
+ parser.add_argument("--gpus", type=int, default=16, help="GPUs the run used (default 16)")
+ args = parser.parse_args(argv)
+ print(f"{'log':<48} {'system':<11} {'step time':>10} {'tokens/s per GPU':>17}")
+ for path in args.logs:
+ framework, seconds = measure(open(path, errors="ignore").read())
+ if seconds is None:
+ note = "no step times" if framework is None else f"fewer than {LAST} steps"
+ print(f"{path:<48} {framework or '-':<11} {note:>28}")
+ continue
+ tokens = ROWS * SEQ / seconds / args.gpus
+ print(f"{path:<48} {framework:<11} {seconds:>9.2f}s {tokens:>17,.0f}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/training/rdsp/bench/setup_node.sh b/training/rdsp/bench/setup_node.sh
deleted file mode 100755
index db4eceb80..000000000
--- a/training/rdsp/bench/setup_node.sh
+++ /dev/null
@@ -1,33 +0,0 @@
-#!/bin/bash
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-# Fresh Linux GPU node -> ready to run recipes/ and bench/common/runs.sh.
-# Python 3.12 venv in ~/venv, torch 2.13, DeepSpeed at the pinned commit every
-# result used, rdsp (editable), Qwen3.5 kernels, and the NeMo container for the
-# Megatron side. Needs NVIDIA drivers, CUDA, Docker with the NVIDIA runtime.
-set -euxo pipefail
-RDSP=$(cd "$(dirname "$0")/.." && pwd)
-unset LD_LIBRARY_PATH # some images' CUDA libs break torch's cuDNN
-command -v uv || curl -LsSf https://astral.sh/uv/install.sh | sh
-export PATH=$HOME/.local/bin:$PATH
-uv venv -p 3.12 ~/venv
-. ~/venv/bin/activate
-# Versions as installed for the October runs (2B, 4B, 27B one node, 35B). The 9B MegatronMIMO
-# runs' node had ray 2.60.0, flash-linear-attention 0.6.0 and liger-kernel 0.8.5 instead.
-uv pip install "torch==2.13.0" "torchvision==0.28.0" "transformers==5.17.0" "ray==2.59.0" \
- cloudpickle "accelerate==1.15.0" safetensors datasets pillow ninja packaging numpy pytest
-CUDA_HOME=/usr/local/cuda-$(python -c "import torch; print(torch.version.cuda)")
-[ -d "$CUDA_HOME" ] || CUDA_HOME=/usr/local/cuda # no toolkit matching torch's CUDA
-echo "export CUDA_HOME=$CUDA_HOME" > ~/cuda_env.sh
-export CUDA_HOME DS_BUILD_OPS=0
-uv pip install --no-build-isolation \
- "git+https://github.com/deepspeedai/DeepSpeed.git@53a2ac44fb664bea838df3981ba4366b91643070"
-uv pip install -e "$RDSP"
-# Qwen3.5 linear attention, fused kernels
-uv pip install "flash-linear-attention==0.5.2" "liger-kernel==0.8.4"
-uv pip install --no-build-isolation "causal-conv1d==1.7.0"
-mkdir -p ~/hf ~/mimo ~/runs
-sudo docker pull nvcr.io/nvidia/nemo:26.08
-python -c "import torch, deepspeed, transformers, ray; print('torch', torch.__version__, \
-'gpus', torch.cuda.device_count(), 'deepspeed', deepspeed.__version__, \
-'transformers', transformers.__version__, 'ray', ray.__version__)"
diff --git a/training/rdsp/bench/torchtitan/run.sh b/training/rdsp/bench/torchtitan/run.sh
deleted file mode 100755
index 0b825098c..000000000
--- a/training/rdsp/bench/torchtitan/run.sh
+++ /dev/null
@@ -1,25 +0,0 @@
-#!/bin/bash
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-# run.sh [CONFIG]: TorchTitan, Qwen3.5-27B TP4 x PP2 on Bridge's exported rows, on the
-# H100 box after setup_box.sh, the 27B download and the export.
-# fit 3 steps (memory check) run 50 steps (STEPS to change)
-# CONFIG: qwen35_27b_cord_tp4pp2 (default, no recompute) or qwen35_27b_cord_tp4pp2_rc.
-# Logs ranks 0 (stage 0) and 4 (stage 1, where the loss is) to logs/-.log.
-set -euo pipefail
-HERE=$(cd "$(dirname "$0")" && pwd)
-LOGS=$HERE/logs; mkdir -p "$LOGS"
-CONFIG=${2:-qwen35_27b_cord_tp4pp2}
-case "${1:-}" in
- fit) STEPS=3 ;;
- run) STEPS=${STEPS:-50} ;;
- *) sed -n 2,6p "$0"; exit 1 ;;
-esac
-# MODEL (default Qwen3.5-27B), EXPORT_NAME (its rows in ~/mimo, default cord_steps-$MODEL), ROWS
-MODEL=${MODEL:-Qwen3.5-27B}
-HF_ASSETS=$(ls -d "$HOME"/hf/hub/models--Qwen--$MODEL/snapshots/* | head -1)
-cd ~/torchtitan
-(unset LD_LIBRARY_PATH && . ~/tt_venv/bin/activate && \
- env PYTHONPATH="$HERE" HF_ASSETS="$HF_ASSETS" EXPORTED="$HOME/mimo/${EXPORT_NAME:-cord_steps-$MODEL}" \
- ROWS=${ROWS:-64} STEPS=$STEPS MODULE=cord_qwen35 CONFIG=$CONFIG NGPU=8 LOG_RANK=${LOG_RANK:-0,4} ./run_train.sh) \
- 2>&1 | tee "$LOGS/$1-$CONFIG${NAME:-}.log" # NAME: a log-name suffix
diff --git a/training/rdsp/bench/torchtitan/run_two_node.sh b/training/rdsp/bench/torchtitan/run_two_node.sh
deleted file mode 100755
index 559d56549..000000000
--- a/training/rdsp/bench/torchtitan/run_two_node.sh
+++ /dev/null
@@ -1,39 +0,0 @@
-#!/bin/bash
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-# run_two_node.sh : TorchTitan over two nodes, Qwen3.5-35B-A3B on Bridge's rows
-# exported at 128 per step. Start it on both nodes at once from ~/rdsp with bench/cluster/both.sh,
-# which sets NNODES, NODE_RANK and MASTER_ADDR:
-# bash bench/cluster/both.sh bash bench/torchtitan/run_two_node.sh fit qwen35_35b_a3b_cord_fsdp16
-# fit 3 steps (memory check) run 50 steps (STEPS to change)
-# Each node logs its local rank 0 (global ranks 0 and 8) to $LOGS/--node.log
-# (default logs/).
-set -euo pipefail
-HERE=$(cd "$(dirname "$0")" && pwd)
-LOGS=${LOGS:-$HERE/logs}; mkdir -p "$LOGS" # LOGS: a layout's own logs directory
-CONFIG=${2:?usage: run_two_node.sh }
-case "${1:-}" in
- fit) STEPS=3 ;;
- run) STEPS=${STEPS:-50} ;;
- *) sed -n 2,8p "$0"; exit 1 ;;
-esac
-# MODEL (default Qwen3.5-35B-A3B), EXPORT_NAME (its rows in ~/mimo, default cord_steps-$MODEL)
-MODEL=${MODEL:-Qwen3.5-35B-A3B}
-HF_ASSETS=$(ls -d "$HOME"/hf/hub/models--Qwen--$MODEL/snapshots/* | head -1)
-# NSYS_DELAY + NSYS_DURATION (seconds): Nsight Systems on node 1's 8 ranks over that window
-# (CUDA kernels and NVTX), report $LOGS/nsys--node0.nsys-rep
-PROFILER=""
-if [ -n "${NSYS_DELAY:-}" ] && [ "$NODE_RANK" = 0 ]; then
- PROFILER="nsys profile -t cuda,nvtx -s none --cpuctxsw=none --delay $NSYS_DELAY \
- --duration ${NSYS_DURATION:-36} --force-overwrite true -o $LOGS/nsys-$CONFIG-node0"
-fi
-cd ~/torchtitan
-# NET=socket: NCCL between the nodes over TCP (NCCL_NET=Socket). NAME: a log-name suffix.
-(unset LD_LIBRARY_PATH && . ~/tt_venv/bin/activate && . "$HERE/../cluster/efa_env.sh" && \
- { [ "${NET:-efa}" != socket ] || export NCCL_NET=Socket; } && \
- env PYTHONPATH="$HERE" HF_ASSETS="$HF_ASSETS" EXPORTED="$HOME/mimo/${EXPORT_NAME:-cord_steps-$MODEL}" \
- ROWS=${ROWS:-128} SEQ=${SEQ:-2048} STEPS=$STEPS PYTORCH_ALLOC_CONF="expandable_segments:True" LOG_RANK=0 \
- $PROFILER torchrun --nnodes "$NNODES" --node_rank "$NODE_RANK" --master_addr "$MASTER_ADDR" \
- --master_port 29413 --nproc_per_node 8 --local-ranks-filter 0 --role rank --tee 3 \
- -m torchtitan.train --module cord_qwen35 --config "$CONFIG") \
- 2>&1 | tee "$LOGS/$1-$CONFIG${NAME:-}-node$NODE_RANK.log"
diff --git a/training/rdsp/bench/torchtitan/setup_box.sh b/training/rdsp/bench/torchtitan/setup_box.sh
deleted file mode 100755
index 91c43bedd..000000000
--- a/training/rdsp/bench/torchtitan/setup_box.sh
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/bin/bash
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-# On the H100 box: TorchTitan at the commit read and checked (3c36a77) in ~/torchtitan, its own
-# venv ~/tt_venv (Python 3.12, the PyTorch nightly for CUDA 13.0 of the date of that commit; the
-# setup fails if that nightly is gone), TorchTitan's requirements + its vision extras. Leaves the
-# rdsp venv alone.
-set -euxo pipefail
-export PATH=$HOME/.local/bin:$PATH
-unset LD_LIBRARY_PATH
-[ -d ~/torchtitan ] || git clone https://github.com/pytorch/torchtitan ~/torchtitan
-git -C ~/torchtitan checkout 3c36a7767cf2222aa4e0d494463f486363c8df99
-uv venv -p 3.12 ~/tt_venv
-. ~/tt_venv/bin/activate
-NIGHTLY=https://download.pytorch.org/whl/nightly/cu130
-uv pip install --pre "torch==2.16.0.dev20261012" "torchvision==0.30.0.dev20261012" --index-url $NIGHTLY
-uv pip install -r ~/torchtitan/requirements.txt -r ~/torchtitan/.ci/docker/requirements-vlm.txt
-uv pip install --no-deps -e ~/torchtitan
-python -c "import torch, torchtitan; print('torch', torch.__version__, 'cuda', torch.version.cuda, 'gpus', torch.cuda.device_count())"
-echo "TT SETUP DONE"
diff --git a/training/rdsp/demo.py b/training/rdsp/demo.py
deleted file mode 100644
index 5f81377c6..000000000
--- a/training/rdsp/demo.py
+++ /dev/null
@@ -1,206 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-
-"""Live demo: the rdsp pipeline engine, end to end, on your laptop.
-
- python demo.py
-
-Runs the real production path (PipelineConfig -> ExecutionPlan -> coordinator
--> Ray actors -> stage adapters) on CPU, with a plain-torch engine stub in the
-DeepSpeed slot (the one component that needs CUDA). Everything else is exactly
-what runs on GPUs.
-
-It trains a toy LM split across 2 Ray actor stages and checks, every step,
-that the pipeline reproduces the monolithic single-process model. Then it
-demonstrates the failure contracts. ~30 seconds.
-
-The same path with real DeepSpeed engines and Qwen3-0.6B, on 2 GPUs with
-DeepSpeed installed (from the repo root):
- pytest tests/integration/test_two_stage_baseline.py
-"""
-
-import logging
-import time
-
-import ray
-import torch
-import torch.nn as nn
-import torch.nn.functional as F
-
-import ray_deepspeed_pipeline as rdsp
-from ray_deepspeed_pipeline.compiler import lower
-from ray_deepspeed_pipeline.coordinator import PipelineCoordinator
-from ray_deepspeed_pipeline.engine import RayPipelineEngine
-from ray_deepspeed_pipeline.errors import StepFailed, UnsupportedEngineMethod
-from ray_deepspeed_pipeline.schedule import generate_commands, peak_in_flight
-from ray_deepspeed_pipeline.stage_group import create_stage_clients
-
-N_MB, ROWS, SEQ, VOCAB, LR, STEPS = 4, 2, 16, 50, 0.05, 5
-
-
-# --- a tiny transformer-shaped LM (embed -> blocks -> norm -> head) ----------
-
-
-class Block(nn.Module):
- def __init__(self):
- super().__init__()
- self.fc = nn.Linear(32, 32)
-
- def forward(self, x):
- return x + torch.tanh(self.fc(x))
-
-
-class ToyLM(nn.Module):
- def __init__(self, n_blocks=8):
- super().__init__()
- self.embed = nn.Embedding(VOCAB, 32)
- self.blocks = nn.ModuleList(Block() for _ in range(n_blocks))
- self.norm = nn.LayerNorm(32)
- self.head = nn.Linear(32, VOCAB, bias=False)
-
- def forward(self, ids):
- x = self.embed(ids)
- for b in self.blocks:
- x = b(x)
- return self.head(self.norm(x))
-
-
-# --- stand-in for the stage-local DeepSpeed engine (the CUDA-only component) -
-
-
-class StubEngine:
- def __init__(self, module, conf):
- self.module = module
- self.optimizer = torch.optim.AdamW(module.parameters(), lr=LR)
-
- def __call__(self, x):
- return self.module(x)
-
- def backward(self, loss):
- loss.backward()
-
- def step(self):
- self.optimizer.step()
- self.optimizer.zero_grad()
-
-
-def stub_engine_factory(module, conf):
- return StubEngine(module, conf)
-
-
-def loss_fn(outputs, labels):
- return F.cross_entropy(outputs.reshape(-1, VOCAB), labels.reshape(-1))
-
-
-def main():
- print(__doc__.split("\n")[0])
- print("=" * 72)
-
- torch.manual_seed(0)
- model = ToyLM()
- ids = torch.randint(0, VOCAB, (N_MB * ROWS, SEQ))
- labels = torch.randint(0, VOCAB, (N_MB * ROWS, SEQ))
-
- def mbs():
- return iter(
- [
- (ids[k * ROWS : (k + 1) * ROWS], labels[k * ROWS : (k + 1) * ROWS])
- for k in range(N_MB)
- ]
- )
-
- # 1. lower the public config to the one internal ExecutionPlan
- cfg = rdsp.PipelineConfig(
- stages=2, partition=rdsp.UniformTransformerBlocks(), microbatches=N_MB
- )
- plan = lower(model, cfg, {"train_batch_size": N_MB * ROWS})
- print(
- f"\n[plan] {len(plan.stages)} stages | {plan.global_microbatches} "
- f"microbatches | schedule {plan.schedule.kind} | hash {plan.plan_hash()[:12]}…"
- )
- for s in plan.stages:
- print(
- f" stage {s.index}: blocks [{s.block_start}:{s.block_stop}), "
- f"{len(s.parameter_names)} param tensors, {s.num_gpus} gpu(s)"
- )
-
- seqs = generate_commands(plan, 1, 0)
- for s, seq in seqs.items():
- trace = " ".join(
- f"{c.kind[0].upper()}{c.microbatch}" for c in seq if c.kind in ("forward", "backward")
- )
- print(f"[1f1b] stage {s}: {trace} (peak cached activations: {peak_in_flight(seq)})")
-
- # 2. real Ray actors, one per stage
- ray.init(
- num_cpus=3, include_dashboard=False, log_to_driver=False, logging_level=logging.WARNING
- )
- clients = create_stage_clients(
- model, plan, loss_fn, engine_factory=stub_engine_factory, use_gpu=False
- )
- engine = RayPipelineEngine(PipelineCoordinator(plan, clients))
- print(
- f"\n[actors] 2 stage actors up; loss_fn on terminal stage only: "
- f"{ray.get(clients[1].actors[0].has_loss_fn.remote())} / "
- f"{ray.get(clients[0].actors[0].has_loss_fn.remote())}"
- )
-
- # 3. train, checking parity against the monolithic model every step
- ref = ToyLM()
- ref.load_state_dict(model.state_dict())
- opt = torch.optim.AdamW(ref.parameters(), lr=LR)
-
- print("\n[check] same data, same starting weights, trained two ways:")
- print(" 'pipeline' = split across the 2 Ray actors above")
- print(" 'monolithic' = the unsplit model in this process (the reference)")
- print(" if the pipeline math is right, the columns must match")
- print(f"\n[train] {'step':>4} {'pipeline loss':>14} {'monolithic':>12} {'|diff|':>10}")
- t0 = time.time()
- for step in range(1, STEPS + 1):
- staged = float(engine.train_batch(data_iter=mbs()))
- graph_loss = loss_fn(ref(ids), labels)
- opt.zero_grad()
- graph_loss.backward()
- opt.step()
- ref_loss = graph_loss.detach()
- diff = abs(staged - float(ref_loss))
- print(f" {step:>4} {staged:>14.6f} {float(ref_loss):>12.6f} {diff:>10.2e}")
- assert diff < 1e-4, "pipeline diverged from the monolithic model!"
- print(
- f"[train] {STEPS} global steps in {time.time() - t0:.1f}s, "
- f"global_steps={engine.global_steps} — parity holds"
- )
-
- # 4. the contracts, demonstrated live
- ev = engine.eval_batch(data_iter=mbs())
- print(
- f"\n[eval] loss {float(ev):.6f} | global_steps still "
- f"{engine.global_steps} (no update, no step)"
- )
-
- # deliberately misuse the library and confirm it refuses cleanly
- try:
- engine.train_batch(data_iter=iter([next(mbs())])) # only 1 of 4 microbatches
- except StepFailed:
- print(
- f"[guard ok] fed 1 of the 4 required microbatches on purpose -> "
- f"clean error, no weights touched (global_steps still {engine.global_steps})"
- )
-
- try:
- engine.backward(None)
- except UnsupportedEngineMethod:
- print(
- "[guard ok] engine.backward() on purpose -> refused; "
- "train_batch() is the only training entry point"
- )
-
- ray.shutdown()
- print("\n" + "=" * 72)
- print("Everything above ran the production runtime; only the stage-local")
- print("engine was a torch stub. The same path with real DeepSpeed engines")
- print("and Qwen3-0.6B: see the GPU acceptance run in this file's docstring.")
-
-
-if __name__ == "__main__":
- main()
diff --git a/training/rdsp/docs/BENCHMARK_RESULTS.md b/training/rdsp/docs/BENCHMARK_RESULTS.md
index 771c69db6..657ca3453 100644
--- a/training/rdsp/docs/BENCHMARK_RESULTS.md
+++ b/training/rdsp/docs/BENCHMARK_RESULTS.md
@@ -1,108 +1,107 @@
# Benchmark results
-rdsp against MegatronMIMO and Megatron-Bridge, training Qwen3.5-2B and 4B on CORD-v2. The first set ran on one AWS g7.48xlarge: 8× RTX PRO 4500 Blackwell, 32 GB, PCIe, no NVLink. A 4B run on 8× H100 with NVLink follows. How to rerun: [GETTING_STARTED.md](GETTING_STARTED.md#reproducing-the-qwen35-2b-and-4b-results). `python bench/common/summarize.py ` prints the table rows from a run's logs. The Qwen3.5-9B, 27B and 35B-A3B results are in the [README](../README.md) and [GETTING_STARTED.md](GETTING_STARTED.md#reproducing-the-blogs-results).
+Qwen3.5 on CORD-v2, two AWS p5.48xlarge nodes (16 H100, NVLink inside a node, EFA between nodes). Step time is the median time per training step; lower is better. A row with several runs gives their average. Commands and settings: [bench/README.md](../bench/README.md).
-## Results: 8× RTX PRO 4500, PCIe
+## Qwen3.5-35B-A3B
-Median over steps 6–50 of one 50-step run, 64 rows of up to 2,048 tokens a step. Cost assumes $5.32/h for 8 GPUs, prorated to 5 for the MIMO layout.
+128 rows a step.
-| Model | Layout | Megatron | rdsp | Step time | Megatron tok/s | rdsp tok/s | Megatron tok/s per GPU | rdsp tok/s per GPU | Megatron $/M tok | rdsp $/M tok |
-|---|---|---|---|---|---|---|---|---|---|---|
-| 2B | Vision 1 GPU + language TP2×DP2, vs MIMO | 9.64 s | 8.30 s | −14% | 13,595 | 15,796 | 2,719 | 3,159 | 0.068 | 0.058 |
-| 2B | TP2×PP2×DP2, vs Bridge | 7.39 s | 5.30 s | −28% | 17,740 | 24,745 | 2,218 | 3,093 | 0.083 | 0.060 |
-| 4B | TP2×PP2×DP2, vs Bridge | 10.04 s | 8.69 s | −13% | 13,058 | 15,087 | 1,632 | 1,886 | 0.113 | 0.098 |
-| 4B | TP4×PP2×DP1, vs Bridge | 15.93 s | 13.29 s | −17% | 8,229 | 9,866 | 1,029 | 1,233 | 0.180 | 0.150 |
+| System | Layout | Recompute | Rows per GPU per microbatch | Runs | Step time | Tokens/s per GPU used |
+|---|---|---|---|---|---|---|
+| rdsp | vision encoder on a 4-GPU stage, then 6 stages of 2 GPUs; Liger's fused expert kernel | every language layer | 2 | 3 | 5.41 s | 3,029 |
+| rdsp, Hugging Face experts | the same | every language layer | 2 | 3 | 6.51 s | 2,517 |
+| Megatron-Bridge | TP1 × PP2 × EP8 from NVIDIA's H100 recipe, HybridEP communication | none | 1 | 1 | 7.93 s | 2,066 |
+| TorchTitan | FSDP over 16 GPUs + EP8 inside each node | none | 1 | 1 | 8.93 s | 1,834 |
-Loss: every pair starts from the same step-0 loss. Over steps 1–49, rdsp's mean difference from Megatron is +0.0005 (2B MIMO layout), +0.003 (4B TP2×PP2×DP2) and −0.0024 (4B TP4×PP2×DP1). Steps 4–5 vary by up to 0.08 between repeated runs of either system, from GPU kernels that aren't bit-for-bit deterministic.
+- rdsp is 1.47× Megatron-Bridge and 1.65× TorchTitan. With Hugging Face's own experts instead of Liger's kernel, it is 1.22× Megatron-Bridge.
+- Without HybridEP, Megatron-Bridge took 8.96 s.
+- MegatronMIMO cannot train this model: its MoE checkpoint conversion fails and its launcher has no expert parallelism.
-The 4B Megatron numbers come from a second machine of the same type.
+## Qwen3.5-27B
-## Results: 8× H100, NVLink
+128 rows a step.
-Qwen3.5-4B on one AWS p5.48xlarge: 8× H100 SXM 80 GB, every pair of GPUs linked by NVLink through NVSwitch (`nvidia-smi topo -m`: NV18). Same software, data, settings and recipes as above. Cost assumes $22.28/h for 8 GPUs (spot, us-east-2).
+| System | Layout | Recompute | Rows per GPU per microbatch | Runs | Step time | Tokens/s per GPU used |
+|---|---|---|---|---|---|---|
+| rdsp | vision encoder on a 2-GPU stage, then 7 stages of 2 GPUs | every language layer | 1 | 3 | 11.52 s | 1,423 |
+| rdsp, FP32 gradients and master | the same | every language layer | 1 | 1 | 11.42 s | 1,435 |
+| rdsp | PP8 × DP2, measured cut | every layer | 1 | 3 | 11.95 s | 1,371 |
+| TorchTitan | FSDP over each node's 8 GPUs, DP2 across the nodes | every layer | 1 | 1 | 13.36 s | 1,227 |
+| Megatron-Bridge | PP8 × DP2, at rdsp's measured cut | every layer | 2 | 1 | 13.39 s | 1,223 |
-| Layout | Megatron | rdsp | Step time | Megatron tok/s | rdsp tok/s | Megatron tok/s per GPU | rdsp tok/s per GPU | Megatron $/M tok | rdsp $/M tok |
-|---|---|---|---|---|---|---|---|---|---|
-| Vision 1 GPU + language TP2×DP2, vs MIMO | 7.99 s | 7.89 s | −1% | 16,413 | 16,606 | 3,283 | 3,321 | 0.236 | 0.233 |
-| TP2×PP2×DP2, vs Bridge | 8.79 s | 6.49 s | −26% | 14,917 | 20,208 | 1,865 | 2,526 | 0.415 | 0.306 |
-| TP4×PP2×DP1, vs Bridge | 18.24 s | 12.30 s | −33% | 7,184 | 10,658 | 898 | 1,332 | 0.861 | 0.581 |
-| Colocated vision + language TP2×PP2×DP2 (rdsp only) | — | 5.62 s | | | 23,322 | — | 2,915 | | 0.265 |
+- rdsp is 1.16× Megatron-Bridge and 1.16× TorchTitan.
+- Megatron-Bridge runs at rdsp's cut because its own even split ran out of memory. At one row per GPU it took 16.09 s.
+- The FP32 row ran on another pair of the same machines with newer code, so it is not a comparison. Without the 16-bit remainder the fullest stage peaked at 63.0 GiB of 79, against 52.4 GiB with it.
-Loss: every pair starts from the same step-0 loss; over steps 1–49 rdsp's mean difference from Megatron is +0.003, −0.003 and −0.008, and colocated's from Megatron-Bridge TP2×PP2×DP2 is −0.002.
+## Qwen3.5-9B
-Per GPU, MIMO's 5-GPU layout is the most efficient here (3,283 and 3,321 tokens/s per GPU); colocated is the fastest per step and the second most efficient per GPU (2,915).
+128 rows a step, no recompute. Every system trained on images prepared before step 1.
-**Read with care:**
-- **One round.** No repeats, so no spread.
-- **The host CPU limits launch-heavy runs.** This instance has an AMD EPYC 7R13. A torch-profiler step on rdsp's language GPUs in the MIMO layout shows the CPU busy for the whole step while GPU kernels run for only part of it: the layout is bound by kernel launches, not by the GPUs. That's why it ends in a near-tie. Megatron's TP4×PP2×DP1 (64 one-row microbatches per GPU, 26.7 TFLOP/s per GPU) is slower here than on the PCIe GPUs, most likely for the same reason. That's an inference, since its profiler trace was lost, and it inflates the −33%.
-- **rdsp's TP4 split is off on H100.** Stage 0 (vision encoder + 12 layers) is busy 12.1 s per step while stage 1 waits 3.2 s. The balanced estimate doesn't model how much less efficiently the encoder's small matrices run under TP4.
-- **Colocated ran without compiling the encoder.** The recipe's `compile_vision` doesn't apply to a colocated encoder (now rejected at start-up); `recipes/qwen35-4b-coloc-tp2pp2dp2.sh` compiles it, and is unmeasured.
-- **NVLink was used by both systems.** With `NCCL_DEBUG=INFO`, every NCCL connection on both sides is `P2P/CUMEM`, with no `SHM` or `NET` fallback.
-- **Defaults on both sides.** Megatron's TP communication overlap (`tp_comm_overlap`) is off in its stock recipe, as on PCIe; rdsp has no equivalent.
+| System | Layout | Rows per GPU per microbatch | Runs | Step time | Tokens/s per GPU used |
+|---|---|---|---|---|---|
+| rdsp | vision encoder on a 4-GPU stage, then 6 stages of 2 GPUs | 2 | 1 | 3.17 s | 5,171 |
+| Megatron-Bridge | DP16 | 1 | 1 | 3.23 s | 5,073 |
+| TorchTitan | FSDP over each node's 8 GPUs, DP2 across the nodes | 1 | 1 | 4.93 s | 3,325 |
-## rdsp settings per layout
+- rdsp is 1.02× Megatron-Bridge, a tie, and 1.56× TorchTitan.
+- Preparing images while training, its default, took Megatron-Bridge 3.28 s.
-Every run uses its recipe in `recipes/`, with `--prefetch --sharded-loss --drop-padding-mask --pad-per-microbatch` and `--cuts balanced` unless noted.
+## MegatronMIMO
-| Layout | Recipe | Extra settings | Cut chosen |
-|---|---|---|---|
-| Vision 1 GPU + TP2×DP2 | `qwen35-2b-vision1-tp2dp2.sh` | `--cuts 0` (vision-only stage), `--loss microbatch-mean`, 2 rows × 32 microbatches, stage 0 compiled | encoder alone |
-| TP2×PP2×DP2 (2B) | `qwen35-2b-tp2pp2dp2.sh` | `--untie-embeddings`, 2 rows × 32 microbatches, vision encoder compiled | 5 of 24 layers on stage 0 |
-| TP2×PP2×DP2 (4B) | `qwen35-4b-tp2pp2dp2.sh` | same | 13 of 32 |
-| TP4×PP2×DP1 (4B) | `qwen35-4b-tp4pp2dp1.sh` | `--untie-embeddings`, 1 row × 64 microbatches, vision encoder compiled | 12 of 32 |
-
-Megatron used its default even split (12 of 24, 16 of 32). It accepts uneven splits through flags; we didn't tune them.
-
-Settings held equal: sequence length 2,048, 64 rows a step, one row per GPU per microbatch; AdamW, learning rate 1e-5 constant, betas 0.9 / 0.95, eps 1e-8, no weight decay, clipping or warm-up; bf16 compute with fp32 gradients and optimizer state split over data parallel; no recompute. `bench/common/runs.sh` turns off Megatron's defaults that differ: clipping, warm-up, cosine decay, the multi-token-prediction head and the shuffling sampler.
-
-Differences that remain:
+128 rows a step, rdsp on MIMO's own layouts, one pair of machines. MIMO's launcher was patched to use BF16 gradients and the 16-bit-remainder master, as rdsp does. Both systems trained on images prepared before step 1, with each process pinned to its GPU's CPUs.
-- **Padding.** Megatron-Bridge pads every row to 2,048 whenever it pipelines (`dataset.pad_to_max_length`, forced when PP > 1). rdsp pads each microbatch to its longest row. So in the vs-Bridge rows Bridge computes about 2 positions per real token against rdsp's 1.1–1.2, and the two do not do equal work. MegatronMIMO's padding changes its step time little (9.60 s with dynamic padding against 9.64 s).
-- **Loss.** Megatron-Bridge trains on the token mean. MegatronMIMO trains on per-microbatch means and can't be changed, so the rdsp run against it does the same (`--loss microbatch-mean`).
-- **Embeddings.** In the pipeline layouts Megatron ties the input embedding and the output layer across stages; rdsp trains two copies (`--untie-embeddings`).
+| Model | Layout | GPUs | System | Runs | Step time | Tokens/s per GPU used |
+|---|---|---|---|---|---|---|
+| 9B | 8 vision GPUs + DP8 | 16 | rdsp | 3 | 3.55 s | 4,610 |
+| 9B | 8 vision GPUs + DP8 | 16 | MegatronMIMO | 2 | 3.71 s | 4,416 |
+| 27B | 1 vision GPU + TP4 × PP2, 2 rows a microbatch | 9 | rdsp | 3 | 14.12 s | 2,062 |
+| 27B | 1 vision GPU + TP4 × PP2, 2 rows a microbatch | 9 | MegatronMIMO | 2 | 14.90 s | 1,955 |
-## The balanced cut
+- rdsp's throughput is 1.04× MIMO's on the 9B and 1.05× on the 27B.
+- MIMO trains on the mean loss per microbatch, rdsp on the mean over the step's tokens. The first step's loss agrees within 0.03%.
+- Without pinning, MIMO took 3.79 s on the 9B and 15.07 s on the 27B.
+- MIMO's most efficient 9B layout, 2 vision GPUs + DP8 on 10 GPUs, took 4.52 s (5,803 tokens/s per GPU; one run, not pinned). rdsp's run on it is left out: three of its ten counted steps took 8–10 s, for an unknown reason.
-`--cuts balanced` estimates each stage's work before training ([ENGINEERING.md](ENGINEERING.md#balanced-cuts)). We checked it by timing every candidate cut for a few steps:
+## rdsp code versions
-| Layout | Even split | Balanced | Fastest measured |
-|---|---|---|---|
-| 2B TP2×PP2×DP2 | 12 | 5 (5.30 s) | 5 |
-| 4B TP2×PP2×DP2 | 16 (out of memory) | 13 (8.69 s) | 13 |
-| 4B TP4×PP2×DP1 | 16 (14.54 s) | 12 (13.29 s) | 11 (13.15 s) |
+The tables were not all rerun with the latest code.
-Under TP4 the estimate misses by one layer (about 1%): the encoder's small matrices lose efficiency when split four ways, and the estimate doesn't model that.
+| Rows | rdsp code |
+|---|---|
+| 35B-A3B; 27B except the FP32 row | before the step's data was sent to the stages as arrays (`wire.py`) |
+| 27B FP32 row; 9B | with the data sent as arrays |
+| MegatronMIMO | later code, with the speed-ups listed under environment variables in GETTING_STARTED |
-## What moved the numbers
+## TorchTitan with more rows per GPU
-rdsp started 40% slower than MegatronMIMO in MIMO's own layout. 2B step time after each change:
+TorchTitan ran faster with several rows per GPU per microbatch, but its first-step loss then came out lower than at one row, and lower than every other system's. The cause is unknown, so the tables use its one-row runs.
-| Change | Step time |
-|---|---|
-| Start: encoder shares the first stage, with recompute | 13.51 s |
-| Vision-only first stage: frees enough memory to drop recompute | 11.3 s |
-| Prefetch: the next step's data (about 576 MB of images) ships while this step runs; dispatch fell from 1.1 s to 1 ms | 10.3 s (12-step run) |
-| `torch.compile` on the vision encoder: its forward and backward fell from 7.8 s to 6.7 s per step | 9.62 s |
-| Split-vocabulary loss: TP ranks keep their slice of the 248k-wide logits instead of gathering 2 GB per microbatch | 9.25 s |
-| No padding mask: rows pad only on the right, so causal attention ignores the padding anyway, and SDPA picks its flash kernel | 9.05 s |
-| bf16 gradients freed after fp32 accumulation (2 bytes per parameter less, as in Megatron), and padding per microbatch (1.71 → 1.20 padded tokens per real token) | 8.30 s |
+| Model | Rows per GPU | Step time | First-step loss against one row |
+|---|---|---|---|
+| 35B-A3B | 8 | 3.95 s | 23% lower |
+| 27B | 4 | 7.33 s | 10% lower |
+| 9B | 2 | 2.79 s | 0.7% lower |
-Same chain for 4B TP2×PP2×DP2: 13.51 s → 11.57 s → 10.58 s → 8.71 s → 8.69 s. The freed gradients removed the out-of-memory errors that had forced recompute, and the balanced cut did the rest.
+## Qwen3.5-35B-A3B, 50-step runs
-## Not included
+The runs behind the blog's Figure 2: one run each, Hugging Face's experts, 128 rows a step. Both rdsp runs chose their own cuts by timing.
-- **4B in MIMO's layout.** Neither system fits it in 32 GB without recompute.
-- **2B TP4.** Qwen3.5-2B has 2 key/value heads, which can't be split 4 ways.
-- **9B and up.** These need 80 GB-class GPUs in these layouts.
-- **Colocated vision.** rdsp only; neither Megatron system supports it for Qwen3.5. 4B ran at 9.66 s, slower than TP2×PP2×DP2; 2B didn't fit.
-- **Repeats.** One 50-step run per configuration.
+| System | Layout | Recompute | Step time | Tokens/s per GPU |
+|---|---|---|---|---|
+| rdsp | vision encoder on a 4-GPU stage, then 6 stages of 2 GPUs; 32 microbatches of 4 rows | every layer | 6.38 s | 2,567 |
+| Megatron-Bridge | TP1 × PP2 × EP8 from NVIDIA's H100 recipe; 16 microbatches of 8 rows | none | 8.67 s | 1,890 |
+| rdsp | PP8 × DP2; 64 microbatches of 2 rows | vision encoder only | 9.60 s | 1,707 |
-## Validation provenance
+## Validated layouts
-The supported layouts in `src/ray_deepspeed_pipeline/support_matrix.py` passed on 2 to 8 L4 GPUs (real DeepSpeed and NCCL, fp32 tiny models, SGD with momentum), with:
-- loss parity against the unsplit model within 1e-4;
-- per-parameter update parity within 2.4e-5 (3e-4 with AutoEP folding);
-- checkpoint round trip;
-- rank-kill recovery.
+Each layout matches the unsplit model on GPUs, with real DeepSpeed and NCCL (`tests/integration/`): loss within 1e-4 (2e-2 for the bf16 baseline), plus checkpoint resume and recovery from a killed GPU process.
-The two-stage baseline uses Qwen3-0.6B in bf16. The three vision placements match the unsplit model on 4× L40S (`tests/integration/test_vl_layouts_gpu.py`, tiny Qwen3.5-VL, fp32). Evidence per row is in `src/ray_deepspeed_pipeline/support_matrix.py`.
+| Layout | Stages | Model |
+|---|---|---|
+| Two-stage baseline | 1 GPU, 1 GPU | Qwen3-0.6B, bf16 |
+| Different data parallelism and ZeRO stage per stage | DP4 with ZeRO-2, DP2 with ZeRO-1, DP2 with ZeRO-0 | tiny model, fp32 |
+| Tensor parallelism inside a stage | 1 GPU, TP2, TP2 × DP2 | tiny Qwen3, fp32 |
+| Expert parallelism inside a stage, also on the TP GPUs | 1 GPU, EP4, EP2 on TP2 | tiny Qwen3-MoE, fp32 |
+| Sequence parallelism inside a stage | SP2, SP2 × DP2, 1 GPU | tiny Qwen3, fp32 |
+| All four combined on one 8-GPU node | SP2, TP2, EP2 on TP2, TP2 | tiny Qwen3-MoE, fp32 |
+| Vision encoder on the first stage, its own stage, or every GPU | 4 GPUs | tiny Qwen3.5-VL, fp32 |
diff --git a/training/rdsp/docs/ENGINEERING.md b/training/rdsp/docs/ENGINEERING.md
index ccd1bb59a..d2f65bf2e 100644
--- a/training/rdsp/docs/ENGINEERING.md
+++ b/training/rdsp/docs/ENGINEERING.md
@@ -1,209 +1,68 @@
# How rdsp works
-rdsp splits a model's stack of blocks into contiguous stages, places each stage on its own group of GPUs, and trains the result so it computes what the unsplit model would. Each GPU runs a Ray actor holding a stock DeepSpeed engine for its stage's slice. Activations go forward and gradients go back over NCCL.
+rdsp cuts a model's stack of blocks into contiguous stages and puts each stage on its own group of GPUs. Every GPU is a Ray actor running a stock DeepSpeed engine for its stage. Activations go forward and gradients go back over NCCL, directly between neighbouring stages. The driver (your process) holds no weights; it plans and schedules.
-Why split by depth: only activations cross a cut, once per microbatch, so it is the cheapest split across slow links. And stages do unequal work (a vision encoder, an output head over a 248k vocabulary), so each stage gets its own GPU count and layout.
+## A training step
-## Design rules
+1. `rdsp.initialize()` turns `PipelineConfig` into a fixed plan: the cuts, each stage's GPUs and DeepSpeed config, and a hash that checkpoints are bound to. Every check runs here, before any actor starts.
+2. `train_batch()` reads exactly one step's microbatches and sends each GPU one Ray call holding its stage's 1F1B schedule.
+3. Each stage runs forwards and backwards in that order, exchanging boundary tensors with its neighbours.
+4. When every stage has finished its backwards, the driver tells all stages to apply their optimizer step.
-**Stock DeepSpeed and Ray.** DeepSpeed is pinned to one commit and installed unmodified; every stage calls `deepspeed.initialize()`. rdsp crosses into DeepSpeed internals in exactly three places, all in `deepspeed_adapter.py`:
+Backward crosses a stage boundary as `engine.backward((out * grad).sum())`, which gives the stage exactly the incoming gradient through DeepSpeed's public backward.
-- `_free_bf16_grads_after_accumulating` wraps one bf16 optimizer method on the instance to free each bf16 gradient once it's folded into fp32 (see Memory). It also does the fold itself, straight from bf16 into the fp32 buffer: one operation where DeepSpeed converts and then adds, with the same result.
-- `_master_in_model_weights` (the remainder master) points each ZeRO partition's master weights at the model's own bf16 partition, so no separate master copy is kept.
-- `reset()` clears two private ZeRO running sums that `zero_grad()` leaves behind, so a retried step doesn't add onto an abandoned one.
+## Stage layouts
-All three depend on the pinned commit (unit tests in `tests/unit/test_deepspeed_adapter_grads.py` and `tests/unit/test_remainder_master_engine.py`, the abandoned-step GPU test); a DeepSpeed upgrade has to re-run the GPU suite.
+Each stage picks its own GPU count and layout, all ordinary DeepSpeed features:
-**The driver never touches tensors.** The driver, meaning the user's process, holds no weights and never receives an activation or gradient. Autograd graphs can't leave their process, so whichever GPU ran a forward runs its backward, the loss is computed on the last stage (labels travel there), and only losses and statuses return to the driver.
-
-**The API doesn't pretend.**
-- `rdsp.initialize()` mirrors `deepspeed.initialize()`, but returns `None` for the optimizer: the real optimizers live in the actors, and a look-alike object whose changes do nothing would be worse.
-- `engine.forward/backward/step` raise and point at `train_batch()`: one step interleaves hundreds of operations across stages, so there's no single "the forward" for them to mean.
-
-## Planning
-
-`rdsp.initialize()` lowers `PipelineConfig` into an immutable plan (`compiler.lower`):
-
-- the cuts;
-- each stage's grid, `gpus = dp × sp × tp`;
-- each stage's DeepSpeed config;
-- the conversion on every edge between stages;
-- a hash that binds checkpoints.
-
-Every check runs here, before any actor starts (the cluster's GPU count just after, still before any actor). TP must divide the key/value heads, rows must divide every stage's DP degree, parameters can't be tied across stages, and so on. Settings that change how a step runs but not what a stage saves (`prefetch`, `recompute`, `compile`, `compile_vision`, `encode_per_microbatch`) are left out of the hash, so toggling them keeps checkpoints loadable.
-
-The splitter finds the model's longest `ModuleList` of same-class blocks; a vision encoder's blocks are never cut. Everything before the blocks goes to the first stage, everything after them to the last.
-
-With `weights=`, the driver model is built empty and each stage reads only its own tensors from the safetensors files.
-
-## One training step
-
-1. The driver takes exactly M `(inputs, labels)` entries. Too few raises `StepFailed` with nothing dispatched; extra entries stay in the iterator.
-2. Each GPU gets one Ray call: its stage's whole 1F1B op list for the step. Stage *s* of *N* runs `min(N−1−s, M)` warm-up forwards, then alternates.
-3. Forward: receive from the overlapping upstream ranks, assemble, `x.detach().requires_grad_()`, run the engine, send downstream asynchronously.
-4. Backward: receive the gradient `g` for this stage's output, then call `engine.backward((out * g).sum())`. Differentiating that scalar reproduces `g` exactly, and it is the only form DeepSpeed's backward accepts. Send `x.grad` upstream. The last stage backpropagates its loss.
-5. Only the M-th backward is a DeepSpeed accumulation boundary. Intra-stage gradient reduction happens once per step.
-6. Each rank reports *ready*. Only when every rank of every stage is ready does the driver send *apply*, and each engine steps exactly once.
-
-Two NCCL groups span all ranks of all stages: `fwd` for activations and `bwd` for gradients. They sit next to each stage's own DeepSpeed world.
-
-An earlier design dispatched every forward and backward from the driver as a separate Ray call. At about 5 ms of Ray overhead per call, that overhead set the pace. The current path is checked against losses recorded from the old one (`test_losses_match_recorded_reference`).
-
-**Failures.**
-- A failure before any apply raises `StepFailed`. Weights are unchanged, links are rebuilt, and on retry each rank discards leftovers (`reset()`) and rewinds its RNG, so the retry equals a clean step.
-- A failure during apply means some stages updated and others didn't. The engine raises `PipelinePoisoned` and refuses every call until `load_checkpoint()`.
-
-## Stages with different layouts
-
-A stage can use several GPUs in four ways, each an ordinary DeepSpeed feature running inside that stage alone:
-
-| | Each GPU gets |
+| | Each GPU of the stage gets |
|---|---|
| DP (any ZeRO stage) | different rows |
-| TP (AutoTP) | the same rows, a slice of every weight matrix |
-| SP (Ulysses) | the same rows, a different stretch of the sequence (not for models with linear-attention layers, such as Qwen3.5) |
-| EP (AutoEP), optionally folded onto TP | different rows, some of the experts |
-
-**Boundaries.** A rank's cell is its block of rows (`rows / dp`) and of sequence (`seq / sp`); TP ranks share a cell. Each receiving rank asks for exactly the upstream pieces that overlap its cell and stitches them together. Only TP rank 0 of a cell sends, and nothing is gathered in one place. Gradients take the same routes in reverse, scaled by `dp_s / dp_(s+1)`: DeepSpeed averages over DP and sums over SP, so without the factor a stage learns at the wrong rate.
-
-**Shapes.** Each message carries a small header with dtype and shape. Normally a header is sent once per step per peer. When a step's microbatches differ in length (per-microbatch padding), every message carries its own.
-
-## Running Hugging Face models without per-model code
-
-`HFModelStage` runs the model's own `forward` on every stage:
-
-- Blocks outside the stage return their input.
-- Modules whose weights the stage doesn't own return their input, or zeros for an embedding.
-- A pre-hook on each block injects what arrived from upstream.
-- The stage's output is whatever the loop hands the next block. Work between blocks counts; work after the last block (norm, head) belongs to the last stage.
-
-The boundary carries the hidden state plus the tensors the model passes to each block: rotary tables, position ids, masks. For Qwen3-VL-32B that's about 5% over the hidden state.
-
-TP uses the model's AutoTP plan. For configs without one, rdsp generates a plan for the standard `q/k/v/o_proj` and `gate/up/down_proj` names, the vision blocks' `attn.qkv`/`attn.proj`/`mlp.linear_fc1/fc2`, and Qwen3.5's linear-attention projections.
-
-Two pieces sit outside AutoTP and split the way Megatron does:
-- **Vocabulary** (`vocab_parallel.py`): each TP rank keeps 1/tp of the embedding's and the output head's rows.
-- **Qwen3.5 linear attention** (`linear_attention_parallel.py`): each TP rank keeps 1/tp of the key heads and of the value heads that read them, with their projections, conv filter, `A_log` and `dt_bias`. The heads' recurrences are independent, so the only communication is a sum of `out_proj`'s output, a sum of the input gradient, and a sum of the shared gated norm's weight gradient. AutoTP's own rule for these projections (`colwise_gather_output`) would split the projections but leave every rank holding every head's conv filter and running every head's recurrence. A layer whose heads don't divide by TP stays whole.
-
-## Vision encoder placement
-
-| Placement | How | Encoder runs on |
-|---|---|---|
-| First stage | default | the first stage's GPUs, in its layout |
-| Vision-only stage | first cut at 0 (`--cuts 0`) | its own stage, with its own GPU count and layout |
-| Colocated | `PipelineConfig(colocated_vision=rdsp.ColocatedVision())` | every GPU, data parallel |
-
-**Vision-only stage.** This stage holds the encoder and nothing else. It sends image embeddings and rotary tables, and the next stage embeds the text itself. This is MegatronMIMO's layout. It freed enough memory to drop recompute and took the 2B MIMO-layout step from 13.51 s to 11.3 s.
-
-**Colocated** (`vision.py`).
-1. Each rank encodes its share of the step's images and sends each image's features to the first-stage ranks whose rows hold it.
-2. The language pipeline runs its normal 1F1B.
-3. The first stage returns each image's feature gradient to the rank that encoded it, and the encoder's gradients are reduced over all ranks.
-
-The encoder trains with a torch optimizer built from the DeepSpeed config, with fp32 master weights and optimizer state split over all ranks.
-
-- `encode_per_microbatch` encodes just ahead of the pipeline's need instead of all at the start, keeping graphs for about 2 × stages microbatches instead of the whole step.
-- Colocation only works for encoders whose output enters through the input embeddings (Qwen3.5). Qwen3-VL's deepstack feeds its first blocks, so it keeps the encoder on the first stage.
-- It matches the unsplit model, but on 32 GB GPUs it's slower than the first-stage placement (4B: 9.66 s vs 8.69 s).
-
-## Balanced cuts
-
-`BalancedTransformerBlocks` picks the contiguous split that minimises the most expensive stage, each stage's cost divided by its GPU count. Ties go to the lowest sum of squared stage costs, so no stage idles.
-
-- A decoder block costs its parameter count.
-- The output head, on the last stage, costs the same way.
-- Embeddings are lookups and cost nothing.
-- The vision encoder costs its parameter count times `vision_token_ratio`, measured from the first batch by `partition.vision_token_ratio`:
-
-```
-ratio = Σ_images patches × (1 + 2 × patches × width / layer_params) / text tokens computed
-```
-
-The second term in the sum is the encoder's attention over each image: about 4 × patches × width multiply-adds per patch, against 2 × layer_params for its matrix products. The denominator counts text tokens at each microbatch's padded length, not the configured maximum.
-
-The estimate takes milliseconds and runs no trial steps. It picks the fastest measured cut in both TP2×PP2×DP2 layouts and is one layer off under TP4 ([BENCHMARK_RESULTS.md](BENCHMARK_RESULTS.md)). It ignores communication and counts MoE experts in full. `ExplicitCuts` overrides it.
-
-**Measured cuts.** `engine.measure_stages()` runs a few calibration steps with every stage timed and records each stage's busy time and peak memory. `BalancedTransformerBlocks(measured=...)` then re-cuts so the slowest stage is as fast as possible, keeping each stage within its GPU's memory. `train_vl.py --cuts measured` does both, at learning rate 0, before training starts. The 27B and 35B-A3B benchmark runs use it.
-
-## Memory
-
-- **2 + 4 + 12/dp bytes per parameter** of training state under bf16 + ZeRO-1 + fp32 accumulation: bf16 weights, fp32 accumulator, then fp32 master and Adam's two moments split over DP (12 bytes at DP=2). rdsp sets `bf16.immediate_grad_update` so each bf16 gradient is added into fp32 as soon as autograd produces it, then frees the bf16 copy; DeepSpeed alone only zeroes it, keeping 2 more bytes per parameter. Megatron spends the same. On 4B this removed the out-of-memory errors that had forced recompute.
-- **Per-microbatch padding.** With `--pad-per-microbatch`, each microbatch is padded to its own longest row, like Megatron's collator, instead of the whole step being padded to its longest row. On CORD-v2 this cut padded tokens from 1.71 to 1.20 per real token.
-- **Recompute** (`recompute=1` per stage, or `ColocatedVision(recompute=True)`) keeps only each block's input and recomputes the rest in backward.
-
-## Data prefetch
-
-With `PipelineConfig(prefetch=True)`, the driver reads the next step's M entries while the current step runs and ships them to the stages ahead of time. For 2B on CORD-v2 that's about 576 MB of images per step, and handing a step to the GPUs fell from 1.1 s to 1 ms.
-
-- The caller passes the same iterator to every `train_batch()`.
-- `initialize(training_data=...)` rejects prefetch, since rdsp would own the iterator.
-- `load_checkpoint()` drops the step that was read ahead.
-
-## Loss
-
-- **Default.** `loss_fn(outputs, labels)` returns one rank's loss for one microbatch, and the step loss is the mean over microbatches and DP ranks.
-- **Token mean.** `TokenMeanLoss(sum_fn, count_fn)` averages over every counted token of the step instead, like Megatron's `calculate_per_token_loss`. The driver counts the step's tokens from the labels before dispatch, so each backward already carries its final weight. `per_microbatch=True` trains on per-microbatch means (MegatronMIMO's only mode) and still reports the token mean.
-- **Split-vocabulary loss.** `next_token_loss_sum` declares `takes_vocab_shards`. On a TP last stage, each rank then keeps its slice of the logits, and the ranks exchange the max, the sum of exponentials and the target logit per token, instead of gathering the full 248k-wide logits (2 GB per microbatch for Qwen3.5). Megatron does the same.
+| TP (DeepSpeed AutoTP) | a slice of every weight matrix |
+| SP (Ulysses) | a stretch of the sequence |
+| EP (DeepSpeed AutoEP) | some of the experts |
-## Checkpoints
+When neighbouring stages have different layouts, each receiving GPU takes only the pieces of the upstream output that it needs. Nothing is gathered in one place.
-Each stage saves with DeepSpeed's own `save_checkpoint`, plus each rank's RNG state. The driver then writes `manifest.json` last and atomically. It holds the plan hash, the step, the data position, and the SHA-256 of every file. A directory without a manifest is an unfinished save and is never loaded.
+## Hugging Face models
-`load_checkpoint()` works in four steps:
-1. Verify the manifest and plan hash.
-2. Rebuild every actor if any died, preferring the same nodes so local files are still there.
-3. Have each stage verify its own files on its node.
-4. Only when every stage passes, load.
+`HFModelStage` runs the model's own `forward` on every stage. Blocks the stage doesn't own pass their input through, and a hook feeds in what arrived from upstream. So any Hugging Face model with a stack of blocks works without per-model code. Each stage loads only its own tensors from the checkpoint.
-A test trains, saves and keeps training, then loads into a pipeline built from different random weights; its losses match bit for bit.
+The vision encoder can sit on the first stage (default), on a stage of its own (first cut at 0), or on every GPU (`ColocatedVision`).
-## How we know it works
+## Choosing the cuts
-One yardstick at every level: the split model must produce the unsplit model's numbers.
+- `BalancedTransformerBlocks` estimates each block's cost from its parameter count and splits so the slowest stage is as fast as possible.
+- `measured=` re-cuts from timed calibration steps and keeps each stage within its GPU memory. `train_vl.py --cuts measured` does both.
+- `ExplicitCuts` sets the cuts by hand.
-- **CPU suite** (about 630 tests). The full runtime runs on Ray with a stub engine:
- - schedules and boundary routing;
- - exact data consumption;
- - the failure contract;
- - checkpoint round trips;
- - 25 HF families trained through `rdsp.initialize()` against the unsplit model;
- - the import-time guarantee that `import ray_deepspeed_pipeline` pulls in neither Ray nor DeepSpeed.
-- **GPU suite.** Every supported layout in `src/ray_deepspeed_pipeline/support_matrix.py` with real DeepSpeed and NCCL, on fp32 tiny models. Each run checks:
- - loss parity within 1e-4;
- - per-parameter update parity;
- - checkpoint resume;
- - a killed rank recovering through `load_checkpoint()`.
+## Failures and checkpoints
-**Why SGD, not Adam, in parity tests.** The first parity test used Adam, which normalizes away a uniformly wrong gradient scale: a stage receiving half its true gradient still trained identically, and a deliberately broken build passed. The tests now use SGD with momentum, and refuse to run unless each step moves the loss by at least 20× the tolerance. That stricter test found four real bugs, all fixed:
+- A failure before any optimizer step raises `StepFailed`. Weights are unchanged, and calling `train_batch()` again with the same iterator repeats the step exactly.
+- A failure during the optimizer step raises `PipelinePoisoned` until `load_checkpoint()`.
+- Each stage saves with DeepSpeed's `save_checkpoint`. The driver writes `manifest.json` last, with every file's hash; a checkpoint without it is never loaded. `load_checkpoint()` restarts dead actors before loading.
-- Under ZeRO-1/2, DeepSpeed replaced instead of accumulating each microbatch's sharded gradient.
-- Qwen3's per-head q/k norms drifted across TP ranks.
-- The SP gradient scale was applied inverted.
-- AutoEP folding sent upstream one rank's partial gradient instead of the average.
+## Where rdsp changes DeepSpeed's behaviour
-## Honest edges
+DeepSpeed is installed unmodified. rdsp patches these parts at run time, all tied to the tested DeepSpeed version:
-- **SP.**
- - Never on the last stage: its labels would straddle ranks.
- - Never on the first stage of a vision model: image positions need the whole sequence.
-- **TP and SP** can't share a stage (a DeepSpeed limitation).
-- **Placement.** One stage fits on one node, unless it needs more GPUs than a node has: then it spans nodes with each tensor-parallel group inside one node, and its checkpoints need storage those nodes share.
-- **Checkpoints.** Node-local: they survive actor loss, not node loss.
-- **No global gradient clipping.** DeepSpeed would clip each stage by its own norm, a different algorithm, so a nonzero `gradient_clipping` is rejected.
-- **Scale.** Two nodes (16 GPUs) is the most it has run on. The 32-GPU four-stage composed layout has run only in its one-node form.
+- `deepspeed_adapter.py`: frees bf16 gradients once they are in the fp32 buffer; points the remainder master weights at the model's bf16 weights; clears two ZeRO running sums on a retried step; skips an unused gradient copy and an unused gradient norm.
+- `fused_grad_accumulation.py`, `tp_input_grads.py`: re-implement AutoTP's linear layers so a matmul adds its weight gradient in place and sibling layers share one all-reduce.
-## Profiling
+## Limitations
-- `RDSP_PROFILE=1` (or `train_vl.py --profile`) prints, per rank and step, the time in forward, backward, waiting on neighbours and the optimizer step. It synchronizes the GPU per reading, so steps run slower.
-- `RDSP_TORCH_PROFILE=` (0-based) writes a torch profiler kernel table for that step to `/tmp/rdsp_torch_profile_stage_rank.txt`.
+- Run on up to two nodes (16 GPUs).
+- 1F1B only; no interleaved stages.
+- No gradient clipping: DeepSpeed would clip each stage by its own norm.
+- No weights shared across stages; untie them first.
+- No SP on the last stage, on the first stage of a vision model, or together with TP.
+- Checkpoints live on each node's disk. A stage spanning nodes needs shared storage.
+- The balanced cut ignores communication and counts all MoE experts, not the active ones.
-## Running the tests
+## Tests
```bash
-python demo.py # CPU, ~30 s: pipeline vs unsplit losses side by side
-pytest -q # CPU suite; GPU tests skip
-pytest -q tests/integration/test_two_stage_baseline.py tests/integration/test_checkpoint_gpu.py # 2 GPUs
-pytest -q tests/integration/test_heterogeneous_pipeline.py # up to 8 GPUs
+pytest -q
```
-The GPU tests need DeepSpeed installed (`bench/setup_node.sh`).
+The CPU suite runs the whole runtime on Ray with a stub engine and checks that a split model matches the unsplit one. On a GPU node the same command also runs the GPU tests: loss and update parity, checkpoint resume and recovery from a killed rank.
diff --git a/training/rdsp/docs/GETTING_STARTED.md b/training/rdsp/docs/GETTING_STARTED.md
index b74cb170f..76bc318e3 100644
--- a/training/rdsp/docs/GETTING_STARTED.md
+++ b/training/rdsp/docs/GETTING_STARTED.md
@@ -1,212 +1,99 @@
# Getting started
-Install rdsp, train with a recipe, and rerun the published benchmarks.
-
## Install
-Linux, CUDA GPUs, Python 3.12. On a fresh node:
+Linux with CUDA GPUs and Python 3.12. On every node:
```bash
-bash bench/setup_node.sh
+bash install.sh && source .venv/bin/activate
```
-It builds `~/venv` with torch 2.13.0, Transformers 5.17.0, Ray 2.59.0, DeepSpeed at commit 53a2ac4 (every result was measured with it), rdsp and the Qwen3.5 kernels, and pulls the NeMo container the Megatron comparisons run in. To install by hand, run its `uv pip install` lines in your own environment.
-
-## Run a recipe
-
-Terms: a *stage* is a contiguous slice of the model on its own GPUs, and a *cut* is the layer where one stage ends. PP is the number of stages; TP splits each layer's matrices across GPUs; DP gives copies of a stage different rows, with ZeRO splitting their optimizer state; EP splits a mixture-of-experts layer's experts. A *microbatch* is the rows a stage processes at a time. TP2×PP2×DP2 is 2 stages of 4 GPUs, each TP2 × DP2.
+It installs rdsp with DeepSpeed (`gpu`) and what the training scripts use (`train`: Accelerate, Datasets, Liger-Kernel, the Qwen3.5 linear-attention kernels) into `.venv`. By hand: `pip install -e ".[gpu,train]"`. On macOS the Liger and linear-attention kernels are left out (they need Linux).
-Each script in `recipes/` is one layout with a published result, plus a text-only starting point. The first 2–5 steps compile and are slower.
-
-| Recipe | Layout | GPUs |
-|---|---|---|
-| `qwen35-2b-vision1-tp2dp2.sh` | vision encoder on 1 GPU + language TP2×DP2 | 5 |
-| `qwen35-2b-tp2pp2dp2.sh` | 2 stages, each TP2×DP2 | 8 |
-| `qwen35-4b-tp2pp2dp2.sh` | 2 stages, each TP2×DP2 | 8 |
-| `qwen35-4b-tp4pp2dp1.sh` | 2 stages, each TP4 | 8 |
-| `qwen35-4b-vision1-tp2dp2.sh` | vision encoder on 1 GPU + language TP2×DP2 | 5, 80 GB each |
-| `qwen35-4b-coloc-tp2pp2dp2.sh` | vision encoder on every GPU + 2 stages of TP2×DP2 | 8, 80 GB each |
-| `qwen3-text-pp.sh` | Qwen3-0.6B: stage 0 DP2 (ZeRO-2), stage 1 TP2 | 4 |
+## Train with the rdsp command
```bash
-./recipes/qwen35-2b-tp2pp2dp2.sh
-./recipes/qwen35-2b-tp2pp2dp2.sh --steps 200 --lr 2e-5 # extra flags override the recipe
+rdsp setup # first node: starts a Ray cluster, prints the join command
+rdsp setup --join # every other node: the command the first node printed
+rdsp nodes # every node and GPU in the cluster
+rdsp train Qwen/Qwen3.5-9B # train on every GPU
```
-## Change the model, data or layout
-
-**Model.** `--model` takes a Hugging Face id: `train_vl.py` for vision-language models, `train.py` for text models. Each stage loads only its own weights.
+When Ray's token authentication is on, the join command the first node prints carries `--token`: Ray refuses a node without it. Keep the token among your nodes.
-**Data.** `train_vl.py --dataset` takes `cord-v2` (images scaled to at most `--max-pixels`), `exported:DIR` (rows exported from Megatron-Bridge's loader by `bench/common/runs.sh export`, as the benchmarks use) or `synthetic`. With `--pad-multiple N --pad-per-microbatch`, as in the recipes, each microbatch is padded to its longest row instead of `--seq`. For your own data, pass `engine.train_batch` an iterator of `(inputs, labels)` entries, as `train_vl.py` does: inputs are a tensor or a dict of tensors (vision models add `pixel_values` and `image_grid_thw`), and each call reads exactly one step's microbatches.
+`rdsp train MODEL` prints the layout and the command it runs, and asks before running (`-y` skips the question). Run without a model on a terminal, it asks for one. Without a cluster it uses this machine's GPUs, and without GPUs it offers the CPU.
-**Layout.** Validated layouts are listed in `src/ray_deepspeed_pipeline/support_matrix.py`.
+How it decides the parallelism you don't set:
+- `-tp` (GPUs splitting each layer) is 1.
+- `-pp` (pipeline stages) is the fewest whose share of the model fits in half a GPU's memory, each stage inside one node. The memory estimate is bf16 weights, fp32 gradients, and fp32 master weights and Adam state split over a stage's copies.
+- `-dp` (copies of each stage) takes the remaining GPUs. Each copy gets one row per microbatch, and each stage at least two microbatches.
+- Blocks recompute in backward when the training state leaves little room for activations.
+- The cuts between stages balance the stages' parameter counts. With `--tune`, rdsp first times every stage for a few steps at learning rate 0 and re-cuts by the times within each GPU's memory. A vision-language model's vision encoder then also gets a stage of its own, with as many GPUs as the timing calls for.
-- `--stages N --stage S:gpus=G,tp=T,zero=Z`: N stages; stage S's GPU count, tensor parallelism and ZeRO stage, with data parallelism G / T. Other keys: `sp`, `ep`, `fold`, `recompute=1`, `recompute_blocks=N` (only the stage's first N decoder layers, plus its vision encoder), `offload=1`, `compile=1`, `compile_vision=1`.
-- `--cuts balanced` (default) estimates the cuts from the model and the first batch. `--cuts measured` then times every stage for `--calibration-steps` steps at learning rate 0 and re-cuts within each GPU's memory. `--cuts even` splits evenly; `--cuts 5,18` sets the cuts by hand.
-- A first cut of `0` (`--cuts 0`, `0,balanced` or `0,measured`) gives the vision encoder a stage of its own. `--colocated-vision` runs it on every GPU instead.
-- `--master-dtype remainder` (with `--grad-dtype bf16`, ZeRO 1 or 2) stores the exact fp32 master weights as the bf16 weights plus a 16-bit remainder: 2 bytes per parameter instead of 4.
+On the CPU (`--cpu`), each device is a worker process (2 by default, `--devices` for more). The processes share the machine's memory, so each gets half of it divided by their number, and its cores, so each runs on the cores divided by their number. Stages take no tensor parallelism there, and the command says `procs=` where a GPU run says `gpus=`.
-**Out of memory.** Cheapest fix first: `--master-dtype remainder --grad-dtype bf16`; a lower first cut, such as `--cuts 4`, since stage 0 holds the vision encoder and the most microbatches in flight; more data parallelism; `recompute=1` on the full stage (about 30% more compute there), or `recompute_blocks=N`.
-
-## Environment variables
-
-| Variable | Effect |
+| Flag | Meaning |
|---|---|
-| `RDSP_PLACEMENT_TIMEOUT_S` (600) | How long a stage waits for its GPUs |
-| `RDSP_P2P_TIMEOUT_S` (300) | How long a stage waits on a neighbour's send or receive before the step fails |
-| `RDSP_ALIVE_TIMEOUT_S` (60) | How long `load_checkpoint()` waits for each stage actor; a silent one is rebuilt |
-| `RDSP_PROFILE=1` | Per rank and step: forward, backward, waiting and optimizer time (as `train_vl.py --profile`; slows steps) |
-| `RDSP_TORCH_PROFILE=` | A torch profiler kernel table for that step in `/tmp/rdsp_torch_profile_stage_rank.txt` |
-
-**Several nodes.** Start Ray on each node with NCCL's network settings in that shell (on AWS with EFA, `bench/cluster/ray_cluster.sh`), then run `train_vl.py` on the first node with `RAY_ADDRESS=auto`; it passes its `RDSP_*`, `NCCL_*` and similar variables to the workers. Stages fill the driver's node first, and a stage wider than a node keeps each tensor-parallel group inside one node.
-
-## Reproducing the blog's results
-
-### What every run shares
-
-| | |
-|---|---|
-| Software | DeepSpeed 53a2ac4 (rdsp), Megatron-Bridge v0.6.0 in the NeMo 26.08 container (also MegatronMIMO), TorchTitan 3c36a77 on torch 2.16.0.dev20261012, Hugging Face Transformers 5.17.0 |
-| Hardware | AWS p5.48xlarge: 8× H100 80GB, NVLink, 32 EFA cards; two nodes in one cluster placement group |
-| Data | CORD-v2, every row padded to 2,048 tokens; rdsp and TorchTitan replay the rows Megatron-Bridge's loader exports, in the same order |
-| Optimizer | AdamW, learning rate 1e-5 constant, betas 0.9 / 0.95, eps 1e-8; no weight decay, clipping or warm-up |
-| Loss | Mean over the step's supervised tokens; in the MIMO comparison, the mean per microbatch, as MIMO trains |
-| Precision | rdsp and Bridge: BF16 gradients, FP32 master weights stored as BF16 plus a 16-bit remainder (`bench/common/meg_extra_bf16.txt` for Bridge). TorchTitan: FP32 weights and gradients, reduced in BF16. 9B MIMO comparison: FP32 gradients and master weights on both, as MIMO fixes them |
-| Step time | Median over steps 6–50 of one 50-step run (`bench/common/medians.py`) |
-| 35B only | Router load-balancing loss and multi-token prediction off on every system; no tokens dropped |
-
-### Setting up the nodes
-
-Use the AWS Deep Learning Base OSS NVIDIA Driver GPU AMI (Ubuntu 22.04) with a 500 GB disk. Put this folder at `~/rdsp` on every node (`ln -s "$PWD" ~/rdsp`) and run everything from there, in bash. Node 1 also needs `~/env2.sh` (`export PRIV1= PRIV2=`) and `~/key2.pem`, an SSH key for `ubuntu` on node 2. Then `bash bench/qwen35_27b/prep.sh` on node 1 sets up both nodes: the environments, the 35B and 27B weights, Megatron-Bridge's checkpoints and exported rows, an NCCL check and the two-node Ray cluster. A rerun skips finished steps. `bench/README.md` lists every script.
-
-### Qwen3.5-35B-A3B, 16 GPUs on two nodes
-
-128 rows a step. On node 1:
-
-```bash
-RECOMPUTE=1 K=4 bash bench/qwen35_35b/rdsp_vision_stage.sh # -> logs/vision_stage/rdsp-k4-rc.log
-bash bench/qwen35_35b/rdsp_pp8dp2.sh # -> logs/pp8dp2/rdsp.log
-bash bench/qwen35_35b/torchtitan.sh fsdp16-ep8-bf16
-. bench/common/two_node.sh # Megatron-Bridge: MEG_COMMON, MEG_TP1
-FAST="rerun_state_machine.check_for_nan_in_loss=false ddp.check_for_nan_in_grad=false dataset.num_workers=8"
-NV="\"model.pipeline_model_parallel_layout='Et*17|t*23L'\" model.cross_entropy_fusion_impl=te"
-bash bench/cluster/both.sh env MODEL=Qwen3.5-35B-A3B RECIPE=qwen35_vl_35b_a3b_sft_16gpu_h100_bf16_config \
- GBS=128 STEPS=50 LOGS=$HOME/rdsp/bench/qwen35_35b/logs/pp2ep8 NET=efa GRAD_REDUCE_FP32=false \
- CUSTOM_NAME=bridge-pp2ep8-nv CUSTOM_TP=1 CUSTOM_PP=2 \
- MEGATRON_EXTRA="$MEG_COMMON $MEG_TP1 $FAST model.expert_model_parallel_size=8 model.batch_p2p_comm=false model.batch_p2p_sync=false $NV" \
- bash bench/common/runs.sh custom-megatron
-```
-
-| System | Layout | Recompute | Step time | Tokens/s per GPU |
-|---|---|---|---|---|
-| rdsp | vision encoder on a 4-GPU stage, then 6 stages of 2 GPUs; 32 microbatches of 4 rows | every layer | 6.38 s | 2,567 |
-| Megatron-Bridge | TP1 × PP2 × EP8 from NVIDIA's H100 recipe, layers 17 \| 23, no interleaving; 16 microbatches of 8 rows | none | 8.67 s | 1,890 |
-| TorchTitan | FSDP over 16 GPUs + EP8 inside each node; 8 microbatches of 16 rows | none | 9.11 s | 1,798 |
-| rdsp | PP8 × DP2; 64 microbatches of 2 rows | vision encoder only | 9.60 s | 1,707 |
-
-Both rdsp runs measure their own cuts. The vision stage's width, 4, comes from the PP8 × DP2 log (`python3 bench/common/layout_from_log.py vision-width bench/qwen35_35b/logs/pp8dp2/rdsp.log 16`).
+| `MODEL` | a Hugging Face id; vision-language models run `train_vl.py`, text models `train.py` |
+| `-pp`, `-tp`, `-dp` | pipeline stages, GPUs per layer, copies of each stage; together they use every device |
+| `--devices N` | use N GPUs instead of all, or N CPU processes with `--cpu` |
+| `--tune` | time the stages first and re-cut by the times; vision encoders get their own stage |
+| `--data` | `cord-v2` or `exported:DIR` for vision-language models, `wikitext` for text, `synthetic` for either |
+| `--steps`, `--batch-size`, `--seq-len`, `--lr` | training steps (50), rows a step (8 a GPU), tokens a row (2048), learning rate |
+| `--cpu` | train on this machine's CPU: small text models, to try rdsp out |
+| `--dry-run` | print the command only |
+| `-- FLAGS` | passed to the training script as they are |
-### Qwen3.5-27B, 8 GPUs on one node
-
-64 rows a step, on node 1 with the Ray cluster down (`. ~/env2.sh && bash bench/cluster/ray_cluster.sh down $PRIV1 $PRIV2`). rdsp runs eight 1-GPU stages with `--cuts measured`. `ROWS` is the rows per microbatch. `RC_PER` is the layers each stage recomputes, out of 6, 9, 9, 9, 9, 9, 8 and 5 at the calibration cut, so `6,8,7,7,6,5,3,0` keeps the activations of 0, 1, 2, 2, 3, 4, 5 and 5 layers. Without it every layer is recomputed. Megatron-Bridge runs PP8 at rdsp's measured cut (its even split runs out of memory), every layer recomputed; in its layout `E` is the embedding, `t*9` nine layers, `L` the loss. TorchTitan runs on another machine of the same type.
-
-```bash
-T=bench/qwen35_27b; mkdir -p $T/logs/pp8
-rdsp27() { # rdsp27
- ( unset LD_LIBRARY_PATH && . ~/venv/bin/activate && . ~/cuda_env.sh && \
- env "${@:2}" DS_BUILD_OPS=0 HF_HOME=$HOME/hf PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
- DATA=exported:$HOME/mimo/cord_steps-Qwen3.5-27B bash $T/rdsp_tune.sh ) > $T/logs/pp8/$1.log 2>&1
-}
-rdsp27 rdsp-rows1 ROWS=1 RC_PER=6,8,7,7,6,5,3,0
-rdsp27 rdsp-rows2 ROWS=2 RC_PER=6,8,7,7,6,5,3,0
-rdsp27 rdsp-rows4 ROWS=4 RC_PER=6,9,8,8,8,7,5,4
-RC_ALL="model.recompute_granularity=full model.recompute_method=uniform model.recompute_num_layers=1"
-FAST="rerun_state_machine.check_for_nan_in_loss=false ddp.check_for_nan_in_grad=false dataset.num_workers=8"
-bridge27() { # bridge27
- NAME=-mbs$1 MEG_RC="$RC_ALL \"model.pipeline_model_parallel_layout='$2'\" $FAST model.batch_p2p_sync=false train.micro_batch_size=$1" \
- bash bench/qwen35_27b/pp8.sh bridge
-}
-bridge27 1 'Et|t*9|t*9|t*9|t*9|t*9|t*10|t*8L'
-bridge27 2 'Et|t*9|t*9|t*9|t*9|t*10|t*10|t*7L'
-bridge27 4 'Et*2|t*9|t*10|t*9|t*10|t*9|t*10|t*5L'
-bash bench/torchtitan/run.sh run qwen35_27b_cord_fsdp8_rc_bf16 # TorchTitan FSDP over 8 GPUs, every layer recomputed
-bash bench/torchtitan/run.sh run qwen35_27b_cord_tp4dp2 # TorchTitan TP4 × FSDP2
-```
-
-If a rerun measures another cut (the second `stages (blocks):` line of the rdsp log), give Bridge that one. At 2 rows per microbatch, Bridge's lighter recompute settings (`recompute_method=block` with 8 or 9 layers, `recompute_granularity=selective`) ran out of memory.
-
-| Rows per microbatch | rdsp | Megatron-Bridge | TorchTitan FSDP |
-|---|---|---|---|
-| 1 | 10.66 s (1,537 tokens/s per GPU) | 15.13 s (1,083) | 13.16 s (1,245) |
-| 2 | 9.28 s | 9.78 s | |
-| 4 | 11.33 s | 10.47 s | |
-| 8 | out of memory | out of memory | |
-
-rdsp and Bridge ran on the same machine. On another machine of the same type, rdsp with every layer recomputed (no `RC_PER`) took 11.09 s at 1 row and 10.03 s at 2 rows. Bridge at 1 row took 14.34–15.13 s across four machines. Bridge TP2 × PP2 × DP2 took 17.47 s, TorchTitan TP4 × FSDP2 38.16 s.
-
-### Vision encoder alone
+## Run a recipe
-The Qwen3.5-27B encoder on one H100, 64 CORD-v2 images, every layer recomputed. From `bench/encoder`; run the Bridge line in the NeMo container with this folder mounted at `/rdsp`, as `bench/common/runs.sh` does:
+Each script in `recipes/` is one tested layout. Extra flags override the recipe's. The 16-GPU recipes run from the first node of a two-node cluster (`rdsp setup`).
-```bash
-mkdir -p logs && python grids.py logs/grids.json 64
-python enc_bench.py --impl bridge --modes fwdbwd --recompute --grids logs/grids.json --out logs/bridge-rc.json
-python enc_bench.py --impl hf --hf-attn sdpa --modes fwdbwd --recompute --grids logs/grids.json \
- --out logs/hf-rc.json
-```
-
-| Per image, median of three runs | Megatron-Bridge | Hugging Face (rdsp) |
+| Recipe | Layout | GPUs |
|---|---|---|
-| Forward and backward, 1 image per call | 173 ms | 114 ms |
-| GPU work in that | 74 ms | 62 ms |
-| The same at 8 images per call | 75 ms | 65 ms |
-
-Without `enc_bench.py --modes fwdbwd --recompute` it also times the forward pass: 1,238 GPU kernels per image for Bridge, 782 for Hugging Face.
-
-### MegatronMIMO
-
-Both systems give the vision encoder one GPU and the language model the same layout, with no recompute. Qwen3.5-9B on one node, 64 rows a step:
+| `qwen35-2b-tp2pp2dp2.sh` | 2 stages, each TP2 × DP2 | 8 |
+| `qwen35-2b-vision1-tp2dp2.sh` | vision encoder on 1 GPU, language TP2 × DP2 | 5 |
+| `qwen35-4b-tp2pp2dp2.sh` | 2 stages, each TP2 × DP2 | 8 |
+| `qwen35-4b-tp4pp2dp1.sh` | 2 stages, each TP4 | 8 |
+| `qwen35-4b-vision1-tp2dp2.sh` | vision encoder on 1 GPU, language TP2 × DP2 | 5 (80 GB) |
+| `qwen35-4b-coloc-tp2pp2dp2.sh` | vision encoder on every GPU, 2 stages of TP2 × DP2 | 8 (80 GB) |
+| `qwen35-9b-vision4-pp6dp2.sh` | vision encoder on 4 GPUs, 6 language stages of 2 GPUs | 16 (80 GB) |
+| `qwen35-27b-vision2-pp7dp2.sh` | vision encoder on 2 GPUs, 7 language stages of 2 GPUs, recompute | 16 (80 GB) |
+| `qwen35-35b-a3b-vision4-pp6dp2.sh` | vision encoder on 4 GPUs, 6 language stages of 2 GPUs, recompute, Liger's expert kernel | 16 (80 GB) |
+| `qwen3-text-pp.sh` | Qwen3-0.6B, text only: a ZeRO-2 stage and a TP2 stage | 4 |
```bash
-bash bench/mimo/bridge_9b.sh prep && bash bench/mimo/mimo_9b.sh convert # weights, rows, MIMO's checkpoint
-for L in 9b_v1_tp2pp2dp1 9b_v1_tp2pp1dp2; do # language TP2 × PP2, then TP2 × DP2
- bash bench/mimo/mimo_9b.sh mimo $L && bash bench/mimo/mimo_9b.sh rdsp $L
-done
+./recipes/qwen35-2b-tp2pp2dp2.sh --steps 200
```
-These write `bench/mimo/logs//mimo.log` and `rdsp.log`. The published TP2 × PP2 rdsp run had 26 steps (`mimo_9b.sh rdsp 9b_v1_tp2pp2dp1 26`). rdsp counts steps from 0, so its medians start at step 5 (`MEDIAN_FIRST=5`, and `MEDIAN_MIN=21` for 26 steps).
-
-Qwen3.5-27B on 9 GPUs of two nodes, 128 rows a step, 10 steps. MIMO's example launcher runs out of memory here as shipped. `MIMO_PATCH=1` runs a patched copy (`bench/mimo/patch_mimo.py`; `bench/mimo/patch.diff` shows the edit) with BF16 gradients and the 16-bit-remainder master, as rdsp. MIMO's library is unchanged.
-
-```bash
-. ~/env2.sh
-MODEL=Qwen3.5-27B RECIPE=qwen35_vl_27b_sft_16gpu_h100_bf16_config GBS=128 STEPS=50 \
- EXPORT_NAME=cord_steps-Qwen3.5-27B-128 bash bench/common/runs.sh export
-MODEL=Qwen3.5-27B CONVERT_TP=4 bash bench/common/runs.sh convert-mimo
-rsync -a -e "ssh -i ~/key2.pem" ~/mimo/cord_steps-Qwen3.5-27B-128 ~/mimo/Qwen3.5-27B-mimo ubuntu@$PRIV2:mimo/
-bash bench/cluster/both.sh env MODEL=Qwen3.5-27B GBS=128 STEPS=10 LOGS=$HOME/rdsp/bench/mimo/logs/27b_v1_tp4pp2dp1 \
- MIMO_PATCH=1 MIMO_NAME=mimo-9gpu-10 MIMO_GPUS=9 MIMO_MBS=1 MIMO_NPROC0=8 MIMO_NPROC1=1 \
- MIMO_LANGUAGE=tp=4,pp=2,dp=1,rank_offset=0 MIMO_IMAGES=tp=1,pp=1,dp=1,rank_offset=8 \
- bash bench/common/runs.sh mimo-layout
-bash bench/cluster/ray_cluster.sh up $PRIV1 $PRIV2
-RDSP_ARGS=--profile bash bench/mimo/rdsp_27b.sh
-```
+## Train your own model
-MIMO prints its step times on node 2, in `~/both-.log`: take steps 4–10 with `MEDIAN_FIRST=4 MEDIAN_MIN=5 python3 bench/common/medians.py bridge `. `rdsp_27b.sh` prints its own median. The published rdsp run had `--profile` on, which synchronizes the GPU per reading.
+`train_vl.py` trains vision-language models and `train.py` text models, both from a Hugging Face id.
-| Model | Language layout | GPUs | rdsp | MIMO | Tokens/s per GPU, rdsp / MIMO |
-|---|---|---|---|---|---|
-| 9B | TP2 × PP2 | 5 | 8.63 s | 9.32 s | 3,039 / 2,814 |
-| 9B | TP2 × DP2 | 5 | 7.73 s | 8.41 s | 3,391 / 3,116 |
-| 27B | TP4 × PP2 | 9 | 31.23 s | 30.82 s | 933 / 945 |
+| Flag | Meaning |
+|---|---|
+| `--model Qwen/Qwen3.5-4B` | the Hugging Face model |
+| `--dataset cord-v2` | `cord-v2`, `synthetic`, or `exported:DIR` (`train_vl.py`) |
+| `--stages 2` | number of pipeline stages |
+| `--stage 0:gpus=4,tp=2,zero=1` | one stage's GPUs and layout; other keys: `sp`, `ep`, `recompute`, `offload`, `compile` |
+| `--cuts balanced` | where to cut: `balanced` (default), `measured`, `even`, or layer numbers such as `5,18`; a first cut of `0` gives the vision encoder its own stage |
+| `--colocated-vision` | run the vision encoder on every GPU instead |
+| `--rows 2 --microbatches 32` | rows per microbatch and microbatches per step |
+| `--master-dtype remainder` | exact fp32 master weights in 2 bytes a parameter (with `--grad-dtype bf16`) |
+| `--untie-embeddings` | needed when the input embedding and output head share a weight and land on different stages |
+
+To use rdsp from your own code, see the Python example in the [README](../README.md#python-api). `train_batch()` takes an iterator of `(inputs, labels)` pairs, where `inputs` is a tensor or a dict of tensors.
-## Reproducing the Qwen3.5-2B and 4B results
+## Environment variables
-Results: [BENCHMARK_RESULTS.md](BENCHMARK_RESULTS.md). One node with 8 GPUs of at least 32 GB (80 GB for the 4B `noncoloc` and `coloc` layouts) and about 300 GB of disk, after `bash bench/setup_node.sh`:
+| Variable (default) | Effect |
+|---|---|
+| `RDSP_PLACEMENT_TIMEOUT_S` (600) | seconds a stage waits for its GPUs |
+| `RDSP_P2P_TIMEOUT_S` (300) | seconds a stage waits on a neighbour before the step fails |
+| `RDSP_PROFILE=1` | prints each stage's forward, backward, wait and optimizer time per step |
+| `RDSP_TORCH_PROFILE=` | writes a torch profiler table for that training step to the temp folder |
+| `RDSP_NSIGHT_STEPS=:` | limits an Nsight Systems capture (`-c cudaProfilerApi`) to those steps |
+| `RDSP_FUSED_GRAD_ADD`, `RDSP_SHARE_TP_ALLREDUCE`, `RDSP_PIN_CPUS`, `RDSP_FREEZE_HEAP` (on) | speed-ups; `0` turns one off |
-```bash
-MODEL=Qwen3.5-2B bash bench/qwen35_small/bench.sh noncoloc tp2
-MODEL=Qwen3.5-4B bash bench/qwen35_small/bench.sh tp2 tp4
-```
+## Reproducing the blog's results
-`noncoloc` pairs MegatronMIMO with the `vision1-tp2dp2` recipe, `tp2` and `tp4` pair Megatron-Bridge with the `tp2pp2dp2` and `tp4pp2dp1` recipes, and `coloc` runs the colocated recipe alone. Logs and `summary.txt` go to `~/bench//r/`.
+The commands and settings behind every published number are in [bench/compare/README.md](../bench/compare/README.md).
diff --git a/training/rdsp/examples/README.md b/training/rdsp/examples/README.md
new file mode 100644
index 000000000..1bf0acf24
--- /dev/null
+++ b/training/rdsp/examples/README.md
@@ -0,0 +1,57 @@
+# Examples
+
+Python scripts that train Qwen3.5 vision-language models with rdsp on 16 GPUs: two nodes of 8 GPUs with 80 GB each. Each script uses the layout of the published results and trains on CORD-v2 receipts.
+
+| Script | Model | Layout |
+|---|---|---|
+| [qwen35_9b.py](qwen35_9b.py) | Qwen3.5-9B | vision encoder on 4 GPUs, then 6 language stages of 2 GPUs |
+| [qwen35_27b.py](qwen35_27b.py) | Qwen3.5-27B | vision encoder on 2 GPUs, then 7 language stages of 2 GPUs, recompute |
+| [qwen35_35b_a3b.py](qwen35_35b_a3b.py) | Qwen3.5-35B-A3B | vision encoder on 4 GPUs, then 6 language stages of 2 GPUs, recompute |
+
+[common.py](common.py) holds what they share: loading the model, the CORD-v2 rows and the DeepSpeed config.
+
+## Run
+
+On both nodes, install rdsp and download the model. Every node reads its stages' weights from its own copy, at the same path:
+
+```bash
+bash install.sh && source .venv/bin/activate
+hf download Qwen/Qwen3.5-27B
+```
+
+Start the cluster:
+
+```bash
+rdsp setup # node 0: prints the join command
+rdsp setup --join ... # node 1: the command node 0 printed
+rdsp nodes # 16 GPUs
+```
+
+Then train, on node 0:
+
+```bash
+python examples/qwen35_27b.py
+```
+
+## What a script does
+
+1. Loads the model as an empty skeleton. No weights are read until each stage loads its own.
+2. Lists the stages: `StageOverride(stage=s, num_gpus=2, recompute=True)` for each.
+3. Builds the pipeline with `rdsp.initialize(model, weights, config, loss_fn, pipeline_config)`. The config is an ordinary DeepSpeed config.
+4. Times every stage for 3 steps without changing the weights, then cuts the layers again so every stage takes the same time.
+5. Trains: each `engine.train_batch(data_iter=data)` is one optimizer step.
+
+`engine.save_checkpoint(dir)` saves every stage and `engine.load_checkpoint(dir)` resumes.
+
+## Your own data
+
+Replace `cord_v2()` in [common.py](common.py) with any endless iterator of `(inputs, labels)` microbatches:
+
+- `inputs`: what the model's processor returns for the microbatch's rows.
+- `labels`: the token ids, with -100 where there is no loss.
+
+## Other GPU counts
+
+Change `STAGES`. The GPU counts add up to the GPUs in the cluster, and each stage's GPU count divides `ROWS`. Or let rdsp pick a layout for the GPUs it finds: `rdsp train Qwen/Qwen3.5-9B`.
+
+The published step times ([docs/BENCHMARK_RESULTS.md](../docs/BENCHMARK_RESULTS.md)) come from the [recipes](../recipes) with the same layouts. Those runs trained on rows prepared before step 1. These scripts prepare each image while training.
diff --git a/training/rdsp/examples/common.py b/training/rdsp/examples/common.py
new file mode 100644
index 000000000..c365112e5
--- /dev/null
+++ b/training/rdsp/examples/common.py
@@ -0,0 +1,84 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+
+"""What the examples share that is not rdsp: the model, the training rows and the DeepSpeed
+config. The rows and Liger's GPU kernels come from train_vl.py, the repository's full script."""
+
+import sys
+from pathlib import Path
+
+import accelerate
+import huggingface_hub
+import torch
+import transformers
+
+import ray_deepspeed_pipeline as rdsp
+from ray_deepspeed_pipeline.config import MASTER_WEIGHTS_KEY, OPTIMIZER_GROUP_NUMEL_KEY
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+from train_vl import ( # noqa: E402
+ apply_liger,
+ cord_rows,
+ drop_padding_mask,
+ microbatches,
+ sharded_loss_sum_liger,
+ token_count,
+)
+
+SEQ = 2048 # tokens a row
+
+# next-token loss averaged over the step's tokens, in Liger's kernel
+LOSS = rdsp.TokenMeanLoss(sharded_loss_sum_liger, token_count)
+
+
+def load(name):
+ """The model as an empty skeleton, its checkpoint folder and its processor. Each stage reads
+ only its own weights from the folder, so every node needs the checkpoint at the same path."""
+ weights = huggingface_hub.snapshot_download(
+ name, allow_patterns=["*.json", "*.safetensors", "*.txt", "*.jinja"]
+ )
+ config = transformers.AutoConfig.from_pretrained(weights)
+ with accelerate.init_empty_weights():
+ model = transformers.AutoModelForImageTextToText.from_config(config, dtype=torch.bfloat16)
+ apply_liger(model) # Liger's fused RMSNorm, SwiGLU and expert kernels
+ return model, weights, transformers.AutoProcessor.from_pretrained(weights)
+
+
+def cord_v2(processor, rows):
+ """Endless microbatches of `rows` CORD-v2 receipts padded to SEQ tokens: the receipt's image
+ and its parse as JSON text, which the loss covers."""
+ receipts = cord_rows(max_pixels=512 * 512, seed=0)
+ for inputs, labels in microbatches(processor, rows, SEQ, receipts):
+ # the padding sits at the end only, so causal attention needs no mask: a faster kernel
+ yield drop_padding_mask(inputs), labels
+
+
+def deepspeed_config(rows, microbatches, lr):
+ """An ordinary DeepSpeed config: every stage builds its own engine and optimizer from it."""
+ return {
+ "train_batch_size": rows * microbatches,
+ "gradient_accumulation_steps": microbatches,
+ "bf16": {"enabled": True},
+ "zero_optimization": {
+ "stage": 1,
+ "reduce_bucket_size": 50_000_000,
+ "allgather_bucket_size": 50_000_000,
+ },
+ "optimizer": {
+ "type": "AdamW",
+ "params": {
+ "lr": lr,
+ "betas": [0.9, 0.95],
+ "eps": 1e-8,
+ "weight_decay": 0.0,
+ "torch_adam": True,
+ "fused": True,
+ },
+ },
+ "gradient_clipping": 0.0,
+ "steps_per_print": 10**9,
+ # rdsp's keys: FP32 master weights kept as the BF16 weights plus a 16-bit remainder
+ # (2 bytes a parameter, not 4), and the optimizer step 250M parameters at a time
+ MASTER_WEIGHTS_KEY: "remainder",
+ OPTIMIZER_GROUP_NUMEL_KEY: 250_000_000,
+ }
diff --git a/training/rdsp/examples/qwen35_27b.py b/training/rdsp/examples/qwen35_27b.py
new file mode 100644
index 000000000..a045f979f
--- /dev/null
+++ b/training/rdsp/examples/qwen35_27b.py
@@ -0,0 +1,63 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+
+"""Qwen3.5-27B on 16 GPUs, two nodes of 8: the vision encoder on a 2-GPU stage, then 7
+language stages of 2 GPUs that recompute their activations. How to run it: README.md."""
+
+import dataclasses
+
+import ray
+from common import LOSS, cord_v2, deepspeed_config, load
+
+import ray_deepspeed_pipeline as rdsp
+
+MODEL = "Qwen/Qwen3.5-27B"
+ROWS, MICROBATCHES = 2, 64 # 128 rows a step, 1 row a GPU per microbatch
+
+# One entry per stage: its GPUs and settings. A stage of 2 GPUs holds two copies of its layers,
+# each training on half of every microbatch.
+# recompute: keep only each layer's input and redo its forward pass during the backward
+# pass, to fit in memory.
+STAGES = (
+ rdsp.StageOverride(stage=0, num_gpus=2), # the vision encoder alone
+ *(rdsp.StageOverride(stage=s, num_gpus=2, recompute=True) for s in range(1, 8)),
+)
+
+
+def main():
+ model, weights, processor = load(MODEL)
+ data = cord_v2(processor, ROWS)
+ # the stages' processes run on the cluster's nodes, with these settings
+ ray.init(runtime_env={"env_vars": {"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True"}})
+
+ def build(partition, lr):
+ engine, _, _, _ = rdsp.initialize(
+ model=model,
+ weights=weights,
+ config=deepspeed_config(ROWS, MICROBATCHES, lr),
+ loss_fn=LOSS,
+ pipeline_config=rdsp.PipelineConfig(
+ stages=len(STAGES),
+ partition=partition,
+ stage_overrides=STAGES,
+ prefetch=True, # send the next step's rows while this one trains
+ ),
+ )
+ return engine
+
+ # Cut the language layers so the stages hold equal parameters, time every stage for a few
+ # steps at learning rate 0 (the weights stay as loaded), then cut again by those times.
+ partition = rdsp.BalancedTransformerBlocks(vision_stage=True)
+ timing = build(partition, lr=0.0)
+ measured = timing.measure_stages(data, steps=3, skip=1)
+ timing.shutdown()
+ engine = build(dataclasses.replace(partition, measured=measured), lr=1e-5)
+ print("layers on each stage:", engine.stage_blocks, flush=True)
+
+ for step in range(50):
+ loss = engine.train_batch(data_iter=data) # one optimizer step over all microbatches
+ print(f"step {step} loss {float(loss):.4f}", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/training/rdsp/examples/qwen35_35b_a3b.py b/training/rdsp/examples/qwen35_35b_a3b.py
new file mode 100644
index 000000000..8723bb90b
--- /dev/null
+++ b/training/rdsp/examples/qwen35_35b_a3b.py
@@ -0,0 +1,72 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+
+"""Qwen3.5-35B-A3B (a mixture of experts) on 16 GPUs, two nodes of 8: the vision encoder on a
+4-GPU stage, then 6 language stages of 2 GPUs that recompute their activations. How to run
+it: README.md."""
+
+import dataclasses
+
+import ray
+from common import LOSS, cord_v2, deepspeed_config, load
+
+import ray_deepspeed_pipeline as rdsp
+
+MODEL = "Qwen/Qwen3.5-35B-A3B"
+ROWS, MICROBATCHES = 4, 32 # 128 rows a step, 2 rows a GPU per microbatch
+
+# One entry per stage: its GPUs and settings. A stage of 2 GPUs holds two copies of its layers,
+# each training on half of every microbatch.
+# recompute: keep only each layer's input and redo its forward pass during the backward
+# pass, to fit in memory.
+STAGES = (
+ rdsp.StageOverride(stage=0, num_gpus=4), # the vision encoder alone
+ *(rdsp.StageOverride(stage=s, num_gpus=2, recompute=True) for s in range(1, 7)),
+)
+
+
+def main():
+ model, weights, processor = load(MODEL)
+ data = cord_v2(processor, ROWS)
+ # the stages' processes run on the cluster's nodes, with these settings
+ ray.init(
+ runtime_env={
+ "env_vars": {
+ "PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True",
+ # Liger compiles its expert kernel during the first step: wait longer
+ "RDSP_P2P_TIMEOUT_S": "900",
+ }
+ }
+ )
+
+ def build(partition, lr):
+ engine, _, _, _ = rdsp.initialize(
+ model=model,
+ weights=weights,
+ config=deepspeed_config(ROWS, MICROBATCHES, lr),
+ loss_fn=LOSS,
+ pipeline_config=rdsp.PipelineConfig(
+ stages=len(STAGES),
+ partition=partition,
+ stage_overrides=STAGES,
+ prefetch=True, # send the next step's rows while this one trains
+ ),
+ )
+ return engine
+
+ # Cut the language layers so the stages hold equal parameters, time every stage for a few
+ # steps at learning rate 0 (the weights stay as loaded), then cut again by those times.
+ partition = rdsp.BalancedTransformerBlocks(vision_stage=True)
+ timing = build(partition, lr=0.0)
+ measured = timing.measure_stages(data, steps=3, skip=1)
+ timing.shutdown()
+ engine = build(dataclasses.replace(partition, measured=measured), lr=1e-5)
+ print("layers on each stage:", engine.stage_blocks, flush=True)
+
+ for step in range(50):
+ loss = engine.train_batch(data_iter=data) # one optimizer step over all microbatches
+ print(f"step {step} loss {float(loss):.4f}", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/training/rdsp/examples/qwen35_9b.py b/training/rdsp/examples/qwen35_9b.py
new file mode 100644
index 000000000..3cabf3ff0
--- /dev/null
+++ b/training/rdsp/examples/qwen35_9b.py
@@ -0,0 +1,61 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+
+"""Qwen3.5-9B on 16 GPUs, two nodes of 8: the vision encoder on a 4-GPU stage, then 6
+language stages of 2 GPUs. How to run it: README.md."""
+
+import dataclasses
+
+import ray
+from common import LOSS, cord_v2, deepspeed_config, load
+
+import ray_deepspeed_pipeline as rdsp
+
+MODEL = "Qwen/Qwen3.5-9B"
+ROWS, MICROBATCHES = 4, 32 # 128 rows a step, 2 rows a GPU per microbatch
+
+# One entry per stage: its GPUs and settings. A stage of 2 GPUs holds two copies of its layers,
+# each training on half of every microbatch.
+STAGES = (
+ rdsp.StageOverride(stage=0, num_gpus=4), # the vision encoder alone
+ *(rdsp.StageOverride(stage=s, num_gpus=2) for s in range(1, 7)),
+)
+
+
+def main():
+ model, weights, processor = load(MODEL)
+ data = cord_v2(processor, ROWS)
+ # the stages' processes run on the cluster's nodes, with these settings
+ ray.init(runtime_env={"env_vars": {"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True"}})
+
+ def build(partition, lr):
+ engine, _, _, _ = rdsp.initialize(
+ model=model,
+ weights=weights,
+ config=deepspeed_config(ROWS, MICROBATCHES, lr),
+ loss_fn=LOSS,
+ pipeline_config=rdsp.PipelineConfig(
+ stages=len(STAGES),
+ partition=partition,
+ stage_overrides=STAGES,
+ prefetch=True, # send the next step's rows while this one trains
+ ),
+ )
+ return engine
+
+ # Cut the language layers so the stages hold equal parameters, time every stage for a few
+ # steps at learning rate 0 (the weights stay as loaded), then cut again by those times.
+ partition = rdsp.BalancedTransformerBlocks(vision_stage=True)
+ timing = build(partition, lr=0.0)
+ measured = timing.measure_stages(data, steps=3, skip=1)
+ timing.shutdown()
+ engine = build(dataclasses.replace(partition, measured=measured), lr=1e-5)
+ print("layers on each stage:", engine.stage_blocks, flush=True)
+
+ for step in range(50):
+ loss = engine.train_batch(data_iter=data) # one optimizer step over all microbatches
+ print(f"step {step} loss {float(loss):.4f}", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/training/rdsp/install.sh b/training/rdsp/install.sh
new file mode 100755
index 000000000..64f0cd533
--- /dev/null
+++ b/training/rdsp/install.sh
@@ -0,0 +1,21 @@
+#!/bin/bash
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+# Install rdsp, DeepSpeed and the training scripts' packages in a new Python 3.12 environment.
+# bash install.sh [environment folder, default .venv]
+# Run it on every node. Then: source .venv/bin/activate && rdsp setup
+set -euo pipefail
+cd "$(dirname "$0")"
+VENV=${1:-.venv}
+if command -v uv > /dev/null; then
+ uv venv --allow-existing -p 3.12 "$VENV" # a rerun reuses it
+ . "$VENV/bin/activate"
+ uv pip install -e ".[gpu,train]"
+else
+ python3 -m venv "$VENV"
+ . "$VENV/bin/activate"
+ pip install --upgrade pip
+ pip install -e ".[gpu,train]"
+fi
+echo
+echo "Installed. Next: source $VENV/bin/activate && rdsp setup"
diff --git a/training/rdsp/pyproject.toml b/training/rdsp/pyproject.toml
index 1995bb2c4..a9c6389e1 100644
--- a/training/rdsp/pyproject.toml
+++ b/training/rdsp/pyproject.toml
@@ -7,19 +7,31 @@ name = "ray-deepspeed-pipeline"
version = "0.0.1"
description = "Pipeline parallelism on Ray + DeepSpeed with per-stage layouts"
requires-python = ">=3.12"
+# the versions every result was measured with, or the oldest they need
dependencies = [
- "torch",
+ "torch>=2.13",
"cloudpickle",
# imported lazily: importing ray_deepspeed_pipeline does not import ray
- "ray",
+ "ray>=2.58",
+ "transformers>=5.17",
]
[project.optional-dependencies]
# deepspeed is only importable on Linux+CUDA; the stage actors import it
# lazily, never at package import time.
-gpu = ["deepspeed"]
-# transformers: the tests of train.py and train_vl.py import those scripts
-dev = ["pytest", "ruff", "transformers"]
+gpu = ["deepspeed>=0.19.3"]
+# what train.py, train_vl.py and recipes/ use; the GPU kernels exist for Linux only
+train = [
+ "accelerate",
+ "datasets",
+ "pillow",
+ "liger-kernel>=0.8.4; sys_platform == 'linux'",
+ "flash-linear-attention>=0.5.2; sys_platform == 'linux'",
+]
+dev = ["pytest", "ruff"]
+
+[project.scripts]
+rdsp = "ray_deepspeed_pipeline.cli:main"
[tool.hatch.build.targets.wheel]
packages = ["src/ray_deepspeed_pipeline"]
@@ -30,7 +42,7 @@ testpaths = ["tests"]
[tool.ruff]
line-length = 100
# Markdown is excluded: the samples in it are laid out by hand
-extend-exclude = ["bench/results", "docs", "*.md"]
+extend-exclude = ["docs", "*.md"]
[tool.ruff.lint]
select = ["E", "F", "W", "I", "B", "UP"]
diff --git a/training/rdsp/recipes/qwen3-text-pp.sh b/training/rdsp/recipes/qwen3-text-pp.sh
index 31cb2713d..fa6cae0b2 100755
--- a/training/rdsp/recipes/qwen3-text-pp.sh
+++ b/training/rdsp/recipes/qwen3-text-pp.sh
@@ -1,13 +1,9 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: Apache-2.0
# DeepSpeed Team
-# Qwen3-0.6B (text only) on 4 GPUs: stage 0 data parallel with ZeRO-2 on 2
-# GPUs, stage 1 tensor parallel on 2 GPUs. WikiText-103.
-#
-# GPUs: 4
-# Measured: not benchmarked; a starting point for text-only models
-#
-# Extra arguments are passed to train.py and override the flags below.
+# Qwen3-0.6B (text only) on WikiText-103: stage 0 data parallel with ZeRO-2 on 2 GPUs,
+# stage 1 tensor parallel on 2 GPUs. A starting point for text models.
+# Extra arguments override the flags below.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
exec python "$ROOT/train.py" \
diff --git a/training/rdsp/recipes/qwen35-27b-vision2-pp7dp2.sh b/training/rdsp/recipes/qwen35-27b-vision2-pp7dp2.sh
new file mode 100755
index 000000000..8b4b04a2a
--- /dev/null
+++ b/training/rdsp/recipes/qwen35-27b-vision2-pp7dp2.sh
@@ -0,0 +1,26 @@
+#!/usr/bin/env bash
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+# Qwen3.5-27B: the vision encoder on a 2-GPU stage, then 7 language stages of 2 GPUs that
+# recompute every layer. The cuts come from timing every stage for a few steps first.
+# 16 GPUs of 80 GB on two nodes: start the cluster with rdsp setup, then run this on the
+# first node.
+# About 11.5 s a step on 16 H100 (two nodes, EFA between them) with exported data.
+# DATA: cord-v2 (default) or exported: (bench/compare/prepare.sh).
+# Extra arguments override the flags below.
+set -euo pipefail
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+export PYTORCH_CUDA_ALLOC_CONF=${PYTORCH_CUDA_ALLOC_CONF:-expandable_segments:True}
+exec python "$ROOT/train_vl.py" \
+ --model Qwen/Qwen3.5-27B --dataset "${DATA:-cord-v2}" \
+ --stages 8 --cuts 0,measured \
+ --stage 0:gpus=2,zero=1 \
+ --stage 1:gpus=2,zero=1,recompute=1 --stage 2:gpus=2,zero=1,recompute=1 \
+ --stage 3:gpus=2,zero=1,recompute=1 --stage 4:gpus=2,zero=1,recompute=1 \
+ --stage 5:gpus=2,zero=1,recompute=1 --stage 6:gpus=2,zero=1,recompute=1 \
+ --stage 7:gpus=2,zero=1,recompute=1 \
+ --rows 2 --microbatches 64 --seq 2048 --pad-multiple 0 \
+ --steps 50 --lr 1e-5 --betas 0.9,0.95 --eps 1e-8 --weight-decay 0.0 \
+ --grad-dtype bf16 --master-dtype remainder --fused-adam --optimizer-group-numel 250000000 \
+ --loss token-mean --liger --prefetch --sharded-loss --drop-padding-mask \
+ "$@"
diff --git a/training/rdsp/recipes/qwen35-2b-tp2pp2dp2.sh b/training/rdsp/recipes/qwen35-2b-tp2pp2dp2.sh
index bf9219f23..927489f8b 100755
--- a/training/rdsp/recipes/qwen35-2b-tp2pp2dp2.sh
+++ b/training/rdsp/recipes/qwen35-2b-tp2pp2dp2.sh
@@ -1,19 +1,10 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: Apache-2.0
# DeepSpeed Team
-# Qwen3.5-2B, 2 pipeline stages, each TP2 x DP2. The vision encoder sits on
-# stage 0; rdsp places the cut (--cuts balanced picks 5 decoder layers for
-# stage 0 on the exported CORD-v2 samples).
-#
-# GPUs: 8 (32 GB each is enough)
-# Measured: 5.30 s per step, 64 rows of up to 2048 tokens, 8x RTX PRO 4500
-# (PCIe), DATA=exported: (Megatron-Bridge: 7.39 s)
-#
-# DATA: cord-v2 (default; downloads CORD-v2, images scaled to --max-pixels)
-# or exported: from bench/common/runs.sh export (the benchmark's samples).
-# Both pad each microbatch to its longest row. The cut and times above were
-# measured on exported data; cord-v2's smaller images change both.
-# Extra arguments are passed to train_vl.py and override the flags below.
+# Qwen3.5-2B: 2 pipeline stages, each TP2 x DP2; the vision encoder sits on stage 0.
+# 8 GPUs of 32 GB. About 5.3 s a step on 8x RTX PRO 4500 (PCIe) with exported data.
+# DATA: cord-v2 (default) or exported: (bench/compare/prepare.sh).
+# Extra arguments override the flags below.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
exec python "$ROOT/train_vl.py" \
diff --git a/training/rdsp/recipes/qwen35-2b-vision1-tp2dp2.sh b/training/rdsp/recipes/qwen35-2b-vision1-tp2dp2.sh
index 7e7009828..e42f6ff5b 100755
--- a/training/rdsp/recipes/qwen35-2b-vision1-tp2dp2.sh
+++ b/training/rdsp/recipes/qwen35-2b-vision1-tp2dp2.sh
@@ -1,18 +1,10 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: Apache-2.0
# DeepSpeed Team
-# Qwen3.5-2B, vision encoder alone on 1 GPU, language model TP2 x DP2 on 4.
-# MegatronMIMO's non-colocated layout.
-#
-# GPUs: 5 (32 GB each is enough)
-# Measured: 8.30 s per step, 64 rows of up to 2048 tokens, 8x RTX PRO 4500
-# (PCIe), DATA=exported: (MegatronMIMO: 9.64 s)
-#
-# DATA: cord-v2 (default; downloads CORD-v2, images scaled to --max-pixels)
-# or exported: from bench/common/runs.sh export (the benchmark's samples).
-# Both pad each microbatch to its longest row. The cut and times above were
-# measured on exported data; cord-v2's smaller images change both.
-# Extra arguments are passed to train_vl.py and override the flags below.
+# Qwen3.5-2B: the vision encoder alone on 1 GPU, the language model TP2 x DP2 on 4.
+# 5 GPUs of 32 GB. About 8.3 s a step on RTX PRO 4500 (PCIe) with exported data.
+# DATA: cord-v2 (default) or exported: (bench/compare/prepare.sh).
+# Extra arguments override the flags below.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
exec python "$ROOT/train_vl.py" \
diff --git a/training/rdsp/recipes/qwen35-35b-a3b-vision4-pp6dp2.sh b/training/rdsp/recipes/qwen35-35b-a3b-vision4-pp6dp2.sh
new file mode 100755
index 000000000..4af9c4e3d
--- /dev/null
+++ b/training/rdsp/recipes/qwen35-35b-a3b-vision4-pp6dp2.sh
@@ -0,0 +1,28 @@
+#!/usr/bin/env bash
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+# Qwen3.5-35B-A3B (mixture of experts): the vision encoder on a 4-GPU stage, then 6 language
+# stages of 2 GPUs that recompute every layer; the experts run in Liger's fused kernel
+# (--moe-experts hf for Hugging Face's). The cuts come from timing every stage for a few
+# steps first. 16 GPUs of 80 GB on two nodes: start the cluster with rdsp setup, then run
+# this on the first node.
+# About 5.4 s a step on 16 H100 (two nodes, EFA between them) with exported data.
+# DATA: cord-v2 (default) or exported: (bench/compare/prepare.sh).
+# Extra arguments override the flags below.
+set -euo pipefail
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+export PYTORCH_CUDA_ALLOC_CONF=${PYTORCH_CUDA_ALLOC_CONF:-expandable_segments:True}
+# Liger compiles its expert kernel on the first step: let the stages wait for each other longer
+export RDSP_P2P_TIMEOUT_S=${RDSP_P2P_TIMEOUT_S:-900}
+exec python "$ROOT/train_vl.py" \
+ --model Qwen/Qwen3.5-35B-A3B --dataset "${DATA:-cord-v2}" \
+ --stages 7 --cuts 0,measured \
+ --stage 0:gpus=4,zero=1 \
+ --stage 1:gpus=2,zero=1,recompute=1 --stage 2:gpus=2,zero=1,recompute=1 \
+ --stage 3:gpus=2,zero=1,recompute=1 --stage 4:gpus=2,zero=1,recompute=1 \
+ --stage 5:gpus=2,zero=1,recompute=1 --stage 6:gpus=2,zero=1,recompute=1 \
+ --rows 4 --microbatches 32 --seq 2048 --pad-multiple 0 \
+ --steps 50 --lr 1e-5 --betas 0.9,0.95 --eps 1e-8 --weight-decay 0.0 \
+ --grad-dtype bf16 --master-dtype remainder --fused-adam --optimizer-group-numel 250000000 \
+ --loss token-mean --liger --moe-experts liger --prefetch --sharded-loss --drop-padding-mask \
+ "$@"
diff --git a/training/rdsp/recipes/qwen35-4b-coloc-tp2pp2dp2.sh b/training/rdsp/recipes/qwen35-4b-coloc-tp2pp2dp2.sh
index 1393b072d..87c6a42d7 100755
--- a/training/rdsp/recipes/qwen35-4b-coloc-tp2pp2dp2.sh
+++ b/training/rdsp/recipes/qwen35-4b-coloc-tp2pp2dp2.sh
@@ -1,19 +1,10 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: Apache-2.0
# DeepSpeed Team
-# Qwen3.5-4B, vision encoder colocated: every GPU encodes 1/8 of the step's
-# images (data parallel, no TP inside the encoder). Language model: 2 pipeline
-# stages, each TP2 x DP2; rdsp places the cut (--cuts balanced picks 19
-# decoder layers for stage 0 on the exported CORD-v2 samples).
-#
-# GPUs: 8, 80 GB class
-# Measured: 5.62 s per step on 8x H100 (NVLink), DATA=exported:, before
-# --vision-compile was added (Megatron-Bridge TP2xPP2xDP2: 8.79 s)
-#
-# DATA: cord-v2 (default; downloads CORD-v2, images scaled to --max-pixels)
-# or exported: from bench/common/runs.sh export (the benchmark's samples).
-# Both pad each microbatch to its longest row.
-# Extra arguments are passed to train_vl.py and override the flags below.
+# Qwen3.5-4B: the vision encoder on every GPU (each encodes 1/8 of the images), the language
+# model on 2 pipeline stages of TP2 x DP2. 8 GPUs of 80 GB. About 5.6 s a step on 8x H100.
+# DATA: cord-v2 (default) or exported: (bench/compare/prepare.sh).
+# Extra arguments override the flags below.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
exec python "$ROOT/train_vl.py" \
diff --git a/training/rdsp/recipes/qwen35-4b-tp2pp2dp2.sh b/training/rdsp/recipes/qwen35-4b-tp2pp2dp2.sh
index 0b8c62c8c..8ff621fb6 100755
--- a/training/rdsp/recipes/qwen35-4b-tp2pp2dp2.sh
+++ b/training/rdsp/recipes/qwen35-4b-tp2pp2dp2.sh
@@ -1,19 +1,10 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: Apache-2.0
# DeepSpeed Team
-# Qwen3.5-4B, 2 pipeline stages, each TP2 x DP2. The vision encoder sits on
-# stage 0; rdsp places the cut (--cuts balanced picks 13 decoder layers for
-# stage 0 on the exported CORD-v2 samples).
-#
-# GPUs: 8, 32 GB each (peak about 25 GB per GPU)
-# Measured: 8.69 s per step, 64 rows of up to 2048 tokens, 8x RTX PRO 4500
-# (PCIe), DATA=exported: (Megatron-Bridge: 10.04 s)
-#
-# DATA: cord-v2 (default; downloads CORD-v2, images scaled to --max-pixels)
-# or exported: from bench/common/runs.sh export (the benchmark's samples).
-# Both pad each microbatch to its longest row. The cut and times above were
-# measured on exported data; cord-v2's smaller images change both.
-# Extra arguments are passed to train_vl.py and override the flags below.
+# Qwen3.5-4B: 2 pipeline stages, each TP2 x DP2; the vision encoder sits on stage 0.
+# 8 GPUs of 32 GB. About 8.7 s a step on 8x RTX PRO 4500 (PCIe) with exported data.
+# DATA: cord-v2 (default) or exported: (bench/compare/prepare.sh).
+# Extra arguments override the flags below.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
exec python "$ROOT/train_vl.py" \
diff --git a/training/rdsp/recipes/qwen35-4b-tp4pp2dp1.sh b/training/rdsp/recipes/qwen35-4b-tp4pp2dp1.sh
index 2177bcad1..ebc1e2eee 100755
--- a/training/rdsp/recipes/qwen35-4b-tp4pp2dp1.sh
+++ b/training/rdsp/recipes/qwen35-4b-tp4pp2dp1.sh
@@ -1,19 +1,10 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: Apache-2.0
# DeepSpeed Team
-# Qwen3.5-4B, 2 pipeline stages, each TP4 (no data parallelism). One row
-# per microbatch, 64 microbatches per step, as Megatron runs this layout.
-# rdsp places the cut (--cuts balanced picks 12 on the exported CORD-v2 samples).
-#
-# GPUs: 8, 32 GB each (peak about 26 GB per GPU)
-# Measured: 13.29 s per step, 64 rows of up to 2048 tokens, 8x RTX PRO 4500
-# (PCIe), DATA=exported: (Megatron-Bridge: 15.93 s)
-#
-# DATA: cord-v2 (default; downloads CORD-v2, images scaled to --max-pixels)
-# or exported: from bench/common/runs.sh export (the benchmark's samples).
-# Both pad each microbatch to its longest row. The cut and times above were
-# measured on exported data; cord-v2's smaller images change both.
-# Extra arguments are passed to train_vl.py and override the flags below.
+# Qwen3.5-4B: 2 pipeline stages, each TP4; one row per microbatch, 64 microbatches a step.
+# 8 GPUs of 32 GB. About 13.3 s a step on 8x RTX PRO 4500 (PCIe) with exported data.
+# DATA: cord-v2 (default) or exported: (bench/compare/prepare.sh).
+# Extra arguments override the flags below.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
exec python "$ROOT/train_vl.py" \
diff --git a/training/rdsp/recipes/qwen35-4b-vision1-tp2dp2.sh b/training/rdsp/recipes/qwen35-4b-vision1-tp2dp2.sh
index b99ef6172..abbc4ec75 100755
--- a/training/rdsp/recipes/qwen35-4b-vision1-tp2dp2.sh
+++ b/training/rdsp/recipes/qwen35-4b-vision1-tp2dp2.sh
@@ -1,17 +1,10 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: Apache-2.0
# DeepSpeed Team
-# Qwen3.5-4B, vision encoder alone on 1 GPU, language model TP2 x DP2 on 4.
-# MegatronMIMO's non-colocated layout.
-#
-# GPUs: 5, 80 GB class (does not fit 32 GB GPUs without recompute)
-# Measured: 7.89 s per step, 64 rows of up to 2048 tokens, 8x H100
-# (NVLink), DATA=exported: (MegatronMIMO: 7.99 s)
-#
-# DATA: cord-v2 (default; downloads CORD-v2, images scaled to --max-pixels)
-# or exported: from bench/common/runs.sh export (the benchmark's samples).
-# Both pad each microbatch to its longest row.
-# Extra arguments are passed to train_vl.py and override the flags below.
+# Qwen3.5-4B: the vision encoder alone on 1 GPU, the language model TP2 x DP2 on 4.
+# 5 GPUs of 80 GB. About 7.9 s a step on H100 with exported data.
+# DATA: cord-v2 (default) or exported: (bench/compare/prepare.sh).
+# Extra arguments override the flags below.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
exec python "$ROOT/train_vl.py" \
diff --git a/training/rdsp/recipes/qwen35-9b-vision4-pp6dp2.sh b/training/rdsp/recipes/qwen35-9b-vision4-pp6dp2.sh
new file mode 100755
index 000000000..f8a92348a
--- /dev/null
+++ b/training/rdsp/recipes/qwen35-9b-vision4-pp6dp2.sh
@@ -0,0 +1,23 @@
+#!/usr/bin/env bash
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+# Qwen3.5-9B: the vision encoder on a 4-GPU stage, then 6 language stages of 2 GPUs. The cuts
+# come from timing every stage for a few steps first. 16 GPUs of 80 GB on two nodes: start
+# the cluster with rdsp setup, then run this on the first node.
+# About 3.2 s a step on 16 H100 (two nodes, EFA between them) with exported data.
+# DATA: cord-v2 (default) or exported: (bench/compare/prepare.sh).
+# Extra arguments override the flags below.
+set -euo pipefail
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+export PYTORCH_CUDA_ALLOC_CONF=${PYTORCH_CUDA_ALLOC_CONF:-expandable_segments:True}
+exec python "$ROOT/train_vl.py" \
+ --model Qwen/Qwen3.5-9B --dataset "${DATA:-cord-v2}" \
+ --stages 7 --cuts 0,measured \
+ --stage 0:gpus=4,zero=1 \
+ --stage 1:gpus=2,zero=1 --stage 2:gpus=2,zero=1 --stage 3:gpus=2,zero=1 \
+ --stage 4:gpus=2,zero=1 --stage 5:gpus=2,zero=1 --stage 6:gpus=2,zero=1 \
+ --rows 4 --microbatches 32 --seq 2048 --pad-multiple 0 \
+ --steps 50 --lr 1e-5 --betas 0.9,0.95 --eps 1e-8 --weight-decay 0.0 \
+ --grad-dtype bf16 --master-dtype remainder --fused-adam --optimizer-group-numel 250000000 \
+ --loss token-mean --liger --prefetch --sharded-loss --drop-padding-mask \
+ "$@"
diff --git a/training/rdsp/src/ray_deepspeed_pipeline/__init__.py b/training/rdsp/src/ray_deepspeed_pipeline/__init__.py
index 923e6cce5..3a0f4704c 100644
--- a/training/rdsp/src/ray_deepspeed_pipeline/__init__.py
+++ b/training/rdsp/src/ray_deepspeed_pipeline/__init__.py
@@ -5,7 +5,6 @@
from ray_deepspeed_pipeline.config import (
BalancedTransformerBlocks,
ColocatedVision,
- ConnectionOverride,
ExplicitCuts,
MeasuredStages,
PipelineConfig,
@@ -20,7 +19,6 @@
"initialize",
"PipelineConfig",
"StageOverride",
- "ConnectionOverride",
"RayPipelineEngine",
"UniformTransformerBlocks",
"ExplicitCuts",
diff --git a/training/rdsp/src/ray_deepspeed_pipeline/api.py b/training/rdsp/src/ray_deepspeed_pipeline/api.py
index 5d49887db..726dcafea 100644
--- a/training/rdsp/src/ray_deepspeed_pipeline/api.py
+++ b/training/rdsp/src/ray_deepspeed_pipeline/api.py
@@ -11,7 +11,7 @@
from ray_deepspeed_pipeline.config import PipelineConfig
from ray_deepspeed_pipeline.data import build_training_dataloader
from ray_deepspeed_pipeline.engine import RayPipelineEngine
-from ray_deepspeed_pipeline.errors import UnsupportedInV1, ValidationError
+from ray_deepspeed_pipeline.errors import UnsupportedFeature, ValidationError
# Pipeline/runtime settings belong in PipelineConfig, never in the DeepSpeed config.
_RESERVED_CONFIG_KEYS = frozenset(
@@ -102,7 +102,7 @@ def _check_model_parameters(model, model_parameters) -> None:
return
params = list(model_parameters)
if any(isinstance(p, dict) for p in params):
- raise UnsupportedInV1(
+ raise UnsupportedFeature(
"parameter groups are not supported: each stage builds its optimizer "
"from the DeepSpeed config over its own parameters"
)
@@ -112,7 +112,7 @@ def _check_model_parameters(model, model_parameters) -> None:
if len(set(ids)) != len(ids):
raise ValidationError("model_parameters lists a parameter twice")
if set(ids) != {id(p) for p in model.parameters()}:
- raise UnsupportedInV1(
+ raise UnsupportedFeature(
"model_parameters must be None or all of model.parameters(): each "
"stage optimizes every parameter it owns, so subsets cannot be honoured"
)
@@ -140,18 +140,18 @@ def initialize(
Raises ValidationError (bad config, unsupported layout, TP that does not
divide the key/value heads, a stage that cannot be placed on the Ray
- cluster) or UnsupportedInV1 (a DeepSpeed feature rdsp does not run)
+ cluster) or UnsupportedFeature (a DeepSpeed feature rdsp does not run)
before training starts."""
if optimizer is not None:
- raise UnsupportedInV1(
- "optimizer must be None in v1: a driver-side optimizer object "
+ raise UnsupportedFeature(
+ "optimizer must be None: a driver-side optimizer object "
"cannot be rebound to stage-local parameters inside actors. "
"Define the optimizer in the DeepSpeed config; each stage "
"constructs it locally via ordinary deepspeed.initialize()"
)
if lr_scheduler is not None:
- raise UnsupportedInV1(
- "lr_scheduler must be None in v1: define the scheduler in the "
+ raise UnsupportedFeature(
+ "lr_scheduler must be None: define the scheduler in the "
"DeepSpeed config; each stage constructs it locally"
)
if not isinstance(model, torch.nn.Module):
diff --git a/training/rdsp/src/ray_deepspeed_pipeline/cli.py b/training/rdsp/src/ray_deepspeed_pipeline/cli.py
new file mode 100644
index 000000000..e5d456e88
--- /dev/null
+++ b/training/rdsp/src/ray_deepspeed_pipeline/cli.py
@@ -0,0 +1,473 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+
+"""The rdsp command.
+
+ rdsp setup [--head | --join ADDRESS] start a Ray cluster on this node, or join one
+ rdsp nodes the cluster's nodes and GPUs
+ rdsp train MODEL [options] train a Hugging Face model on every GPU
+ rdsp train MODEL --cpu the same on this machine's CPU
+ rdsp train MODEL [options] -- FLAGS FLAGS go to the training script as they are
+
+rdsp train decides the parallelism it is not given. Tensor parallelism (-tp) is 1 unless set.
+Pipeline stages (-pp) are the fewest whose share of the model fits in half a device's memory,
+with each stage inside one node; the remaining devices become data-parallel copies (-dp) of
+every stage. Run without a model on a terminal, it asks for one.
+"""
+
+import argparse
+import os
+import shlex
+import shutil
+import socket
+import subprocess
+import sys
+from dataclasses import dataclass
+from pathlib import Path
+
+REPO = Path(__file__).resolve().parents[2] # train.py and train_vl.py sit at the repo root
+
+# training state per parameter, in bytes: what every copy of a stage holds, and what ZeRO-1
+# splits over its copies. GPU: bf16 weights and fp32 gradients, then fp32 master weights and
+# Adam's two moments. CPU: fp32 weights, gradients and moments, no ZeRO.
+GPU_BYTES = (6.0, 12.0)
+CPU_BYTES = (16.0, 0.0)
+MEMORY_SHARE = 0.5 # the rest of a device's memory for activations, buffers and the runtime
+CPU_WORKERS = 2 # processes on a CPU run: more of them share the same cores
+# GPU memory when the driver cannot see a GPU, by Ray's accelerator_type
+GPU_GIB = {"H100": 80, "H200": 141, "A100": 80, "L40S": 48, "L4": 24, "A10G": 24}
+
+
+@dataclass
+class Parallelism:
+ pp: int
+ tp: int
+ dp: int
+ recompute: bool
+ gib: float | None # training state per device
+ why: str
+
+
+def choose_parallelism(
+ devices_per_node: list[int],
+ params: float | None,
+ device_gib: float,
+ *,
+ pp: int | None = None,
+ tp: int = 1,
+ dp: int | None = None,
+ state_bytes: tuple[float, float] = GPU_BYTES,
+ shared_memory: bool = False,
+) -> Parallelism:
+ """pp x tp x dp over every device. shared_memory: the devices share device_gib (CPU
+ processes on one machine) instead of having that much each."""
+ total, node = sum(devices_per_node), min(devices_per_node)
+ if tp < 1 or node % tp:
+ raise SystemExit(f"-tp {tp} must divide the {node} devices of a node")
+ fixed, split = state_bytes
+ # half a device's memory; CPU processes split half the machine's
+ budget = MEMORY_SHARE * device_gib / (total if shared_memory else 1)
+
+ def gib(p, d):
+ return params * (fixed + split / d) / (p * tp) / 2**30 if params else None
+
+ unit = "process" if shared_memory else "device"
+ if pp is not None or dp is not None:
+ pp = pp or total // (tp * dp)
+ dp = dp or total // (tp * pp)
+ if pp * tp * dp != total:
+ raise SystemExit(
+ f"-pp {pp} x -tp {tp} x -dp {dp} = {pp * tp * dp}, not {total} devices"
+ )
+ why = "as given"
+ else:
+ # a stage of tp x dp devices inside one node; widest first, so the fewest stages
+ copies = [d for d in range(node // tp, 0, -1) if node % (tp * d) == 0]
+ fitting = [d for d in copies if params is None or gib(total // (tp * d), d) <= budget]
+ dp = (fitting or copies[-1:])[0]
+ pp = total // (tp * dp)
+ if params is None:
+ why = "model size unknown: one stage per node"
+ pp, dp = len(devices_per_node), node // tp
+ elif fitting:
+ why = f"the fewest stages that fit {budget:.0f} GiB a {unit}"
+ else:
+ why = f"does not fit {budget:.0f} GiB a {unit} even at {pp} stages: add devices"
+ state = gib(pp, dp)
+ recompute = state is not None and state > 0.6 * budget # little room left for activations
+ return Parallelism(pp, tp, dp, recompute, state, why)
+
+
+def layout_flags(par: Parallelism, batch: int, cpu: bool, cuts: str = "balanced") -> list[str]:
+ """train_vl.py / train.py flags: equal stages, one row per data-parallel copy per
+ microbatch, at least two microbatches per stage so the pipeline fills. A stage's GPUs (on
+ the CPU, its processes) are its copies times tp; GPU stages split the optimizer (ZeRO-1)."""
+ flags = ["--stages", str(par.pp), "--cuts", cuts]
+ keys = f"{'procs' if cpu else 'gpus'}={par.tp * par.dp}"
+ keys += f",tp={par.tp}" * (par.tp > 1) + ",zero=1" * (not cpu) + ",recompute=1" * par.recompute
+ for s in range(par.pp):
+ flags += ["--stage", f"{s}:{keys}"]
+ microbatches = max(batch // par.dp, 2 * par.pp)
+ return flags + ["--rows", str(par.dp), "--microbatches", str(microbatches)]
+
+
+# -- environment ---------------------------------------------------------------------------
+
+
+def local_gpus() -> tuple[int, float | None]:
+ """(GPUs on this machine, GiB of the first one); (0, None) without CUDA."""
+ try:
+ import torch
+ except ImportError:
+ return 0, None
+ if not torch.cuda.is_available():
+ return 0, None
+ return torch.cuda.device_count(), torch.cuda.get_device_properties(0).total_memory / 2**30
+
+
+def system_gib() -> float:
+ return os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES") / 2**30
+
+
+def check_environment() -> list[tuple[str, bool, str]]:
+ """(name, ok, detail) for what a node needs."""
+ out = [("python", sys.version_info >= (3, 12), sys.version.split()[0])]
+ for module in ("torch", "deepspeed", "ray", "transformers"):
+ try:
+ mod = __import__(module)
+ out.append((module, True, getattr(mod, "__version__", "")))
+ except Exception as e: # deepspeed raises more than ImportError without CUDA
+ out.append((module, False, f"{type(e).__name__}: {e}"[:70]))
+ gpus, gib = local_gpus()
+ out.append(("GPUs", gpus > 0, f"{gpus} x {gib:.0f} GiB" if gpus else "none visible"))
+ return out
+
+
+def node_ip() -> str:
+ """This machine's address on the network it would reach others through."""
+ with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
+ try:
+ s.connect(("10.255.255.255", 1)) # no packet is sent
+ return s.getsockname()[0]
+ except OSError:
+ return "127.0.0.1"
+
+
+def cluster_nodes(address: str | None) -> list[dict] | None:
+ """Alive nodes of the running Ray cluster, or None if there is none."""
+ import ray
+
+ try:
+ ray.init(address=address or "auto", logging_level="ERROR", log_to_driver=False)
+ except (ConnectionError, RuntimeError):
+ return None
+ try:
+ return [n for n in ray.nodes() if n["Alive"]]
+ finally:
+ ray.shutdown()
+
+
+def node_gpu_gib(nodes: list[dict]) -> float | None:
+ for node in nodes:
+ for key in node["Resources"]:
+ if key.startswith("accelerator_type:"):
+ return GPU_GIB.get(key.split(":", 1)[1])
+ return None
+
+
+def model_info(model: str) -> tuple[bool, bool, float | None]:
+ """(has a vision encoder, ties its embeddings, parameters or None) from the Hub."""
+ import transformers
+
+ config = transformers.AutoConfig.from_pretrained(model)
+ text = config.get_text_config() if hasattr(config, "get_text_config") else config
+ params = None
+ try:
+ import huggingface_hub
+
+ params = huggingface_hub.HfApi().model_info(model).safetensors.total
+ except Exception:
+ pass
+ vision = getattr(config, "vision_config", None) is not None
+ return vision, bool(getattr(text, "tie_word_embeddings", False)), params
+
+
+# -- prompts -------------------------------------------------------------------------------
+
+
+def interactive() -> bool:
+ return sys.stdin.isatty() and sys.stdout.isatty()
+
+
+def ask(question: str, default: str) -> str:
+ if not interactive():
+ return default
+ answer = input(f"{question} [{default}]: ").strip()
+ return answer or default
+
+
+def show(command: list[str], env: dict) -> str:
+ prefix = " ".join(f"{k}={v}" for k, v in env.items())
+ return (prefix + " " if prefix else "") + " ".join(shlex.quote(c) for c in command)
+
+
+# -- commands ------------------------------------------------------------------------------
+
+
+def token_path() -> Path:
+ """Where Ray keeps a node's cluster token (its token authentication)."""
+ return Path(os.environ.get("RAY_AUTH_TOKEN_PATH") or Path.home() / ".ray" / "auth_token")
+
+
+def cluster_token() -> str | None:
+ """The token a cluster started on this node requires of other nodes, or None if Ray's
+ token authentication is off."""
+ if os.environ.get("RAY_AUTH_MODE", "").lower() == "disabled":
+ return None
+ if os.environ.get("RAY_AUTH_TOKEN"):
+ return os.environ["RAY_AUTH_TOKEN"]
+ path = token_path()
+ return path.read_text().strip() if path.exists() else None
+
+
+def save_token(token: str) -> bool:
+ """Keep the cluster's token on this node, so its later Ray drivers (rdsp train) present it
+ too. False if the node already holds a different one, which stays."""
+ path = token_path()
+ if path.exists():
+ return path.read_text().strip() == token
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(token)
+ path.chmod(0o600)
+ return True
+
+
+def join_command(port: int) -> str:
+ """What every other node runs to join the cluster just started here."""
+ token = cluster_token()
+ return f"rdsp setup --join {node_ip()}:{port}" + (f" --token {token}" if token else "")
+
+
+def setup(args) -> int:
+ for name, ok, detail in check_environment():
+ print(f" {'ok ' if ok else 'MISSING'} {name:<13} {detail}")
+ beside = Path(sys.executable).parent / "ray" # this environment's, if it is not on PATH
+ ray_cli = shutil.which("ray") or (str(beside) if beside.exists() else None)
+ if ray_cli is None:
+ print("ray is not installed: run install.sh first", file=sys.stderr)
+ return 1
+ gpus, _ = local_gpus()
+ head, join = args.head, args.join
+ if not head and not join:
+ choice = ask("Start a new cluster on this node, or join one? (start/join)", "start")
+ head = choice.startswith("s")
+ join = None if head else ask("Address of the cluster's first node (host:port)", "")
+ if not head and not join:
+ print("an address is needed to join", file=sys.stderr)
+ return 1
+ if join and args.token is None:
+ args.token = ask("The cluster's token (printed by its first node; empty if none)", "")
+ token = None if head else (args.token or None)
+ command = [ray_cli, "start", "--disable-usage-stats", f"--num-gpus={gpus}"]
+ if head:
+ command += ["--head", f"--port={args.port}"]
+ else:
+ command += [f"--address={join if ':' in join else f'{join}:{args.port}'}"]
+ print(f"$ {show(command, {'RAY_AUTH_TOKEN': ''} if token else {})}")
+ if args.dry_run:
+ return 0
+ env = {**os.environ, "RAY_AUTH_TOKEN": token} if token else None
+ if subprocess.run(command, env=env).returncode != 0:
+ if not head:
+ print(
+ "could not join: check the address, and if the cluster uses token "
+ "authentication, pass the --token its first node printed",
+ file=sys.stderr,
+ )
+ return 1
+ if token and not save_token(token):
+ print(f"note: {token_path()} holds another cluster's token and was left as it is")
+ if head:
+ print(f"\nOn every other node:\n {join_command(args.port)}")
+ if cluster_token():
+ print("The token lets a machine join this cluster: share it only with your nodes.")
+ print("Then: rdsp nodes to check, and rdsp train MODEL to train.")
+ return 0
+
+
+def nodes(args) -> int:
+ found = cluster_nodes(args.address)
+ if found is None:
+ print("no Ray cluster running: run rdsp setup", file=sys.stderr)
+ return 1
+ for node in found:
+ resources = node["Resources"]
+ kinds = [k.split(":", 1)[1] for k in resources if k.startswith("accelerator_type:")]
+ kind = kinds[0] if kinds else ""
+ print(f" {node['NodeManagerAddress']:<16} {int(resources.get('GPU', 0))} GPUs {kind}")
+ total = sum(int(n["Resources"].get("GPU", 0)) for n in found)
+ print(f" {len(found)} node{'s' * (len(found) > 1)}, {total} GPUs")
+ return 0
+
+
+def plan(args, devices_per_node: list[int], device_gib: float) -> tuple[list[str], dict, str]:
+ """(command, environment, summary) for rdsp train."""
+ vision, tied, params = model_info(args.model)
+ if args.cpu and vision:
+ raise SystemExit("CPU runs train text models; vision-language models need NVIDIA GPUs")
+ par = choose_parallelism(
+ devices_per_node,
+ params,
+ device_gib,
+ pp=args.pipeline_parallel_size,
+ tp=args.tensor_parallel_size,
+ dp=args.data_parallel_size,
+ state_bytes=CPU_BYTES if args.cpu else GPU_BYTES,
+ shared_memory=args.cpu,
+ )
+ devices = sum(devices_per_node)
+ batch = args.batch_size or (2 if args.cpu else 8) * devices
+ seq = args.seq_len or (128 if args.cpu else 2048)
+ script = REPO / ("train_vl.py" if vision else "train.py")
+ if not script.exists():
+ raise SystemExit(f"{script.name} not found: rdsp train runs from a checkout of the repo")
+ command = [sys.executable, str(script), "--model", args.model]
+ command += ["--dataset" if vision else "--data", args.data or default_data(vision, args.cpu)]
+ command += ["--steps", str(args.steps), "--seq", str(seq), "--lr", str(args.lr)]
+ if not vision:
+ command += ["--dtype", "fp32" if args.cpu else "bf16"]
+ # --tune: time the stages first and re-cut by the times; a vision-language model's
+ # vision encoder also gets a stage of its own, sized by them (train_vl.py --cuts auto)
+ cuts = ("auto" if vision else "measured") if args.tune and par.pp > 1 else "balanced"
+ command += layout_flags(par, batch, cpu=args.cpu, cuts=cuts)
+ if vision and tied and par.pp > 1:
+ command.append("--untie-embeddings") # the tied pair would land on two stages
+ env = {}
+ if args.cpu: # a private Ray on DeepSpeed's CPU backend; each process gets its share of the
+ # cores (Ray otherwise gives an actor one thread)
+ threads = os.environ.get("OMP_NUM_THREADS") or max(1, (os.cpu_count() or 1) // devices)
+ env = {"RAY_ADDRESS": "local", "DS_ACCELERATOR": "cpu", "OMP_NUM_THREADS": str(threads)}
+ size = f"{params / 1e9:.2f}B parameters" if params else "size unknown"
+ unit = "process" if args.cpu else "GPU"
+ state = f", about {par.gib:.1f} GiB of training state a {unit}" if par.gib else ""
+ tuning = {
+ "auto": "\nTuning: time equal stages, give the vision encoder a stage sized by the times, "
+ "re-cut the decoder",
+ "measured": "\nTuning: time the stages, then re-cut by the times",
+ }.get(cuts, "\nTuning: one stage, nothing to tune" if args.tune else "")
+ summary = (
+ f"Model: {args.model} ({size}, {'vision-language' if vision else 'text'})\n"
+ f"Parallelism: pp={par.pp} tp={par.tp} dp={par.dp} ({par.why}{state}"
+ f"{', recompute' * par.recompute}){tuning}"
+ )
+ return command + list(args.extra), env, summary
+
+
+def default_data(vision: bool, cpu: bool) -> str:
+ return "synthetic" if cpu else ("cord-v2" if vision else "wikitext")
+
+
+def train(args) -> int:
+ found = None if args.cpu else cluster_nodes(args.address)
+ if found:
+ gpus = [g for g in (int(n["Resources"].get("GPU", 0)) for n in found) if g > 0]
+ where, device_gib = f"{sum(gpus)} GPUs on {len(gpus)} node(s)", node_gpu_gib(found)
+ else:
+ count, device_gib = (0, None) if args.cpu else local_gpus()
+ gpus = [count] if count else []
+ where = f"{count} GPUs on this machine"
+ if not gpus and not args.cpu:
+ print("No NVIDIA GPUs here or in a Ray cluster.")
+ if not interactive() or not ask("Train on this machine's CPU? (y/n)", "y").startswith("y"):
+ print("rdsp train MODEL --cpu trains on this machine's CPU", file=sys.stderr)
+ return 1
+ args.cpu = True
+ if args.cpu:
+ gpus = [args.devices or CPU_WORKERS]
+ device_gib = system_gib()
+ where = (
+ f"{gpus[0]} worker processes on this machine's CPU "
+ f"({os.cpu_count()} cores and {device_gib:.0f} GiB of memory, shared)"
+ )
+ elif args.devices:
+ if args.devices > sum(gpus):
+ raise SystemExit(f"--devices {args.devices}: only {sum(gpus)} GPUs found")
+ gpus = trim(gpus, args.devices)
+ where = f"{args.devices} of {where}"
+ if args.model is None:
+ args.model = ask("Model (a Hugging Face id)", "HuggingFaceTB/SmolLM2-135M")
+ device_gib = local_gpus()[1] or device_gib or 80.0 if not args.cpu else device_gib
+ command, env, summary = plan(args, gpus, device_gib)
+ print(f"Devices: {where}" + ("" if args.cpu else f", {device_gib:.0f} GiB each"))
+ print(f"{summary}\n\n{show(command, env)}\n", flush=True)
+ if args.dry_run:
+ return 0
+ if interactive() and not args.yes and not ask("Run it?", "Y").lower().startswith("y"):
+ return 0
+ run_env = {**os.environ, **env}
+ if found:
+ run_env.setdefault("RAY_ADDRESS", args.address or "auto")
+ return subprocess.run(command, env=run_env, cwd=REPO).returncode
+
+
+def trim(devices_per_node: list[int], wanted: int) -> list[int]:
+ """The first nodes' devices, up to wanted in all."""
+ out = []
+ for n in devices_per_node:
+ take = min(n, wanted - sum(out))
+ if take:
+ out.append(take)
+ return out
+
+
+def build_parser() -> argparse.ArgumentParser:
+ p = argparse.ArgumentParser(prog="rdsp", description="Pipeline-parallel training on Ray.")
+ sub = p.add_subparsers(dest="command", required=True)
+
+ s = sub.add_parser("setup", help="start or join a Ray cluster on this node")
+ s.add_argument("--head", action="store_true", help="start a new cluster here")
+ s.add_argument("--join", metavar="ADDRESS", help="join the cluster at host[:port]")
+ s.add_argument("--token", help="the cluster's token, when it uses Ray's token authentication")
+ s.add_argument("--port", type=int, default=6379)
+ s.add_argument("--dry-run", action="store_true", help="print the command only")
+ s.set_defaults(func=setup)
+
+ n = sub.add_parser("nodes", help="list the cluster's nodes and GPUs")
+ n.add_argument("--address", help="Ray cluster address (default: the running one)")
+ n.set_defaults(func=nodes)
+
+ t = sub.add_parser("train", help="train a Hugging Face model")
+ t.add_argument("model", nargs="?", help="Hugging Face model id")
+ t.add_argument("--data", help="cord-v2, wikitext, synthetic or exported:DIR")
+ t.add_argument("-pp", "--pipeline-parallel-size", type=int, metavar="N", help="stages")
+ t.add_argument("-tp", "--tensor-parallel-size", type=int, default=1, metavar="N")
+ t.add_argument("-dp", "--data-parallel-size", type=int, metavar="N", help="copies of a stage")
+ t.add_argument("--devices", type=int, help="GPUs to use (default all), or CPU processes")
+ t.add_argument("--cpu", action="store_true", help="train on this machine's CPU")
+ t.add_argument(
+ "--tune",
+ action="store_true",
+ help="time the stages for a few steps first and re-cut by the times; a vision-language "
+ "model's vision encoder also gets its own stage, sized by them",
+ )
+ t.add_argument("--steps", type=int, default=50)
+ t.add_argument("--batch-size", type=int, help="rows a step (default 8 a GPU, 2 a CPU process)")
+ t.add_argument("--seq-len", type=int, help="tokens a row (default 2048, 128 on CPU)")
+ t.add_argument("--lr", type=float, default=1e-5)
+ t.add_argument("--address", help="Ray cluster address (default: the running one)")
+ t.add_argument("-y", "--yes", action="store_true", help="run without asking")
+ t.add_argument("--dry-run", action="store_true", help="print the command only")
+ t.set_defaults(func=train)
+ return p
+
+
+def main(argv=None) -> int:
+ argv = list(sys.argv[1:] if argv is None else argv)
+ extra = argv[argv.index("--") + 1 :] if "--" in argv else [] # for the training script
+ args = build_parser().parse_args(argv[: len(argv) - len(extra) - bool(extra or "--" in argv)])
+ args.extra = extra
+ return args.func(args)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/training/rdsp/src/ray_deepspeed_pipeline/compiler.py b/training/rdsp/src/ray_deepspeed_pipeline/compiler.py
index 88746f3e6..b7c70dc9e 100644
--- a/training/rdsp/src/ray_deepspeed_pipeline/compiler.py
+++ b/training/rdsp/src/ray_deepspeed_pipeline/compiler.py
@@ -217,7 +217,13 @@ def _colocated_vision(model, pipeline_config: PipelineConfig, ds_config: dict |
f"embeddings"
)
partition = pipeline_config.partition
- if isinstance(partition, ExplicitCuts) and partition.cuts and partition.cuts[0] == 0:
+ first_only = pipeline_config.colocated_vision.first_stage_only
+ if (
+ isinstance(partition, ExplicitCuts)
+ and partition.cuts
+ and partition.cuts[0] == 0
+ and not first_only
+ ):
raise ValidationError(
"a first cut at 0 makes a vision-only first stage, which colocated vision "
"leaves empty; cut after at least one block"
@@ -229,7 +235,7 @@ def _colocated_vision(model, pipeline_config: PipelineConfig, ds_config: dict |
f"colocated vision puts it on no stage; use ColocatedVision(compile=True)"
)
conf = ds_config if isinstance(ds_config, dict) else {}
- kind = conf.get("optimizer", {}).get("type", "AdamW")
+ kind = (conf.get("optimizer") or {}).get("type", "AdamW")
if kind.lower() not in VISION_OPTIMIZERS:
raise ValidationError(f"colocated vision supports Adam, AdamW or SGD, got {kind!r}")
names = tuple(n for n, _ in model.named_parameters() if n.startswith(module + "."))
@@ -239,6 +245,8 @@ def _colocated_vision(model, pipeline_config: PipelineConfig, ds_config: dict |
recompute=pipeline_config.colocated_vision.recompute,
compile=pipeline_config.colocated_vision.compile,
encode_per_microbatch=(pipeline_config.colocated_vision.encode_per_microbatch),
+ first_stage_only=first_only,
+ encode_chunk=pipeline_config.colocated_vision.encode_chunk,
)
@@ -293,7 +301,7 @@ def lower(model, pipeline_config: PipelineConfig, ds_config: dict | None) -> Exe
if clip > 0:
raise ValidationError(
f"gradient_clipping={clip} would clip each stage by its own gradient "
- f"norm, which is not global-norm clipping; unsupported in v1 — set "
+ f"norm, which is not global-norm clipping; unsupported: set "
f"gradient_clipping to 0 (rdsp also turns off DeepSpeed's default "
f"of 1.0 for every stage)"
)
@@ -339,7 +347,6 @@ def lower(model, pipeline_config: PipelineConfig, ds_config: dict | None) -> Exe
block_stop=part.block_stop,
num_gpus=grid.world,
ds_config_json=_stage_ds_config(ds_config, override, rows // grid.dp, part.index),
- process_group_tag=f"stage{part.index}",
dp=grid.dp,
tp=grid.tp,
sp=grid.sp,
@@ -355,20 +362,6 @@ def lower(model, pipeline_config: PipelineConfig, ds_config: dict | None) -> Exe
)
)
- # a ConnectionOverride only asserts the conversion the layouts imply
- for conn in pipeline_config.connection_overrides:
- if conn.dest != conn.source + 1 or not 0 <= conn.source < n - 1:
- raise ValidationError(
- f"connection ({conn.source}->{conn.dest}) is not an adjacent forward "
- f"edge of a {n}-stage pipeline"
- )
- derived = conversion_name(grids[conn.source], grids[conn.dest])
- if conn.conversion is not None and conn.conversion != derived:
- raise ValidationError(
- f"connection {conn.source}->{conn.dest} declares conversion "
- f"{conn.conversion!r} but the stage layouts require {derived!r}"
- )
-
connections = tuple(
StageConnection(
source=i,
diff --git a/training/rdsp/src/ray_deepspeed_pipeline/config.py b/training/rdsp/src/ray_deepspeed_pipeline/config.py
index f5b1062c2..9ed194031 100644
--- a/training/rdsp/src/ray_deepspeed_pipeline/config.py
+++ b/training/rdsp/src/ray_deepspeed_pipeline/config.py
@@ -143,38 +143,26 @@ class StageOverride:
@dataclass(frozen=True)
class ColocatedVision:
"""Run the vision encoder on every GPU of the pipeline instead of on the
- first stage: each rank encodes a share of the step's images, the first
- stage receives their features (see vision.py). For vision encoders whose
- output enters the decoder only through the input embeddings (Qwen3.5;
- not Qwen3-VL's deepstack). The encoder trains with a plain torch
- optimizer (Adam/AdamW/SGD) built from the DeepSpeed config's optimizer
- and scheduler, with fp32 master weights and optimizer state split over
- all ranks. recompute: keep only each encoder block's input for backward.
- compile: torch.compile each encoder block (shapes dynamic).
- encode_per_microbatch: in training, encode each microbatch's images just ahead
- of the pipeline's need and backpropagate them as soon as their gradients
- exist, instead of all at the start and end of the step: a rank keeps
- graphs for about 2 x stages microbatches' images instead of the step's,
- but the encoder work lands inside the pipeline schedule (vision.py,
- vision_schedule), which slows the step when the encoder is heavy."""
+ first stage (vision.py). Each rank encodes a share of the step's images
+ and sends the features to the first stage. Only for encoders whose output
+ enters the decoder through the input embeddings (Qwen3.5, not Qwen3-VL).
+ The encoder trains with a torch Adam/AdamW/SGD built from the DeepSpeed
+ config, its fp32 master weights and optimizer state split over all ranks.
+
+ recompute: recompute each encoder block in backward.
+ compile: torch.compile each encoder block.
+ encode_per_microbatch: encode and backpropagate each microbatch's images
+ inside the pipeline schedule instead of all at the start and end of the
+ step. Less memory; slower when the encoder is heavy.
+ first_stage_only: only the first stage's GPUs encode, each its own rows'
+ images, in batches rather than inside each microbatch's forward.
+ encode_chunk: with encode_per_microbatch, microbatches per encoder call."""
recompute: bool = False
compile: bool = False
encode_per_microbatch: bool = False
-
-
-@dataclass(frozen=True)
-class ConnectionOverride:
- """Declares the tensor conversion on the edge from stage `source` to
- stage `source + 1` (identity, replicate-to-shard, shard-to-replicate or
- shard-to-shard). The conversion is always derived from the two stages'
- layouts; a declared one must match it, or lower() raises
- ValidationError. Use it to make a layout's expectation explicit."""
-
- source: int
- dest: int
- # None: derived from the two stages' layouts; if given, must match it.
- conversion: str | None = None
+ first_stage_only: bool = False
+ encode_chunk: int = 1
@dataclass(frozen=True)
@@ -186,7 +174,8 @@ class PipelineConfig:
microbatches: microbatches per step; None takes the DeepSpeed config's
gradient_accumulation_steps. stage_overrides: per-stage GPUs and
parallelism (StageOverride); stages without one get 1 GPU.
- colocated_vision, prefetch: see their comments below. Invalid
+ colocated_vision: run the vision encoder on every GPU (ColocatedVision).
+ prefetch: see its comment below. Invalid
combinations raise ValidationError when the config is built or lowered,
before any Ray actor exists."""
@@ -195,7 +184,6 @@ class PipelineConfig:
schedule: str = "1f1b"
microbatches: int | None = None
stage_overrides: tuple[StageOverride, ...] = ()
- connection_overrides: tuple[ConnectionOverride, ...] = ()
colocated_vision: ColocatedVision | None = None
# read the next training step's microbatches from the data iterator while
# this step runs, and ship them to the stages ahead of time. The caller
@@ -205,11 +193,10 @@ class PipelineConfig:
def __post_init__(self):
object.__setattr__(self, "stage_overrides", tuple(self.stage_overrides))
- object.__setattr__(self, "connection_overrides", tuple(self.connection_overrides))
if self.stages < 1:
raise ValidationError(f"stages must be >= 1, got {self.stages}")
if self.schedule != "1f1b":
- raise ValidationError(f"unsupported schedule {self.schedule!r}; v1 supports '1f1b'")
+ raise ValidationError(f"unsupported schedule {self.schedule!r}; rdsp runs '1f1b'")
if self.microbatches is not None and self.microbatches < 1:
raise ValidationError(f"microbatches must be positive, got {self.microbatches}")
if not isinstance(
@@ -242,9 +229,12 @@ def __post_init__(self):
raise ValidationError(
f"colocated_vision must be a ColocatedVision, got {type(self.colocated_vision)}"
)
- for connection in self.connection_overrides:
- if not isinstance(connection, ConnectionOverride):
+ if self.colocated_vision is not None:
+ chunk = self.colocated_vision.encode_chunk
+ if not isinstance(chunk, int) or chunk < 1:
+ raise ValidationError(f"ColocatedVision.encode_chunk must be >= 1, got {chunk}")
+ if chunk > 1 and not self.colocated_vision.encode_per_microbatch:
raise ValidationError(
- "connection_overrides entries must be ConnectionOverride, "
- f"got {type(connection)}"
+ "ColocatedVision.encode_chunk batches microbatches the encoder takes "
+ "one at a time: it needs encode_per_microbatch=True"
)
diff --git a/training/rdsp/src/ray_deepspeed_pipeline/coordinator.py b/training/rdsp/src/ray_deepspeed_pipeline/coordinator.py
index edaf3ac05..11ef27793 100644
--- a/training/rdsp/src/ray_deepspeed_pipeline/coordinator.py
+++ b/training/rdsp/src/ray_deepspeed_pipeline/coordinator.py
@@ -277,7 +277,13 @@ def _run(self, data_iter: Iterator, train: bool) -> float:
"the same iterator to every train_batch() call"
)
self._ahead = None
- entries, prepared = future.result() # raises if the iterator ran out
+ entries, prepared, error = future.result() # raises if the iterator ran out
+ if error is not None: # kept, so the retry runs this step's entries
+ self._retry = (data_iter, entries)
+ raise StepFailed(
+ f"preparing this step ahead failed before any stage started: "
+ f"{type(error).__name__}: {error}"
+ ) from error
else:
# consume exactly the step's microbatches before dispatching anything
entries = take_microbatch_entries(data_iter, self._plan.global_microbatches)
@@ -324,15 +330,19 @@ def _drop_read_ahead(self) -> None:
future.exception() # wait; its entries and errors are dropped
def _read_ahead(self, data_iter):
- """The next step's entries, and each stage's payload made ready."""
+ """The next step's entries, and each stage's payload made ready, or the
+ error that stopped it (the entries are returned either way)."""
entries = take_microbatch_entries(data_iter, self._plan.global_microbatches)
inputs, labels = [e[0] for e in entries], [e[1] for e in entries]
prepared = {}
- for s, worker in enumerate(self._workers):
- prepare = getattr(worker, "prepare", None)
- if prepare is not None:
- prepared[s] = prepare(**self._stage_payload(s, inputs, labels))
- return entries, prepared
+ try:
+ for s, worker in enumerate(self._workers):
+ prepare = getattr(worker, "prepare", None)
+ if prepare is not None:
+ prepared[s] = prepare(**self._stage_payload(s, inputs, labels))
+ except Exception as e:
+ return entries, None, e
+ return entries, prepared, None
def _run_step(self, sequences, inputs, labels, train: bool, prepared=None, ahead=None) -> list:
"""Send each stage its whole op list as one command; stages exchange
diff --git a/training/rdsp/src/ray_deepspeed_pipeline/data.py b/training/rdsp/src/ray_deepspeed_pipeline/data.py
index 809c718b9..d99c54e79 100644
--- a/training/rdsp/src/ray_deepspeed_pipeline/data.py
+++ b/training/rdsp/src/ray_deepspeed_pipeline/data.py
@@ -31,8 +31,7 @@ def take_microbatch_entries(data_iter, n: int) -> list[tuple]:
) from None
if not isinstance(entry, (tuple, list)) or len(entry) != 2:
raise ValidationError(
- f"entry {i} violates the v1 data contract: expected a 2-tuple "
- f"(inputs, labels), got {type(entry).__name__} "
+ f"entry {i} is not an (inputs, labels) pair: got {type(entry).__name__} "
f"of length {len(entry) if hasattr(entry, '__len__') else '?'}"
)
entries.append((entry[0], entry[1]))
diff --git a/training/rdsp/src/ray_deepspeed_pipeline/deepspeed_adapter.py b/training/rdsp/src/ray_deepspeed_pipeline/deepspeed_adapter.py
index bf70b2ec7..4b6599c35 100644
--- a/training/rdsp/src/ray_deepspeed_pipeline/deepspeed_adapter.py
+++ b/training/rdsp/src/ray_deepspeed_pipeline/deepspeed_adapter.py
@@ -22,6 +22,8 @@
from ray_deepspeed_pipeline.config import MASTER_WEIGHTS_KEY, OPTIMIZER_GROUP_NUMEL_KEY
from ray_deepspeed_pipeline.errors import CheckpointError, ValidationError
+from ray_deepspeed_pipeline.fused_grad_accumulation import GradAccumulation, fuse_linear_grads
+from ray_deepspeed_pipeline.tp_input_grads import share_input_grad_reductions
# TP plan style -> AutoTP layer spec fields
_TP_SPECS = {
@@ -189,6 +191,59 @@ def _with_immediate_grad_update(conf: dict) -> dict:
return conf
+def _without_throughput_timer(conf: dict) -> dict:
+ """DeepSpeed's throughput timer off. With no DeepSpeed data loader (a stage
+ engine never has one) it synchronizes the whole device before every forward
+ and at every step, from its third step on. A device-wide sync also waits for
+ this rank's async sends, which finish only when the neighbouring stage
+ receives, so every microbatch would wait for the other stages. The timer
+ only feeds DeepSpeed's own throughput printout; the driver times steps
+ itself. An explicit "timers" setting in the config is kept."""
+ conf.setdefault("timers", {"throughput": {"enabled": False}})
+ return conf
+
+
+def _without_division_by_one(engine) -> None:
+ """The engine divides the gradient of every module output by
+ gradient_accumulation_steps, which a stage engine sets to 1: a copy of that
+ gradient per microbatch, as large as the whole logits tensor on the last
+ stage."""
+ if getattr(engine, "_backward_prologue_per_tensor", None) is not None and (
+ engine.gradient_accumulation_steps() == 1
+ ):
+ engine._backward_prologue_per_tensor = lambda grad: grad
+
+
+def _plain_stage_gradients(ds_config: dict) -> bool:
+ """Whether the stage accumulates gradients in param.grad and nothing rewrites them on the way:
+ ZeRO 0 or 1 without offload or expert parallelism. Elsewhere (ZeRO 2 and 3 partition or move
+ the gradients, offload and AutoEP handle them in their own hooks) the layers keep autograd's
+ own accumulation."""
+ zero = ds_config.get("zero_optimization") or {}
+ if int(zero.get("stage", 0) or 0) > 1:
+ return False
+ if any(zero.get(k) for k in ("offload_optimizer", "offload_param")):
+ return False
+ ep = ds_config.get("expert_parallel") or {}
+ return int(ep.get("autoep_size", 1) or 1) <= 1
+
+
+def _without_unused_grad_norm(optimizer) -> None:
+ """DeepSpeed's ZeRO-1/2 step computes the gradient norm of every optimizer group, with one
+ all-reduce and one host read each, and multiplies the gradients by one over the loss scale,
+ whether or not anything clips or scales. Both are used only by clipping and loss scaling,
+ so without either (bf16, no clipping) they are skipped. engine.get_global_grad_norm() then
+ reports 0."""
+ if type(optimizer).__name__ != "DeepSpeedZeroOptimizer": # the ZeRO-1/2 optimizer
+ return
+ clip = float(getattr(optimizer, "clip_grad", 0.0) or 0.0)
+ scaler = getattr(optimizer, "loss_scaler", None)
+ if clip > 0 or getattr(scaler, "dynamic", False) or float(optimizer.loss_scale) != 1.0:
+ return
+ optimizer.scaled_global_norm = lambda norm_type=2: torch.zeros(())
+ optimizer.unscale_and_clip_grads = lambda grad_groups_flat, total_norm: None
+
+
def _free_bf16_grads_after_accumulating(optimizer) -> None:
"""Under immediate_grad_update, free each parameter's bf16 gradient once
it is in the fp32 buffer. DeepSpeed only zeroes it, so a bf16 copy of
@@ -317,6 +372,7 @@ def _deepspeed_engine_factory(stage_module, ds_config: dict):
import deepspeed
conf = _with_immediate_grad_update(json.loads(json.dumps(ds_config))) # deep copy
+ conf = _without_throughput_timer(conf)
conf["gradient_accumulation_steps"] = 1 # the coordinator accumulates (module doc)
group_numel = int(conf.pop(OPTIMIZER_GROUP_NUMEL_KEY, 0) or 0)
remainder_optimizer = _remainder_optimizer(conf)
@@ -464,9 +520,20 @@ def __init__(
stage_module._rdsp_logit_shards = bool(getattr(loss_fn, "takes_vocab_shards", False))
self.engine = (engine_factory or _deepspeed_engine_factory)(stage_module, ds_config)
self.device = next(self.engine.module.parameters()).device
+ _without_division_by_one(self.engine)
+ _without_unused_grad_norm(getattr(self.engine, "optimizer", None))
_free_bf16_grads_after_accumulating(getattr(self.engine, "optimizer", None))
self._install_tp_grad_allreduce()
self._install_folded_moe_grad_average()
+ self._accumulation = GradAccumulation()
+ fused = os.environ.get("RDSP_FUSED_GRAD_ADD", "1") != "0" and _plain_stage_gradients(
+ ds_config
+ )
+ if fused:
+ fuse_linear_grads(self.engine.module, self._accumulation)
+ if os.environ.get("RDSP_SHARE_TP_ALLREDUCE", "1") != "0":
+ # an unfused run keeps autograd's accumulation here too
+ share_input_grad_reductions(self.engine.module, self._accumulation if fused else None)
self._rng_at_generation_start = None
self._acts = {} # mb -> (input_leaf_or_None, output)
self._losses = {} # mb -> graph loss (terminal only)
@@ -592,8 +659,10 @@ def backward(self, mb: int, grad=None):
# ZeRO-1/2 otherwise treat every backward as one and overwrite (not add)
# the reduced gradient, keeping only the last microbatch's
set_boundary = getattr(self.engine, "set_gradient_accumulation_boundary", None)
+ last = self._backwards == self.n_mb - 1
if set_boundary is not None:
- set_boundary(self._backwards == self.n_mb - 1)
+ set_boundary(last)
+ self._accumulation.fuse = not last
if self.is_last:
loss = self._losses.pop(mb)
self.engine.backward(loss / self.n_mb) # summed grads = full-step mean
diff --git a/training/rdsp/src/ray_deepspeed_pipeline/errors.py b/training/rdsp/src/ray_deepspeed_pipeline/errors.py
index da34d19f8..a35375f7b 100644
--- a/training/rdsp/src/ray_deepspeed_pipeline/errors.py
+++ b/training/rdsp/src/ray_deepspeed_pipeline/errors.py
@@ -12,8 +12,8 @@ class ValidationError(RdspError):
"""A public argument failed validation before any actor work."""
-class UnsupportedInV1(ValidationError):
- """A deepspeed.initialize() argument form this package rejects (e.g. a
+class UnsupportedFeature(ValidationError):
+ """A deepspeed.initialize() argument form rdsp does not run (e.g. a
preconstructed optimizer)."""
diff --git a/training/rdsp/src/ray_deepspeed_pipeline/fused_grad_accumulation.py b/training/rdsp/src/ray_deepspeed_pipeline/fused_grad_accumulation.py
new file mode 100644
index 000000000..53887583f
--- /dev/null
+++ b/training/rdsp/src/ray_deepspeed_pipeline/fused_grad_accumulation.py
@@ -0,0 +1,145 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+
+"""Weight gradients of linear layers and embeddings added straight into .grad.
+
+Autograd computes a linear layer's weight gradient into a new tensor as large as the weight and
+then adds it to .grad: two kernels that each move every weight byte, once per microbatch. A
+step with many small microbatches (one row each) spends more on that than on the matmul's own
+gradient. Here the matmul that computes the gradient adds it: grad = grad + g^T x in one call
+(Megatron-LM's gradient accumulation fusion).
+
+An embedding's gradient is zero but for the rows its tokens read. Autograd fills a tensor the
+size of the vocabulary with it and adds that; here only those rows are added to.
+
+The last microbatch of a step takes autograd's own path, so the optimizer's hooks, which reduce
+a parameter's gradient when its last one is in, see it as usual.
+"""
+
+import functools
+import sys
+
+import torch
+import torch.nn as nn
+
+from ray_deepspeed_pipeline.tp_input_grads import GradAccumulation, add_weight_grad, flag
+from ray_deepspeed_pipeline.vision import ENCODER_NAMES
+
+__all__ = ["GradAccumulation", "fuse_linear_grads"]
+
+
+class _FusedLinear(torch.autograd.Function):
+ @staticmethod
+ def forward(ctx, x, weight, state):
+ ctx.state, ctx.weight = state, weight # a leaf: its .grad is what backward adds to
+ ctx.save_for_backward(x)
+ return torch.matmul(x, weight.transpose(-1, -2))
+
+ @staticmethod
+ def backward(ctx, grad):
+ (x,), weight = ctx.saved_tensors, ctx.weight
+ grad_x = grad.matmul(weight) if ctx.needs_input_grad[0] else None
+ grad_w = None
+ if ctx.needs_input_grad[1]:
+ grad_w = add_weight_grad(weight, grad, x, ctx.state)
+ return grad_x, grad_w, None
+
+
+class _FusedEmbedding(torch.autograd.Function):
+ @staticmethod
+ def forward(ctx, ids, weight, state):
+ ctx.state, ctx.weight = state, weight
+ ctx.save_for_backward(ids)
+ return torch.nn.functional.embedding(ids, weight)
+
+ @staticmethod
+ def backward(ctx, grad):
+ (ids,), weight = ctx.saved_tensors, ctx.weight
+ rows, flat = grad.reshape(-1, grad.shape[-1]), ids.reshape(-1)
+ if ctx.state.fuse and weight.grad is not None:
+ weight.grad.index_add_(0, flat, rows.to(weight.grad.dtype))
+ return None, None, None
+ grad_w = torch.zeros_like(weight)
+ return None, grad_w.index_add_(0, flat, rows.to(grad_w.dtype)), None
+
+
+def _embedding_forward(layer, state, ids):
+ return _FusedEmbedding.apply(ids, layer.weight, state)
+
+
+def _plain_embedding(layer) -> bool:
+ return type(layer) is nn.Embedding and not any(
+ (
+ layer.padding_idx is not None,
+ layer.max_norm is not None,
+ layer.scale_grad_by_freq,
+ layer.sparse,
+ )
+ )
+
+
+def _matmul(state, x, weight):
+ return _FusedLinear.apply(x, weight, state)
+
+
+def _forward(layer, state, x):
+ out = _matmul(state, x, layer.weight)
+ return out if layer.bias is None else out + layer.bias
+
+
+def _row_split_forward(layer, state, x):
+ """DeepSpeed's LinearAllreduce: the ranks' partial outputs summed."""
+ from deepspeed.module_inject.layers import RowParallel, add_bias
+
+ out = _matmul(state, x, layer.weight)
+ if not flag(layer, "defer_collectives_to_compiler"):
+ out = RowParallel.apply(layer.mp_group, out, not layer.is_training_mode())
+ return out if layer.bias is None else add_bias(out, layer.bias)
+
+
+def _column_split_forward(layer, state, x):
+ """DeepSpeed's LinearLayer with its own input-gradient all-reduce."""
+ from deepspeed.module_inject.layers import ColumnParallel, add_bias
+
+ if layer.mp_group is not None and not flag(layer, "defer_collectives_to_compiler"):
+ x = ColumnParallel.apply(layer.mp_group, x)
+ out = _matmul(state, x, layer.weight)
+ return out if layer.bias is None else add_bias(out, layer.bias)
+
+
+def _tensor_parallel_forward(layer, state):
+ """The fused forward of a layer AutoTP split, or None if it is not one. DeepSpeed is not
+ imported for it: only an imported DeepSpeed has split anything."""
+ layers = sys.modules.get("deepspeed.module_inject.layers")
+ if layers is None:
+ return None
+ if type(layer) is layers.LinearAllreduce:
+ return functools.partial(_row_split_forward, layer, state)
+ if type(layer) is layers.LinearLayer and not any(
+ flag(layer, name) for name in ("gather_output", "tp_overlap_comm")
+ ):
+ return functools.partial(_column_split_forward, layer, state)
+ return None
+
+
+def fuse_linear_grads(root: nn.Module, state: GradAccumulation) -> list[str]:
+ """Run root's linear layers, plain and AutoTP's, and its embeddings with fused gradient
+ accumulation. Returns their names. Call it before
+ tp_input_grads.share_input_grad_reductions, which keeps these forwards for the calls it
+ cannot join. Left alone: vision encoders (some are compiled), frozen weights, any other
+ kind of layer."""
+ done = []
+ for name, layer in root.named_modules():
+ weight = getattr(layer, "weight", None)
+ if set(name.split(".")) & set(ENCODER_NAMES) or not getattr(weight, "requires_grad", False):
+ continue
+ if type(layer) is nn.Linear:
+ layer.forward = functools.partial(_forward, layer, state)
+ elif _plain_embedding(layer):
+ layer.forward = functools.partial(_embedding_forward, layer, state)
+ elif (forward := _tensor_parallel_forward(layer, state)) is not None:
+ layer.forward = forward
+ else:
+ continue
+ done.append(name)
+ return done
diff --git a/training/rdsp/src/ray_deepspeed_pipeline/gated_norm.py b/training/rdsp/src/ray_deepspeed_pipeline/gated_norm.py
new file mode 100644
index 000000000..13aef7d31
--- /dev/null
+++ b/training/rdsp/src/ray_deepspeed_pipeline/gated_norm.py
@@ -0,0 +1,38 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+
+"""Qwen3.5's gated RMSNorm (inside the gated delta-net) on PyTorch's fused kernel.
+
+Hugging Face's runs about a dozen elementwise kernels forward, and twice as many in backward, on
+the widest tensor of the layer. Here the norm is one kernel. The math is the same; the norm's
+weight and the gate are applied in fp32 as HF does, and HF's bf16 rounding between them is not
+repeated."""
+
+import functools
+
+import torch
+import torch.nn as nn
+
+
+def _gated_rms_norm(norm, hidden_states, gate):
+ x = torch.nn.functional.rms_norm(
+ hidden_states.float(),
+ (hidden_states.shape[-1],),
+ norm.weight.float(),
+ norm.variance_epsilon,
+ )
+ return (x * torch.nn.functional.silu(gate.float())).type_as(hidden_states)
+
+
+def fuse_gated_norms(root: nn.Module) -> int:
+ """Run root's gated RMSNorms on the fused kernel, instance by instance (the patch travels
+ with the stage modules to their workers). Returns how many."""
+ fused = 0
+ for module in root.modules():
+ if type(module).__name__ != "Qwen3_5RMSNormGated" or "forward" in vars(module):
+ continue
+ if getattr(module, "activation", None) != "silu":
+ continue
+ module.forward = functools.partial(_gated_rms_norm, module)
+ fused += 1
+ return fused
diff --git a/training/rdsp/src/ray_deepspeed_pipeline/hf_stage.py b/training/rdsp/src/ray_deepspeed_pipeline/hf_stage.py
index 4c084a74d..90440b42f 100644
--- a/training/rdsp/src/ray_deepspeed_pipeline/hf_stage.py
+++ b/training/rdsp/src/ray_deepspeed_pipeline/hf_stage.py
@@ -18,6 +18,7 @@
arguments; blocks sharing the same tensors are sent as one group.
"""
+import contextlib
import copy
import json
import os
@@ -147,6 +148,26 @@ def _unpack(extras: dict) -> dict:
return per_block
+@contextlib.contextmanager
+def _no_packed_rows():
+ """Hugging Face's mask setup without its search for several sequences packed in one row,
+ which reads a value back from the GPU in every forward."""
+ try:
+ from transformers import masking_utils
+ except ImportError:
+ yield
+ return
+ real = getattr(masking_utils, "find_packed_sequence_indices", None)
+ if real is None: # a version that does not search
+ yield
+ return
+ masking_utils.find_packed_sequence_indices = lambda position_ids: None
+ try:
+ yield
+ finally:
+ masking_utils.find_packed_sequence_indices = real
+
+
class HFModelStage(nn.Module):
"""forward(x=None, position_ids=None, **kwargs). Stage 0: the model's
inputs, as x (input ids) or as keyword tensors. Later stages: x is the
@@ -290,7 +311,10 @@ def forward(self, x=None, position_ids=None, **kwargs):
kw["position_ids"] = position_ids
try:
if not self.is_first:
- out = self.model(inputs_embeds=self._setup_input(x), **kw)
+ # positions here are the row's own (a shard's, under sequence
+ # parallelism): nothing packed; the masks blocks get come from upstream
+ with _no_packed_rows():
+ out = self.model(inputs_embeds=self._setup_input(x), **kw)
elif isinstance(x, dict):
out = self.model(**x, **kw)
else:
@@ -517,3 +541,25 @@ def load_meta_parameters(stage: nn.Module, weights_dir: str | None) -> None:
stage.get_submodule(module_name)._parameters[leaf] = nn.Parameter(
value, requires_grad=param.requires_grad
)
+ if isinstance(stage, HFModelStage):
+ _tie_embeddings(stage.model)
+
+
+def ties_embeddings(model: nn.Module) -> bool:
+ """Whether the model's config shares one weight between the input embedding and the
+ output head (tie_word_embeddings, on the text config where there is one)."""
+ config = getattr(model, "config", None)
+ text = config.get_text_config() if hasattr(config, "get_text_config") else config
+ return bool(getattr(text, "tie_word_embeddings", False))
+
+
+def _tie_embeddings(model: nn.Module) -> None:
+ """Share the input embedding's weight with the output head when the config ties them and
+ this stage holds both. A model built under init_empty_weights is not tied, and loading
+ fills the head from the embedding's tensor as a copy of its own."""
+ if not ties_embeddings(model):
+ return
+ embedding, head = model.get_input_embeddings(), model.get_output_embeddings()
+ if head is None or isinstance(embedding, _Unowned) or isinstance(head, _Unowned):
+ return
+ head.weight = embedding.weight
diff --git a/training/rdsp/src/ray_deepspeed_pipeline/linear_attention_parallel.py b/training/rdsp/src/ray_deepspeed_pipeline/linear_attention_parallel.py
index 29daef4a5..a09da834f 100644
--- a/training/rdsp/src/ray_deepspeed_pipeline/linear_attention_parallel.py
+++ b/training/rdsp/src/ray_deepspeed_pipeline/linear_attention_parallel.py
@@ -100,6 +100,7 @@ def span(start, width):
layer.conv_dim = len(qkv)
layer.norm.weight.register_hook(functools.partial(_summed, group=group))
+ layer._rdsp_input_group = group # tp_input_grads: whose input projections may share this
layer.register_forward_pre_hook(
functools.partial(_sum_input_grad, group=group), with_kwargs=True
)
@@ -113,6 +114,8 @@ def _summed(grad: torch.Tensor, group) -> torch.Tensor:
def _sum_input_grad(module, args, kwargs, group):
+ if getattr(module, "_rdsp_joint_inputs", False): # tp_input_grads does it
+ return None
if "hidden_states" in kwargs:
kwargs = dict(
kwargs, hidden_states=SumGradOverRanks.apply(kwargs["hidden_states"], group())
diff --git a/training/rdsp/src/ray_deepspeed_pipeline/losses.py b/training/rdsp/src/ray_deepspeed_pipeline/losses.py
index 353fc85d7..6664f7533 100644
--- a/training/rdsp/src/ray_deepspeed_pipeline/losses.py
+++ b/training/rdsp/src/ray_deepspeed_pipeline/losses.py
@@ -14,22 +14,31 @@
from collections.abc import Callable
from dataclasses import dataclass
+from ray_deepspeed_pipeline.vocab_parallel import next_token_loss_sum
+
+
+def next_token_count(labels, ignore_index: int = -100) -> int:
+ """Tokens next_token_loss_sum counts: every label after the first that is
+ not ignore_index."""
+ return int((labels[:, 1:] != ignore_index).sum())
+
@dataclass(frozen=True)
class TokenMeanLoss:
"""loss_fn whose step loss is (summed token loss over all microbatches
and ranks) / (their token count). sum_fn(outputs, labels): the summed
- per-token loss of one rank's rows; count_fn(labels): how many tokens it
- sums. The driver counts the step's tokens from the labels before the
- step, so every backward already carries the final weight.
+ per-token loss of one rank's rows (default: next-token cross entropy);
+ count_fn(labels): how many tokens it sums. The driver counts the step's
+ tokens from the labels before the step, so every backward already
+ carries the final weight.
per_microbatch: train instead on each rank's microbatch's own token mean,
averaged over microbatches and ranks (Megatron's default, without
calculate_per_token_loss), while still reporting the step's token mean,
as Megatron logs it."""
- sum_fn: Callable
- count_fn: Callable
+ sum_fn: Callable = next_token_loss_sum
+ count_fn: Callable = next_token_count
per_microbatch: bool = False
def __call__(self, outputs, labels):
diff --git a/training/rdsp/src/ray_deepspeed_pipeline/p2p.py b/training/rdsp/src/ray_deepspeed_pipeline/p2p.py
index 8ce623f3d..85093b2bf 100644
--- a/training/rdsp/src/ray_deepspeed_pipeline/p2p.py
+++ b/training/rdsp/src/ray_deepspeed_pipeline/p2p.py
@@ -11,9 +11,9 @@
Why two groups: NCCL runs a communicator's point-to-point ops in issue order,
so with one shared group a stage's gradient receive could queue behind its
own activation send (and its neighbour's behind theirs) and deadlock. One
-direction per group keeps each group's dependencies acyclic. Sends are async
-and kept alive until the step ends; receives block, and 1F1B order
-guarantees each one's matching send is eventually issued.
+direction per group keeps each group's dependencies acyclic. Sends are async;
+each tensor is kept alive until its send has finished. Receives block, and
+1F1B order guarantees each one's matching send is eventually issued.
When a step's microbatches are equal-sized, each (direction, peer, slot)
sends its shape header once per step; both ends walk microbatches in the same
@@ -91,7 +91,7 @@ def __init__(
self.cpu = dist.ProcessGroupGloo(
dist.PrefixStore(f"e{epoch}/cpu", store), rank, world, timeout
)
- self._pending = [] # (work, tensor) sends in flight this step
+ self._pending = [] # (work, tensor) sends not known to have finished
self._shapes = {} # (direction, peer, slot) -> decoded header, this step
self._varying = False # this step's microbatches differ in length
self._announced = set() # (direction, peer, slot) already sent a header this step
@@ -135,6 +135,18 @@ def end_step(self) -> None:
for work, _ in pending:
work.wait()
+ def _drop_finished(self) -> None:
+ """Let go of the tensors whose sends have finished. Holding all of a
+ step's boundary tensors until end_step costs the sending rank two per
+ microbatch on a middle stage. wait() raises what end_step would have."""
+ in_flight = []
+ for work, t in self._pending:
+ if work.is_completed():
+ work.wait()
+ else:
+ in_flight.append((work, t))
+ self._pending = in_flight
+
# -- transfers -------------------------------------------------------------
def _pg(self, direction: str):
@@ -144,6 +156,7 @@ def send(
self, direction: str, t: torch.Tensor, peer: int, mb: int, slot: int = 0, n_extras: int = 0
) -> None:
pg = self._pg(direction)
+ self._drop_finished()
t = t.detach().contiguous()
if (direction, peer, slot) not in self._announced or (self._varying and slot != 1):
self._announced.add((direction, peer, slot))
diff --git a/training/rdsp/src/ray_deepspeed_pipeline/partition.py b/training/rdsp/src/ray_deepspeed_pipeline/partition.py
index c862e9d31..145adae2b 100644
--- a/training/rdsp/src/ray_deepspeed_pipeline/partition.py
+++ b/training/rdsp/src/ray_deepspeed_pipeline/partition.py
@@ -281,6 +281,26 @@ def fits(s, j, i):
)
+def vision_stage_gpus(measured, n_blocks: int, stage_gpus: int, total_gpus: int) -> int | None:
+ """GPUs for a vision-only first stage, from steps measured on equal stages of stage_gpus
+ GPUs each (the vision encoder on stage 0 with some decoder blocks): the count, a multiple
+ of stage_gpus, that minimizes the slower of the vision encoder's time over its GPUs and
+ the decoder's over the rest. Decoder time per block comes from the stages after the first
+ (the middle ones when there are, else the last one, whose time includes the head). None if
+ no count leaves GPUs for the decoder."""
+ ranges = measured.block_ranges(n_blocks)
+ later = range(1, len(ranges) - 1) if len(ranges) > 2 else range(1, len(ranges))
+ blocks = sum(ranges[s][1] - ranges[s][0] for s in later)
+ options = range(stage_gpus, total_gpus, stage_gpus)
+ if not blocks or not options:
+ return None
+ rate = sum(measured.seconds[s] for s in later) / blocks
+ first = ranges[0][1] - ranges[0][0]
+ vision = max(0.0, measured.seconds[0] - first * rate) * stage_gpus # GPU-seconds a step
+ decoder = sum(measured.seconds) * stage_gpus - vision
+ return min(options, key=lambda k: max(vision / k, decoder / (total_gpus - k)))
+
+
def _decoder_stages(measured):
"""A vision-only first stage's measurements left out: the decoder stages' own, for
re-cutting the decoder alone. The vision stage keeps its GPUs and its cut at 0."""
@@ -368,8 +388,12 @@ def stage_of_block(b: int) -> int:
first_block, last_block = block_positions[0], block_positions[-1]
# a vision-only first stage (first cut at 0) holds only the vision
- # encoder; the embeddings go to the first decoder stage
- encoder = _vision_encoder_path(model) if stages > 1 and bounds[1] == 0 else None
+ # encoder; the embeddings go to the first decoder stage. With the encoder
+ # on no stage (colocated vision on the first stage's GPUs) that first stage
+ # keeps the embeddings and receives the features, as any first stage does.
+ encoder = (
+ _vision_encoder_path(model) if stages > 1 and bounds[1] == 0 and exclude is None else None
+ )
assignment: dict[str, int] = {}
by_id: dict[int, list[str]] = {}
for i, (name, param) in enumerate(named):
@@ -383,17 +407,18 @@ def stage_of_block(b: int) -> int:
else:
raise ValidationError(
f"parameter {name} is interleaved with the block list; "
- f"v1 supports strictly sequential layouts only"
+ f"rdsp supports strictly sequential layouts only"
)
assignment[name] = stage
by_id.setdefault(id(param), []).append(name)
+ _check_declared_tie(model, named, assignment)
for names in by_id.values():
stage_set = {assignment[n] for n in names}
if len(stage_set) > 1:
raise ValidationError(
f"tied parameters {names} land on stages {sorted(stage_set)}: "
- f"cross-stage tied parameters are unsupported in v1 — untie "
+ f"cross-stage tied parameters are unsupported: untie "
f"them (e.g. tie_word_embeddings=False) or change the partition"
)
@@ -408,6 +433,27 @@ def stage_of_block(b: int) -> int:
)
+def _check_declared_tie(model: nn.Module, named: list, assignment: dict) -> None:
+ """Reject a model whose config ties the input embedding to the output head when the two
+ land on different stages: a skeleton built under init_empty_weights holds them as two
+ meta tensors, so the identity check below cannot see the tie, and each stage would
+ train its own copy."""
+ from ray_deepspeed_pipeline.hf_stage import ties_embeddings # imports this module
+
+ if not hasattr(model, "get_input_embeddings") or not ties_embeddings(model):
+ return
+ embedding, head = model.get_input_embeddings(), model.get_output_embeddings()
+ if head is None or getattr(embedding, "weight", None) is None:
+ return
+ where = {id(p): assignment[n] for n, p in named if n in assignment}
+ stages = {where.get(id(embedding.weight)), where.get(id(head.weight))}
+ if None not in stages and len(stages) > 1:
+ raise ValidationError(
+ f"the config ties the input embedding to the output head, which land on stages "
+ f"{sorted(stages)}; set tie_word_embeddings=False (untie them) or change the partition"
+ )
+
+
class GenericSequentialStage(nn.Module):
"""Pre-modules, a block slice and post-modules chained sequentially. For
models whose blocks take only the previous output."""
@@ -559,6 +605,12 @@ def owns(sub):
head=copy.deepcopy(model.lm_head) if any(n.startswith("lm_head.") for n in names) else None,
rotary=copy.deepcopy(parent.rotary_emb),
)
+ if (
+ stage.emb is not None
+ and stage.head is not None
+ and (model.lm_head.weight is parent.embed_tokens.weight)
+ ): # copied apart above: one weight again, as in the model
+ stage.head.weight = stage.emb.weight
attach_tp_plan(stage, getattr(getattr(model, "config", None), "base_model_tp_plan", None))
# attention implementation, head counts and MoE routing for the engine.
# Not named `config`: DeepSpeed would prefer HF's unfiltered TP plan.
@@ -576,7 +628,7 @@ def owns(sub):
def select_stage_builder(model: nn.Module):
"""The stage builder a model needs, decided from its structure.
- HF causal LMs of a _CAUSAL_LM_TYPES type with the llama-style layout
+ HF causal LMs of a _CAUSAL_LM_TYPES type with real weights and the llama-style layout
(`embed_tokens`, `norm` and `rotary_emb` next to the block list, `lm_head`
at the top) get build_causal_lm_stage, unless they use eager attention:
that stage passes no mask, which SDPA and flash attention read as causal
@@ -593,8 +645,10 @@ def select_stage_builder(model: nn.Module):
config = getattr(model, "config", None)
model_type = getattr(config, "model_type", None)
eager = getattr(config, "_attn_implementation", None) == "eager"
+ skeleton = any(p.is_meta for p in model.parameters()) # weights load per stage: HF builder
if (
- model_type in _CAUSAL_LM_TYPES
+ not skeleton
+ and model_type in _CAUSAL_LM_TYPES
and not eager
and present == set(_CAUSAL_LM_PARTS)
and has_head
diff --git a/training/rdsp/src/ray_deepspeed_pipeline/plan.py b/training/rdsp/src/ray_deepspeed_pipeline/plan.py
index ab59138a8..83f658a97 100644
--- a/training/rdsp/src/ray_deepspeed_pipeline/plan.py
+++ b/training/rdsp/src/ray_deepspeed_pipeline/plan.py
@@ -12,7 +12,7 @@
import json
from dataclasses import dataclass
-SCHEMA_VERSION = "4"
+SCHEMA_VERSION = "5"
@dataclass(frozen=True)
@@ -27,7 +27,6 @@ class StageSpec:
num_gpus: int
# canonical JSON of this stage's ordinary DeepSpeed config
ds_config_json: str
- process_group_tag: str
# stage-local rank grid (num_gpus = dp * sp * tp); ep folds onto it
dp: int = 1
tp: int = 1
@@ -69,6 +68,8 @@ class VisionSpec:
recompute: bool = False
compile: bool = False
encode_per_microbatch: bool = False
+ first_stage_only: bool = False
+ encode_chunk: int = 1
# fields that change how a step runs, not a stage's parameters or saved state
@@ -80,6 +81,8 @@ class VisionSpec:
"compile",
"compile_vision",
"encode_per_microbatch",
+ "first_stage_only",
+ "encode_chunk",
}
)
diff --git a/training/rdsp/src/ray_deepspeed_pipeline/protocols.py b/training/rdsp/src/ray_deepspeed_pipeline/protocols.py
index 778042cac..a975b06b5 100644
--- a/training/rdsp/src/ray_deepspeed_pipeline/protocols.py
+++ b/training/rdsp/src/ray_deepspeed_pipeline/protocols.py
@@ -1,26 +1,12 @@
# SPDX-License-Identifier: Apache-2.0
# DeepSpeed Team
-"""Internal contracts: the engine/coordinator seam and the worker command protocol."""
+"""The command a stage worker runs, and resolving a worker's result."""
import dataclasses
import json
-from collections.abc import Iterator
from dataclasses import dataclass
-from typing import Any, Protocol
-
-# "step"/"eval_step" carry a stage's whole op list for one step (stage-local dispatch)
-COMMAND_KINDS = (
- "forward",
- "backward",
- "ready",
- "apply",
- "eval",
- "save",
- "load",
- "step",
- "eval_step",
-)
+from typing import Any
@dataclass(frozen=True)
@@ -34,7 +20,9 @@ class Command:
generation: int
global_step: int
stage: int
- kind: str # one of COMMAND_KINDS
+ # forward, backward, eval, ready (inside a stage's "step"/"eval_step" op list), apply,
+ # save, load
+ kind: str
microbatch: int | None
predecessors: tuple[str, ...]
@@ -45,28 +33,6 @@ def canonical_json(self) -> str:
return json.dumps(self.to_canonical_dict(), sort_keys=True, separators=(",", ":"))
-@dataclass(frozen=True)
-class CommandResult:
- command_id: str
- status: str # "ok" | "failed"
- detail: str = ""
-
-
-class Coordinator(Protocol):
- """Runs one global step at a time and owns global_steps."""
-
- @property
- def global_steps(self) -> int: ...
-
- def train_batch(self, data_iter: Iterator) -> Any: ...
-
- def eval_batch(self, data_iter: Iterator) -> Any: ...
-
- def save_checkpoint(self, save_dir: str, tag: str | None, **kwargs) -> Any: ...
-
- def load_checkpoint(self, load_dir: str, tag: str | None, **kwargs) -> Any: ...
-
-
def resolve(result: Any) -> Any:
"""Return a plain value, calling .result() on a future-like result."""
if hasattr(result, "result") and callable(result.result):
diff --git a/training/rdsp/src/ray_deepspeed_pipeline/stage_group.py b/training/rdsp/src/ray_deepspeed_pipeline/stage_group.py
index 404c0556b..fad145a7f 100644
--- a/training/rdsp/src/ray_deepspeed_pipeline/stage_group.py
+++ b/training/rdsp/src/ray_deepspeed_pipeline/stage_group.py
@@ -27,8 +27,11 @@
from ray_deepspeed_pipeline.protocols import Command
from ray_deepspeed_pipeline.stage_worker import StageWorkerActor
from ray_deepspeed_pipeline.vision import VisionLayout, build_vision_tower, route_images
+from ray_deepspeed_pipeline.wire import to_wire
_PLACEMENT_TIMEOUT_S = float(os.environ.get("RDSP_PLACEMENT_TIMEOUT_S", "600"))
+# how long a stage waits for the machine it was planned on before taking any machine
+_HARD_PLACEMENT_S = float(os.environ.get("RDSP_HARD_PLACEMENT_S", "120"))
def _p2p_timeout_s() -> float:
@@ -143,12 +146,16 @@ def _rank_payloads(self, inputs, labels) -> list[dict]:
elif inputs is not None:
cell_inputs = [slice_inputs(x, cell) for x in inputs]
payloads.append(
- {
- "inputs": cell_inputs,
- "labels": [cell_slice(y, cell) for y in labels] if labels is not None else None,
- "vision": routes,
- "token_total": token_total,
- }
+ to_wire(
+ {
+ "inputs": cell_inputs,
+ "labels": (
+ [cell_slice(y, cell) for y in labels] if labels is not None else None
+ ),
+ "vision": routes,
+ "token_total": token_total,
+ }
+ )
)
return payloads
@@ -332,6 +339,41 @@ def bundles_in_rank_order(bundles_to_node: dict, node_order: list, group_size: i
return order
+def place_stage(num_gpus: int, strategy: str, target: str | None, *, hard: bool, timeout: float):
+ """A ready placement group of num_gpus GPUs. hard: the node the plan chose for the stage
+ (target) is where it goes: the group waits for that node's GPUs (the previous engine's may
+ not have been released yet, as after --cuts measured's calibration engine), instead of
+ landing on another node, which adds a crossing between machines to every microbatch. If the
+ node stays busy for _HARD_PLACEMENT_S, or without hard (a node id kept from an earlier
+ placement, whose node may be gone), the target is only preferred."""
+ import ray
+ from ray.exceptions import GetTimeoutError
+ from ray.util.placement_group import placement_group
+
+ bundles = [{"GPU": 1, "CPU": 1}] * num_gpus
+ if hard and target is not None:
+ pg = placement_group(
+ bundles,
+ strategy=strategy,
+ bundle_label_selector=[{"ray.io/node-id": target}] * num_gpus,
+ )
+ try:
+ ray.get(pg.ready(), timeout=min(_HARD_PLACEMENT_S, timeout))
+ return pg
+ except GetTimeoutError:
+ ray.util.remove_placement_group(pg)
+ except Exception:
+ ray.util.remove_placement_group(pg)
+ raise
+ pg = placement_group(bundles, strategy=strategy, _soft_target_node_id=target)
+ try:
+ ray.get(pg.ready(), timeout=timeout)
+ except Exception:
+ ray.util.remove_placement_group(pg)
+ raise
+ return pg
+
+
def _nodes_in_fill_order() -> list[tuple[str, int]]:
"""Alive nodes with GPUs: the driver's first, the rest by address."""
import ray
@@ -367,12 +409,12 @@ def create_stage_clients(
tensor-parallel groups stay inside a node. prefer_nodes: per-stage node
ids to reuse on a rebuild, so node-local shards stay reachable after an
actor (not node) failure. Without them, on several nodes, stages fill the
- driver's node first, then the next (fill_nodes_in_order). weights: HF
+ driver's node first, then the next (fill_nodes_in_order), each waiting for the
+ node planned for it (place_stage). weights: HF
checkpoint dir each stage loads its meta-device parameters from. On any
failure every started stage is shut down.
"""
import ray
- from ray.util.placement_group import placement_group
from ray.util.scheduling_strategies import PlacementGroupSchedulingStrategy
if not ray.is_initialized():
@@ -393,10 +435,11 @@ def create_stage_clients(
actor_cls = ray.remote(StageWorkerActor)
nodes = _nodes_in_fill_order() if use_gpu else []
max_node_gpus = max((gpus for _, gpus in nodes), default=0)
- if use_gpu and prefer_nodes is None and len(nodes) > 1:
+ planned = use_gpu and prefer_nodes is None and len(nodes) > 1
+ if planned:
prefer_nodes = fill_nodes_in_order([s.num_gpus for s in plan.stages], nodes)
- clients = []
+ clients, groups = [], [] # groups: every placement group made, released on failure
n_stages = len(plan.stages)
# chosen from the model itself, so rdsp.initialize() (which passes no
# builder) and recovery rebuilds get the right one too
@@ -407,6 +450,7 @@ def create_stage_clients(
layout = VisionLayout(
first=Grid(dp=first.dp, sp=first.sp, tp=first.tp),
world=sum(spec.num_gpus for spec in plan.stages),
+ first_stage_only=vision.first_stage_only,
)
tower_ref = ray.put((build_vision_tower(model, vision.module), vision))
try:
@@ -431,28 +475,21 @@ def create_stage_clients(
spans = spec.num_gpus > max_node_gpus
strategy = "PACK" if spans else "STRICT_PACK"
target = prefer_nodes[spec.index] if prefer_nodes and not spans else None
- pg = placement_group(
- [{"GPU": 1, "CPU": 1}] * spec.num_gpus,
- strategy=strategy,
- _soft_target_node_id=target,
- )
try:
- ray.get(pg.ready(), timeout=_PLACEMENT_TIMEOUT_S)
+ pg = place_stage(
+ spec.num_gpus, strategy, target, hard=planned, timeout=_PLACEMENT_TIMEOUT_S
+ )
except Exception as e:
- ray.util.remove_placement_group(pg)
raise ValidationError(
f"stage {spec.index}: cannot place {spec.num_gpus} GPUs "
f"({strategy}) in this Ray cluster: {e}"
) from e
+ groups.append(pg)
if spans:
table = ray.util.placement_group_table(pg)["bundles_to_node_id"]
- try:
- bundle_of_rank = bundles_in_rank_order(
- table, [node for node, _ in nodes], spec.tp * spec.sp
- )
- except ValidationError:
- ray.util.remove_placement_group(pg)
- raise
+ bundle_of_rank = bundles_in_rank_order(
+ table, [node for node, _ in nodes], spec.tp * spec.sp
+ )
module_ref = ray.put(module)
actors = []
for rank in range(spec.num_gpus):
@@ -504,5 +541,10 @@ def create_stage_clients(
except Exception:
for client in clients:
client.shutdown()
+ for pg in groups: # also the stage that failed before it had a client
+ try:
+ ray.util.remove_placement_group(pg)
+ except Exception:
+ pass
raise
return clients
diff --git a/training/rdsp/src/ray_deepspeed_pipeline/stage_worker.py b/training/rdsp/src/ray_deepspeed_pipeline/stage_worker.py
index ff4d50722..9fd7dffad 100644
--- a/training/rdsp/src/ray_deepspeed_pipeline/stage_worker.py
+++ b/training/rdsp/src/ray_deepspeed_pipeline/stage_worker.py
@@ -14,6 +14,7 @@
import json
import os
import socket
+import tempfile
import time
import traceback
@@ -36,6 +37,8 @@
from ray_deepspeed_pipeline.losses import token_weight
from ray_deepspeed_pipeline.varlen_attention import register_if_used
from ray_deepspeed_pipeline.vision import vision_schedule
+from ray_deepspeed_pipeline.wire import from_wire
+from ray_deepspeed_pipeline.worker_host import freeze_heap, pin_to_gpu_socket
_VISION_FILE = "colocated_vision.pt"
@@ -49,6 +52,32 @@ def _free_port() -> int:
return sock.getsockname()[1]
+class _TraceWindow:
+ """RDSP_NSIGHT_STEPS="first:last" (or one step, "first"): capture only those of this
+ worker's steps (0-based, inclusive) in Nsight Systems started with `-c cudaProfilerApi`:
+ torch.cuda.profiler starts before `first` and stops after `last`. Off unless set."""
+
+ def __init__(self, spec: str | None = None):
+ spec = os.environ.get("RDSP_NSIGHT_STEPS") if spec is None else spec
+ self.window = None
+ if spec:
+ first, _, last = spec.partition(":")
+ self.window = (int(first), int(last or first))
+ self.step = -1
+
+ def before(self) -> bool:
+ """Whether this step starts the capture."""
+ self.step += 1
+ if self.window and self.step == self.window[0]:
+ torch.cuda.profiler.start()
+ return True
+ return False
+
+ def after(self) -> None:
+ if self.window and self.step == self.window[1]:
+ torch.cuda.profiler.stop()
+
+
class _PhaseTimer:
"""Wall time per phase of a step when RDSP_PROFILE=1 (or set_profile),
printed as one JSON line per rank and kept in `records`. Pending compute
@@ -87,6 +116,9 @@ def report(self, **where) -> None:
if torch.cuda.is_available(): # GB now, and peak since the last report
ms["mem_gb"] = round(torch.cuda.memory_allocated() / 2**30, 2)
ms["peak_gb"] = round(torch.cuda.max_memory_allocated() / 2**30, 2)
+ # NCCL, the CUDA context, other libraries: not the allocator's
+ free, total = torch.cuda.mem_get_info()
+ ms["outside_gb"] = round((total - free - torch.cuda.memory_reserved()) / 2**30, 2)
torch.cuda.reset_peak_memory_stats()
print(json.dumps({"rdsp_profile": where, **ms}), flush=True)
self.records.append({**where, **ms})
@@ -159,6 +191,7 @@ def bootstrap(self, master_addr: str, master_port: int) -> dict | None:
load_meta_parameters(module, init["weights"])
if init["backend"] == "nccl":
torch.cuda.set_device(0)
+ pin_to_gpu_socket()
module = module.to("cuda")
torch.distributed.init_process_group(
init["backend"],
@@ -189,6 +222,7 @@ def _build_vision(self, vision, weights, ds_config_json):
tower, spec = vision # the tower and its plan.VisionSpec
register_if_used(tower)
self._vision_per_microbatch = spec.encode_per_microbatch
+ self._vision_chunk = spec.encode_chunk
load_meta_parameters(tower, weights)
if spec.recompute:
recompute_blocks(tower)
@@ -344,17 +378,34 @@ def _warm_up_links(self):
def run_step(self, *args, **kwargs):
"""_run_step, under the torch profiler on the training step named by
RDSP_TORCH_PROFILE (0-based), whose kernel table goes to
- /tmp/rdsp_torch_profile_stage_rank.txt."""
+ rdsp_torch_profile_stage_rank_.txt in the temporary directory."""
+ if not hasattr(self, "_trace"):
+ self._trace = _TraceWindow()
+ if self._trace.before(): # which process is which stage, for reading the traces
+ where = {"stage": self.stage, "rank": self.rank, "pid": os.getpid()}
+ print(json.dumps({"nsight_capture": where}), flush=True)
+ try:
+ return self._run_step_profiled(*args, **kwargs)
+ finally:
+ self._trace.after()
+
+ def _run_step_profiled(self, generation, ops, train, **kwargs):
+ """One step, under the torch profiler when RDSP_TORCH_PROFILE names it."""
at = os.environ.get("RDSP_TORCH_PROFILE")
self._steps_run = getattr(self, "_steps_run", 0) + 1
- if at is None or self._steps_run - 1 != int(at):
- return self._run_step(*args, **kwargs)
+ if self._steps_run == 2: # after the first step, which compiles and fills the caches
+ freeze_heap()
+ if train:
+ self._train_steps = getattr(self, "_train_steps", 0) + 1
+ if at is None or not train or self._train_steps - 1 != int(at):
+ return self._run_step(generation, ops, train, **kwargs)
from torch.profiler import ProfilerActivity, profile
with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA]) as prof:
- out = self._run_step(*args, **kwargs)
+ out = self._run_step(generation, ops, train, **kwargs)
torch.cuda.synchronize()
- path = f"/tmp/rdsp_torch_profile_stage{self.stage}_rank{self.rank}.txt"
+ name = f"rdsp_torch_profile_stage{self.stage}_rank{self.rank}_{os.getpid()}.txt"
+ path = os.path.join(tempfile.gettempdir(), name)
with open(path, "w") as f:
f.write(
prof.key_averages().table(
@@ -383,6 +434,10 @@ def _run_step(
self._enter_generation(generation)
prev, next_ = self._peers()
adapter, p2p, timer = self.adapter, self.p2p, self._timer
+ # tensors again, sharing Ray's memory unless nothing copies them to a GPU
+ inputs, labels, vision = from_wire(
+ (inputs, labels, vision), copy=adapter.device.type == "cpu"
+ )
# DeepSpeed averages gradients over DP and sums over SP, so the gradient
# entering this stage must be dp_s x dL/d(output): scale by dp_s/dp_{s+1}
scale = gradient_scale(self._grids[self.stage + 1].dp, self.grid.dp) if next_ else 1.0
@@ -399,7 +454,7 @@ def _run_step(
self._local_features, self._image_rows, self._mine = {}, [], {}
if train and self._vision_per_microbatch:
schedule, tail = vision_schedule(
- ops, set(vision["own_mb"].values()), len(self._grids)
+ ops, set(vision["own_mb"].values()), len(self._grids), self._vision_chunk
)
else: # everything at once, backpropagated at the end
with timer.phase("vision_forward"):
@@ -412,8 +467,8 @@ def _run_step(
with timer.phase("vision_backward"):
self._vision_backward(vision, backpropagate)
with timer.phase("vision_forward"):
- for m in encode:
- self._encode_images(vision, train, m)
+ if encode: # the chunk's images in one encoder call
+ self._encode_images(vision, train, set(encode))
self.executed.append(command_id)
if kind == "ready":
ready = adapter.ready()
@@ -482,13 +537,13 @@ def _run_step(
def _global_rank(self) -> int:
return self._offsets[self.stage] + self.rank
- def _encode_images(self, vision: dict, train: bool, mb: int | None = None) -> None:
- """Encode this rank's images (of microbatch mb, or all) in one batch
+ def _encode_images(self, vision: dict, train: bool, mbs=None) -> None:
+ """Encode this rank's images (of the microbatches in mbs, or all) in one batch
and send each image's features to the first-stage ranks of its row
(over gloo: a send may wait for its receiver as long as needed
without holding the GPU)."""
me, p2p = self._global_rank(), self.p2p
- own = [e for e in vision["own"] if mb is None or vision["own_mb"][e[0]] == mb]
+ own = [e for e in vision["own"] if mbs is None or vision["own_mb"][e[0]] in mbs]
features = self.vision.forward([(i, px, grid) for i, px, grid, _, _ in own], train)
for image, _, _, dests, _ in own:
for dest in dests:
diff --git a/training/rdsp/src/ray_deepspeed_pipeline/support_matrix.py b/training/rdsp/src/ray_deepspeed_pipeline/support_matrix.py
deleted file mode 100644
index 0cf745420..000000000
--- a/training/rdsp/src/ray_deepspeed_pipeline/support_matrix.py
+++ /dev/null
@@ -1,160 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-
-"""Supported configurations. Default-deny: a row is supported only once its
-validation test has passed and the run is recorded here. When and where each
-validation ran is in docs/BENCHMARK_RESULTS.md."""
-
-from dataclasses import dataclass
-
-
-@dataclass(frozen=True)
-class SupportRow:
- row_id: str
- dtype: str
- stages: int
- gpus_per_stage: int
- dp: int
- tp: int
- ep: int
- sp: int
- zero_stage: int
- schedule: str
- boundaries: str
- model_fixture: str
- microbatches: int
- supported: bool
-
-
-BASELINE_ROW = SupportRow(
- row_id="two-stage-baseline",
- dtype="bf16",
- stages=2,
- gpus_per_stage=1,
- dp=1,
- tp=1,
- ep=1,
- sp=1,
- zero_stage=0,
- schedule="1f1b",
- boundaries="identity",
- model_fixture="Qwen/Qwen3-0.6B",
- microbatches=4,
- # Evidence (2x L4): eval and train loss parity with the unsplit model
- # (rel 2e-2, bf16), loss decreases, exact microbatch consumption, eval leaves
- # weights unchanged, engine surface.
- supported=True,
-)
-
-
-@dataclass(frozen=True)
-class HeterogeneousRow:
- """A per-stage-heterogeneous configuration.
-
- `stages` describes each stage's grid as text; `requires` lists rows that must
- be supported first; `evidence` records the passing run of a supported row.
- """
-
- row_id: str
- scope: str
- stages: tuple[str, ...]
- requires: tuple[str, ...] = ()
- supported: bool = False
- evidence: str = ""
- note: str = "" # why an unsupported row is not yet validated
-
-
-_PARITY_EVIDENCE = (
- "8x L4, DeepSpeed 0.19.3+53a2ac44: test_row_parity_global_microbatch_checkpoint_failure"
- "[{row}] passed: SGD loss parity with a single-process fp32 baseline (rel 1e-4, learnable "
- "data), exact N-entry consumption, checkpoint round trip into a fresh differently "
- "initialized pipeline, non-zero-rank kill -> StepFailed -> whole-pipeline recovery"
-)
-
-HETEROGENEOUS_ROWS = (
- HeterogeneousRow(
- "static-boundary",
- "replicate<->shard StageConnection conversion",
- ("1 GPU", "dp=2", "1 GPU"),
- supported=True,
- evidence=_PARITY_EVIDENCE.format(row="static-boundary"),
- ),
- HeterogeneousRow(
- "resource-mesh",
- "differing per-stage GPU counts and meshes",
- ("dp=2", "dp=4", "dp=2"),
- supported=True,
- evidence=_PARITY_EVIDENCE.format(row="resource-mesh"),
- ),
- HeterogeneousRow(
- "dp-zero",
- "differing per-stage DP degrees and ZeRO stages",
- ("dp=4 ZeRO-2", "dp=2 ZeRO-1", "dp=2 ZeRO-0"),
- supported=True,
- evidence=_PARITY_EVIDENCE.format(row="dp-zero"),
- ),
- HeterogeneousRow(
- "autotp",
- "stage-local AutoTP",
- ("1 GPU", "tp=2", "tp=2 x dp=2"),
- supported=True,
- evidence=(
- _PARITY_EVIDENCE.format(row="autotp") + "; tiny random Qwen3 (fp32); per-TP-rank "
- "shards in the checkpoint; test_row_gradient_parity_per_parameter[autotp] passed: "
- "91 parameters, worst update error 2.4e-5 against matching reference slices. "
- "Needs rdsp's q_norm/k_norm TP gradient-sum hook (AutoTP leaves them partial)"
- ),
- ),
- HeterogeneousRow(
- "autoep-folding",
- "stage-local AutoEP plus Parallel Folding",
- ("1 GPU", "ep=4", "ep=2 folded with tp=2"),
- supported=True,
- evidence=(
- _PARITY_EVIDENCE.format(row="autoep-folding") + "; tiny random Qwen3-MoE (8 "
- "experts, top-2, fp32); test_row_gradient_parity_per_parameter passed: 76 "
- "parameters, worst 3.0e-4 (folded-stage input_layernorm), rest <= 1.8e-5. Needs "
- "rdsp's TP-average hook at folded MoE inputs"
- ),
- ),
- HeterogeneousRow(
- "sequence-parallel",
- "stage-local Ulysses sequence parallelism",
- ("sp=2", "sp=2 x dp=2", "1 GPU"),
- supported=True,
- evidence=(
- _PARITY_EVIDENCE.format(row="sequence-parallel") + "; tiny random Qwen3 (fp32); "
- "SP ranks >= 1 checkpoint through the model-rank-0 mpu wrapper; "
- "test_row_gradient_parity_per_parameter passed: 91 parameters, worst 2.4e-5. "
- "SP stages average gradients over dp only (DeepSpeed sums over SP)"
- ),
- ),
- HeterogeneousRow(
- "four-stage-mixed",
- "the four stage kinds above composed (32 GPUs, 4 nodes)",
- (
- "dp=4 x sp=2, ZeRO-2",
- "tp=4 x dp=2, ZeRO-1",
- "ep=8 AutoEP + Parallel Folding",
- "tp=2 x dp=4",
- ),
- requires=(
- "static-boundary",
- "resource-mesh",
- "dp-zero",
- "autotp",
- "autoep-folding",
- "sequence-parallel",
- ),
- note=(
- "all six prerequisites are supported, and the same four stage kinds composed "
- "on one 8-GPU node pass every check (test_*[four-stage-mixed-mini], 85 "
- "parameters, worst update error 2.4e-5). The 32-GPU, 4-node run has not been "
- "done, so cross-node rendezvous, placement and node-local checkpoints are "
- "unvalidated. Command: pytest tests/integration/test_heterogeneous_pipeline.py "
- "-k four-stage-mixed"
- ),
- ),
-)
-
-ROWS = (BASELINE_ROW, *HETEROGENEOUS_ROWS)
diff --git a/training/rdsp/src/ray_deepspeed_pipeline/tp_input_grads.py b/training/rdsp/src/ray_deepspeed_pipeline/tp_input_grads.py
new file mode 100644
index 000000000..af19c7ab4
--- /dev/null
+++ b/training/rdsp/src/ray_deepspeed_pipeline/tp_input_grads.py
@@ -0,0 +1,175 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+
+"""Tensor-parallel layers that read one input: one all-reduce of its gradient, hidden behind the
+weight gradients.
+
+AutoTP's column-split layer all-reduces its input's gradient over the tensor-parallel ranks in
+backward and waits for it. An attention layer has three of them on one input (q, k, v), an MLP two
+(gate, up) and a gated delta-net layer four, so a block does three to five where Megatron, whose
+projections are fused, does one or two, and Megatron computes its weight gradients meanwhile. The
+all-reduce is a sum over ranks, so the layers' input gradients can be summed first. Here the
+siblings run as one autograd function: its backward starts the one all-reduce, computes the weight
+gradients, then waits.
+
+Siblings run together when the first of them is called; the others take their result. One that is
+handed another tensor than the first got, or is never called, computes nothing wrong: it falls back
+to its own layer.
+"""
+
+import functools
+import sys
+
+import torch
+import torch.distributed as dist
+import torch.nn as nn
+
+# children of one module whose inputs are the same tensor in Hugging Face's layers
+_SIBLINGS = (("q_proj", "k_proj", "v_proj"), ("gate_proj", "up_proj"))
+# the gated delta-net's, split by linear_attention_parallel: their module holds the group
+_GATED_DELTA = ("in_proj_qkv", "in_proj_z", "in_proj_b", "in_proj_a")
+
+
+class GradAccumulation:
+ """Shared by a stage's linear layers. fuse: this backward may add into a .grad that exists."""
+
+ def __init__(self):
+ self.fuse = False
+
+
+def add_weight_grad(weight, grad, x, state):
+ """The weight gradient of y = x W^T given dL/dy (`grad`): added into weight.grad by the
+ matmul that computes it when state allows, else returned for autograd to accumulate."""
+ rows = grad.reshape(-1, grad.shape[-1]).t()
+ columns = x.reshape(-1, x.shape[-1])
+ if state is not None and state.fuse and weight.grad is not None:
+ weight.grad.addmm_(rows, columns)
+ return None
+ return rows.matmul(columns)
+
+
+class _JointColumns(torch.autograd.Function):
+ """y_i = x W_i^T for several weights; backward all-reduces the sum of the input gradients
+ while the weight gradients are computed."""
+
+ @staticmethod
+ def forward(ctx, x, group, state, *weights):
+ ctx.set_materialize_grads(False) # an output nothing used has no gradient
+ ctx.group, ctx.state, ctx.weights = group, state, weights
+ ctx.save_for_backward(x)
+ return tuple(torch.matmul(x, w.transpose(-1, -2)) for w in weights)
+
+ @staticmethod
+ def backward(ctx, *grads):
+ (x,) = ctx.saved_tensors
+ grad_x = handle = None
+ if ctx.needs_input_grad[0]:
+ for g, w in zip(grads, ctx.weights, strict=True):
+ if g is None:
+ continue
+ if grad_x is None:
+ grad_x = g.matmul(w).contiguous()
+ else:
+ grad_x.view(-1, grad_x.shape[-1]).addmm_(g.reshape(-1, g.shape[-1]), w)
+ if grad_x is not None:
+ handle = dist.all_reduce(grad_x, group=ctx.group, async_op=True)
+ grad_w = [
+ add_weight_grad(w, g, x, ctx.state) if g is not None and w.requires_grad else None
+ for g, w in zip(grads, ctx.weights, strict=True)
+ ]
+ if handle is not None:
+ handle.wait()
+ return grad_x, None, None, *grad_w
+
+
+class _Siblings:
+ """One module's column-split layers, whose outputs are computed at the first call."""
+
+ def __init__(self, layers, group, state):
+ self.layers, self.group, self.state = layers, group, state
+ self.clear()
+
+ def clear(self, *_):
+ self._raw, self._outputs = None, {}
+
+ def output(self, layer, x):
+ if self._raw is not x:
+ if self._raw is not None: # another tensor than the siblings': its own layer
+ return None
+ outputs = _JointColumns.apply(
+ x, self.group(), self.state, *(other.weight for other in self.layers)
+ )
+ self._raw = x
+ self._outputs = dict(zip(map(id, self.layers), outputs, strict=True))
+ # taken once: a second call on one input must be a second computation
+ return self._outputs.pop(id(layer), None)
+
+
+def _reduced_input(layer, group, x):
+ """A split gated delta-net's input projection on its own, with the all-reduce its module's
+ pre-hook leaves to tp_input_grads."""
+ from ray_deepspeed_pipeline.vocab_parallel import SumGradOverRanks
+
+ return layer(SumGradOverRanks.apply(x, group()))
+
+
+def flag(layer, name: str) -> bool:
+ """A DeepSpeed layer's switch; False on versions without it (0.19.3 has neither
+ gather_output nor defer_collectives_to_compiler)."""
+ return bool(getattr(layer, name, False))
+
+
+def _shareable(layer, linear_layer) -> bool:
+ return (
+ type(layer) is linear_layer
+ and layer.mp_group is not None
+ and not any(
+ flag(layer, name)
+ for name in ("gather_output", "tp_overlap_comm", "defer_collectives_to_compiler")
+ )
+ )
+
+
+def _forward(layer, siblings, own, x):
+ out = siblings.output(layer, x)
+ if out is None:
+ return own(x)
+ if layer.bias is None:
+ return out
+ from deepspeed.module_inject.layers import add_bias
+
+ return add_bias(out, layer.bias)
+
+
+def share_input_grad_reductions(
+ root: nn.Module, state: GradAccumulation | None = None
+) -> list[str]:
+ """Let root's column-split layers on one input share an all-reduce, and overlap it. state: the
+ fused gradient accumulation they take part in. Returns the names of the modules."""
+ loaded = sys.modules.get("deepspeed.module_inject.layers")
+ done = []
+ for name, module in root.named_modules():
+ joined = []
+ if loaded is not None:
+ for names in _SIBLINGS:
+ layers = [getattr(module, n, None) for n in names]
+ if all(_shareable(layer, loaded.LinearLayer) for layer in layers):
+ joined.append((layers, functools.partial(getattr, layers[0], "mp_group")))
+ split = getattr(module, "_rdsp_input_group", None) # a split gated delta-net
+ if split is not None and all(
+ type(getattr(module, n, None)) is nn.Linear for n in _GATED_DELTA
+ ):
+ joined.append(([getattr(module, n) for n in _GATED_DELTA], split))
+ module._rdsp_joint_inputs = True # its own pre-hook all-reduce is not needed
+ for layers, group in joined:
+ siblings = _Siblings(layers, group, state)
+ for layer in layers:
+ own = layer.forward
+ if group is split:
+ own = functools.partial(_reduced_input, layer.forward, group)
+ layer.forward = functools.partial(_forward, layer, siblings, own)
+ # also after an exception: recomputation stops a forward early with one
+ module.register_forward_hook(siblings.clear, always_call=True)
+ if joined:
+ done.append(name)
+ return done
diff --git a/training/rdsp/src/ray_deepspeed_pipeline/varlen_attention.py b/training/rdsp/src/ray_deepspeed_pipeline/varlen_attention.py
index 47af95aca..45623ad49 100644
--- a/training/rdsp/src/ray_deepspeed_pipeline/varlen_attention.py
+++ b/training/rdsp/src/ray_deepspeed_pipeline/varlen_attention.py
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# DeepSpeed Team
-"""Vision attention as one variable-length flash attention call per layer.
+"""Vision attention without a GPU-to-CPU read per layer.
Hugging Face's Qwen-VL vision encoders attend within each image. Under SDPA
they split each layer's q, k and v per image on the host (`lengths.tolist()`:
@@ -10,7 +10,10 @@
kernel instead, and read the longest image's length once per forward.
PyTorch's own varlen_attn (FlashAttention, with a backward) is such a kernel,
so rdsp registers it under a name containing "flash" and points only the
-vision encoder's config at it; the language model's attention is unchanged.
+vision encoder's config at it (NAME); the language model's attention is
+unchanged. PACKED keeps SDPA's own kernels: where the pixels are one image,
+the usual case of a microbatch row per rank, it is one SDPA call over them,
+else one per image, the image lengths read once per forward.
The registry is per process: stage workers unpickle modules built on the
driver, so they register the function again (register_if_used).
@@ -21,6 +24,7 @@
from ray_deepspeed_pipeline.errors import ValidationError
NAME = "rdsp_flash_varlen"
+PACKED = "rdsp_flash_packed_sdpa" # "flash": how Hugging Face knows to pass the boundaries
def varlen_attention_forward(
@@ -63,10 +67,55 @@ def varlen_attention_forward(
return out.unsqueeze(0), None
+def _image_lengths(cu_seq_lens: torch.Tensor) -> list[int]:
+ """Read once per forward: every layer gets the same boundaries tensor."""
+ lengths = getattr(cu_seq_lens, "_rdsp_lengths", None)
+ if lengths is None:
+ lengths = (cu_seq_lens[1:] - cu_seq_lens[:-1]).tolist()
+ cu_seq_lens._rdsp_lengths = lengths
+ return lengths
+
+
+def packed_sdpa_forward(
+ module,
+ query,
+ key,
+ value,
+ attention_mask=None,
+ *,
+ scaling=None,
+ dropout=0.0,
+ cu_seq_lens_q=None,
+ max_length_q=None,
+ is_causal=False,
+ **kwargs,
+):
+ """As varlen_attention_forward, through SDPA. The longest image being all
+ the tokens means there is one image."""
+ if cu_seq_lens_q is None or attention_mask is not None or dropout or is_causal:
+ raise ValidationError(
+ f"{PACKED} runs packed sequences only: cu_seq_lens, no mask, no dropout, not causal"
+ )
+ sdpa = torch.nn.functional.scaled_dot_product_attention
+ if max_length_q == query.shape[2]:
+ out = sdpa(query, key, value, scale=scaling)
+ else:
+ lengths = _image_lengths(cu_seq_lens_q)
+ out = torch.cat(
+ [
+ sdpa(q, k, v, scale=scaling)
+ for q, k, v in zip(*(t.split(lengths, dim=2) for t in (query, key, value)))
+ ],
+ dim=2,
+ )
+ return out.transpose(1, 2).contiguous(), None
+
+
def register() -> None:
from transformers import AttentionInterface
AttentionInterface.register(NAME, varlen_attention_forward)
+ AttentionInterface.register(PACKED, packed_sdpa_forward)
def _configs(module: torch.nn.Module) -> list:
@@ -80,21 +129,30 @@ def _configs(module: torch.nn.Module) -> list:
return list(found.values())
-def use_varlen_vision_attention(model: torch.nn.Module) -> None:
- """Run the model's vision encoder attention through NAME: every config
- object the encoder's modules hold."""
+def _use(model: torch.nn.Module, name: str) -> None:
+ """Every config object the vision encoder's modules hold."""
from ray_deepspeed_pipeline.vision import find_vision_encoder
register()
for config in _configs(model.get_submodule(find_vision_encoder(model))):
- config._attn_implementation = NAME
+ config._attn_implementation = name
+
+
+def use_varlen_vision_attention(model: torch.nn.Module) -> None:
+ """Run the model's vision encoder attention through NAME."""
+ _use(model, NAME)
+
+
+def use_packed_vision_attention(model: torch.nn.Module) -> None:
+ """Run the model's vision encoder attention through PACKED."""
+ _use(model, PACKED)
def register_if_used(module: torch.nn.Module) -> None:
- """Register NAME in this process if a config in `module` names it."""
+ """Register both in this process if a config in `module` names one."""
try:
configs = _configs(module)
except ImportError: # no transformers: no Hugging Face configs either
return
- if any(c._attn_implementation == NAME for c in configs):
+ if any(c._attn_implementation in (NAME, PACKED) for c in configs):
register()
diff --git a/training/rdsp/src/ray_deepspeed_pipeline/vision.py b/training/rdsp/src/ray_deepspeed_pipeline/vision.py
index 14ad927ff..8778c1356 100644
--- a/training/rdsp/src/ray_deepspeed_pipeline/vision.py
+++ b/training/rdsp/src/ray_deepspeed_pipeline/vision.py
@@ -27,18 +27,18 @@
from ray_deepspeed_pipeline.errors import StepFailed, ValidationError
# attribute names Hugging Face vision-language models give their vision encoder
-_ENCODER_NAMES = ("visual", "vision_tower", "vision_model")
+ENCODER_NAMES = ("visual", "vision_tower", "vision_model")
def find_vision_encoder(model: nn.Module) -> str:
"""Module path of the model's vision encoder (e.g. "model.visual")."""
for name, module in model.named_modules():
has_params = next(module.parameters(), None) is not None
- if name.rsplit(".", 1)[-1] in _ENCODER_NAMES and has_params:
+ if name.rsplit(".", 1)[-1] in ENCODER_NAMES and has_params:
return name
raise ValidationError(
f"{type(model).__name__} has no vision encoder (a module named one of "
- f"{_ENCODER_NAMES}); colocated vision needs one"
+ f"{ENCODER_NAMES}); colocated vision needs one"
)
@@ -101,10 +101,13 @@ def forward(self, pixel_values, grid_thw=None, **kwargs):
@dataclass(frozen=True)
class VisionLayout:
"""first: the first stage's rank grid; world: ranks over all stages
- (global rank = stage offset + stage-local rank, the first stage first)."""
+ (global rank = stage offset + stage-local rank, the first stage first);
+ first_stage_only: every image is encoded by the first-stage cell that
+ needs it, none by the other stages (ColocatedVision.first_stage_only)."""
first: Grid
world: int
+ first_stage_only: bool = False
# share of a fair split each first-stage cell encodes itself: enough to start
@@ -120,7 +123,9 @@ def _owners(images: list, layout: VisionLayout, cell_rows: int, cell_ranks) -> d
which are idle while the pipeline fills, the last stage's ranks first."""
# last stage first: it finishes its pipeline work first, and the first
# microbatches' feature gradients are the first to come back
- others = list(range(layout.world - 1, layout.first.world - 1, -1))
+ others = (
+ [] if layout.first_stage_only else list(range(layout.world - 1, layout.first.world - 1, -1))
+ )
own_first = int(len(images) / layout.world * _FIRST_STAGE_SHARE) if others else len(images)
owner, taken, rest = {}, {}, []
for image, _, row in images:
@@ -183,7 +188,7 @@ def cell_ranks(row):
return {"own": own, "need": need, "own_mb": own_mb}
-def vision_schedule(ops: list, microbatches, n_stages: int):
+def vision_schedule(ops: list, microbatches, n_stages: int, chunk: int = 1):
"""When a rank encodes and backpropagates its images of each microbatch
during a training step, so that it keeps a graph for only about
2 x n_stages microbatches' images instead of the whole step's. ops: the
@@ -195,15 +200,20 @@ def vision_schedule(ops: list, microbatches, n_stages: int):
first stage may run that far ahead, and encoding early never blocks (the
features leave over asynchronous sends). It is backpropagated before the
forward of m + n_stages: in 1F1B the first stage has done m's backward,
- and sent its feature gradients, before any stage starts that forward."""
+ and sent its feature gradients, before any stage starts that forward.
+
+ chunk: microbatches taken together, in order, so one encoder call (and
+ one backward) covers their images; a chunk is encoded when its first
+ microbatch would be and backpropagated when its last one would be."""
forward = {mb: i for i, (kind, mb, _) in enumerate(ops) if kind == "forward"}
+ ordered = sorted(microbatches)
before, end = {}, []
- for m in sorted(microbatches):
- before.setdefault(forward[max(0, m - n_stages)], ([], []))[1].append(m)
- if m + n_stages in forward:
- before.setdefault(forward[m + n_stages], ([], []))[0].append(m)
+ for group in (ordered[i : i + chunk] for i in range(0, len(ordered), chunk)):
+ before.setdefault(forward[max(0, group[0] - n_stages)], ([], []))[1].extend(group)
+ if group[-1] + n_stages in forward:
+ before.setdefault(forward[group[-1] + n_stages], ([], []))[0].extend(group)
else:
- end.append(m)
+ end.extend(group)
return before, end
@@ -216,7 +226,7 @@ def _optimizer(params, ds_config: dict):
"""The DeepSpeed config's optimizer as a torch optimizer (Adam, AdamW or
SGD; DeepSpeed's Adam is AdamW unless adam_w_mode is off), plus its LR
scheduler as DeepSpeed would build it."""
- opt = ds_config.get("optimizer", {})
+ opt = ds_config.get("optimizer") or {}
kind, args = opt.get("type", "AdamW"), dict(opt.get("params", {}))
if kind.lower() not in VISION_OPTIMIZERS or args.pop("adam_w_mode", True) is False:
raise ValidationError(f"colocated vision supports Adam, AdamW or SGD, got {kind!r}")
@@ -257,7 +267,7 @@ class ColocatedVisionEngine:
def __init__(self, tower: VisionTower, ds_config: dict, device: torch.device):
self.tower = tower.to(device)
self.device = device
- bf16 = ds_config.get("bf16", {}).get("enabled", False)
+ bf16 = (ds_config.get("bf16") or {}).get("enabled", False)
self.autocast = torch.bfloat16 if bf16 else None
self._config = ds_config
self._params = [p for p in self.tower.module.parameters() if p.requires_grad]
diff --git a/training/rdsp/src/ray_deepspeed_pipeline/vocab_parallel.py b/training/rdsp/src/ray_deepspeed_pipeline/vocab_parallel.py
index 34a767111..dd6d179db 100644
--- a/training/rdsp/src/ray_deepspeed_pipeline/vocab_parallel.py
+++ b/training/rdsp/src/ray_deepspeed_pipeline/vocab_parallel.py
@@ -83,39 +83,80 @@ class VocabShard:
group: object # the tensor-parallel process group
+# positions per pass of the unsharded loss: the fp32 copy of the logits is this many rows of it
+_LOSS_CHUNK = 512
+
+
+def _softmax_minus_target(logits, target, start, group, ignore_index):
+ """(per-token loss, softmax minus the target's one-hot in fp32) for logits whose vocabulary
+ is split over group's ranks, in place on a fp32 copy."""
+ x = logits.to(torch.float32, copy=True)
+ top = x.max(dim=-1).values
+ dist.all_reduce(top, op=dist.ReduceOp.MAX, group=group)
+ x.sub_(top.unsqueeze(-1))
+ local = target - start
+ mine = (local >= 0) & (local < x.shape[-1])
+ index = local.clamp(0, x.shape[-1] - 1).unsqueeze(-1)
+ picked = x.gather(-1, index).squeeze(-1).masked_fill(~mine, 0)
+ dist.all_reduce(picked, group=group)
+ x.exp_()
+ total = x.sum(dim=-1)
+ dist.all_reduce(total, group=group)
+ counted = target != ignore_index
+ loss = (total.log() - picked) * counted
+ x.div_(total.unsqueeze(-1))
+ x.scatter_add_(-1, index, -mine.to(x.dtype).unsqueeze(-1))
+ x.mul_(counted.unsqueeze(-1))
+ return loss, x
+
+
+def _whole_vocabulary(logits, target, ignore_index, grad):
+ """The same for logits holding the whole vocabulary, with PyTorch's log-softmax kernel: the
+ per-token loss, and softmax minus one-hot written into `grad` (the logits' dtype; None:
+ the loss only)."""
+ x = torch.log_softmax(logits.float(), dim=-1)
+ counted = (target != ignore_index).unsqueeze(-1)
+ index = target.clamp(min=0).unsqueeze(-1)
+ loss = -x.gather(-1, index).squeeze(-1) * counted.squeeze(-1)
+ if grad is None:
+ return loss
+ x.exp_().scatter_add_(-1, index, torch.full_like(x[..., :1], -1.0))
+ torch.mul(x, counted, out=grad)
+ return loss
+
+
class _ShardedCrossEntropy(torch.autograd.Function):
"""Per-token cross entropy over logits split along the vocabulary. The
ranks agree on each token's max logit, exp-sum and target logit; the
gradient, softmax minus the target's one-hot, needs no exchange and is
- kept from forward in the logits' dtype."""
+ kept from forward in the logits' dtype. Without a group (the whole
+ vocabulary on this rank) it runs a chunk of positions at a time, so the
+ fp32 copy of the logits is one chunk of it and not all."""
@staticmethod
def forward(ctx, logits, target, start, group, ignore_index):
- x = logits.float()
- top = x.max(dim=-1).values
- dist.all_reduce(top, op=dist.ReduceOp.MAX, group=group)
- x.sub_(top.unsqueeze(-1))
- local = target - start
- mine = (local >= 0) & (local < x.shape[-1])
- index = local.clamp(0, x.shape[-1] - 1).unsqueeze(-1)
- picked = x.gather(-1, index).squeeze(-1).masked_fill(~mine, 0)
- dist.all_reduce(picked, group=group)
- x.exp_()
- total = x.sum(dim=-1)
- dist.all_reduce(total, group=group)
- counted = target != ignore_index
- loss = (total.log() - picked) * counted
- x.div_(total.unsqueeze(-1))
- x.scatter_add_(-1, index, -mine.to(x.dtype).unsqueeze(-1))
- x.mul_(counted.unsqueeze(-1))
- ctx.save_for_backward(x.to(logits.dtype))
- return loss
+ if group is not None:
+ loss, grad = _softmax_minus_target(logits, target, start, group, ignore_index)
+ ctx.save_for_backward(grad.to(logits.dtype))
+ return loss
+ # (rows, positions, vocabulary), row by row: each row's positions are contiguous
+ grad = torch.empty_like(logits) if ctx.needs_input_grad[0] else None # None: eval
+ losses = []
+ for r, (row, row_target) in enumerate(zip(logits, target, strict=True)):
+ for i in range(0, len(row), _LOSS_CHUNK):
+ span = slice(i, i + _LOSS_CHUNK)
+ out = None if grad is None else grad[r, span]
+ losses.append(_whole_vocabulary(row[span], row_target[span], ignore_index, out))
+ if grad is not None:
+ ctx.save_for_backward(grad)
+ return torch.cat(losses).view(target.shape)
@staticmethod
def backward(ctx, grad):
(softmax_minus_target,) = ctx.saved_tensors
+ # in place: the saved tensor is as large as the logits, and this is its only use
return (
- softmax_minus_target * grad.unsqueeze(-1).to(softmax_minus_target.dtype),
+ softmax_minus_target.mul_(grad.unsqueeze(-1).to(softmax_minus_target.dtype)),
None,
None,
None,
@@ -128,19 +169,11 @@ def next_token_loss_sum(logits, labels, ignore_index: int = -100):
ignore_index labels do not count), for full logits or a vocab-parallel
head's shard. As a stage's loss (or a TokenMeanLoss's sum_fn) it lets
tensor-parallel stages skip gathering the logits."""
- shard = getattr(logits, "vocab_shard", None)
+ shard = getattr(logits, "vocab_shard", None) or VocabShard(0, None)
logits, target = logits[:, :-1], labels[:, 1:].to(logits.device)
- width = logits.shape[-1]
- if shard is None:
- return F.cross_entropy(
- logits.float().reshape(-1, width),
- target.reshape(-1),
- ignore_index=ignore_index,
- reduction="sum",
- )
- return _ShardedCrossEntropy.apply(
- logits.reshape(-1, width), target.reshape(-1), shard.start, shard.group, ignore_index
- ).sum()
+ if shard.group is not None:
+ logits, target = logits.reshape(-1, logits.shape[-1]), target.reshape(-1)
+ return _ShardedCrossEntropy.apply(logits, target, shard.start, shard.group, ignore_index).sum()
next_token_loss_sum.takes_vocab_shards = True
diff --git a/training/rdsp/src/ray_deepspeed_pipeline/wire.py b/training/rdsp/src/ray_deepspeed_pipeline/wire.py
new file mode 100644
index 000000000..a40e26156
--- /dev/null
+++ b/training/rdsp/src/ray_deepspeed_pipeline/wire.py
@@ -0,0 +1,53 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+
+"""A step's data on its way to the stage workers.
+
+Ray passes numpy arrays through shared memory without copying them but pickles tensors, and a
+step's images (hundreds of MB per rank) would be unpickled while the GPUs wait. So tensors
+travel as arrays.
+"""
+
+import warnings
+from dataclasses import dataclass
+
+import numpy as np
+import torch
+
+
+@dataclass(frozen=True)
+class _Array:
+ """A tensor's values; dtype: its name, where numpy has none (bfloat16: its bits)."""
+
+ values: np.ndarray
+ dtype: str | None = None
+
+
+def to_wire(data):
+ """`data` with every tensor in its dicts, lists and tuples replaced by an _Array."""
+ if torch.is_tensor(data):
+ t = data.detach().cpu().contiguous()
+ if t.dtype == torch.bfloat16:
+ return _Array(t.view(torch.int16).numpy(), "bfloat16")
+ return _Array(t.numpy())
+ if isinstance(data, dict):
+ return {k: to_wire(v) for k, v in data.items()}
+ if isinstance(data, (list, tuple)):
+ return type(data)(to_wire(v) for v in data)
+ return data
+
+
+def from_wire(data, copy: bool = False):
+ """The tensors back. They share the arrays' memory, which is read-only where Ray holds it:
+ copy=True where they may be written to or outlive the step (no move to a GPU follows)."""
+ if isinstance(data, _Array):
+ values = data.values.copy() if copy else data.values
+ with warnings.catch_warnings(): # read-only: see above
+ warnings.filterwarnings("ignore", message=".*not writable.*")
+ t = torch.from_numpy(values)
+ return t.view(getattr(torch, data.dtype)) if data.dtype else t
+ if isinstance(data, dict):
+ return {k: from_wire(v, copy) for k, v in data.items()}
+ if isinstance(data, (list, tuple)):
+ return type(data)(from_wire(v, copy) for v in data)
+ return data
diff --git a/training/rdsp/src/ray_deepspeed_pipeline/worker_host.py b/training/rdsp/src/ray_deepspeed_pipeline/worker_host.py
new file mode 100644
index 000000000..f15a8ac65
--- /dev/null
+++ b/training/rdsp/src/ray_deepspeed_pipeline/worker_host.py
@@ -0,0 +1,54 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+
+"""Host-side settings of a stage worker. With one sequence or two per microbatch a worker's GPU
+waits on the launching thread, so the host counts."""
+
+import gc
+import os
+
+import torch
+
+
+def parse_cpulist(text: str) -> set[int]:
+ """The CPUs of a sysfs list, "0-3,8,10-11"."""
+ cpus = set()
+ for part in text.strip().split(","):
+ if part:
+ first, _, last = part.partition("-")
+ cpus.update(range(int(first), int(last or first) + 1))
+ return cpus
+
+
+def gpu_cpus(root: str = "/sys/bus/pci/devices") -> set[int]:
+ """The CPUs on the socket of this process's GPU; empty where sysfs does not say."""
+ if not torch.cuda.is_available():
+ return set()
+ p = torch.cuda.get_device_properties(0)
+ name = f"{p.pci_domain_id:04x}:{p.pci_bus_id:02x}:{p.pci_device_id:02x}.0"
+ try:
+ with open(os.path.join(root, name, "local_cpulist")) as f:
+ return parse_cpulist(f.read())
+ except OSError:
+ return set()
+
+
+def pin_to_gpu_socket() -> bool:
+ """Run this process on its GPU's socket (RDSP_PIN_CPUS=0 switches it off). Threads started
+ later inherit it. Returns whether it did."""
+ if os.environ.get("RDSP_PIN_CPUS", "1") == "0" or not hasattr(os, "sched_setaffinity"):
+ return False
+ allowed = os.sched_getaffinity(0) & gpu_cpus()
+ if not allowed:
+ return False
+ os.sched_setaffinity(0, allowed)
+ return True
+
+
+def freeze_heap() -> None:
+ """Move everything alive now out of the garbage collector's sight. Once a worker is set up its
+ objects live until it exits, and a full collection would walk them all, between two launches
+ (RDSP_FREEZE_HEAP=0 switches it off)."""
+ if os.environ.get("RDSP_FREEZE_HEAP", "1") != "0":
+ gc.collect()
+ gc.freeze()
diff --git a/training/rdsp/tests/architecture/test_dependency_boundaries.py b/training/rdsp/tests/architecture/test_dependency_boundaries.py
index c35435e78..fdd74fd52 100644
--- a/training/rdsp/tests/architecture/test_dependency_boundaries.py
+++ b/training/rdsp/tests/architecture/test_dependency_boundaries.py
@@ -33,7 +33,6 @@ def test_compile_path_never_imports_ray_or_deepspeed():
f"{PKG}.plan",
f"{PKG}.config",
f"{PKG}.protocols",
- f"{PKG}.support_matrix",
):
assert _import_leaks(module, ["ray", "deepspeed", "cupy"]) == [], module
@@ -44,7 +43,7 @@ def test_schema_modules_are_plain_data():
import ast
import importlib.util
- for module in (f"{PKG}.plan", f"{PKG}.config", f"{PKG}.protocols", f"{PKG}.support_matrix"):
+ for module in (f"{PKG}.plan", f"{PKG}.config", f"{PKG}.protocols"):
source = open(importlib.util.find_spec(module).origin).read()
for node in ast.walk(ast.parse(source)):
names = (
diff --git a/training/rdsp/tests/unit/test_bench_export.py b/training/rdsp/tests/bench/test_bench_export.py
similarity index 97%
rename from training/rdsp/tests/unit/test_bench_export.py
rename to training/rdsp/tests/bench/test_bench_export.py
index c15621c24..b0a015667 100644
--- a/training/rdsp/tests/unit/test_bench_export.py
+++ b/training/rdsp/tests/bench/test_bench_export.py
@@ -11,7 +11,10 @@
import torch
HERE = os.path.dirname(os.path.abspath(__file__))
-sys.path[:0] = [os.path.join(HERE, "..", "..", "bench", "common"), os.path.join(HERE, "..", "..")]
+sys.path[:0] = [
+ os.path.join(HERE, "..", "..", "bench", "compare", "lib"),
+ os.path.join(HERE, "..", ".."),
+]
from export_bridge_batches import save_step, to_rdsp_sample # noqa: E402
diff --git a/training/rdsp/tests/bench/test_bench_scripts.py b/training/rdsp/tests/bench/test_bench_scripts.py
new file mode 100644
index 000000000..e184a90bd
--- /dev/null
+++ b/training/rdsp/tests/bench/test_bench_scripts.py
@@ -0,0 +1,103 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+
+"""The table scripts under DRY=1: every system prints one command, rdsp's flags parse with
+train_vl.py, and every TorchTitan config they name exists in cord_qwen35.py."""
+
+import importlib.util
+import os
+import re
+import shlex
+import subprocess
+
+import pytest
+
+ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")
+BENCH = os.path.join(ROOT, "bench", "compare")
+SYSTEMS = [
+ ("qwen35_35b.sh", ["rdsp"]),
+ ("qwen35_35b.sh", ["rdsp-hf"]),
+ ("qwen35_35b.sh", ["bridge"]),
+ ("qwen35_35b.sh", ["torchtitan"]),
+ ("qwen35_35b.sh", ["figure2-vision"]),
+ ("qwen35_35b.sh", ["figure2-pp8"]),
+ ("qwen35_27b.sh", ["rdsp"]),
+ ("qwen35_27b.sh", ["rdsp-fp32"]),
+ ("qwen35_27b.sh", ["rdsp-pp8"]),
+ ("qwen35_27b.sh", ["rdsp-pp8-cut"]),
+ ("qwen35_27b.sh", ["bridge"]),
+ ("qwen35_27b.sh", ["torchtitan"]),
+ ("qwen35_9b.sh", ["rdsp"]),
+ ("qwen35_9b.sh", ["bridge"]),
+ ("qwen35_9b.sh", ["torchtitan"]),
+ ("mimo.sh", ["9b", "rdsp"]),
+ ("mimo.sh", ["9b", "mimo"]),
+ ("mimo.sh", ["27b", "rdsp"]),
+ ("mimo.sh", ["27b", "mimo"]),
+ ("mimo.sh", ["9b-10gpu", "rdsp"]),
+ ("mimo.sh", ["9b-10gpu", "mimo"]),
+]
+
+
+def dry(script, args, **env):
+ out = subprocess.run(
+ ["bash", os.path.join(BENCH, script), *args],
+ capture_output=True,
+ text=True,
+ env={**os.environ, "DRY": "1", "LAYOUT": "Et*9|t*9L", **env},
+ )
+ assert out.returncode == 0, out.stderr
+ return [line for line in out.stdout.splitlines() if not line.startswith("LAYOUT=")]
+
+
+def train_vl_parser():
+ spec = importlib.util.spec_from_file_location("train_vl", os.path.join(ROOT, "train_vl.py"))
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module.build_parser()
+
+
+@pytest.mark.parametrize(
+ "script,args", SYSTEMS, ids=lambda v: v if isinstance(v, str) else "-".join(v)
+)
+def test_every_system_prints_one_command(script, args):
+ assert len(dry(script, args)) == 1
+
+
+def train_vl_flags(command):
+ """The flags a printed rdsp command gives train_vl.py: a recipe's own, then the extras."""
+ words = shlex.split(command)
+ recipe = next((w for w in words if w.startswith("recipes/")), None)
+ if recipe is None:
+ return words[words.index("train_vl.py") + 1 :]
+ body = shlex.split(open(os.path.join(ROOT, recipe)).read().replace("\\\n", " "), comments=True)
+ own = body[body.index("$ROOT/train_vl.py") + 1 : body.index("$@")]
+ return own + words[words.index(recipe) + 1 :]
+
+
+@pytest.mark.parametrize(
+ "script,args", [s for s in SYSTEMS if s[1][-1].startswith(("rdsp", "figure2"))]
+)
+def test_rdsp_flags_parse(script, args):
+ (command,) = dry(script, args)
+ parsed = train_vl_parser().parse_args(train_vl_flags(command))
+ assert parsed.rows * parsed.microbatches == 128 # every run trains 128 rows a step
+
+
+def test_megatron_runs_join_the_other_nodes():
+ (command,) = dry("qwen35_35b.sh", ["bridge"], NNODES="2", NODE_RANK="1", MASTER_ADDR="10.1.2.3")
+ assert "--nnodes 2 --node_rank 1 --master_addr 10.1.2.3" in command
+
+
+def test_the_27b_mimo_language_runs_on_node_0_and_vision_on_node_1():
+ (node0,) = dry("mimo.sh", ["27b", "mimo"], NNODES="2", NODE_RANK="0")
+ (node1,) = dry("mimo.sh", ["27b", "mimo"], NNODES="2", NODE_RANK="1")
+ assert "--nproc_per_node 8" in node0 and "--nproc_per_node 1" in node1
+
+
+def test_every_torchtitan_config_exists():
+ titan = open(os.path.join(BENCH, "torchtitan", "cord_qwen35.py")).read()
+ for script in ("qwen35_35b.sh", "qwen35_27b.sh", "qwen35_9b.sh"):
+ (command,) = dry(script, ["torchtitan"])
+ config = re.search(r"--config (\S+)", command).group(1)
+ assert f"def {config}(" in titan, config
diff --git a/training/rdsp/tests/bench/test_bridge_replay.py b/training/rdsp/tests/bench/test_bridge_replay.py
new file mode 100644
index 000000000..8c2502ec2
--- /dev/null
+++ b/training/rdsp/tests/bench/test_bridge_replay.py
@@ -0,0 +1,78 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+
+"""bench/compare/lib/bridge_replay.py: runs Megatron-Bridge's own launcher with a train loader that
+builds every batch of the run before step 1. Checked on a stand-in for Bridge's package: its
+loaders module gets its batches from build_pretraining_data_loader, as in v0.6.0."""
+
+import os
+import subprocess
+import sys
+
+ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")
+REPLAY = os.path.join(ROOT, "bench", "compare", "lib", "bridge_replay.py")
+LOADERS = """
+def build_pretraining_data_loader(dataset, consumed, kind, micro_batch_size, num_workers,
+ data_sharding, *, data_parallel_size, global_batch_size, **kw):
+ return Loader()
+
+
+class Loader:
+ built = 0
+ batch_sampler = "kept"
+
+ def __iter__(self):
+ for i in range(LENGTH):
+ Loader.built += 1
+ yield i
+
+
+def setup_data_iterators():
+ loader = build_pretraining_data_loader("rows", 0, "single", 2, 8, True, data_parallel_size=4,
+ global_batch_size=32, seed=1)
+ assert loader.batch_sampler == "kept"
+ return iter(loader)
+"""
+LAUNCHER = """
+import sys
+import os
+assert "megatron" not in sys.modules # Bridge sets its environment before it imports anything
+from megatron.bridge.data.loaders import Loader, setup_data_iterators
+batches = setup_data_iterators()
+print("built", Loader.built, "args", sys.argv[1:], "name", __name__, os.path.basename(__file__))
+print("batches", list(batches))
+"""
+
+
+def launch(tmp_path, steps, length=100):
+ package = tmp_path / "megatron" / "bridge" / "data"
+ package.mkdir(parents=True)
+ for folder in (package.parent.parent, package.parent, package):
+ (folder / "__init__.py").write_text("")
+ (package / "loaders.py").write_text(LOADERS.replace("LENGTH", str(length)))
+ script = tmp_path / "scripts" / "training" / "run_recipe.py"
+ script.parent.mkdir(parents=True)
+ script.write_text(LAUNCHER)
+ return subprocess.run(
+ [sys.executable, REPLAY, "--recipe", "x"],
+ capture_output=True,
+ text=True,
+ check=False,
+ cwd=tmp_path,
+ env={**os.environ, "PYTHONPATH": str(tmp_path), "BRIDGE_REPLAY_STEPS": str(steps)},
+ )
+
+
+def test_every_batch_is_built_before_the_first_is_used(tmp_path):
+ out = launch(tmp_path, 3)
+ assert out.returncode == 0, out.stderr
+ # 3 steps x 32 rows / 4 data-parallel copies / 2 rows a microbatch, and none beyond the run
+ assert "built 12 args ['--recipe', 'x'] name __main__ run_recipe.py" in out.stdout
+ assert f"batches {list(range(12))}" in out.stdout
+ assert "BRIDGE_REPLAY: 12 batches ready before step 1" in out.stdout
+
+
+def test_a_loader_that_ends_early_stops_the_run(tmp_path):
+ out = launch(tmp_path, 3, length=5)
+ assert out.returncode != 0
+ assert "BRIDGE_REPLAY: 5 of 12 batches" in out.stderr
diff --git a/training/rdsp/tests/unit/test_two_node_layout_from_log.py b/training/rdsp/tests/bench/test_layout_from_log.py
similarity index 64%
rename from training/rdsp/tests/unit/test_two_node_layout_from_log.py
rename to training/rdsp/tests/bench/test_layout_from_log.py
index 24a77d130..b78055ae0 100644
--- a/training/rdsp/tests/unit/test_two_node_layout_from_log.py
+++ b/training/rdsp/tests/bench/test_layout_from_log.py
@@ -1,14 +1,14 @@
# SPDX-License-Identifier: Apache-2.0
# DeepSpeed Team
-"""bench/common/layout_from_log.py: Bridge's cut and the vision stage's
+"""bench/compare/lib/layout_from_log.py: Bridge's cut and the vision stage's
width for the two-node runs, read from rdsp's run 1 log rather than picked by hand."""
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
-sys.path.insert(0, os.path.join(HERE, "..", "..", "bench", "common"))
+sys.path.insert(0, os.path.join(HERE, "..", "..", "bench", "compare", "lib"))
import layout_from_log as lfl # noqa: E402
@@ -47,3 +47,30 @@ def test_vision_width_balances_vision_and_language_gpu_time():
assert lfl.vision_width(m["cuts"], m["seconds"], 40, 2, 16) == 4
# little vision: the narrowest stage
assert lfl.vision_width(m["cuts"], (2.6,) + m["seconds"][1:], 40, 2, 16) == 2
+
+
+def test_megatron_layout_is_rdsp_cut_exactly():
+ # Bridge's pipeline_model_parallel_layout: E (embedding, and the vision encoder) on the
+ # first stage, L (loss) on the last, t*n the decoder layers of each stage
+ blocks = [b - a for a, b in lfl.last_stage_blocks(LOG)]
+ assert lfl.megatron_layout(blocks) == "Et|t*7|t*7|t*7|t*7|t*7|t*3|tL"
+
+
+def test_megatron_layout_cli(capsys):
+ import subprocess
+
+ path = os.path.join(os.environ.get("TMPDIR", "/tmp"), "rdsp-layout-test.log")
+ with open(path, "w") as f:
+ f.write(LOG)
+ out = subprocess.run(
+ [
+ sys.executable,
+ os.path.join(HERE, "..", "..", "bench", "compare", "lib", "layout_from_log.py"),
+ "megatron-layout",
+ path,
+ ],
+ capture_output=True,
+ text=True,
+ check=True,
+ )
+ assert out.stdout.strip() == "Et|t*7|t*7|t*7|t*7|t*7|t*3|tL"
diff --git a/training/rdsp/tests/bench/test_patch_mimo.py b/training/rdsp/tests/bench/test_patch_mimo.py
new file mode 100644
index 000000000..efcd2ec10
--- /dev/null
+++ b/training/rdsp/tests/bench/test_patch_mimo.py
@@ -0,0 +1,89 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+
+"""bench/compare/lib/patch_mimo.py, on a launcher that has the lines it edits: with MIMO_REPLAY=1
+the loader builds every batch of the run before training starts, as rdsp's and TorchTitan's replayed
+rows are ready before theirs; without it, the loader is read while training."""
+
+import os
+import subprocess
+import sys
+import types
+
+import pytest
+
+ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")
+PATCH = os.path.join(ROOT, "bench", "compare", "lib", "patch_mimo.py")
+LAUNCHER = """import os
+from collections.abc import Iterator
+from typing import Any
+
+
+def unused(optimizer_cfg, torch, cfg, args, standard_provider):
+ optimizer_cfg.use_precision_aware_optimizer = False
+ optimizer_cfg.main_grads_dtype = torch.float32
+ optimizer_cfg.main_params_dtype = torch.float32
+ dict(
+ grad_reduce_in_fp32=True,
+ )
+ cfg.mixed_precision = "bf16_mixed" if not args.fp32 else None
+ if hasattr(standard_provider, "mtp_num_layers"):
+ pass
+
+
+def outer(cfg, train_loader):
+ def build():
+ loader_iter: Iterator[dict[str, Any]] = iter(train_loader)
+ return loader_iter
+
+ return build()
+"""
+
+
+class Loader:
+ """Counts the batches it has built; more of them than the run needs."""
+
+ def __init__(self):
+ self.built = 0
+
+ def __iter__(self):
+ for i in range(100):
+ self.built += 1
+ yield {"batch": i}
+
+
+def patched(tmp_path, monkeypatch, replay):
+ path = tmp_path / "launcher.py"
+ path.write_text(LAUNCHER)
+ subprocess.run([sys.executable, PATCH, str(path)], check=True, capture_output=True)
+ if replay is None:
+ monkeypatch.delenv("MIMO_REPLAY", raising=False)
+ else:
+ monkeypatch.setenv("MIMO_REPLAY", replay)
+ module = types.ModuleType("launcher")
+ exec(path.read_text(), module.__dict__)
+ train = types.SimpleNamespace(train_iters=3, global_batch_size=16, micro_batch_size=4)
+ return module, types.SimpleNamespace(train=train)
+
+
+def test_replay_builds_every_batch_before_training(tmp_path, monkeypatch):
+ module, cfg = patched(tmp_path, monkeypatch, "1")
+ loader = Loader()
+ batches = module.outer(cfg, loader)
+ assert loader.built == 12 # 3 steps x 16 rows / 4 a microbatch, and none beyond the run
+ assert [b["batch"] for b in batches] == list(range(12))
+
+
+@pytest.mark.parametrize("replay", [None, "0"])
+def test_without_replay_the_loader_is_read_while_training(tmp_path, monkeypatch, replay):
+ module, cfg = patched(tmp_path, monkeypatch, replay)
+ loader = Loader()
+ batches = module.outer(cfg, loader)
+ assert loader.built == 0
+ assert next(batches) == {"batch": 0}
+
+
+def test_a_loader_that_ends_early_stops_the_run(tmp_path, monkeypatch):
+ module, cfg = patched(tmp_path, monkeypatch, "1")
+ with pytest.raises(RuntimeError, match="MIMO_REPLAY"):
+ module.outer(cfg, [{"batch": 0}])
diff --git a/training/rdsp/tests/bench/test_results.py b/training/rdsp/tests/bench/test_results.py
new file mode 100644
index 000000000..88821748c
--- /dev/null
+++ b/training/rdsp/tests/bench/test_results.py
@@ -0,0 +1,67 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+
+"""bench/results.py: the median of training steps 6-15 from each framework's log format."""
+
+import os
+import sys
+
+import pytest
+
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "bench"))
+
+import results # noqa: E402
+
+
+def rdsp_log(ms, steps=15, slow_first=0): # rdsp counts steps from 0
+ return "".join(
+ f"step {i} loss 0.5 {99999 if i < slow_first else ms} ms 1 real tok/s\n"
+ for i in range(steps)
+ )
+
+
+def megatron_log(ms, steps=15, slow_first=0): # Megatron counts iterations from 1
+ return "".join(
+ f" iteration {i}/ {steps} | consumed samples: 1 | elapsed time per iteration (ms): "
+ f"{99999 if i <= slow_first else ms} |\n"
+ for i in range(1, steps + 1)
+ )
+
+
+def titan_log(ms, steps=15, slow_first=0): # the gap between "step: N" stamps, from 1
+ lines, t = [], 0.0
+ for i in range(1, steps + 1):
+ t += (99999 if i <= slow_first else ms) / 1000
+ h, rem = divmod(t, 3600)
+ m, s = divmod(rem, 60)
+ stamp = f"{int(h):02d}:{int(m):02d}:{int(s):02d},{int(round((s % 1) * 1000)):03d}"
+ lines.append(
+ f"[rank0]:[titan] 2026-01-01 {stamp} - torchtitan.observability.metrics - INFO - "
+ f"step: {i:2d} loss: 0.5\n"
+ )
+ return "".join(lines)
+
+
+@pytest.mark.parametrize(
+ "log,framework", [(rdsp_log, "rdsp"), (megatron_log, "megatron"), (titan_log, "torchtitan")]
+)
+def test_the_first_five_steps_do_not_count(log, framework):
+ assert results.measure(log(5410, slow_first=5)) == (framework, pytest.approx(5.41))
+
+
+def test_a_run_short_of_fifteen_steps_has_no_median():
+ assert results.measure(rdsp_log(5000, steps=12)) == ("rdsp", None)
+
+
+def test_the_other_node_of_a_megatron_run_reads_its_step_time_lines():
+ text = "".join("Step Time : 7.93s\n" for _ in range(15))
+ assert results.measure(text) == ("megatron", pytest.approx(7.93))
+
+
+def test_tokens_per_gpu_follow_the_gpus_used(tmp_path, capsys):
+ log = tmp_path / "rdsp.log"
+ log.write_text(rdsp_log(5410))
+ results.main([str(log)])
+ assert "3,028" in capsys.readouterr().out # 128 x 2,048 tokens / 5.41 s / 16 GPUs
+ results.main([str(log), "--gpus", "9"])
+ assert "5,384" in capsys.readouterr().out
diff --git a/training/rdsp/tests/bench/test_torchtitan_configs.py b/training/rdsp/tests/bench/test_torchtitan_configs.py
new file mode 100644
index 000000000..a9f34b356
--- /dev/null
+++ b/training/rdsp/tests/bench/test_torchtitan_configs.py
@@ -0,0 +1,183 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+
+"""bench/compare/torchtitan/cord_qwen35.py builds the 16-GPU configs the table scripts run (imported
+against stand-ins for TorchTitan, which CPU test machines do not have)."""
+
+import ast
+import importlib.util
+import os
+import re
+import sys
+import types
+
+import pytest
+
+ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")
+TITAN = os.path.join(ROOT, "bench", "compare", "torchtitan", "cord_qwen35.py")
+
+
+class _Made:
+ """What a stand-in TorchTitan class returns: its name and the arguments it got."""
+
+ def __init__(self, kind, args, kwargs):
+ self.kind, self.args = kind, args
+ self.__dict__.update(kwargs)
+
+
+class _Stub:
+ """A stand-in for any TorchTitan name: calling it records the call; attributes
+ (Foo.Config) are stand-ins too."""
+
+ def __init__(self, name):
+ self.__name__ = name
+
+ def __call__(self, *args, **kwargs):
+ return _Made(self.__name__, args, kwargs)
+
+ def __getattr__(self, attr):
+ if attr.startswith("__"):
+ raise AttributeError(attr)
+ return _Stub(f"{self.__name__}.{attr}")
+
+
+class _StubModule(types.ModuleType):
+ def __getattr__(self, name):
+ if name.startswith("__"):
+ raise AttributeError(name)
+ return _Stub(name)
+
+
+@pytest.fixture
+def titan(monkeypatch):
+ """bench/compare/torchtitan/cord_qwen35.py imported against stand-ins for TorchTitan and
+ cord_data, so its config functions run on a CPU without TorchTitan installed."""
+ tree = ast.parse(open(TITAN).read())
+ for node in tree.body:
+ if isinstance(node, ast.ImportFrom) and node.module:
+ parts = node.module.split(".")
+ for i in range(1, len(parts) + 1):
+ name = ".".join(parts[:i])
+ monkeypatch.setitem(sys.modules, name, _StubModule(name))
+ sys.modules["torchtitan.models.qwen3_5"].QWEN3_5_SPECIAL_TOKENS = {}
+ # the model's layers, for the MoE configs that switch the router's balancing loss off
+ sys.modules["torchtitan.models.qwen3_5"].build_model_config = lambda *args, **kwargs: _Made(
+ "build_model_config", args, {**kwargs, "layers": []}
+ )
+ sys.modules["cord_data"].ROWS_PER_STEP = 128
+ monkeypatch.setenv("EXPORTED", "/rows")
+ monkeypatch.setenv("HF_ASSETS", "/weights")
+ monkeypatch.delenv("MB_ROWS", raising=False)
+ spec = importlib.util.spec_from_file_location("cord_qwen35_under_test", TITAN)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+@pytest.mark.parametrize(
+ "name,tp,shard",
+ [
+ ("qwen35_9b_cord_fsdp16_bf16", 1, 16),
+ ("qwen35_9b_cord_fsdp16_rc_bf16", 1, 16),
+ ("qwen35_9b_cord_tp2fsdp8_bf16", 2, 8),
+ ("qwen35_9b_cord_tp4fsdp4_bf16", 4, 4),
+ ],
+)
+def test_titan_9b_configs(titan, name, tp, shard):
+ config = getattr(titan, name)()
+ assert config.model.args[0] == "9B"
+ assert config.parallelism.tensor_parallel_degree == tp
+ assert config.parallelism.data_parallel_shard_degree == shard
+ assert tp * shard == 16
+ # rows dealt to as many copies as FSDP has, as Megatron deals them
+ assert config.dataloader.data_parallel == shard
+ # gradients reduced in bf16, as Bridge and rdsp send theirs
+ assert config.training.mixed_precision_reduce == "bfloat16"
+ assert config.training.num_tokens_per_train_step == 128 * 2048
+
+
+def test_titan_9b_rc_recomputes_every_block(titan):
+ assert titan.qwen35_9b_cord_fsdp16_rc_bf16().activation_checkpoint.kind == "FullAC.Config"
+ assert titan.qwen35_9b_cord_fsdp16_bf16().activation_checkpoint is None
+
+
+@pytest.mark.parametrize(
+ "name",
+ [
+ "qwen35_27b_cord_fsdp16_bf16",
+ "qwen35_27b_cord_fsdp16_rc_bf16",
+ "qwen35_27b_cord_fsdp16_ffnrc_bf16",
+ ],
+)
+def test_titan_27b_16gpu_configs(titan, name):
+ config = getattr(titan, name)()
+ assert config.model.args[0] == "27B"
+ assert config.parallelism.data_parallel_shard_degree == 16
+ assert config.training.mixed_precision_reduce == "bfloat16"
+
+
+@pytest.mark.parametrize("rows,tokens", [(None, 2048), ("2", 4096), ("4", 8192)])
+def test_titan_rows_per_microbatch_from_env(titan, monkeypatch, rows, tokens):
+ # MB_ROWS (default 1): rows each GPU runs per microbatch, for the 1/2/4-row search
+ if rows:
+ monkeypatch.setenv("MB_ROWS", rows)
+ config = titan.qwen35_9b_cord_fsdp16_bf16()
+ assert config.training.num_tokens_per_microbatch_per_dp_rank == tokens
+
+
+@pytest.mark.parametrize(
+ "name,flavor,shard,replicate,ep,full_ac",
+ [
+ ("qwen35_35b_a3b_cord_fsdp16_ep8_rc_bf16", "35B-A3B", 16, 1, 8, True),
+ ("qwen35_35b_a3b_cord_fsdp16_ep16_bf16", "35B-A3B", 16, 1, 16, False),
+ ("qwen35_35b_a3b_cord_fsdp16_ep16_rc_bf16", "35B-A3B", 16, 1, 16, True),
+ ("qwen35_9b_cord_hsdp2x8_bf16", "9B", 8, 2, 1, False),
+ ("qwen35_27b_cord_hsdp2x8_rc_bf16", "27B", 8, 2, 1, True),
+ ],
+)
+def test_titan_audit_layouts(titan, name, flavor, shard, replicate, ep, full_ac):
+ config = getattr(titan, name)()
+ p = config.parallelism
+ assert config.model.args[0] == flavor
+ assert p.data_parallel_shard_degree == shard
+ assert getattr(p, "data_parallel_replicate_degree", 1) == replicate
+ assert getattr(p, "expert_parallel_degree", 1) == ep
+ # every GPU is one data-parallel copy: 16 copies take the step's rows
+ assert config.dataloader.data_parallel == 16
+ assert config.training.mixed_precision_reduce == "bfloat16"
+ ac = config.activation_checkpoint
+ assert (ac is not None and ac.kind == "FullAC.Config") == full_ac
+
+
+def test_titan_9b_keeps_gathered_weights_for_backward(titan):
+ config = titan.qwen35_9b_cord_fsdp16_noreshard_bf16()
+ assert config.parallelism.fsdp_reshard_after_forward == "never"
+ assert config.parallelism.data_parallel_shard_degree == 16
+ assert config.training.mixed_precision_reduce == "bfloat16"
+
+
+@pytest.mark.parametrize(
+ "name",
+ [
+ "qwen35_9b_cord_fsdp16_bf16",
+ "qwen35_27b_cord_fsdp16_rc_bf16",
+ "qwen35_35b_a3b_cord_fsdp16_ep8_bf16",
+ ],
+)
+def test_titan_tracing_off(titan, name):
+ # TorchTitan's NCCL flight recorder and structured logging off, as Bridge's NaN checks are
+ config = getattr(titan, name)()
+ assert config.comm.trace_buf_size == 0
+ assert config.debug.enable_structured_logging is False
+
+
+def test_every_listed_titan_config_builds(titan):
+ # every TorchTitan config a table script names exists and builds
+ scripts = [
+ os.path.join(ROOT, "bench", "compare", f"qwen35_{m}.sh") for m in ("9b", "27b", "35b")
+ ]
+ names = [n for p in scripts for n in re.findall(r"titan torchtitan (\w+)", open(p).read())]
+ assert names
+ for name in names:
+ config = getattr(titan, name)()
+ assert config.training.mixed_precision_reduce == "bfloat16", name
diff --git a/training/rdsp/tests/contract/test_initialize_return_tuple.py b/training/rdsp/tests/contract/test_initialize_return_tuple.py
index f365ce5f4..bebadbe5e 100644
--- a/training/rdsp/tests/contract/test_initialize_return_tuple.py
+++ b/training/rdsp/tests/contract/test_initialize_return_tuple.py
@@ -9,7 +9,7 @@
from torch.utils.data import DataLoader
import ray_deepspeed_pipeline as rdsp
-from ray_deepspeed_pipeline.errors import UnsupportedInV1, ValidationError
+from ray_deepspeed_pipeline.errors import UnsupportedFeature, ValidationError
def _init(model, pipeline_config, **overrides):
@@ -37,14 +37,14 @@ def test_third_element_none_without_training_data(fake_coordinator, tiny_model,
def test_preconstructed_optimizer_rejected(fake_coordinator, tiny_model, pipeline_config):
opt = torch.optim.AdamW(tiny_model.parameters())
- with pytest.raises(UnsupportedInV1):
+ with pytest.raises(UnsupportedFeature):
_init(tiny_model, pipeline_config, optimizer=opt)
def test_preconstructed_scheduler_rejected(fake_coordinator, tiny_model, pipeline_config):
opt = torch.optim.AdamW(tiny_model.parameters())
sched = torch.optim.lr_scheduler.StepLR(opt, step_size=1)
- with pytest.raises(UnsupportedInV1):
+ with pytest.raises(UnsupportedFeature):
_init(tiny_model, pipeline_config, lr_scheduler=sched)
@@ -72,13 +72,13 @@ def test_all_model_parameters_accepted(fake_coordinator, tiny_model, pipeline_co
def test_parameter_subsets_and_groups_rejected(fake_coordinator, tiny_model, pipeline_config):
"""Each stage optimizes every parameter it owns; anything narrower would be
silently ignored, so it is refused."""
- with pytest.raises(UnsupportedInV1, match="subsets"):
+ with pytest.raises(UnsupportedFeature, match="subsets"):
_init(tiny_model, pipeline_config, model_parameters=tiny_model[0].parameters())
groups = [
{"params": list(tiny_model[0].parameters()), "lr": 0.1},
{"params": list(tiny_model[2].parameters())},
]
- with pytest.raises(UnsupportedInV1, match="groups"):
+ with pytest.raises(UnsupportedFeature, match="groups"):
_init(tiny_model, pipeline_config, model_parameters=groups)
diff --git a/training/rdsp/tests/integration/test_stage_placement.py b/training/rdsp/tests/integration/test_stage_placement.py
new file mode 100644
index 000000000..f440424ae
--- /dev/null
+++ b/training/rdsp/tests/integration/test_stage_placement.py
@@ -0,0 +1,87 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+
+"""Where a stage's GPUs land on a cluster of several nodes. The pipeline's stages are planned to
+fill nodes in order, so that it crosses between nodes as few times as it can; a stage placed on
+another node because its own looked busy for a moment makes every microbatch cross more often
+(measured: 9B on two nodes, 3.5 s a step with one crossing, 4.3 s with three). A local Ray with
+two 8-GPU nodes; no CUDA."""
+
+import threading
+import time
+
+import pytest
+
+ray = pytest.importorskip("ray")
+from ray.cluster_utils import Cluster # noqa: E402
+from ray.util.placement_group import placement_group_table, remove_placement_group # noqa: E402
+
+from ray_deepspeed_pipeline.stage_group import place_stage # noqa: E402
+
+
+@pytest.fixture
+def two_nodes():
+ if ray.is_initialized():
+ ray.shutdown()
+ cluster = Cluster(initialize_head=True, head_node_args={"num_cpus": 32, "num_gpus": 8})
+ cluster.add_node(num_cpus=32, num_gpus=8)
+ ray.init(address=cluster.address, log_to_driver=False)
+ nodes = sorted(
+ (n["NodeID"] for n in ray.nodes() if n["Resources"].get("GPU")),
+ key=lambda i: i != ray.get_runtime_context().get_node_id(), # the driver's node first
+ )
+ yield nodes
+ ray.shutdown()
+ cluster.shutdown()
+
+
+def node_of(pg):
+ return next(iter(set(placement_group_table(pg)["bundles_to_node_id"].values())))
+
+
+@ray.remote(num_gpus=8)
+class Holder:
+ def ready(self):
+ return 1
+
+
+def occupy(node):
+ holder = Holder.options(
+ scheduling_strategy=ray.util.scheduling_strategies.NodeAffinitySchedulingStrategy(
+ node_id=node, soft=False
+ )
+ ).remote()
+ ray.get(holder.ready.remote())
+ return holder
+
+
+def test_a_planned_stage_waits_for_its_own_machine(two_nodes):
+ first, second = two_nodes
+ holder = occupy(first) # e.g. the calibration engine, still releasing its GPUs
+ threading.Timer(4.0, lambda: ray.kill(holder)).start()
+ start = time.monotonic()
+ pg = place_stage(4, "STRICT_PACK", first, hard=True, timeout=60)
+ assert node_of(pg) == first
+ assert time.monotonic() - start > 2 # it waited for the GPUs, it did not move to `second`
+ remove_placement_group(pg)
+
+
+def test_a_planned_stage_falls_back_when_its_machine_stays_busy(two_nodes, monkeypatch):
+ first, second = two_nodes
+ monkeypatch.setattr("ray_deepspeed_pipeline.stage_group._HARD_PLACEMENT_S", 1.0)
+ holder = occupy(first) # kept: Ray stops an actor whose handle is gone
+ pg = place_stage(4, "STRICT_PACK", first, hard=True, timeout=60)
+ assert holder is not None
+ assert node_of(pg) == second
+ remove_placement_group(pg)
+
+
+def test_a_preference_kept_from_a_rebuild_stays_soft(two_nodes):
+ first, second = two_nodes
+ holder = occupy(first) # the stage's old machine, gone or busy
+ start = time.monotonic()
+ pg = place_stage(4, "STRICT_PACK", first, hard=False, timeout=60)
+ assert holder is not None
+ assert node_of(pg) == second
+ assert time.monotonic() - start < 10
+ remove_placement_group(pg)
diff --git a/training/rdsp/tests/integration/test_two_stage_baseline.py b/training/rdsp/tests/integration/test_two_stage_baseline.py
index 231c23b2a..739db9e9a 100644
--- a/training/rdsp/tests/integration/test_two_stage_baseline.py
+++ b/training/rdsp/tests/integration/test_two_stage_baseline.py
@@ -150,8 +150,7 @@ def test_parity_loss_and_detached_cpu_loss_no_objectref(first_row):
def test_parity_optimizer_update_and_deepspeed_pipeline_behavior(first_row):
- """Repeated steps on one batch must reduce the loss. Exact gradient parity
- of the external-gradient backward is covered by tests/spikes."""
+ """Repeated steps on one batch must reduce the loss."""
model, plan, clients, engine, batch = first_row
losses = [float(engine.train_batch(data_iter=iter(microbatches(batch)))) for _ in range(3)]
assert losses[-1] < losses[0], f"loss must decrease when overfitting: {losses}"
diff --git a/training/rdsp/tests/integration/test_vl_pipeline.py b/training/rdsp/tests/integration/test_vl_pipeline.py
index 6e23bcb83..3468a0254 100644
--- a/training/rdsp/tests/integration/test_vl_pipeline.py
+++ b/training/rdsp/tests/integration/test_vl_pipeline.py
@@ -458,6 +458,31 @@ def test_colocated_vision_matches_unsplit_model(
assert got == pytest.approx(expected, rel=1e-4)
+@needs_qwen3_5
+@pytest.mark.parametrize(
+ "colocated",
+ [
+ rdsp.ColocatedVision(first_stage_only=True),
+ rdsp.ColocatedVision(first_stage_only=True, encode_per_microbatch=True, encode_chunk=2),
+ ],
+ ids=["whole-step", "chunks-of-2"],
+)
+def test_first_stage_vision_batches_match_unsplit_model(ray_ctx, stub_engines, colocated):
+ """A vision-only first stage (first cut at 0, 2 data-parallel ranks) whose encoder runs
+ batched: each rank encodes its own rows' images several microbatches at a time instead
+ of once per microbatch, and trains as the unsplit model does."""
+ model, reference = qwen3_5_vl_pair(seed=8)
+ expected = unsplit_losses(reference, make_batches(), steps=3)
+ got = pipelined_losses(
+ model,
+ (0, 3),
+ steps=3,
+ overrides=(StageOverride(stage=0, num_gpus=2),),
+ colocated_vision=colocated,
+ )
+ assert got == pytest.approx(expected, rel=1e-4)
+
+
def test_prefetch_matches_unsplit_model(ray_ctx, stub_engines):
"""Reading the next step ahead changes when data moves, not what trains."""
torch.manual_seed(0)
diff --git a/training/rdsp/tests/spikes/test_deepspeed_public_reuse.py b/training/rdsp/tests/spikes/test_deepspeed_public_reuse.py
deleted file mode 100644
index 18f8adf08..000000000
--- a/training/rdsp/tests/spikes/test_deepspeed_public_reuse.py
+++ /dev/null
@@ -1,479 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-
-"""Public DeepSpeed APIs alone support stage-local pipeline stages (no Ray).
-
-Checked on GPUs, with only public DeepSpeed APIs at the pinned revision
-53a2ac44fb664bea838df3981ba4366b91643070 (no DeepSpeed file is modified):
- - concurrent stage-local default process groups with isolated collectives
- - external-gradient backward on a non-terminal stage, two candidates:
- "vjp": engine.backward((out * grad).sum() * gas)
- "direct": out.backward(gradient=grad)
- with loss/grad/optimizer-step parity vs a monolithic connected baseline,
- across ZeRO 0/1/2/3, fp32/bf16, multi-output stages with non-floating
- metadata, and gradient accumulation
- - stage-local checkpoint save/load round trip and next-step parity
-
-Workers are plain torch.multiprocessing processes: Ray is deliberately absent.
-"""
-
-import dataclasses
-import os
-import tempfile
-
-import numpy as np
-import pytest
-import torch
-import torch.distributed as dist
-import torch.multiprocessing as mp
-import torch.nn as nn
-
-deepspeed = pytest.importorskip("deepspeed")
-
-NEEDED_GPUS = 4
-pytestmark = pytest.mark.skipif(
- not torch.cuda.is_available() or torch.cuda.device_count() < NEEDED_GPUS,
- reason=f"needs {NEEDED_GPUS} CUDA devices",
-)
-
-LR = 1e-2
-BATCH = 8 # full global batch rows; DP=2 -> 4 rows per rank
-
-
-# --------------------------------------------------------------------------
-# fixtures: tiny deterministic stage modules
-# --------------------------------------------------------------------------
-
-
-class TwoHeadStage(nn.Module):
- """Multi-output first stage: two float outputs + non-floating metadata."""
-
- def __init__(self):
- super().__init__()
- self.body = nn.Linear(16, 32)
- self.h1 = nn.Linear(32, 8)
- self.h2 = nn.Linear(32, 8)
-
- def forward(self, x):
- b = torch.tanh(self.body(x))
- meta = torch.tensor([x.shape[0]], dtype=torch.long, device=x.device)
- return self.h1(b), self.h2(b), meta
-
-
-class TwoHeadConsumer(nn.Module):
- def __init__(self):
- super().__init__()
- self.out = nn.Linear(8, 4)
-
- def forward(self, a, b, meta):
- assert meta.dtype == torch.long # metadata passed through untouched
- return self.out(a + b)
-
-
-def build_stages(multi_output):
- torch.manual_seed(0)
- if multi_output:
- return TwoHeadStage(), TwoHeadConsumer()
- stage0 = nn.Sequential(nn.Linear(16, 32), nn.Tanh(), nn.Linear(32, 32), nn.Tanh())
- stage1 = nn.Sequential(nn.Linear(32, 4))
- return stage0, stage1
-
-
-def make_data(dtype):
- torch.manual_seed(1)
- x = torch.randn(BATCH, 16).to(dtype)
- y = torch.randn(BATCH, 4).to(dtype)
- return x, y
-
-
-def ds_config(zero, dtype, gas):
- micro = BATCH // (2 * gas) # DP world is 2 in every parity run
- cfg = {
- "train_batch_size": BATCH,
- "train_micro_batch_size_per_gpu": micro,
- "gradient_accumulation_steps": gas,
- "optimizer": {
- "type": "AdamW",
- "params": {
- "lr": LR,
- "betas": [0.9, 0.999],
- "eps": 1e-8,
- "weight_decay": 0.0,
- "torch_adam": True,
- },
- },
- "zero_optimization": {"stage": zero},
- "steps_per_print": 1000,
- "wall_clock_breakdown": False,
- }
- if dtype == torch.bfloat16:
- cfg["bf16"] = {"enabled": True}
- return cfg
-
-
-def engine_named_grads(engine, prefix):
- from deepspeed.utils import safe_get_full_grad
-
- out = {}
- for n, p in engine.module.named_parameters():
- g = safe_get_full_grad(p)
- if g is not None:
- out[f"{prefix}.{n}"] = g.detach().float().cpu().numpy().copy()
- return out
-
-
-def named_grads(module, prefix):
- return {
- f"{prefix}.{n}": p.grad.detach().float().cpu().numpy().copy()
- for n, p in module.named_parameters()
- if p.grad is not None
- }
-
-
-def named_params(module, prefix):
- return {
- f"{prefix}.{n}": p.detach().float().cpu().numpy().copy()
- for n, p in module.named_parameters()
- }
-
-
-def monolithic_baseline(multi_output, dtype, device):
- """Same seeded stage modules, one connected graph, full batch, torch AdamW.
- Returns (grads, params_after_step)."""
- stage0, stage1 = build_stages(multi_output)
- stage0.to(device, dtype)
- stage1.to(device, dtype)
- x, y = make_data(dtype)
- x, y = x.to(device), y.to(device)
-
- opt = torch.optim.AdamW(
- [*stage0.parameters(), *stage1.parameters()],
- lr=LR,
- betas=(0.9, 0.999),
- eps=1e-8,
- weight_decay=0.0,
- )
- outs = stage0(x)
- outs = outs if isinstance(outs, tuple) else (outs,)
- loss = nn.functional.mse_loss(stage1(*outs), y)
- loss.backward()
- grads = {**named_grads(stage0, "s0"), **named_grads(stage1, "s1")}
- opt.step()
- params = {**named_params(stage0, "s0"), **named_params(stage1, "s1")}
- return float(loss), grads, params
-
-
-# --------------------------------------------------------------------------
-# external-gradient backward parity worker (2 ranks, GPUs 0-1)
-# --------------------------------------------------------------------------
-
-
-@dataclasses.dataclass
-class ParityCfg:
- zero: int
- path: str # "vjp" | "direct"
- dtype_name: str # "fp32" | "bf16"
- gas: int = 1
- multi_output: bool = False
-
- @property
- def dtype(self):
- return torch.bfloat16 if self.dtype_name == "bf16" else torch.float32
-
- @property
- def row_id(self):
- return (
- f"zero{self.zero}-{self.path}-{self.dtype_name}"
- + (f"-gas{self.gas}" if self.gas > 1 else "")
- + ("-multiout" if self.multi_output else "")
- )
-
-
-def _parity_worker(rank, cfg: ParityCfg, port, q):
- try:
- os.environ["LOCAL_RANK"] = str(rank)
- os.environ["RANK"] = str(rank)
- os.environ["WORLD_SIZE"] = "2"
- torch.cuda.set_device(rank)
- dist.init_process_group(
- "nccl", init_method=f"tcp://127.0.0.1:{port}", rank=rank, world_size=2
- )
- device = torch.device(f"cuda:{rank}")
-
- stage0, stage1 = build_stages(cfg.multi_output)
- conf = ds_config(cfg.zero, cfg.dtype, cfg.gas)
- engine0, _, _, _ = deepspeed.initialize(
- model=stage0,
- model_parameters=stage0.parameters(),
- config=conf,
- dist_init_required=False,
- )
- engine1, _, _, _ = deepspeed.initialize(
- model=stage1,
- model_parameters=stage1.parameters(),
- config=conf,
- dist_init_required=False,
- )
-
- x, y = make_data(cfg.dtype)
- rows = BATCH // 2
- x = x[rank * rows : (rank + 1) * rows].to(device)
- y = y[rank * rows : (rank + 1) * rows].to(device)
-
- micro = rows // cfg.gas
- losses = []
- for k in range(cfg.gas):
- xm, ym = x[k * micro : (k + 1) * micro], y[k * micro : (k + 1) * micro]
-
- outs = engine0(xm)
- outs = outs if isinstance(outs, tuple) else (outs,)
- cut = tuple(
- o.detach().requires_grad_(True) if o.is_floating_point() else o for o in outs
- )
- loss = nn.functional.mse_loss(engine1(*cut), ym)
- losses.append(loss.detach().float().cpu())
-
- engine1.backward(loss)
- grads_in = tuple(c.grad if c.is_floating_point() else None for c in cut)
-
- if cfg.path == "vjp":
- # engine.backward rescales by 1/gas internally; the incoming
- # grads already carry stage1's 1/gas, so cancel one factor.
- vjp = sum((o * g).sum() for o, g in zip(outs, grads_in) if g is not None)
- engine0.backward(vjp * engine0.gradient_accumulation_steps())
- else:
- torch.autograd.backward(
- [o for o, g in zip(outs, grads_in) if g is not None],
- [g for g in grads_in if g is not None],
- )
-
- # capture on the boundary micro-step, after allreduce inside
- # backward, before step() consumes the grads
- if k == cfg.gas - 1:
- grads = {**engine_named_grads(engine0, "s0"), **engine_named_grads(engine1, "s1")}
-
- engine1.step()
- engine0.step()
-
- params = {}
- if cfg.zero >= 3:
- with deepspeed.zero.GatheredParameters(
- [*engine0.module.parameters(), *engine1.module.parameters()]
- ):
- params = {
- **named_params(engine0.module, "s0"),
- **named_params(engine1.module, "s1"),
- }
- else:
- params = {**named_params(engine0.module, "s0"), **named_params(engine1.module, "s1")}
-
- mean_loss_t = torch.stack(losses).mean().to(device)
- dist.all_reduce(mean_loss_t)
- mean_loss = float(mean_loss_t) / 2
- if rank == 0:
- q.put(("ok", cfg.row_id, mean_loss, grads, params))
- except Exception as e: # report, don't hang the parent
- if rank == 0:
- q.put(("error", cfg.row_id, f"{type(e).__name__}: {e}", None, None))
- raise
- finally:
- if dist.is_initialized():
- dist.destroy_process_group()
-
-
-PARITY_ROWS = [
- ParityCfg(0, "vjp", "fp32"),
- ParityCfg(0, "direct", "fp32"),
- ParityCfg(1, "vjp", "fp32"),
- ParityCfg(1, "direct", "fp32"),
- ParityCfg(2, "vjp", "fp32"),
- ParityCfg(3, "vjp", "fp32"),
- ParityCfg(0, "vjp", "bf16"), # the first support row's dtype
- ParityCfg(0, "direct", "bf16"),
- ParityCfg(1, "vjp", "fp32", gas=2),
- ParityCfg(1, "vjp", "fp32", multi_output=True),
-]
-
-# rows the supported configurations depend on -> hard assert; the rest is
-# recorded evidence (xfail on failure)
-REQUIRED = {
- "zero0-vjp-fp32",
- "zero1-vjp-fp32",
- "zero0-vjp-bf16",
- "zero1-vjp-fp32-gas2",
- "zero1-vjp-fp32-multiout",
-}
-
-
-@pytest.mark.parametrize("cfg", PARITY_ROWS, ids=lambda c: c.row_id)
-def test_external_grad_backward_parity(cfg):
- ctx = mp.get_context("spawn")
- q = ctx.SimpleQueue()
- port = 29500 + abs(hash(cfg.row_id)) % 500
- try:
- mp.spawn(_parity_worker, args=(cfg, port, q), nprocs=2, join=True)
- except Exception as e:
- if cfg.row_id in REQUIRED:
- raise
- pytest.xfail(f"evidence row {cfg.row_id} failed to run: {e}")
-
- status, row, loss, grads, params = q.get()
- if status == "error":
- if row in REQUIRED:
- pytest.fail(f"required row {row}: {loss}")
- pytest.xfail(f"evidence row {row}: {loss}")
-
- ref_loss, ref_grads, ref_params = monolithic_baseline(
- cfg.multi_output, cfg.dtype, torch.device("cuda:0")
- )
-
- bf16 = cfg.dtype_name == "bf16"
- gtol = dict(rtol=3e-2, atol=1e-3) if bf16 else dict(rtol=1e-4, atol=1e-6)
- print(f"\n[{row}] loss={loss:.6f} ref={ref_loss:.6f} n_grads={len(grads)}")
- assert np.isclose(loss, ref_loss, rtol=3e-2 if bf16 else 1e-5, atol=1e-3), (
- f"{row}: loss diverges"
- )
- assert grads.keys() == ref_grads.keys(), f"{row}: missing grads"
- for name in ref_grads:
- assert np.allclose(grads[name], ref_grads[name], **gtol), (
- f"{row}: grad mismatch {name} "
- f"(max diff {np.abs(grads[name] - ref_grads[name]).max():.3e})"
- )
- if not bf16: # bf16 keeps fp32 masters inside DS; step parity is fp32-only
- for name in ref_params:
- assert np.allclose(params[name], ref_params[name], rtol=1e-4, atol=1e-6), (
- f"{row}: post-step param mismatch {name}"
- )
-
-
-# --------------------------------------------------------------------------
-# concurrent stage-local worlds, collective isolation (4 ranks, 2 cohorts)
-# --------------------------------------------------------------------------
-
-
-def _isolation_worker(global_rank, q):
- cohort, local = divmod(global_rank, 2)
- os.environ["LOCAL_RANK"] = str(global_rank)
- torch.cuda.set_device(global_rank)
- dist.init_process_group(
- "nccl", init_method=f"tcp://127.0.0.1:{29400 + cohort}", rank=local, world_size=2
- )
- device = torch.device(f"cuda:{global_rank}")
-
- # collective isolation: each cohort all-reduces its own marker value
- marker = torch.full((4,), float(cohort + 1), device=device)
- dist.all_reduce(marker)
-
- torch.manual_seed(cohort) # cohorts run DIFFERENT models concurrently
- model = nn.Linear(8, 8)
- engine, _, _, _ = deepspeed.initialize(
- model=model,
- model_parameters=model.parameters(),
- config=ds_config(zero=1, dtype=torch.float32, gas=1),
- dist_init_required=False,
- )
- x = torch.randn(4, 8, device=device)
- loss = engine(x).pow(2).mean()
- engine.backward(loss)
- engine.step()
-
- q.put(
- (
- global_rank,
- cohort,
- marker.cpu().numpy(),
- dist.get_world_size(),
- engine.module.weight.detach().float().cpu().numpy().copy(),
- )
- )
- dist.destroy_process_group()
-
-
-def test_stage_local_worlds_are_isolated():
- ctx = mp.get_context("spawn")
- q = ctx.SimpleQueue()
- mp.spawn(_isolation_worker, args=(q,), nprocs=4, join=True)
- results = sorted((q.get() for _ in range(4)), key=lambda r: r[0])
-
- for global_rank, cohort, marker, world, _ in results:
- assert world == 2, f"rank {global_rank}: world leaked across cohorts"
- expected = 2.0 * (cohort + 1) # sum over exactly its own cohort
- assert np.allclose(marker, np.full((4,), expected, dtype=np.float32)), (
- f"rank {global_rank}: cohort {cohort} allreduce crossed cohorts: {marker}"
- )
-
- # DP replicas agree within a cohort; cohorts hold different models
- assert np.array_equal(results[0][4], results[1][4]), "cohort A replicas diverged"
- assert np.array_equal(results[2][4], results[3][4]), "cohort B replicas diverged"
- assert not np.allclose(results[0][4], results[2][4]), "cohorts unexpectedly share model state"
-
-
-# --------------------------------------------------------------------------
-# stage-local checkpoint round trip (2 ranks)
-# --------------------------------------------------------------------------
-
-
-def _checkpoint_worker(rank, zero, port, ckpt_dir, q):
- os.environ["LOCAL_RANK"] = str(rank)
- torch.cuda.set_device(rank)
- dist.init_process_group("nccl", init_method=f"tcp://127.0.0.1:{port}", rank=rank, world_size=2)
- device = torch.device(f"cuda:{rank}")
- conf = ds_config(zero, torch.float32, gas=1)
-
- def fresh_engine():
- torch.manual_seed(7)
- model = nn.Sequential(nn.Linear(16, 32), nn.Tanh(), nn.Linear(32, 4))
- engine, _, _, _ = deepspeed.initialize(
- model=model, model_parameters=model.parameters(), config=conf, dist_init_required=False
- )
- return engine
-
- def one_step(engine, seed):
- torch.manual_seed(seed)
- x = torch.randn(BATCH, 16)[rank * 4 : (rank + 1) * 4].to(device)
- y = torch.randn(BATCH, 4)[rank * 4 : (rank + 1) * 4].to(device)
- loss = nn.functional.mse_loss(engine(x), y)
- engine.backward(loss)
- engine.step()
-
- engine_a = fresh_engine()
- one_step(engine_a, seed=11) # give optimizer real state
- engine_a.save_checkpoint(ckpt_dir, tag="p2") # every rank saves its shard
- saved = named_params(engine_a.module, "m")
-
- engine_b = fresh_engine() # new engine, same world
- engine_b.load_checkpoint(ckpt_dir, tag="p2")
- loaded = named_params(engine_b.module, "m")
-
- # restored state matches, and both engines evolve identically afterwards
- one_step(engine_a, seed=12)
- one_step(engine_b, seed=12)
- after_a = named_params(engine_a.module, "m")
- after_b = named_params(engine_b.module, "m")
-
- if rank == 0:
- q.put((saved, loaded, after_a, after_b))
- dist.destroy_process_group()
-
-
-@pytest.mark.parametrize("zero", [0, 1])
-def test_stage_local_checkpoint_roundtrip(zero):
- ctx = mp.get_context("spawn")
- q = ctx.SimpleQueue()
- with tempfile.TemporaryDirectory() as ckpt_dir:
- mp.spawn(_checkpoint_worker, args=(zero, 29300 + zero, ckpt_dir, q), nprocs=2, join=True)
- saved, loaded, after_a, after_b = q.get()
- for name in saved:
- assert np.array_equal(saved[name], loaded[name]), f"zero{zero}: {name} not restored exactly"
- for name in after_a:
- assert np.allclose(after_a[name], after_b[name], rtol=1e-6, atol=1e-8), (
- f"zero{zero}: post-restore step diverged at {name} (optimizer state?)"
- )
-
-
-def test_environment_report():
- print(
- f"\ntorch {torch.__version__} | deepspeed {deepspeed.__version__} | "
- f"cuda {torch.version.cuda} | gpus: "
- f"{[torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())]}"
- )
diff --git a/training/rdsp/tests/unit/test_bench_script.py b/training/rdsp/tests/unit/test_bench_script.py
deleted file mode 100644
index 5c4eef853..000000000
--- a/training/rdsp/tests/unit/test_bench_script.py
+++ /dev/null
@@ -1,78 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-
-"""bench/qwen35_small/bench.sh: which runs.sh cases a layout launches, in what order,
-and what it skips. DRY_RUN=1 prints the plan instead of running it."""
-
-import os
-import subprocess
-
-import pytest
-
-ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")
-BENCH = os.path.join(ROOT, "bench", "qwen35_small", "bench.sh")
-
-
-def plan(tmp_path, *layouts, model="Qwen3.5-4B", **env):
- out = subprocess.run(
- ["bash", BENCH, *layouts],
- capture_output=True,
- text=True,
- check=False,
- env={**os.environ, "HOME": str(tmp_path), "DRY_RUN": "1", "MODEL": model, **env},
- )
- return out.returncode, out.stdout + out.stderr
-
-
-def test_each_layout_runs_megatron_then_rdsp(tmp_path):
- code, out = plan(tmp_path, "noncoloc", "tp2", "tp4", "coloc")
- assert code == 0, out
- cases = [line.split()[-1] for line in out.splitlines() if line.startswith("run ")]
- assert cases == [
- "convert",
- "export",
- "noncoloc-mimo",
- "noncoloc-rdsp",
- "shared-megatron",
- "shared-rdsp",
- "tp4pp2-megatron",
- "tp4pp2-rdsp",
- "coloc-rdsp",
- ]
-
-
-def test_all_means_every_layout(tmp_path):
- assert plan(tmp_path, "all")[1] == plan(tmp_path, "noncoloc", "tp2", "tp4", "coloc")[1]
-
-
-def test_layouts_without_a_recipe_for_the_model_are_skipped(tmp_path):
- code, out = plan(tmp_path, "all", model="Qwen3.5-2B")
- assert code == 0, out
- assert "skip tp4: no recipes/qwen35-2b-tp4pp2dp1.sh" in out
- assert "skip coloc: no recipes/qwen35-2b-coloc-tp2pp2dp2.sh" in out
- cases = [line.split()[-1] for line in out.splitlines() if line.startswith("run ")]
- assert "noncoloc-rdsp" in cases and "tp4pp2-megatron" not in cases
-
-
-def test_existing_checkpoints_and_samples_are_reused(tmp_path):
- work = tmp_path / "mimo"
- (work / "std" / "Qwen3.5-4B").mkdir(parents=True)
- (work / "Qwen3.5-4B-mimo").mkdir()
- steps = work / "cord_steps-Qwen3.5-4B"
- steps.mkdir()
- for i in range(50):
- (steps / f"step_{i:05d}.pt").touch()
- out = plan(tmp_path, "tp2")[1]
- cases = [line.split()[-1] for line in out.splitlines() if line.startswith("run ")]
- assert cases == ["shared-megatron", "shared-rdsp"]
-
-
-def test_rounds_get_their_own_log_directories(tmp_path):
- out = plan(tmp_path, "tp2", ROUNDS="2")[1]
- assert f"{tmp_path}/bench/Qwen3.5-4B/r1" in out and f"{tmp_path}/bench/Qwen3.5-4B/r2" in out
-
-
-@pytest.mark.parametrize("layouts", [(), ("tp8",)])
-def test_unknown_or_missing_layout_prints_usage(tmp_path, layouts):
- code, out = plan(tmp_path, *layouts)
- assert code != 0 and "noncoloc" in out and "coloc" in out
diff --git a/training/rdsp/tests/unit/test_bench_summarize.py b/training/rdsp/tests/unit/test_bench_summarize.py
deleted file mode 100644
index 1635a2d5a..000000000
--- a/training/rdsp/tests/unit/test_bench_summarize.py
+++ /dev/null
@@ -1,121 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-
-"""bench/common/summarize.py pairs each Megatron run with its rdsp run and
-prints one results row per pair."""
-
-import os
-import sys
-
-HERE = os.path.dirname(os.path.abspath(__file__))
-sys.path.insert(0, os.path.join(HERE, "..", "..", "bench", "common"))
-
-import pytest # noqa: E402
-import summarize # noqa: E402
-
-PUBLISHED = os.path.join(HERE, "..", "..", "bench", "qwen35_small", "logs")
-# the 2B/4B/H100 logs are not in the repository; the tests that read them run where they are
-needs_published_logs = pytest.mark.skipif(
- not os.path.isdir(PUBLISHED), reason="bench/qwen35_small/logs not here"
-)
-
-
-def _megatron_log(ms: float) -> str:
- return "".join(
- f" iteration {i + 1:8d}/ 50 | consumed samples: {64 * (i + 1)} | "
- f"elapsed time per iteration (ms): {ms:.1f} | lm loss: 5.0E-01 |\n"
- for i in range(50)
- )
-
-
-def _rdsp_log(ms: int) -> str:
- return "".join(
- f"step {i} loss 0.5000 {ms} ms 1 real tok/s 2 padded tok/s real 65000 supervised 13000\n"
- for i in range(50)
- )
-
-
-def test_pairs_megatron_and_rdsp_logs(tmp_path, capsys):
- (tmp_path / "shared-megatron.log").write_text(_megatron_log(10000.0))
- (tmp_path / "shared-rdsp.log").write_text(_rdsp_log(8000))
- summarize.main([str(tmp_path)])
- out = capsys.readouterr().out
- row = next(line for line in out.splitlines() if "TP2xPP2xDP2" in line)
- assert "10.00" in row and "8.00" in row and "-20%" in row
- per_gpu = row.split()[-2:] # tokens/s per GPU: 64 rows x 2048 over 10 s / 8 s, 8 GPUs
- assert per_gpu == ["1638", "2048"]
- assert "TP4xPP2xDP1" not in out # pairs without logs are left out
-
-
-def test_tokens_per_second_follow_rows_and_sequence_length(tmp_path, capsys):
- (tmp_path / "shared-megatron.log").write_text(_megatron_log(10000.0))
- (tmp_path / "shared-rdsp.log").write_text(_rdsp_log(8000))
- summarize.main([str(tmp_path), "--rows", "128", "--seq", "1024"])
- row = next(line for line in capsys.readouterr().out.splitlines() if "TP2xPP2xDP2" in line)
- assert row.split()[-5:-3] == ["13107", "16384"] # 128 x 1024 over 10 s and 8 s
-
-
-def test_mimo_layout_gets_its_row_on_five_gpus(tmp_path, capsys):
- (tmp_path / "noncoloc-mimo.log").write_text(_megatron_log(10000.0))
- (tmp_path / "noncoloc-rdsp.log").write_text(_rdsp_log(8000))
- summarize.main([str(tmp_path)])
- row = next(
- line
- for line in capsys.readouterr().out.splitlines()
- if line.startswith("vision 1 GPU + language TP2xDP2")
- )
- assert "-20%" in row and row.split()[-2:] == ["2621", "3277"] # 64 x 2048 / 10 s, 8 s, 5 GPUs
-
-
-def test_rdsp_only_layout_gets_a_row_without_megatron(tmp_path, capsys):
- """Colocated vision has no Megatron counterpart: its row shows rdsp alone."""
- (tmp_path / "coloc-rdsp.log").write_text(_rdsp_log(5000))
- summarize.main([str(tmp_path)])
- row = next(line for line in capsys.readouterr().out.splitlines() if "colocated" in line)
- assert "5.00" in row and row.count("-") >= 2
-
-
-@needs_published_logs
-def test_published_2b_and_4b_logs_give_the_benchmark_results_numbers(capsys):
- """bench/qwen35_small/logs holds the logs behind BENCHMARK_RESULTS.md's PCIe table;
- summarize.py on them prints every step time it reports."""
- rows = []
- for size in ("2b", "4b"):
- summarize.main([os.path.join(PUBLISHED, size)])
- rows += capsys.readouterr().out.splitlines()[1:]
- got = [tuple(line.split()[-8:-6]) for line in rows]
- assert got == [("9.64", "8.30"), ("7.39", "5.30"), ("10.04", "8.69"), ("15.93", "13.29")]
- with open(os.path.join(HERE, "..", "..", "docs", "BENCHMARK_RESULTS.md")) as f:
- doc = f.read()
- for megatron, rdsp in got:
- assert f"| {megatron} s | {rdsp} s |" in doc
-
-
-@needs_published_logs
-def test_published_h100_logs_give_the_benchmark_results_numbers(capsys):
- """bench/qwen35_small/logs/h100 holds the 8x H100 logs; summarize.py on them prints
- every step time BENCHMARK_RESULTS.md reports for H100."""
- summarize.main([os.path.join(PUBLISHED, "h100")])
- rows = capsys.readouterr().out.splitlines()[1:]
- got = [tuple(line.split()[-8:-6]) for line in rows]
- assert got == [("7.99", "7.89"), ("8.79", "6.49"), ("18.24", "12.30"), ("-", "5.62")]
- with open(os.path.join(HERE, "..", "..", "docs", "BENCHMARK_RESULTS.md")) as f:
- doc = f.read()
- for megatron, rdsp in got:
- cell = "—" if megatron == "-" else f"{megatron} s"
- assert f"| {cell} | {rdsp} s |" in doc, (megatron, rdsp)
-
-
-@needs_published_logs
-def test_docs_report_tokens_per_gpu_from_the_logs(capsys):
- """Every published row's tokens/s per GPU (both systems) appears in
- BENCHMARK_RESULTS.md, as printed by summarize.py."""
- values = set()
- for size in ("2b", "4b", "h100"):
- summarize.main([os.path.join(PUBLISHED, size)])
- for line in capsys.readouterr().out.splitlines()[1:]:
- values.update(v for v in line.split()[-2:] if v != "-")
- with open(os.path.join(HERE, "..", "..", "docs", "BENCHMARK_RESULTS.md")) as f:
- doc = f.read()
- for v in sorted(values):
- assert f"| {int(v):,} |" in doc, v
diff --git a/training/rdsp/tests/unit/test_cli.py b/training/rdsp/tests/unit/test_cli.py
new file mode 100644
index 000000000..efeaa6bc3
--- /dev/null
+++ b/training/rdsp/tests/unit/test_cli.py
@@ -0,0 +1,208 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+
+"""The rdsp command: the parallelism rdsp train picks, the command it runs (which the training
+script must parse), and the Ray command rdsp setup runs. No cluster or GPU needed."""
+
+import importlib.util
+import os
+import types
+
+import pytest
+
+from ray_deepspeed_pipeline import cli
+
+ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")
+
+
+def parser_of(script):
+ spec = importlib.util.spec_from_file_location(script[:-3], os.path.join(ROOT, script))
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module.build_parser()
+
+
+def flag(flags, name):
+ return flags[flags.index(name) + 1]
+
+
+def test_a_small_model_gets_one_stage_and_data_parallel_copies():
+ par = cli.choose_parallelism([8], params=0.6e9, device_gib=80)
+ assert (par.pp, par.tp, par.dp) == (1, 1, 8)
+
+
+def test_a_bigger_model_gets_the_fewest_stages_that_fit():
+ par = cli.choose_parallelism([8, 8], params=9.4e9, device_gib=80)
+ assert (par.pp, par.dp) == (2, 8) and par.gib <= 0.5 * 80
+
+
+def test_stages_stay_inside_a_node():
+ par = cli.choose_parallelism([4, 4, 4], params=20e9, device_gib=80)
+ assert 4 % (par.tp * par.dp) == 0
+
+
+def test_given_sizes_fill_in_the_rest_and_must_multiply_to_the_devices():
+ assert cli.choose_parallelism([8], 7e9, 80, pp=2).dp == 4
+ assert cli.choose_parallelism([8], 7e9, 80, pp=2, tp=2).dp == 2
+ with pytest.raises(SystemExit, match="not 8 devices"):
+ cli.choose_parallelism([8], 7e9, 80, pp=3, dp=2)
+
+
+def test_a_model_too_big_says_so():
+ assert "does not fit" in cli.choose_parallelism([8], 27e9, 80).why
+
+
+def test_cpu_processes_share_the_machines_memory():
+ small = cli.choose_parallelism([2], 0.135e9, 24, state_bytes=cli.CPU_BYTES, shared_memory=True)
+ larger = cli.choose_parallelism([2], 0.6e9, 24, state_bytes=cli.CPU_BYTES, shared_memory=True)
+ assert (small.pp, small.dp) == (1, 2) and (larger.pp, larger.dp) == (2, 1)
+
+
+def test_every_copy_gets_one_row_and_every_stage_two_microbatches():
+ par = cli.choose_parallelism([8], 7e9, 80, pp=4)
+ flags = cli.layout_flags(par, batch=4, cpu=False)
+ assert flag(flags, "--rows") == "2" and flag(flags, "--microbatches") == "8"
+
+
+def args(**kw):
+ defaults = dict(
+ model="Qwen/Qwen3-0.6B",
+ data=None,
+ pipeline_parallel_size=None,
+ tensor_parallel_size=1,
+ data_parallel_size=None,
+ cpu=False,
+ tune=False,
+ steps=50,
+ batch_size=None,
+ seq_len=None,
+ lr=1e-5,
+ extra=[],
+ )
+ return types.SimpleNamespace(**{**defaults, **kw})
+
+
+def test_a_text_model_runs_train_py_with_flags_it_parses(monkeypatch):
+ monkeypatch.setattr(cli, "model_info", lambda model: (False, True, 0.6e9))
+ command, env, summary = cli.plan(args(), [8], 80.0)
+ assert command[1].endswith("train.py") and env == {} and "pp=1" in summary
+ parser_of("train.py").parse_args(command[2:])
+
+
+def test_a_vision_model_runs_train_vl_and_unties_across_stages(monkeypatch):
+ monkeypatch.setattr(cli, "model_info", lambda model: (True, True, 2.3e9))
+ command, _, _ = cli.plan(args(model="Qwen/Qwen3.5-2B", pipeline_parallel_size=2), [8], 80.0)
+ assert command[1].endswith("train_vl.py") and "--untie-embeddings" in command
+ parser_of("train_vl.py").parse_args(command[2:])
+
+
+@pytest.mark.parametrize("vision,cuts", [(True, "auto"), (False, "measured")])
+def test_tune_times_the_stages_first(monkeypatch, vision, cuts):
+ monkeypatch.setattr(cli, "model_info", lambda model: (vision, False, 9e9))
+ command, _, summary = cli.plan(args(tune=True, pipeline_parallel_size=2), [8], 80.0)
+ assert flag(command, "--cuts") == cuts and "Tuning" in summary
+ parser_of("train_vl.py" if vision else "train.py").parse_args(command[2:])
+
+
+def test_a_cpu_run_uses_fp32_its_own_ray_and_a_share_of_the_cores(monkeypatch):
+ monkeypatch.setattr(cli, "model_info", lambda model: (False, True, 0.6e9))
+ monkeypatch.setattr(cli.os, "cpu_count", lambda: 10)
+ monkeypatch.delenv("OMP_NUM_THREADS", raising=False)
+ command, env, _ = cli.plan(args(cpu=True), [2], 24.0)
+ assert env == {"RAY_ADDRESS": "local", "DS_ACCELERATOR": "cpu", "OMP_NUM_THREADS": "5"}
+ parsed = parser_of("train.py").parse_args(command[2:])
+ assert parsed.dtype == "fp32" and parsed.data == "synthetic"
+ assert "procs=1" in flag(command, "--stage") and "gpus" not in " ".join(command)
+
+
+def test_a_cpu_run_refuses_a_vision_model(monkeypatch):
+ monkeypatch.setattr(cli, "model_info", lambda model: (True, False, 2e9))
+ with pytest.raises(SystemExit, match="text models"):
+ cli.plan(args(cpu=True), [2], 24.0)
+
+
+def test_without_gpus_or_cpu_flag_train_stops(monkeypatch, capsys):
+ monkeypatch.setattr(cli, "cluster_nodes", lambda address: None)
+ monkeypatch.setattr(cli, "local_gpus", lambda: (0, None))
+ assert cli.main(["train", "Qwen/Qwen3-0.6B"]) == 1
+ assert "--cpu" in capsys.readouterr().err
+
+
+def test_the_model_is_the_argument_and_parallelism_takes_vllm_style_flags():
+ parsed = cli.build_parser().parse_args(["train", "Qwen/Qwen3-0.6B", "-pp", "2", "-tp", "2"])
+ assert parsed.model == "Qwen/Qwen3-0.6B"
+ assert (parsed.pipeline_parallel_size, parsed.tensor_parallel_size) == (2, 2)
+
+
+@pytest.fixture
+def quiet_setup(monkeypatch):
+ monkeypatch.setattr(cli, "check_environment", lambda: [])
+ monkeypatch.setattr(cli, "local_gpus", lambda: (8, 80.0))
+ monkeypatch.setattr(cli.shutil, "which", lambda name: "/usr/bin/ray")
+
+
+def test_setup_starts_a_cluster(quiet_setup, capsys):
+ assert cli.main(["setup", "--head", "--dry-run"]) == 0
+ out = capsys.readouterr().out
+ assert "/usr/bin/ray start --disable-usage-stats --num-gpus=8 --head --port=6379" in out
+
+
+def test_setup_joins_a_cluster_at_the_default_port(quiet_setup, capsys):
+ assert cli.main(["setup", "--join", "10.0.0.5", "--dry-run"]) == 0
+ assert "--address=10.0.0.5:6379" in capsys.readouterr().out
+
+
+def test_flags_after_a_double_dash_go_to_the_training_script(monkeypatch):
+ seen = []
+ monkeypatch.setattr(cli, "train", lambda parsed: seen.append(parsed) or 0)
+ assert cli.main(["train", "M", "-pp", "2", "--", "--zero", "2"]) == 0
+ assert seen[0].pipeline_parallel_size == 2 and seen[0].extra == ["--zero", "2"]
+
+
+@pytest.fixture
+def token_file(tmp_path, monkeypatch):
+ path = tmp_path / "auth_token"
+ monkeypatch.setenv("RAY_AUTH_TOKEN_PATH", str(path))
+ monkeypatch.delenv("RAY_AUTH_TOKEN", raising=False)
+ monkeypatch.delenv("RAY_AUTH_MODE", raising=False)
+ monkeypatch.setattr(cli, "node_ip", lambda: "10.0.0.5")
+ return path
+
+
+def test_the_first_node_prints_its_token_in_the_join_command(token_file):
+ assert cli.join_command(6379) == "rdsp setup --join 10.0.0.5:6379"
+ token_file.write_text("secret\n")
+ assert cli.join_command(6379) == "rdsp setup --join 10.0.0.5:6379 --token secret"
+
+
+def test_no_token_when_token_authentication_is_off(token_file, monkeypatch):
+ token_file.write_text("secret")
+ monkeypatch.setenv("RAY_AUTH_MODE", "disabled")
+ assert "--token" not in cli.join_command(6379)
+
+
+def test_joining_passes_the_token_to_ray_and_keeps_it(quiet_setup, token_file, monkeypatch):
+ seen = {}
+
+ def run(command, env=None):
+ seen.update(command=command, env=env)
+ return types.SimpleNamespace(returncode=0)
+
+ monkeypatch.setattr(cli.subprocess, "run", run)
+ assert cli.main(["setup", "--join", "10.0.0.5", "--token", "secret"]) == 0
+ assert seen["env"]["RAY_AUTH_TOKEN"] == "secret"
+ assert token_file.read_text() == "secret" and token_file.stat().st_mode & 0o777 == 0o600
+
+
+def test_a_dry_run_hides_the_token(quiet_setup, token_file, capsys):
+ assert cli.main(["setup", "--join", "10.0.0.5", "--token", "secret", "--dry-run"]) == 0
+ out = capsys.readouterr().out
+ assert "RAY_AUTH_TOKEN=" in out and "secret" not in out
+
+
+def test_a_refused_join_says_what_to_check(quiet_setup, token_file, monkeypatch, capsys):
+ monkeypatch.setattr(
+ cli.subprocess, "run", lambda c, env=None: types.SimpleNamespace(returncode=1)
+ )
+ assert cli.main(["setup", "--join", "10.0.0.5"]) == 1
+ assert "--token" in capsys.readouterr().err
diff --git a/training/rdsp/tests/unit/test_compiler.py b/training/rdsp/tests/unit/test_compiler.py
index a2bdf15c8..b1d2deea7 100644
--- a/training/rdsp/tests/unit/test_compiler.py
+++ b/training/rdsp/tests/unit/test_compiler.py
@@ -13,7 +13,6 @@
from ray_deepspeed_pipeline.compiler import lower, resolve_microbatches
from ray_deepspeed_pipeline.config import (
- ConnectionOverride,
ExplicitCuts,
PipelineConfig,
StageOverride,
@@ -67,7 +66,6 @@ def test_simple_advanced_same_plan():
StageOverride(stage=0, num_gpus=1),
StageOverride(stage=1, num_gpus=1),
),
- connection_overrides=(ConnectionOverride(source=0, dest=1),),
),
DS,
)
@@ -95,29 +93,6 @@ def test_heterogeneous_one_global_count():
assert plan.global_microbatches == plan.schedule.global_microbatches == 4
-def test_unsupported_layout_rejected_before_ray():
- with pytest.raises(ValidationError, match="layouts require 'identity'"):
- lower(
- ToyLM(),
- simple_config(
- connection_overrides=(
- ConnectionOverride(source=0, dest=1, conversion="replicate-to-shard"),
- )
- ),
- DS,
- )
- with pytest.raises(ValidationError, match="adjacent"):
- lower(
- ToyLM(),
- PipelineConfig(
- stages=3,
- partition=UniformTransformerBlocks(),
- connection_overrides=(ConnectionOverride(source=2, dest=3),),
- ),
- DS,
- )
-
-
def test_duplicate_stage_override_rejected():
with pytest.raises(ValidationError, match="duplicate"):
lower(
diff --git a/training/rdsp/tests/unit/test_config.py b/training/rdsp/tests/unit/test_config.py
index 6c039b249..12934f90a 100644
--- a/training/rdsp/tests/unit/test_config.py
+++ b/training/rdsp/tests/unit/test_config.py
@@ -9,7 +9,6 @@
import ray_deepspeed_pipeline as rdsp
from ray_deepspeed_pipeline.config import (
- ConnectionOverride,
ExplicitCuts,
PipelineConfig,
StageOverride,
@@ -26,7 +25,6 @@ def test_schema_fields_frozen():
"schedule",
"microbatches",
"stage_overrides",
- "connection_overrides",
"colocated_vision",
"prefetch",
]
@@ -53,11 +51,6 @@ def test_schema_fields_frozen():
partition=UniformTransformerBlocks(),
stage_overrides=(StageOverride(stage=0, num_gpus=0),),
),
- dict(
- stages=2,
- partition=UniformTransformerBlocks(),
- connection_overrides=("not-an-override",),
- ),
],
)
def test_invalid_configs_rejected(kwargs):
@@ -69,12 +62,6 @@ def test_explicit_cuts_normalizes_to_tuple():
assert ExplicitCuts(cuts=[2, 4]).cuts == (2, 4)
-def test_connection_override_defaults():
- c = ConnectionOverride(source=0, dest=1)
- assert c.conversion is None # None: derived from layouts
- assert [f.name for f in dataclasses.fields(c)] == ["source", "dest", "conversion"]
-
-
def test_deepspeed_config_path_is_loaded(tmp_path, monkeypatch, tiny_model):
"""A config given as a JSON path reaches planning as its contents."""
import json
diff --git a/training/rdsp/tests/unit/test_coordinator.py b/training/rdsp/tests/unit/test_coordinator.py
index c14ac7c68..5690887ea 100644
--- a/training/rdsp/tests/unit/test_coordinator.py
+++ b/training/rdsp/tests/unit/test_coordinator.py
@@ -353,6 +353,27 @@ def test_a_retry_under_prefetch_keeps_the_step_read_ahead():
assert workers[0].last_inputs == ["x4", "x5"]
+def test_a_step_that_cannot_be_prepared_ahead_is_retried_with_its_entries():
+ coord, workers = build_prefetching()
+ data = iter([(f"x{k}", f"y{k}") for k in range(8)])
+ calls, real = [], workers[1].prepare
+
+ def fails_on_the_read_ahead(**payload):
+ calls.append(1)
+ if len(calls) == 2: # the reader preparing x2, x3 during the first step
+ raise ValueError("cannot split the rows")
+ return real(**payload)
+
+ workers[1].prepare = fails_on_the_read_ahead
+ coord.train_batch(data)
+ with pytest.raises(StepFailed, match="ahead"):
+ coord.train_batch(data)
+ coord.train_batch(data)
+ assert workers[0].last_inputs == ["x2", "x3"], "the failed step's entries are not skipped"
+ coord.train_batch(data)
+ assert workers[0].last_inputs == ["x4", "x5"]
+
+
def test_eval_batch_takes_its_own_iterator_beside_the_engines_loader():
from torch.utils.data import DataLoader
diff --git a/training/rdsp/tests/unit/test_data_consumption.py b/training/rdsp/tests/unit/test_data_consumption.py
index b9ef0930f..5526def23 100644
--- a/training/rdsp/tests/unit/test_data_consumption.py
+++ b/training/rdsp/tests/unit/test_data_consumption.py
@@ -32,7 +32,7 @@ def test_surplus_not_consumed():
def test_non_2tuple_entry_rejected():
- with pytest.raises(ValidationError, match="2-tuple"):
+ with pytest.raises(ValidationError, match=r"not an \(inputs, labels\) pair"):
take_microbatch_entries(iter([("a", "b", "c")]), 1)
with pytest.raises(ValidationError):
take_microbatch_entries(iter(["just-inputs"]), 1)
diff --git a/training/rdsp/tests/unit/test_docs_flags.py b/training/rdsp/tests/unit/test_docs_flags.py
index 2a8243cac..39ca5f477 100644
--- a/training/rdsp/tests/unit/test_docs_flags.py
+++ b/training/rdsp/tests/unit/test_docs_flags.py
@@ -1,9 +1,9 @@
# SPDX-License-Identifier: Apache-2.0
# DeepSpeed Team
-"""Every flag the docs pass to train_vl.py, train.py or a recipe exists in that
-script's parser, in fenced code blocks and in inline code alike. Inline code
-that starts with a flag (`--cuts balanced`) must be a flag of either script."""
+"""Every flag the docs pass to train_vl.py, train.py, a recipe or the rdsp command exists in
+its parser, in fenced code blocks and in inline code alike. Inline code that starts with a
+flag (`--cuts balanced`) must be a flag of one of them."""
import glob
import importlib.util
@@ -16,6 +16,14 @@
DOCS = [os.path.join(ROOT, "README.md")] + sorted(glob.glob(os.path.join(ROOT, "docs", "*.md")))
_SCRIPT = re.compile(r"(train_vl\.py|train\.py|recipes/[\w.-]+\.sh)")
_FLAG = re.compile(r"(? set[str]:
+ from ray_deepspeed_pipeline.cli import build_parser
+
+ subparsers = next(a for a in build_parser()._actions if a.dest == "command")
+ return set(subparsers.choices[command]._option_string_actions)
def _parser(script: str):
@@ -68,8 +76,29 @@ def bare_flags():
return sorted(found)
+def rdsp_flags():
+ """(doc, subcommand, flag) for every flag after `rdsp `, up to a `--`."""
+ found = set()
+ for doc in DOCS:
+ with open(doc) as f:
+ text = f.read()
+ for command in _commands(text):
+ match = _RDSP.search(command)
+ if match is not None:
+ rest = command[match.end() :].split("#", 1)[0].split(" -- ")[0]
+ found.update(
+ (os.path.basename(doc), match.group(1), f) for f in _FLAG.findall(rest)
+ )
+ return sorted(found)
+
+
+@pytest.mark.parametrize("doc,command,flag", rdsp_flags())
+def test_every_rdsp_flag_exists(doc, command, flag):
+ assert flag in _cli_options(command), f"{doc}: rdsp {command} has no {flag}"
+
+
def test_docs_document_flags():
- assert len(documented_flags()) >= 5
+ assert documented_flags() # the scanner finds the docs' commands
assert len(bare_flags()) >= 10
@@ -84,4 +113,5 @@ def test_every_inline_flag_exists(doc, flag):
options = set(_parser("train_vl.py")._option_string_actions) | set(
_parser("train.py")._option_string_actions
)
- assert flag in options, f"{doc}: neither train_vl.py nor train.py has {flag}"
+ options |= set().union(*(_cli_options(c) for c in ("setup", "nodes", "train")))
+ assert flag in options, f"{doc}: no training script or rdsp command has {flag}"
diff --git a/training/rdsp/tests/unit/test_examples.py b/training/rdsp/tests/unit/test_examples.py
new file mode 100644
index 000000000..c78993012
--- /dev/null
+++ b/training/rdsp/tests/unit/test_examples.py
@@ -0,0 +1,60 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+
+"""Every example in examples/ trains what its recipe trains: the same model, stages, rows,
+loss and DeepSpeed config."""
+
+import importlib
+import os
+import shlex
+import sys
+
+import pytest
+
+ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")
+EXAMPLES = {
+ "qwen35_9b": "qwen35-9b-vision4-pp6dp2.sh",
+ "qwen35_27b": "qwen35-27b-vision2-pp7dp2.sh",
+ "qwen35_35b_a3b": "qwen35-35b-a3b-vision4-pp6dp2.sh",
+}
+
+
+@pytest.fixture(scope="module")
+def modules():
+ sys.path.insert(0, os.path.join(ROOT, "examples"))
+ try:
+ yield importlib.import_module("common"), importlib.import_module("train_vl")
+ finally:
+ sys.path.remove(os.path.join(ROOT, "examples"))
+
+
+def recipe_args(train_vl, recipe):
+ text = open(os.path.join(ROOT, "recipes", recipe)).read().replace("\\\n", " ")
+ words = shlex.split(text, comments=True)
+ flags = words[words.index("$ROOT/train_vl.py") + 1 : words.index("$@")]
+ return train_vl.build_parser().parse_args(flags)
+
+
+@pytest.mark.parametrize("name,recipe", EXAMPLES.items())
+def test_an_example_matches_its_recipe(modules, name, recipe):
+ common, train_vl = modules
+ example = importlib.import_module(name)
+ args = recipe_args(train_vl, recipe)
+
+ assert example.MODEL == args.model
+ assert (example.ROWS, example.MICROBATCHES, common.SEQ) == (
+ args.rows,
+ args.microbatches,
+ args.seq,
+ )
+ assert [(s.num_gpus, s.recompute) for s in example.STAGES] == [
+ (s.num_gpus, s.recompute) for s in args.stage
+ ]
+ assert {s.zero_stage for s in args.stage} == {1} and args.cuts == "0,measured"
+ assert common.LOSS == train_vl.loss_function(args)
+
+ ours = common.deepspeed_config(example.ROWS, example.MICROBATCHES, lr=args.lr)
+ theirs = train_vl.ds_config(args)
+ assert ours["zero_optimization"].pop("stage") == 1 # the recipe sets it per stage
+ theirs["zero_optimization"].pop("stage")
+ assert ours == theirs
diff --git a/training/rdsp/tests/unit/test_fused_grad_accumulation.py b/training/rdsp/tests/unit/test_fused_grad_accumulation.py
new file mode 100644
index 000000000..c7f8bfae6
--- /dev/null
+++ b/training/rdsp/tests/unit/test_fused_grad_accumulation.py
@@ -0,0 +1,201 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+
+"""Weight gradients added straight into .grad by the matmul that computes them: the same
+gradients as autograd's own accumulation, one kernel instead of two."""
+
+import os
+
+import pytest
+import torch
+import torch.nn as nn
+
+from ray_deepspeed_pipeline.fused_grad_accumulation import GradAccumulation, fuse_linear_grads
+
+os.environ.setdefault("DS_ACCELERATOR", "cpu") # not the Mac's MPS
+
+
+class Net(nn.Module):
+ def __init__(self, bias):
+ super().__init__()
+ self.a = nn.Linear(8, 16, bias=bias)
+ self.b = nn.Linear(16, 4, bias=False)
+ self.scale = nn.Parameter(torch.ones(4)) # not a linear layer: autograd's own path
+
+ def forward(self, x):
+ return self.b(torch.nn.functional.silu(self.a(x))) * self.scale
+
+
+def _nets(bias, dtype=torch.float64):
+ torch.manual_seed(0)
+ plain = Net(bias).to(dtype)
+ fused = Net(bias).to(dtype)
+ fused.load_state_dict(plain.state_dict())
+ state = GradAccumulation()
+ names = fuse_linear_grads(fused, state)
+ return plain, fused, state, names
+
+
+def _microbatches(n, dtype=torch.float64):
+ g = torch.Generator().manual_seed(1)
+ return [torch.randn(2, 5, 8, generator=g, dtype=dtype) for _ in range(n)]
+
+
+def _accumulate(net, batches, state=None):
+ xs = []
+ for i, x in enumerate(batches):
+ if state is not None:
+ state.fuse = i < len(batches) - 1 # the last one takes autograd's path (the hooks)
+ x = x.clone().requires_grad_()
+ net(x).square().sum().backward()
+ xs.append(x.grad)
+ return xs
+
+
+@pytest.mark.parametrize("bias", [False, True])
+def test_accumulated_gradients_equal_autograds(bias):
+ plain, fused, state, names = _nets(bias)
+ assert names == ["a", "b"]
+ batches = _microbatches(4)
+ want, got = _accumulate(plain, batches), _accumulate(fused, batches, state)
+ for a, b in zip(want, got, strict=True):
+ assert torch.allclose(a, b) # input gradients
+ for (name, p), q in zip(plain.named_parameters(), fused.parameters(), strict=True):
+ assert torch.allclose(p.grad, q.grad), name
+
+
+def test_the_weight_gradient_is_not_allocated_apart_from_the_total():
+ # autograd would hand AccumulateGrad a second tensor as large as the weight; here .grad's
+ # own storage is updated in place
+ _, fused, state, _ = _nets(False)
+ batches = _microbatches(3)
+ state.fuse = False
+ fused(batches[0]).square().sum().backward()
+ total = fused.a.weight.grad
+ before = total.clone()
+ state.fuse = True
+ fused(batches[1]).square().sum().backward()
+ assert fused.a.weight.grad is total
+ assert not torch.equal(total, before)
+
+
+def test_the_last_microbatch_runs_autograds_hooks_on_the_whole_gradient():
+ # DeepSpeed reduces a parameter's gradient in a post-accumulate hook, at the last microbatch
+ plain, fused, state, _ = _nets(False)
+ seen = []
+ fused.a.weight.register_post_accumulate_grad_hook(lambda p: seen.append(p.grad.clone()))
+ batches = _microbatches(3)
+ _accumulate(plain, batches)
+ _accumulate(fused, batches, state)
+ assert torch.allclose(seen[-1], plain.a.weight.grad)
+
+
+def test_the_first_backward_creates_the_gradient():
+ _, fused, state, _ = _nets(False)
+ state.fuse = True
+ fused(_microbatches(1)[0]).square().sum().backward()
+ assert fused.a.weight.grad is not None
+
+
+def test_a_gradient_freed_between_microbatches_starts_over():
+ # the fp32-accumulation optimizers take .grad away after each microbatch
+ plain, fused, state, _ = _nets(False)
+ state.fuse = True
+ x = _microbatches(1)[0]
+ for net in (plain, fused):
+ net(x).square().sum().backward()
+ for p in net.parameters():
+ p.grad = None
+ net(x).square().sum().backward()
+ for p, q in zip(plain.parameters(), fused.parameters(), strict=True):
+ assert torch.allclose(p.grad, q.grad)
+
+
+def test_under_recomputation():
+ plain, fused, state, _ = _nets(False)
+ batches = _microbatches(3)
+ for net, st in ((plain, None), (fused, state)):
+ for i, x in enumerate(batches):
+ if st is not None:
+ st.fuse = i < 2
+ x = x.clone().requires_grad_()
+ out = torch.utils.checkpoint.checkpoint(net, x, use_reentrant=False)
+ out.square().sum().backward()
+ for p, q in zip(plain.parameters(), fused.parameters(), strict=True):
+ assert torch.allclose(p.grad, q.grad)
+
+
+def test_frozen_and_vision_layers_are_left_alone():
+ net = nn.ModuleDict({"visual": nn.Linear(4, 4), "layers": nn.Linear(4, 4)})
+ net["frozen"] = nn.Linear(4, 4)
+ net["frozen"].weight.requires_grad_(False)
+ assert fuse_linear_grads(net, GradAccumulation()) == ["layers"]
+
+
+def test_bf16_gradients_stay_bf16_and_close():
+ plain, fused, state, _ = _nets(False, torch.bfloat16)
+ batches = _microbatches(8, torch.bfloat16)
+ _accumulate(plain, batches)
+ _accumulate(fused, batches, state)
+ for p, q in zip(plain.parameters(), fused.parameters(), strict=True):
+ assert q.grad.dtype is torch.bfloat16
+ assert torch.allclose(p.grad.float(), q.grad.float(), rtol=5e-2, atol=5e-2)
+
+
+def _embedding_pair():
+ torch.manual_seed(0)
+ plain, fused = (nn.Sequential(nn.Embedding(50, 6), nn.Linear(6, 3)) for _ in range(2))
+ fused.load_state_dict(plain.state_dict())
+ state = GradAccumulation()
+ return plain, fused, state, fuse_linear_grads(fused, state)
+
+
+def test_an_embeddings_gradient_adds_only_the_rows_it_read():
+ plain, fused, state, names = _embedding_pair()
+ assert names == ["0", "1"]
+ ids = [
+ torch.randint(0, 50, (2, 7), generator=torch.Generator().manual_seed(i)) for i in range(4)
+ ]
+ for net, st in ((plain, None), (fused, state)):
+ for i, x in enumerate(ids):
+ if st is not None:
+ st.fuse = i < len(ids) - 1
+ net(x).square().sum().backward()
+ for p, q in zip(plain.parameters(), fused.parameters(), strict=True):
+ assert torch.allclose(p.grad, q.grad)
+
+
+def test_an_embedding_adds_in_place():
+ _, fused, state, _ = _embedding_pair()
+ ids = torch.tensor([[1, 2, 2]])
+ fused(ids).square().sum().backward()
+ total = fused[0].weight.grad
+ state.fuse = True
+ fused(ids).square().sum().backward()
+ assert fused[0].weight.grad is total
+ assert total[5].abs().sum() == 0 # a row no token used
+
+
+def test_embeddings_with_padding_or_scaling_are_left_alone():
+ net = nn.ModuleDict(
+ {
+ "padded": nn.Embedding(8, 4, padding_idx=0),
+ "normed": nn.Embedding(8, 4, max_norm=1.0),
+ "scaled": nn.Embedding(8, 4, scale_grad_by_freq=True),
+ "sparse": nn.Embedding(8, 4, sparse=True),
+ }
+ )
+ assert fuse_linear_grads(net, GradAccumulation()) == []
+
+
+def test_only_stages_that_keep_gradients_in_grad_are_fused():
+ from ray_deepspeed_pipeline.deepspeed_adapter import _plain_stage_gradients
+
+ assert _plain_stage_gradients({})
+ assert _plain_stage_gradients({"zero_optimization": {"stage": 1}})
+ assert not _plain_stage_gradients({"zero_optimization": {"stage": 2}})
+ assert not _plain_stage_gradients({"zero_optimization": {"stage": 3}})
+ offload = {"stage": 1, "offload_optimizer": {"device": "cpu"}}
+ assert not _plain_stage_gradients({"zero_optimization": offload})
+ assert not _plain_stage_gradients({"expert_parallel": {"autoep_size": 2}})
+ assert _plain_stage_gradients({"expert_parallel": {"autoep_size": 1}})
diff --git a/training/rdsp/tests/unit/test_gated_norm.py b/training/rdsp/tests/unit/test_gated_norm.py
new file mode 100644
index 000000000..349f3d15c
--- /dev/null
+++ b/training/rdsp/tests/unit/test_gated_norm.py
@@ -0,0 +1,64 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+
+"""Qwen3.5's gated RMSNorm on the fused kernel against Hugging Face's own forward."""
+
+import pickle
+
+import pytest
+import torch
+
+from ray_deepspeed_pipeline.gated_norm import fuse_gated_norms
+
+modeling = pytest.importorskip("transformers.models.qwen3_5.modeling_qwen3_5")
+
+
+def _pair(dtype):
+ torch.manual_seed(0)
+ want = torch.nn.ModuleDict({"norm": modeling.Qwen3_5RMSNormGated(16)}).to(dtype)
+ with torch.no_grad():
+ want["norm"].weight.normal_(1, 0.2)
+ got = torch.nn.ModuleDict({"norm": modeling.Qwen3_5RMSNormGated(16)}).to(dtype)
+ got.load_state_dict(want.state_dict())
+ assert fuse_gated_norms(got) == 1
+ return want["norm"], got["norm"]
+
+
+def _run(norm, dtype):
+ g = torch.Generator().manual_seed(1)
+ h = (torch.randn(2, 5, 3, 16, generator=g) * 3).to(dtype).requires_grad_()
+ gate = torch.randn(2, 5, 3, 16, generator=g).to(dtype).requires_grad_()
+ out = norm(h, gate)
+ (out * 0.1).float().sum().backward()
+ return out.detach().float(), h.grad.float(), gate.grad.float(), norm.weight.grad.float()
+
+
+def test_in_fp32_it_is_hugging_faces():
+ want, got = _pair(torch.float32)
+ for a, b in zip(_run(want, torch.float32), _run(got, torch.float32), strict=True):
+ assert torch.allclose(a, b, atol=1e-5)
+
+
+def test_in_bf16_it_keeps_the_dtype_and_is_close():
+ want, got = _pair(torch.bfloat16)
+ assert (
+ got(torch.ones(1, 16, dtype=torch.bfloat16), torch.ones(1, 16, dtype=torch.bfloat16)).dtype
+ is torch.bfloat16
+ )
+ for a, b in zip(_run(want, torch.bfloat16), _run(got, torch.bfloat16), strict=True):
+ assert torch.allclose(a, b, rtol=5e-2, atol=5e-2)
+
+
+def test_only_that_class_and_only_once():
+ net = torch.nn.ModuleDict({"a": torch.nn.LayerNorm(4), "b": modeling.Qwen3_5RMSNorm(4)})
+ assert fuse_gated_norms(net) == 0
+ net["c"] = modeling.Qwen3_5RMSNormGated(4)
+ assert fuse_gated_norms(net) == 1
+ assert fuse_gated_norms(net) == 0
+
+
+def test_the_patch_travels_with_the_instance():
+ _, got = _pair(torch.float32)
+ copy = pickle.loads(pickle.dumps(got))
+ x, gate = torch.randn(2, 16), torch.randn(2, 16)
+ assert torch.allclose(copy(x, gate), got(x, gate))
diff --git a/training/rdsp/tests/unit/test_hf_stage_sync.py b/training/rdsp/tests/unit/test_hf_stage_sync.py
new file mode 100644
index 000000000..0b12cae37
--- /dev/null
+++ b/training/rdsp/tests/unit/test_hf_stage_sync.py
@@ -0,0 +1,81 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+
+"""A stage after the first runs the model's setup code without waiting for the GPU.
+
+Hugging Face looks, in every forward, for several sequences packed in one row: a value read back
+from the GPU before the stage's blocks are launched. A later stage's positions are always the
+row's own 0, 1, 2, ...; there is nothing to find, and the read held the host until the hidden
+state had arrived."""
+
+import pytest
+import torch
+
+transformers = pytest.importorskip("transformers")
+
+from ray_deepspeed_pipeline.config import ExplicitCuts # noqa: E402
+from ray_deepspeed_pipeline.hf_stage import build_hf_stage # noqa: E402
+from ray_deepspeed_pipeline.partition import partition_parameters # noqa: E402
+
+
+def stages():
+ cfg = transformers.Qwen3Config(
+ vocab_size=64,
+ hidden_size=32,
+ intermediate_size=64,
+ num_hidden_layers=4,
+ num_attention_heads=2,
+ num_key_value_heads=2,
+ head_dim=16,
+ tie_word_embeddings=False,
+ )
+ cfg._attn_implementation = "sdpa"
+ torch.manual_seed(0)
+ model = transformers.Qwen3ForCausalLM(cfg).float().eval()
+ parts = partition_parameters(model, ExplicitCuts((2,)), 2)
+ built = [
+ build_hf_stage(model, p.block_start, p.block_stop, p.parameter_names, stage_index=i)
+ for i, p in enumerate(parts)
+ ]
+ return model, built
+
+
+@pytest.fixture
+def host_reads(monkeypatch):
+ reads = []
+ for name in ("__bool__", "item", "tolist"):
+ real = getattr(torch.Tensor, name)
+ monkeypatch.setattr(
+ torch.Tensor, name, lambda self, _real=real, _n=name: reads.append(_n) or _real(self)
+ )
+ return reads
+
+
+def test_a_later_stage_reads_nothing_back(host_reads):
+ model, (first, last) = stages()
+ ids = torch.randint(0, 64, (2, 8))
+ with torch.no_grad():
+ expected = model(input_ids=ids, use_cache=False).logits
+ hidden, extras = first(ids)
+ host_reads.clear()
+ logits = last(hidden, **extras)
+ assert host_reads == []
+ assert torch.allclose(logits, expected, atol=1e-5)
+
+
+def test_the_first_stage_still_finds_packed_rows(host_reads):
+ _, (first, _) = stages()
+ with torch.no_grad():
+ first(torch.randint(0, 64, (2, 8)))
+ assert "__bool__" in host_reads
+
+
+def test_the_check_is_put_back(monkeypatch):
+ from transformers import masking_utils
+
+ before = masking_utils.find_packed_sequence_indices
+ _, (first, last) = stages()
+ with torch.no_grad():
+ hidden, extras = first(torch.randint(0, 64, (2, 8)))
+ last(hidden, **extras)
+ assert masking_utils.find_packed_sequence_indices is before
diff --git a/training/rdsp/tests/unit/test_liger_loss.py b/training/rdsp/tests/unit/test_liger_loss.py
new file mode 100644
index 000000000..e4cf2222b
--- /dev/null
+++ b/training/rdsp/tests/unit/test_liger_loss.py
@@ -0,0 +1,83 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+
+"""The choice of the stage loss: Liger's kernel where a rank holds the whole vocabulary. Liger
+itself is not installed here, so a stand-in computes what its kernel documents."""
+
+import os
+import sys
+import types
+
+import pytest
+import torch
+import torch.nn.functional as F
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, os.path.join(HERE, "..", ".."))
+
+import train_vl # noqa: E402
+from ray_deepspeed_pipeline.vocab_parallel import VocabShard # noqa: E402
+
+
+@pytest.fixture
+def liger(monkeypatch):
+ calls = []
+
+ class LigerCrossEntropyLoss:
+ def __init__(self, ignore_index, reduction):
+ calls.append(reduction)
+ self.ignore_index, self.reduction = ignore_index, reduction
+
+ def __call__(self, logits, target):
+ # per token, rounded to the logits' dtype as the kernel's output is
+ loss = F.cross_entropy(
+ logits.float(), target, ignore_index=self.ignore_index, reduction="none"
+ )
+ return loss.to(logits.dtype)
+
+ transformers = types.ModuleType("liger_kernel.transformers")
+ transformers.LigerCrossEntropyLoss = LigerCrossEntropyLoss
+ monkeypatch.setitem(sys.modules, "liger_kernel", types.ModuleType("liger_kernel"))
+ monkeypatch.setitem(sys.modules, "liger_kernel.transformers", transformers)
+ return calls
+
+
+def _batch():
+ g = torch.Generator().manual_seed(0)
+ logits = (torch.randn(1, 64, 100, generator=g) * 3).bfloat16()
+ labels = torch.randint(0, 100, (1, 64), generator=g)
+ labels[0, :10] = -100
+ return logits, labels
+
+
+def test_it_sums_the_per_token_losses_in_fp32(liger):
+ logits, labels = _batch()
+ want = F.cross_entropy(
+ logits[:, :-1].float().reshape(-1, 100),
+ labels[:, 1:].reshape(-1),
+ ignore_index=-100,
+ reduction="sum",
+ )
+ got = train_vl.sharded_loss_sum_liger(logits, labels)
+ assert liger == ["none"]
+ assert got.dtype is torch.float32
+ assert torch.allclose(got, want, rtol=5e-3)
+
+
+def test_a_vocabulary_shard_takes_the_sharded_loss(liger, monkeypatch):
+ logits, labels = _batch()
+ logits.vocab_shard = VocabShard(0, object())
+ monkeypatch.setattr(train_vl.rdsp, "next_token_loss_sum", lambda logits, labels: "sharded")
+ assert train_vl.sharded_loss_sum_liger(logits, labels) == "sharded"
+ assert liger == []
+
+
+def test_liger_and_sharded_loss_together_choose_it():
+ def chosen(flags):
+ args = train_vl.build_parser().parse_args(flags)
+ return train_vl.loss_function(args).sum_fn
+
+ assert chosen(["--sharded-loss", "--liger"]) is train_vl.sharded_loss_sum_liger
+ assert chosen(["--sharded-loss"]) is train_vl.rdsp.next_token_loss_sum
+ assert chosen(["--liger"]) is train_vl.token_loss_sum_liger
+ assert train_vl.sharded_loss_sum_liger.takes_vocab_shards
diff --git a/training/rdsp/tests/unit/test_linear_attention_parallel.py b/training/rdsp/tests/unit/test_linear_attention_parallel.py
index ace1d5289..defb576fa 100644
--- a/training/rdsp/tests/unit/test_linear_attention_parallel.py
+++ b/training/rdsp/tests/unit/test_linear_attention_parallel.py
@@ -17,6 +17,7 @@
import torch.multiprocessing as mp
from ray_deepspeed_pipeline.linear_attention_parallel import shard_linear_attention
+from ray_deepspeed_pipeline.tp_input_grads import GradAccumulation, share_input_grad_reductions
transformers = pytest.importorskip("transformers")
if not hasattr(transformers, "Qwen3_5TextConfig"):
@@ -73,12 +74,21 @@ def _reference_kernels():
setattr(modeling_qwen3_5, name, inspect.unwrap(getattr(modeling_qwen3_5, name)))
-def _rank(rank, init_file, out_dir):
+def _rank(rank, init_file, out_dir, joint=False):
dist.init_process_group("gloo", init_method=f"file://{init_file}", rank=rank, world_size=TP)
_reference_kernels()
full = layer()
sharded = copy.deepcopy(full)
replaced = shard_linear_attention(sharded, rank=rank, world=TP, group=lambda: dist.group.WORLD)
+ reduced, real = [], dist.all_reduce
+ if joint: # the input projections' all-reduce shared, and overlapped (tp_input_grads)
+ assert share_input_grad_reductions(sharded, GradAccumulation()) == [""]
+
+ def counted(*args, **kwargs):
+ reduced.append(args[0].shape)
+ return real(*args, **kwargs)
+
+ dist.all_reduce = counted
x = torch.randn(2, 6, HIDDEN, generator=torch.Generator().manual_seed(1))
target = torch.randn(2, 6, HIDDEN, generator=torch.Generator().manual_seed(2))
@@ -111,19 +121,23 @@ def close(a, b):
"dt_bias": close(sharded.dt_bias.grad, g["dt_bias"][value_heads]),
"out_proj": close(sharded.out_proj.weight.grad, g["out_proj.weight"][:, value_cols]),
"norm": close(sharded.norm.weight.grad, g["norm.weight"]),
+ "input_reductions": sum(shape == x.shape for shape in reduced),
},
os.path.join(out_dir, f"r{rank}.pt"),
)
dist.destroy_process_group()
-def test_head_parallel_layer_matches_the_unsplit_layer():
+@pytest.mark.parametrize("joint", [False, True])
+def test_head_parallel_layer_matches_the_unsplit_layer(joint):
with tempfile.TemporaryDirectory() as d:
- mp.spawn(_rank, args=(os.path.join(d, "init"), d), nprocs=TP)
+ mp.spawn(_rank, args=(os.path.join(d, "init"), d, joint), nprocs=TP)
for rank in range(TP):
r = torch.load(os.path.join(d, f"r{rank}.pt"))
assert r.pop("replaced") == [""] # the layer itself
assert r.pop("heads") == (K_HEADS // TP, V_HEADS // TP)
+ # the output's sum, and one for the input gradient of all four projections
+ assert r.pop("input_reductions") == 2
assert all(r.values()), {k: v for k, v in r.items() if not v}
diff --git a/training/rdsp/tests/unit/test_measured_cut.py b/training/rdsp/tests/unit/test_measured_cut.py
index 9e42a6c01..b56f24011 100644
--- a/training/rdsp/tests/unit/test_measured_cut.py
+++ b/training/rdsp/tests/unit/test_measured_cut.py
@@ -298,3 +298,13 @@ def test_skipped_steps_set_no_memory_peak():
records = [[{"records": warm_up + steady, "total_gib": 80.0}]]
m = measured_stages(plan, records, skip=1, reserve_gib=5.0)
assert m.peak_gib == (51.0,)
+
+
+def test_a_heavy_vision_encoder_gets_more_gpus_of_its_own():
+ from ray_deepspeed_pipeline.partition import vision_stage_gpus
+
+ ones = (1,) * 8
+ heavy = MeasuredStages((3, 9, 15, 21, 27, 33, 38), (16, 6, 6, 6, 6, 6, 5.5, 3), ones, ones, 70)
+ light = MeasuredStages((5, 10, 15, 20, 25, 30, 35), (5.5,) * 7 + (6,), ones, ones, 70)
+ assert vision_stage_gpus(heavy, 40, 2, 16) == 4
+ assert vision_stage_gpus(light, 40, 2, 16) == 2
diff --git a/training/rdsp/tests/unit/test_nsight_window.py b/training/rdsp/tests/unit/test_nsight_window.py
new file mode 100644
index 000000000..b5d9233de
--- /dev/null
+++ b/training/rdsp/tests/unit/test_nsight_window.py
@@ -0,0 +1,47 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+
+"""RDSP_NSIGHT_STEPS="first:last": Nsight Systems captures only those steps of a worker."""
+
+import torch
+
+from ray_deepspeed_pipeline.stage_worker import _TraceWindow
+
+
+def record(monkeypatch):
+ calls = []
+ monkeypatch.setattr(torch.cuda.profiler, "start", lambda: calls.append("start"))
+ monkeypatch.setattr(torch.cuda.profiler, "stop", lambda: calls.append("stop"))
+ return calls
+
+
+def run(window, steps, calls):
+ for step in range(steps):
+ window.before()
+ calls.append(step)
+ window.after()
+
+
+def test_the_capture_starts_and_stops_around_the_listed_steps(monkeypatch):
+ calls = record(monkeypatch)
+ run(_TraceWindow("2:3"), 5, calls)
+ assert calls == [0, 1, "start", 2, 3, "stop", 4]
+
+
+def test_without_the_variable_nothing_is_captured(monkeypatch):
+ calls = record(monkeypatch)
+ monkeypatch.delenv("RDSP_NSIGHT_STEPS", raising=False)
+ run(_TraceWindow(), 3, calls)
+ assert calls == [0, 1, 2]
+
+
+def test_before_says_whether_this_step_starts_the_capture(monkeypatch):
+ record(monkeypatch)
+ window = _TraceWindow("1:2")
+ assert [window.before() for _ in range(3)] == [False, True, False]
+
+
+def test_one_step_is_captured_alone(monkeypatch):
+ calls = record(monkeypatch)
+ run(_TraceWindow("1"), 3, calls)
+ assert calls == [0, "start", 1, "stop", 2]
diff --git a/training/rdsp/tests/unit/test_p2p.py b/training/rdsp/tests/unit/test_p2p.py
index 0ed31f780..e5a267e86 100644
--- a/training/rdsp/tests/unit/test_p2p.py
+++ b/training/rdsp/tests/unit/test_p2p.py
@@ -3,9 +3,12 @@
"""Stage-to-stage exchange over gloo: two ranks in one process, one thread each."""
+import gc
import socket
import threading
+import weakref
+import pytest
import torch
from ray_deepspeed_pipeline.p2p import PipelineP2P, make_store
@@ -120,3 +123,77 @@ def test_boundary_limits_are_validation_errors():
p2p = PipelineP2P.__new__(PipelineP2P)
with pytest.raises(ValidationError, match="extra tensors"):
p2p.send_boundary("fwd", torch.zeros(1), {str(i): torch.zeros(1) for i in range(63)}, 1, 0)
+
+
+class _Send:
+ """A send's handle, finished when the test says so. `tensor`: a weak
+ reference to the tensor handed to the process group."""
+
+ def __init__(self, tensor, error=None):
+ self.tensor, self.done, self.error, self.waited = weakref.ref(tensor), False, error, False
+
+ def is_completed(self):
+ return self.done
+
+ def wait(self):
+ self.waited = True
+ if self.error:
+ raise self.error
+
+
+class _Group:
+ """Process group stand-in that only records its sends."""
+
+ def __init__(self):
+ self.sends = []
+
+ def send(self, tensors, peer, tag):
+ self.sends.append(_Send(tensors[0]))
+ return self.sends[-1]
+
+
+def _sender():
+ store = make_store("127.0.0.1", _port(), 1, True, 30)
+ p2p = PipelineP2P(store, 0, 1, 0, 30, torch.device("cpu"))
+ p2p.fwd = p2p.bwd = _Group()
+ p2p.begin_step()
+ return p2p
+
+
+def _held(p2p):
+ gc.collect()
+ return [w.tensor() is not None for w in p2p.fwd.sends]
+
+
+def test_a_sent_tensor_is_freed_when_its_send_finishes_not_at_the_steps_end():
+ # every boundary tensor of the step stayed allocated until end_step: with 64 microbatches
+ # of 40 MiB, 5 GiB on the rank that sends activations and gradients
+ p2p = _sender()
+ for mb in range(8):
+ p2p.send("fwd", torch.randn(4, 4), 1, mb)
+ for work in p2p.fwd.sends:
+ work.done = True
+ p2p.send("fwd", torch.randn(4, 4), 1, 8)
+ # microbatch 0 is a header and a tensor; only microbatch 8's send is still in flight
+ assert _held(p2p) == [False] * 9 + [True]
+ assert all(w.waited for w in p2p.fwd.sends[:-1]) # an error would still have been raised
+
+
+def test_a_send_still_in_flight_keeps_its_tensor_until_the_step_ends():
+ p2p = _sender()
+ for mb in range(4):
+ p2p.send("fwd", torch.randn(4, 4), 1, mb)
+ assert _held(p2p) == [True] * 5
+ p2p.end_step()
+ assert _held(p2p) == [False] * 5
+ assert all(w.waited for w in p2p.fwd.sends)
+
+
+def test_a_failed_send_still_raises():
+ p2p = _sender()
+ p2p.send("fwd", torch.randn(4, 4), 1, 0)
+ p2p.fwd.sends[-1].done = True
+ p2p.fwd.sends[-1].error = RuntimeError("peer gone")
+ with pytest.raises(RuntimeError, match="peer gone"):
+ p2p.send("fwd", torch.randn(4, 4), 1, 1)
+ p2p.end_step()
diff --git a/training/rdsp/tests/unit/test_partition.py b/training/rdsp/tests/unit/test_partition.py
index 05dac9028..d1eb7ac61 100644
--- a/training/rdsp/tests/unit/test_partition.py
+++ b/training/rdsp/tests/unit/test_partition.py
@@ -392,3 +392,40 @@ def test_per_head_norms_get_their_tp_gradient_sum_when_the_config_plan_omits_the
"layers.*.self_attn.k_norm",
}
assert stage._tp_plan["layers.*.self_attn.q_proj"] == "colwise"
+
+
+def _tied_skeleton():
+ """A tiny Qwen3 whose config ties the embedding to the head, built as rdsp.initialize
+ gets it: under init_empty_weights, where the two are separate meta tensors."""
+ transformers = pytest.importorskip("transformers")
+ accelerate = pytest.importorskip("accelerate")
+ config = transformers.Qwen3Config(
+ vocab_size=64,
+ hidden_size=32,
+ intermediate_size=64,
+ num_hidden_layers=2,
+ num_attention_heads=4,
+ num_key_value_heads=2,
+ head_dim=8,
+ tie_word_embeddings=True,
+ )
+ with accelerate.init_empty_weights():
+ return transformers.Qwen3ForCausalLM(config)
+
+
+def test_a_declared_tie_across_stages_is_rejected_on_a_skeleton():
+ skeleton = _tied_skeleton()
+ with pytest.raises(ValidationError, match="tie_word_embeddings=False"):
+ partition_parameters(skeleton, UniformTransformerBlocks(), 2)
+
+
+def test_a_declared_tie_on_one_stage_is_one_weight_after_loading(tmp_path):
+ from ray_deepspeed_pipeline.hf_stage import build_hf_stage, load_meta_parameters
+
+ skeleton = _tied_skeleton()
+ skeleton.config._attn_implementation = "eager" # the HF stage builder
+ type(skeleton)(skeleton.config).save_pretrained(tmp_path)
+ (part,) = partition_parameters(skeleton, UniformTransformerBlocks(), 1)
+ stage = build_hf_stage(skeleton, 0, part.block_stop, part.parameter_names, stage_index=0)
+ load_meta_parameters(stage, str(tmp_path))
+ assert stage.model.lm_head.weight is stage.model.model.embed_tokens.weight
diff --git a/training/rdsp/tests/unit/test_plan.py b/training/rdsp/tests/unit/test_plan.py
index b9bfdc019..f2155d2bc 100644
--- a/training/rdsp/tests/unit/test_plan.py
+++ b/training/rdsp/tests/unit/test_plan.py
@@ -26,7 +26,6 @@ def make_plan(microbatches=4):
block_stop=i + 1,
num_gpus=1,
ds_config_json="{}",
- process_group_tag=f"stage{i}",
)
for i in range(2)
)
diff --git a/training/rdsp/tests/unit/test_protocols.py b/training/rdsp/tests/unit/test_protocols.py
index bc75dd2a8..85a3be07a 100644
--- a/training/rdsp/tests/unit/test_protocols.py
+++ b/training/rdsp/tests/unit/test_protocols.py
@@ -8,12 +8,7 @@
import pytest
-from ray_deepspeed_pipeline.protocols import (
- COMMAND_KINDS,
- Command,
- CommandResult,
- resolve,
-)
+from ray_deepspeed_pipeline.protocols import Command, resolve
def test_command_canonical_roundtrip():
@@ -40,26 +35,6 @@ def test_command_canonical_roundtrip():
cmd.kind = "backward"
-def test_command_kinds_cover_the_runtime_verbs():
- assert set(COMMAND_KINDS) == {
- "forward",
- "backward",
- "ready",
- "apply",
- "eval",
- "save",
- "load",
- # stage-local dispatch: a stage's whole step
- "step",
- "eval_step",
- }
-
-
-def test_result_schema():
- r = CommandResult(command_id="x", status="ok")
- assert r.detail == ""
-
-
def test_resolve_unwraps_future_like_and_passes_values():
class Fut:
def result(self):
diff --git a/training/rdsp/tests/unit/test_public_api.py b/training/rdsp/tests/unit/test_public_api.py
index 307c3154b..c2f65c0ba 100644
--- a/training/rdsp/tests/unit/test_public_api.py
+++ b/training/rdsp/tests/unit/test_public_api.py
@@ -17,7 +17,7 @@
def test_layout_types_are_public():
- assert {"StageOverride", "ConnectionOverride"} <= set(rdsp.__all__)
+ assert {"StageOverride", "ColocatedVision"} <= set(rdsp.__all__)
def _stated(obj) -> bool:
diff --git a/training/rdsp/tests/unit/test_readme_results.py b/training/rdsp/tests/unit/test_readme_results.py
deleted file mode 100644
index 0fe34c6d2..000000000
--- a/training/rdsp/tests/unit/test_readme_results.py
+++ /dev/null
@@ -1,77 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-
-"""The README's headline step times are the medians of the published runs' logs, as
-bench/common/medians.py computes them, and its ratios follow from them.
-The logs are not in the repository; these tests run where they are."""
-
-import os
-import sys
-
-import pytest
-
-ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")
-sys.path.insert(0, os.path.join(ROOT, "bench", "common"))
-
-import medians # noqa: E402
-
-# model: (rdsp, Megatron-Bridge, TorchTitan), each a (log format, log under bench/)
-LOGS = {
- "35B": (
- ("rdsp", "qwen35_35b/logs/vision_stage/rdsp-k4-rc.log"),
- ("bridge", "qwen35_35b/logs/pp2ep8/bridge-pp2ep8-nv.log"),
- (
- "titan",
- "qwen35_35b/logs/fsdp16/run-qwen35_35b_a3b_cord_fsdp16_ep8_bf16-node0.log",
- ),
- ),
- "27B": (
- ("rdsp", "qwen35_27b/logs/pp8/rdsp-nov21fix-rows1-best.log"),
- ("bridge", "qwen35_27b/logs/pp8/bridge-nov21fix-mbs1-best.log"),
- ("titan", "torchtitan/logs/run-qwen35_27b_cord_fsdp8_rc_bf16.log"),
- ),
-}
-
-
-def _logs_present(model: str) -> bool:
- return all(os.path.exists(os.path.join(ROOT, "bench", log)) for _, log in LOGS[model])
-
-
-needs_logs = pytest.mark.parametrize(
- "model",
- [
- pytest.param(m, marks=pytest.mark.skipif(not _logs_present(m), reason="logs not here"))
- for m in sorted(LOGS)
- ],
-)
-
-
-def readme() -> str:
- with open(os.path.join(ROOT, "README.md")) as f:
- return f.read()
-
-
-@needs_logs
-def test_the_results_row_is_the_cited_logs_medians(model):
- ours, bridge, titan = (
- medians.median(kind, os.path.join(ROOT, "bench", log)) for kind, log in LOGS[model]
- )
- row = f"| **{ours:.2f} s** | {bridge:.2f} s | {titan:.2f} s |"
- assert row in readme()
-
-
-@needs_logs
-def test_the_ratios_follow_from_the_step_times(model):
- ours, bridge, titan = (
- medians.median(kind, os.path.join(ROOT, "bench", log)) for kind, log in LOGS[model]
- )
- text = readme()
- assert f"{bridge / ours:.2f}×" in text
- assert f"{titan / ours:.2f}×" in text
-
-
-def test_rdsp_steps_are_counted_as_logged():
- """rdsp's log counts from step 0, and medians.py keeps its numbers."""
- log = "".join(f"step {i} loss 0.5 {1000 * (i + 1)} ms\n" for i in range(50))
- assert min(medians.rdsp(log)) == 0
- assert medians.rdsp(log)[6] == 7.0
diff --git a/training/rdsp/tests/unit/test_recipes.py b/training/rdsp/tests/unit/test_recipes.py
index 0d3cb5f95..33772b64e 100644
--- a/training/rdsp/tests/unit/test_recipes.py
+++ b/training/rdsp/tests/unit/test_recipes.py
@@ -20,6 +20,9 @@
"qwen35-4b-tp2pp2dp2.sh",
"qwen35-4b-tp4pp2dp1.sh",
"qwen35-4b-vision1-tp2dp2.sh",
+ "qwen35-9b-vision4-pp6dp2.sh",
+ "qwen35-27b-vision2-pp7dp2.sh",
+ "qwen35-35b-a3b-vision4-pp6dp2.sh",
)
@@ -48,4 +51,3 @@ def test_every_recipe_parses(recipe):
text = open(os.path.join(ROOT, "recipes", recipe)).read()
script, args = _command(text)
_parser(script).parse_args(args)
- assert "GPUs:" in text and "Measured:" in text
diff --git a/training/rdsp/tests/unit/test_stage_engine_sync.py b/training/rdsp/tests/unit/test_stage_engine_sync.py
new file mode 100644
index 000000000..18a99eaa2
--- /dev/null
+++ b/training/rdsp/tests/unit/test_stage_engine_sync.py
@@ -0,0 +1,67 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+
+"""A stage engine's forward never synchronizes the device. DeepSpeed's throughput timer
+does, before every forward, when the engine has no DeepSpeed data loader (rdsp's stage
+engines never have one). A device-wide sync also waits for the stage's async sends to its
+neighbours, so it ties every microbatch to the other stages. CPU, one rank, gloo; needs
+DeepSpeed."""
+
+import os
+import sys
+
+import pytest
+import torch
+
+os.environ.setdefault("DS_ACCELERATOR", "cpu") # not the Mac's MPS
+deepspeed = pytest.importorskip("deepspeed")
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, os.path.join(HERE, "..", ".."))
+
+import train_vl # noqa: E402
+from ray_deepspeed_pipeline.deepspeed_adapter import _deepspeed_engine_factory # noqa: E402
+
+
+@pytest.fixture(scope="module", autouse=True)
+def gloo():
+ os.environ.update(
+ MASTER_ADDR="127.0.0.1", MASTER_PORT="29547", RANK="0", WORLD_SIZE="1", LOCAL_RANK="0"
+ )
+ # left initialized, as test_remainder_master_engine.py leaves it: DeepSpeed keeps its
+ # groups for the session (this module sorts after test_linear_attention_parallel.py,
+ # which starts and destroys its own default group)
+ deepspeed.init_distributed(dist_backend="gloo")
+
+
+def stage_engine():
+ flags = ["--stages", "1", "--stage", "0:gpus=1", "--rows", "1", "--microbatches", "1"]
+ flags += ["--zero", "1", "--grad-dtype", "bf16"] # as the benchmark runs
+ conf = train_vl.ds_config(train_vl.build_parser().parse_args(flags))
+ conf.update(train_micro_batch_size_per_gpu=1, train_batch_size=1)
+ torch.manual_seed(0)
+ model = torch.nn.Sequential(*[torch.nn.Linear(16, 16) for _ in range(2)]).to(torch.bfloat16)
+ return _deepspeed_engine_factory(model, conf)
+
+
+def test_forward_never_synchronizes_the_device(monkeypatch):
+ engine = stage_engine()
+ accelerator = deepspeed.accelerator.get_accelerator()
+ syncs = []
+ monkeypatch.setattr(accelerator, "synchronize", lambda *a, **k: syncs.append(1))
+ in_forward = []
+ for _ in range(5): # DeepSpeed's timer starts syncing at its third step
+ before = len(syncs)
+ out = engine(torch.randn(1, 16, dtype=torch.bfloat16))
+ in_forward.append(len(syncs) - before)
+ engine.backward(out.float().sum())
+ engine.step()
+ assert in_forward == [0] * 5
+
+
+def test_an_explicit_timer_setting_is_kept():
+ from ray_deepspeed_pipeline.deepspeed_adapter import _without_throughput_timer
+
+ assert _without_throughput_timer({})["timers"] == {"throughput": {"enabled": False}}
+ mine = {"timers": {"throughput": {"enabled": True, "synchronized": False}}}
+ assert _without_throughput_timer(mine)["timers"] == mine["timers"]
diff --git a/training/rdsp/tests/unit/test_support_matrix.py b/training/rdsp/tests/unit/test_support_matrix.py
deleted file mode 100644
index 0ecda0e9b..000000000
--- a/training/rdsp/tests/unit/test_support_matrix.py
+++ /dev/null
@@ -1,47 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-
-"""The support matrix is default-deny and internally consistent."""
-
-from ray_deepspeed_pipeline.support_matrix import BASELINE_ROW, HETEROGENEOUS_ROWS, ROWS
-
-
-def test_default_deny():
- # a row claims support only with a recorded passing acceptance run; the
- # first row has passed its own
- assert BASELINE_ROW.supported
- for row in HETEROGENEOUS_ROWS:
- assert not row.supported or row.evidence, row.row_id
-
-
-def test_first_row_definition():
- assert BASELINE_ROW.row_id == "two-stage-baseline"
- assert (BASELINE_ROW.stages, BASELINE_ROW.gpus_per_stage) == (2, 1)
- assert BASELINE_ROW.dtype == "bf16" and BASELINE_ROW.zero_stage == 0
- assert BASELINE_ROW.schedule == "1f1b" and BASELINE_ROW.boundaries == "identity"
- assert (BASELINE_ROW.dp, BASELINE_ROW.tp, BASELINE_ROW.ep, BASELINE_ROW.sp) == (1, 1, 1, 1)
-
-
-def test_row_ids_unique():
- ids = [r.row_id for r in ROWS]
- assert len(ids) == len(set(ids))
-
-
-def test_composed_row_requires_every_prerequisite():
- by_id = {r.row_id: r for r in HETEROGENEOUS_ROWS}
- for row in HETEROGENEOUS_ROWS:
- assert all(req in by_id for req in row.requires), row.row_id
- if row.supported:
- assert all(by_id[req].supported for req in row.requires), (
- f"{row.row_id} cannot be supported before {row.requires}"
- )
- assert set(by_id["four-stage-mixed"].requires) == set(by_id) - {"four-stage-mixed"}
-
-
-def test_rows_carry_no_project_history():
- """Row ids and evidence name what was validated, not when or in which phase."""
- import re
-
- for row in ROWS:
- text = " ".join(str(v) for v in vars(row).values())
- assert not re.search(r"\bp\d+-|20\d\d-\d\d-\d\d|§|rerun after", text), row.row_id
diff --git a/training/rdsp/tests/unit/test_tp_input_grads.py b/training/rdsp/tests/unit/test_tp_input_grads.py
new file mode 100644
index 000000000..0b99fb63c
--- /dev/null
+++ b/training/rdsp/tests/unit/test_tp_input_grads.py
@@ -0,0 +1,267 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+
+"""Tensor-parallel layers that read the same input share one all-reduce of its gradient: two
+processes stand in for two tensor-parallel ranks, and DeepSpeed's own split layers (one
+all-reduce per input projection) are the reference."""
+
+import copy
+import os
+import tempfile
+
+import pytest
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+os.environ.setdefault("DS_ACCELERATOR", "cpu") # a Mac's GPU would otherwise get the weights
+pytest.importorskip("deepspeed")
+
+TP, HIDDEN, WIDE = 2, 16, 32
+
+
+class Attention(nn.Module):
+ """The projections of a Hugging Face attention layer, called the way it calls them."""
+
+ def __init__(self):
+ super().__init__()
+ self.q_proj = nn.Linear(HIDDEN, HIDDEN, bias=False)
+ self.k_proj = nn.Linear(HIDDEN, HIDDEN, bias=False)
+ self.v_proj = nn.Linear(HIDDEN, HIDDEN, bias=False)
+ self.o_proj = nn.Linear(HIDDEN, HIDDEN, bias=False)
+
+ def forward(self, hidden_states):
+ q, k, v = self.q_proj(hidden_states), self.k_proj(hidden_states), self.v_proj(hidden_states)
+ return self.o_proj(torch.sigmoid(q) * k + v)
+
+
+class MLP(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.gate_proj = nn.Linear(HIDDEN, WIDE, bias=False)
+ self.up_proj = nn.Linear(HIDDEN, WIDE, bias=False)
+ self.down_proj = nn.Linear(WIDE, HIDDEN, bias=False)
+
+ def forward(self, x):
+ return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
+
+
+class SecondInputMLP(MLP):
+ """up_proj reads something else than gate_proj: nothing may be shared between them."""
+
+ def forward(self, x):
+ return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(2 * x))
+
+
+class Block(nn.Module):
+ def __init__(self, mlp):
+ super().__init__()
+ self.self_attn, self.mlp = Attention(), mlp()
+
+ def forward(self, x):
+ x = x + self.self_attn(hidden_states=x)
+ return x + self.mlp(x)
+
+
+def _split(block, group):
+ from deepspeed.module_inject import layers
+
+ for module, rows, columns in (
+ (block.self_attn, ("q_proj", "k_proj", "v_proj"), ("o_proj",)),
+ (block.mlp, ("gate_proj", "up_proj"), ("down_proj",)),
+ ):
+ for name in rows:
+ setattr(module, name, layers.LinearLayer(getattr(module, name), group))
+ for name in columns:
+ setattr(module, name, layers.LinearAllreduce(getattr(module, name), group))
+ return block
+
+
+def _run(block, checkpoint, counter, steps=1):
+ x = torch.randn(2, 6, HIDDEN, generator=torch.Generator().manual_seed(1)).requires_grad_()
+ target = torch.randn(2, 6, HIDDEN, generator=torch.Generator().manual_seed(2))
+ for _ in range(steps):
+ if checkpoint:
+ out = torch.utils.checkpoint.checkpoint(block, x, use_reentrant=False)
+ else:
+ out = block(x)
+ counter[0] = 0
+ (out * target).sum().backward()
+ return {
+ "out": out.detach(),
+ "x": x.grad,
+ **{n: p.grad for n, p in block.named_parameters()},
+ }, counter[0]
+
+
+def _rank(rank, init_file, out_dir):
+ os.environ["DS_ACCELERATOR"] = "cpu"
+ import deepspeed.comm as ds_comm
+ import torch.distributed as dist
+ from deepspeed.module_inject import layers
+
+ from ray_deepspeed_pipeline.fused_grad_accumulation import (
+ GradAccumulation,
+ fuse_linear_grads,
+ )
+ from ray_deepspeed_pipeline.tp_input_grads import share_input_grad_reductions
+
+ os.environ.update(RANK=str(rank), LOCAL_RANK=str(rank), WORLD_SIZE=str(TP))
+ dist.init_process_group("gloo", init_method=f"file://{init_file}", rank=rank, world_size=TP)
+ ds_comm.init_distributed("gloo", auto_mpi_discovery=False)
+ layers.set_autotp_mode(training=True)
+ group, counter = dist.new_group(list(range(TP))), [0]
+ real = torch.distributed.all_reduce # DeepSpeed's own calls end there too
+
+ def counted(*args, **kwargs):
+ counter[0] += 1
+ return real(*args, **kwargs)
+
+ torch.distributed.all_reduce = counted
+ result = {}
+ for case, mlp in (("plain", MLP), ("other_input", SecondInputMLP)):
+ for checkpoint in (False, True):
+ torch.manual_seed(0)
+ base = Block(mlp)
+ theirs = _split(copy.deepcopy(base), group)
+ ours = _split(copy.deepcopy(base), group)
+ shared = share_input_grad_reductions(ours)
+ expected, n_expected = _run(theirs, checkpoint, counter, steps=2)
+ got, n_got = _run(ours, checkpoint, counter, steps=2)
+ result[case, checkpoint] = (shared, expected, n_expected, got, n_got)
+ for share in (True, False):
+ fused, state = _split(copy.deepcopy(base), group), GradAccumulation()
+ fused_names = fuse_linear_grads(fused, state)
+ if share:
+ share_input_grad_reductions(fused, state)
+ state.fuse = True # the second backward adds in place
+ got, _ = _run(fused, checkpoint, counter, steps=2)
+ result["fused", case, checkpoint, share] = (fused_names, expected, got)
+ older, state = _split(copy.deepcopy(base), group), GradAccumulation()
+ for m in older.modules(): # as DeepSpeed 0.19.3's layers: no such attributes
+ for name in ("gather_output", "defer_collectives_to_compiler"):
+ vars(m).pop(name, None)
+ fuse_linear_grads(older, state)
+ share_input_grad_reductions(older, state)
+ got, _ = _run(older, checkpoint, counter, steps=2)
+ result["older", case, checkpoint] = (expected, got)
+ torch.save(result, f"{out_dir}/{rank}.pt")
+ dist.destroy_process_group()
+
+
+@pytest.fixture(scope="module")
+def results():
+ with tempfile.TemporaryDirectory() as d:
+ torch.multiprocessing.spawn(_rank, args=(f"{d}/init", d), nprocs=TP)
+ return [torch.load(f"{d}/{r}.pt") for r in range(TP)]
+
+
+@pytest.mark.parametrize("checkpoint", [False, True])
+@pytest.mark.parametrize("case", ["plain", "other_input"])
+def test_every_gradient_matches_deepspeeds_own_layers(results, case, checkpoint):
+ for rank in results:
+ _, expected, _, got, _ = rank[case, checkpoint]
+ assert set(expected) == set(got)
+ for name in expected:
+ assert torch.allclose(expected[name], got[name], atol=1e-6), name
+
+
+@pytest.mark.parametrize("share", [True, False])
+@pytest.mark.parametrize("checkpoint", [False, True])
+@pytest.mark.parametrize("case", ["plain", "other_input"])
+def test_fused_gradient_accumulation_in_split_layers(results, case, checkpoint, share):
+ for rank in results:
+ names, expected, got = rank["fused", case, checkpoint, share]
+ assert len(names) == 7 # q, k, v, o, gate, up, down
+ for name in expected:
+ assert torch.allclose(expected[name], got[name], atol=1e-6), name
+
+
+@pytest.mark.parametrize("checkpoint", [False, True])
+@pytest.mark.parametrize("case", ["plain", "other_input"])
+def test_layers_of_an_older_deepspeed(results, case, checkpoint):
+ for rank in results:
+ expected, got = rank["older", case, checkpoint]
+ for name in expected:
+ assert torch.allclose(expected[name], got[name], atol=1e-6), name
+
+
+def test_the_projections_of_one_input_take_one_all_reduce(results):
+ for rank in results:
+ shared, _, before, _, after = rank["plain", False]
+ assert shared == ["self_attn", "mlp"]
+ assert (before, after) == (5, 2) # q, k, v, gate, up -> attention, mlp
+
+
+def test_a_layer_reading_another_tensor_keeps_its_own_all_reduce(results):
+ for rank in results:
+ _, _, before, _, after = rank["other_input", False]
+ # attention shares; up_proj reads 2 * x, so it keeps its own and gate_proj the mlp's
+ assert (before, after) == (5, 3)
+
+
+def test_nothing_to_share_without_tensor_parallel_layers():
+ from ray_deepspeed_pipeline.tp_input_grads import share_input_grad_reductions
+
+ assert share_input_grad_reductions(Block(MLP)) == []
+
+
+def _engine_rank(rank, init_file, out_dir):
+ """The stage adapter on a block with a tensor-parallel plan."""
+ os.environ["DS_ACCELERATOR"] = "cpu"
+ import deepspeed
+ import torch.distributed as dist
+
+ from ray_deepspeed_pipeline.deepspeed_adapter import DeepSpeedStageAdapter
+ from ray_deepspeed_pipeline.partition import attach_tp_plan
+
+ os.environ.update(RANK=str(rank), LOCAL_RANK=str(rank), WORLD_SIZE=str(TP))
+ dist.init_process_group("gloo", init_method=f"file://{init_file}", rank=rank, world_size=TP)
+ deepspeed.init_distributed("gloo", auto_mpi_discovery=False)
+ plan = {f"self_attn.{n}": "colwise" for n in ("q_proj", "k_proj", "v_proj")}
+ plan |= {"self_attn.o_proj": "rowwise", "mlp.down_proj": "rowwise"}
+ plan |= {f"mlp.{n}": "colwise" for n in ("gate_proj", "up_proj")}
+ calls = {}
+ for switch in ("1", "0"):
+ os.environ["RDSP_SHARE_TP_ALLREDUCE"] = switch
+ torch.manual_seed(0)
+ block = Block(MLP)
+ attach_tp_plan(block, plan)
+ adapter = DeepSpeedStageAdapter(
+ block,
+ {
+ "train_micro_batch_size_per_gpu": 2,
+ "gradient_accumulation_steps": 1,
+ "bf16": {"enabled": False},
+ "tensor_parallel": {"autotp_size": TP},
+ "optimizer": {
+ "type": "AdamW",
+ "params": {"lr": 1e-3, "torch_adam": True},
+ },
+ },
+ n_microbatches=1,
+ is_first=False,
+ is_last=False,
+ )
+ counter, real = [0], torch.distributed.all_reduce
+
+ def counted(*args, _c=counter, _r=real, **kwargs):
+ # the input gradients only: DeepSpeed reduces its parameters' gradients too
+ tensor = args[0] if args else kwargs["tensor"]
+ _c[0] += tensor.shape == (2, 6, HIDDEN)
+ return _r(*args, **kwargs)
+
+ out = adapter.forward(0, torch.randn(2, 6, HIDDEN))
+ torch.distributed.all_reduce = counted
+ adapter.backward(0, grad=torch.ones_like(out))
+ torch.distributed.all_reduce = real
+ calls[switch] = counter[0]
+ torch.save(calls, f"{out_dir}/{rank}.pt")
+ dist.destroy_process_group()
+
+
+def test_the_stage_engine_shares_unless_switched_off():
+ with tempfile.TemporaryDirectory() as d:
+ torch.multiprocessing.spawn(_engine_rank, args=(f"{d}/init", d), nprocs=TP)
+ for r in range(TP):
+ assert torch.load(f"{d}/{r}.pt") == {"1": 2, "0": 5}
diff --git a/training/rdsp/tests/unit/test_train_vl.py b/training/rdsp/tests/unit/test_train_vl.py
new file mode 100644
index 000000000..a72c18e78
--- /dev/null
+++ b/training/rdsp/tests/unit/test_train_vl.py
@@ -0,0 +1,378 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+
+"""train_vl.py: --cuts, the optimizer flags, --moe-experts hf and the worker environment."""
+
+import os
+import sys
+
+import pytest
+import torch
+from torch import nn
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, os.path.join(HERE, "..", ".."))
+
+import ray_deepspeed_pipeline as rdsp # noqa: E402
+import train_vl # noqa: E402
+
+# train_vl.py --cuts: each spelling maps to one partition policy.
+
+
+def test_balanced_measures_the_vision_ratio_from_the_first_step():
+ policy = train_vl.partition_policy("balanced", ratio=lambda: 2.5)
+ assert policy == rdsp.BalancedTransformerBlocks(vision_token_ratio=2.5)
+
+
+@pytest.mark.parametrize("cuts", ["0,balanced", "0,measured"])
+def test_zero_then_balanced_gives_the_encoder_its_own_stage(cuts):
+ # 0,measured calibrates with this cut, then re-cuts the decoder stages
+ policy = train_vl.partition_policy(cuts, ratio=lambda: 1 / 0)
+ assert policy == rdsp.BalancedTransformerBlocks(vision_stage=True)
+
+
+@pytest.mark.parametrize(
+ "cuts,policy",
+ [
+ ("even", rdsp.UniformTransformerBlocks()),
+ ("0,16", rdsp.ExplicitCuts((0, 16))),
+ ("13", rdsp.ExplicitCuts((13,))),
+ ],
+)
+def test_even_and_explicit_cuts(cuts, policy):
+ assert train_vl.partition_policy(cuts, ratio=lambda: 1 / 0) == policy
+
+
+def test_measured_calibrates_with_the_balanced_cut():
+ policy = train_vl.partition_policy("measured", ratio=lambda: 2.5)
+ assert policy == rdsp.BalancedTransformerBlocks(vision_token_ratio=2.5)
+
+
+def test_calibration_measures_at_learning_rate_zero_and_shuts_down():
+ """calibrated_policy: profiled steps on the run's own first batches, the
+ engine shut down after, the estimate re-cut by what it measured."""
+ args = train_vl.build_parser().parse_args(
+ [
+ "--cuts",
+ "measured",
+ "--calibration-steps",
+ "3",
+ "--microbatches",
+ "2",
+ "--drop-padding-mask",
+ ]
+ )
+ assert train_vl.ds_config(args, lr=0.0)["optimizer"]["params"]["lr"] == 0.0
+ assert train_vl.ds_config(args)["optimizer"]["params"]["lr"] == args.lr
+
+ measured = rdsp.MeasuredStages(
+ cuts=(3,), seconds=(2.0, 1.0), peak_gib=(1, 1), bytes_per_param=(1, 1), limit_gib=70
+ )
+
+ class Engine:
+ shut = False
+
+ def measure_stages(self, data_iter, steps, skip):
+ self.read = list(data_iter)
+ return measured
+
+ def shutdown(self):
+ self.shut = True
+
+ import torch
+
+ data = iter(
+ [
+ ({"input_ids": torch.ones(1, 4), "attention_mask": torch.ones(1, 4)}, i)
+ for i in range(100)
+ ]
+ )
+ engine = Engine()
+ estimate = rdsp.BalancedTransformerBlocks(vision_token_ratio=2.5)
+ policy = train_vl.calibrated_policy(args, engine, data, estimate)
+ assert policy == rdsp.BalancedTransformerBlocks(vision_token_ratio=2.5, measured=measured)
+ assert engine.shut
+ assert [y for _, y in engine.read] == list(range(8)) # 3 steps and one read ahead
+ assert all("attention_mask" not in x for x, _ in engine.read)
+
+
+@pytest.mark.parametrize("flags", [["--calibration-steps", "1"], ["--optimizer-group-numel", "-5"]])
+def test_out_of_range_numbers_are_refused_when_parsed(flags, capsys):
+ # one calibration step leaves none to measure (the first is not counted)
+ with pytest.raises(SystemExit):
+ train_vl.build_parser().parse_args(flags)
+ assert flags[0] in capsys.readouterr().err
+
+
+# train_vl.py optimizer flags. --master-dtype bf16 sets DeepSpeed's two
+# low-precision state keys and is refused wherever DeepSpeed would ignore them;
+# --master-dtype remainder asks the stage adapter for RemainderAdamW under the
+# same conditions; --fused-adam asks PyTorch's AdamW for its fused kernel.
+
+
+STAGES = ["--stages", "2", "--stage", "0:gpus=4,tp=4,zero=1", "--stage", "1:gpus=4,tp=4,zero=1"]
+
+
+def parse(*flags):
+ return train_vl.build_parser().parse_args([*STAGES, *flags])
+
+
+def test_fp32_is_the_default_and_adds_nothing():
+ args = parse()
+ assert args.master_dtype == "fp32"
+ bf16 = train_vl.ds_config(args)["bf16"]
+ assert "bf16_master_weights_and_grads" not in bf16 and "bf16_optimizer_states" not in bf16
+ assert train_vl.optimizer_problem(args) is None
+
+
+def test_bf16_sets_both_keys_and_leaves_grads_bf16():
+ args = parse("--master-dtype", "bf16", "--grad-dtype", "bf16")
+ conf = train_vl.ds_config(args)
+ assert conf["bf16"]["bf16_master_weights_and_grads"] is True
+ assert conf["bf16"]["bf16_optimizer_states"] is True
+ assert "data_types" not in conf # gradients accumulate in the model's bf16
+ assert train_vl.optimizer_problem(args) is None
+
+
+def test_remainder_asks_the_adapter_and_leaves_deepspeed_s_keys_alone():
+ args = parse("--master-dtype", "remainder", "--grad-dtype", "bf16")
+ conf = train_vl.ds_config(args)
+ assert conf["rdsp_master_weights"] == "remainder"
+ assert "bf16_master_weights_and_grads" not in conf["bf16"]
+ assert "data_types" not in conf
+ assert train_vl.optimizer_problem(args) is None
+ assert "rdsp_master_weights" not in train_vl.ds_config(parse())
+
+
+@pytest.mark.parametrize(
+ "master,flags,needs",
+ [
+ ("bf16", [], "--grad-dtype bf16"),
+ ("remainder", [], "--grad-dtype bf16"),
+ ("bf16", ["--grad-dtype", "bf16", "--colocated-vision"], "replicated"),
+ ],
+)
+def test_low_precision_masters_refused_where_deepspeed_would_keep_fp32(master, flags, needs):
+ problem = train_vl.optimizer_problem(parse("--master-dtype", master, *flags))
+ assert needs in problem and f"--master-dtype {master}" in problem
+
+
+def test_remainder_master_works_with_colocated_vision():
+ """The replicated encoder keeps fp32 master weights; the remainder master is as exact as
+ fp32 (bf16 weight + 16-bit remainder), so the model trains as one fp32-master model."""
+ args = parse("--master-dtype", "remainder", "--grad-dtype", "bf16", "--colocated-vision")
+ assert train_vl.optimizer_problem(args) is None
+
+
+@pytest.mark.parametrize("master", ["bf16", "remainder"])
+@pytest.mark.parametrize(
+ "stage,needs",
+ [
+ ("1:gpus=4,tp=4,zero=0", "stage 1 has 0"),
+ ("1:gpus=4,tp=4", "stage 1 has 0"), # inherits --zero's default 0
+ ("1:gpus=4,tp=4,zero=1,offload=1", "offload"),
+ ],
+)
+def test_low_precision_masters_need_zero_1_or_2_without_offload_on_every_stage(
+ master, stage, needs
+):
+ args = train_vl.build_parser().parse_args(
+ [
+ "--stages",
+ "2",
+ "--stage",
+ "0:gpus=4,tp=4,zero=1",
+ "--stage",
+ stage,
+ "--master-dtype",
+ master,
+ "--grad-dtype",
+ "bf16",
+ ]
+ )
+ assert needs in train_vl.optimizer_problem(args)
+
+
+def test_main_exits_before_loading_anything():
+ with pytest.raises(SystemExit):
+ train_vl.main([*STAGES, "--master-dtype", "bf16"])
+
+
+def test_fused_adam_is_off_by_default_and_passed_to_torch_adamw_when_asked():
+ assert "fused" not in train_vl.ds_config(parse())["optimizer"]["params"]
+ params = train_vl.ds_config(parse("--fused-adam"))["optimizer"]["params"]
+ assert params["fused"] is True and params["torch_adam"] is True
+ assert train_vl.optimizer_problem(parse("--fused-adam")) is None
+ assert train_vl.optimizer_problem(parse("--fused-adam", "--grad-dtype", "bf16")) is None
+
+
+def test_fused_adam_refused_under_offload():
+ args = train_vl.build_parser().parse_args(
+ [
+ "--stages",
+ "2",
+ "--stage",
+ "0:gpus=4,tp=4,zero=1",
+ "--stage",
+ "1:gpus=4,tp=4,zero=1,offload=1",
+ "--fused-adam",
+ ]
+ )
+ assert "stage 1 offloads" in train_vl.optimizer_problem(args)
+
+
+def test_stage_key_recompute_blocks():
+ (stage,) = parse().stage[:1]
+ assert stage.recompute_blocks is None
+ args = train_vl.build_parser().parse_args(
+ ["--stages", "1", "--stage", "0:gpus=8,tp=2,recompute_blocks=24"]
+ )
+ assert args.stage[0].recompute_blocks == 24 and not args.stage[0].recompute
+
+
+# --moe-experts hf: Liger binds its fused-experts forward onto each routed-experts module
+# instance (as liger_kernel's _bind_method_to_module does); restore_hf_experts removes that
+# binding so the class's own forward runs again, and leaves every other patch alone.
+
+
+class Experts(nn.Module):
+ def forward(self, x):
+ return x + 1
+
+
+class Block(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.experts, self.shared = Experts(), Experts()
+
+
+def bind(module, name, fn): # liger_kernel.transformers.monkey_patch._bind_method_to_module
+ module.__dict__[name] = fn.__get__(module, module.__class__)
+
+
+def test_only_the_routed_experts_get_their_own_forward_back():
+ model = nn.Sequential(Block(), Block())
+ for block in model:
+ bind(block.experts, "forward", lambda self, x: x * 100)
+ bind(block.experts, "_get_name", lambda self: "LigerExperts")
+ bind(block.shared, "forward", lambda self, x: x * 7) # a SwiGLU patch: kept
+ bind(block.shared, "_get_name", lambda self: "LigerQwen3MoeSwiGLUMLP")
+ assert train_vl.restore_hf_experts(model) == 2
+ x = torch.ones(2)
+ for block in model:
+ assert torch.equal(block.experts(x), x + 1)
+ assert torch.equal(block.shared(x), x * 7)
+ assert train_vl.restore_hf_experts(model) == 0
+
+
+def test_flag_defaults_to_liger():
+ args = train_vl.build_parser().parse_args([])
+ assert args.moe_experts == "liger"
+ assert train_vl.build_parser().parse_args(["--moe-experts", "hf"]).moe_experts == "hf"
+
+
+def test_hf_experts_without_liger_is_refused():
+ # without --liger nothing installs Liger's expert kernel: "hf" would silently do nothing
+ parse = train_vl.build_parser().parse_args
+ assert "--liger" in train_vl.experts_problem(parse(["--moe-experts", "hf"]))
+ assert train_vl.experts_problem(parse(["--moe-experts", "hf", "--liger"])) is None
+ assert train_vl.experts_problem(parse([])) is None
+
+
+def test_main_exits_on_hf_experts_without_liger(capsys):
+ with pytest.raises(SystemExit):
+ train_vl.main(["--moe-experts", "hf"])
+ assert "--moe-experts hf" in capsys.readouterr().err
+
+
+# train_vl.worker_env: the driver's settings Ray gives every worker of the job, so actors
+# on a cluster started apart from the driver (`ray start` on each of two nodes) see them.
+
+
+def test_passes_what_actors_read_and_nothing_else():
+ env = {
+ "RDSP_PROFILE": "1",
+ "RDSP_P2P_TIMEOUT_S": "600",
+ "NCCL_SOCKET_IFNAME": "^lo,docker",
+ "FI_PROVIDER": "efa",
+ "HF_HOME": "/home/ubuntu/hf",
+ "PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True",
+ "DS_BUILD_OPS": "0",
+ "CUDA_HOME": "/usr/local/cuda-13.0",
+ "LD_LIBRARY_PATH": "/opt/amazon/ofi-nccl/lib",
+ "CUDA_VISIBLE_DEVICES": "0,1",
+ "HOME": "/home/ubuntu",
+ "PATH": "/usr/bin",
+ "RAY_ADDRESS": "auto",
+ }
+ got = train_vl.worker_env(env)
+ assert got == {
+ k: env[k]
+ for k in (
+ "RDSP_PROFILE",
+ "RDSP_P2P_TIMEOUT_S",
+ "NCCL_SOCKET_IFNAME",
+ "FI_PROVIDER",
+ "HF_HOME",
+ "PYTORCH_CUDA_ALLOC_CONF",
+ "DS_BUILD_OPS",
+ "CUDA_HOME",
+ "LD_LIBRARY_PATH",
+ )
+ }
+
+
+def test_credentials_stay_on_the_driver():
+ # Ray stores a job's runtime_env with the job, where others can read it
+ env = {
+ "HF_TOKEN": "hf_x",
+ "HF_HUB_TOKEN": "hf_y",
+ "HUGGING_FACE_HUB_TOKEN": "hf_z",
+ "RDSP_API_KEY": "k",
+ "TORCH_SECRET": "s",
+ "HF_HOME": "/hf",
+ "HF_HUB_OFFLINE": "1",
+ }
+ assert train_vl.worker_env(env) == {"HF_HOME": "/hf", "HF_HUB_OFFLINE": "1"}
+
+
+def test_ray_gets_an_nsight_config_only_when_asked():
+ environ = {"HF_HOME": "/x", "RDSP_NSIGHT": '{"t": "cuda,nvtx", "c": "cudaProfilerApi"}'}
+ env = train_vl.ray_runtime_env(environ)
+ assert env["_nsight"] == {"t": "cuda,nvtx", "c": "cudaProfilerApi"}
+ assert env["env_vars"] == train_vl.worker_env(environ)
+ assert "_nsight" not in train_vl.ray_runtime_env({"HF_HOME": "/x"})
+
+
+# --cuts auto: equal stages timed first, then the vision encoder on a stage sized by the times
+
+
+def test_auto_gives_the_vision_encoder_a_stage_sized_by_the_times():
+ from ray_deepspeed_pipeline.config import MeasuredStages
+
+ stages = [f"{s}:gpus=2,tp=1,zero=1,recompute=1" for s in range(8)]
+ args = train_vl.build_parser().parse_args(
+ ["--stages", "8", "--cuts", "auto", "--rows", "2", "--microbatches", "64"]
+ + [w for s in stages for w in ("--stage", s)]
+ )
+ ones = (1,) * 8
+ # stage 0: 3 decoder blocks at 1 s each, plus 13 s of vision encoder
+ equal = MeasuredStages((3, 9, 15, 21, 27, 33, 38), (16, 6, 6, 6, 6, 6, 5.5, 3), ones, ones, 70)
+ vision = MeasuredStages((0, 7, 14, 21, 28, 35), (7,) * 7, ones[:7], ones[:7], 70)
+ timings = [equal, vision]
+
+ class Engine:
+ stage_blocks = [(0, 3), (3, 9), (9, 15), (15, 21), (21, 27), (27, 33), (33, 38), (38, 40)]
+
+ def measure_stages(self, data, steps, skip):
+ return timings.pop(0)
+
+ def shutdown(self):
+ pass
+
+ policy = train_vl.auto_policy(
+ args, lambda partition, conf: Engine(), rdsp.BalancedTransformerBlocks(), lambda: iter([])
+ )
+ assert [s.num_gpus for s in args.stage] == [4] + [2] * 6 # the published 35B layout
+ assert (args.stages, args.rows, args.microbatches) == (7, 4, 32)
+ assert policy.vision_stage and policy.measured is vision
diff --git a/training/rdsp/tests/unit/test_train_vl_cuts.py b/training/rdsp/tests/unit/test_train_vl_cuts.py
deleted file mode 100644
index 35cdbb60f..000000000
--- a/training/rdsp/tests/unit/test_train_vl_cuts.py
+++ /dev/null
@@ -1,100 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-
-"""train_vl.py --cuts: each spelling maps to one partition policy."""
-
-import os
-import sys
-
-import pytest
-
-HERE = os.path.dirname(os.path.abspath(__file__))
-sys.path.insert(0, os.path.join(HERE, "..", ".."))
-
-import ray_deepspeed_pipeline as rdsp # noqa: E402
-import train_vl # noqa: E402
-
-
-def test_balanced_measures_the_vision_ratio_from_the_first_step():
- policy = train_vl.partition_policy("balanced", ratio=lambda: 2.5)
- assert policy == rdsp.BalancedTransformerBlocks(vision_token_ratio=2.5)
-
-
-@pytest.mark.parametrize("cuts", ["0,balanced", "0,measured"])
-def test_zero_then_balanced_gives_the_encoder_its_own_stage(cuts):
- # 0,measured calibrates with this cut, then re-cuts the decoder stages
- policy = train_vl.partition_policy(cuts, ratio=lambda: 1 / 0)
- assert policy == rdsp.BalancedTransformerBlocks(vision_stage=True)
-
-
-@pytest.mark.parametrize(
- "cuts,policy",
- [
- ("even", rdsp.UniformTransformerBlocks()),
- ("0,16", rdsp.ExplicitCuts((0, 16))),
- ("13", rdsp.ExplicitCuts((13,))),
- ],
-)
-def test_even_and_explicit_cuts(cuts, policy):
- assert train_vl.partition_policy(cuts, ratio=lambda: 1 / 0) == policy
-
-
-def test_measured_calibrates_with_the_balanced_cut():
- policy = train_vl.partition_policy("measured", ratio=lambda: 2.5)
- assert policy == rdsp.BalancedTransformerBlocks(vision_token_ratio=2.5)
-
-
-def test_calibration_measures_at_learning_rate_zero_and_shuts_down():
- """calibrated_policy: profiled steps on the run's own first batches, the
- engine shut down after, the estimate re-cut by what it measured."""
- args = train_vl.build_parser().parse_args(
- [
- "--cuts",
- "measured",
- "--calibration-steps",
- "3",
- "--microbatches",
- "2",
- "--drop-padding-mask",
- ]
- )
- assert train_vl.ds_config(args, lr=0.0)["optimizer"]["params"]["lr"] == 0.0
- assert train_vl.ds_config(args)["optimizer"]["params"]["lr"] == args.lr
-
- measured = rdsp.MeasuredStages(
- cuts=(3,), seconds=(2.0, 1.0), peak_gib=(1, 1), bytes_per_param=(1, 1), limit_gib=70
- )
-
- class Engine:
- shut = False
-
- def measure_stages(self, data_iter, steps, skip):
- self.read = list(data_iter)
- return measured
-
- def shutdown(self):
- self.shut = True
-
- import torch
-
- data = iter(
- [
- ({"input_ids": torch.ones(1, 4), "attention_mask": torch.ones(1, 4)}, i)
- for i in range(100)
- ]
- )
- engine = Engine()
- estimate = rdsp.BalancedTransformerBlocks(vision_token_ratio=2.5)
- policy = train_vl.calibrated_policy(args, engine, data, estimate)
- assert policy == rdsp.BalancedTransformerBlocks(vision_token_ratio=2.5, measured=measured)
- assert engine.shut
- assert [y for _, y in engine.read] == list(range(8)) # 3 steps and one read ahead
- assert all("attention_mask" not in x for x, _ in engine.read)
-
-
-@pytest.mark.parametrize("flags", [["--calibration-steps", "1"], ["--optimizer-group-numel", "-5"]])
-def test_out_of_range_numbers_are_refused_when_parsed(flags, capsys):
- # one calibration step leaves none to measure (the first is not counted)
- with pytest.raises(SystemExit):
- train_vl.build_parser().parse_args(flags)
- assert flags[0] in capsys.readouterr().err
diff --git a/training/rdsp/tests/unit/test_train_vl_moe_experts.py b/training/rdsp/tests/unit/test_train_vl_moe_experts.py
deleted file mode 100644
index c5e43e054..000000000
--- a/training/rdsp/tests/unit/test_train_vl_moe_experts.py
+++ /dev/null
@@ -1,68 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-
-"""--moe-experts hf: Liger binds its fused-experts forward onto each routed-experts module
-instance (as liger_kernel's _bind_method_to_module does); restore_hf_experts removes that
-binding so the class's own forward runs again, and leaves every other patch alone."""
-
-import os
-import sys
-
-import pytest
-import torch
-from torch import nn
-
-HERE = os.path.dirname(os.path.abspath(__file__))
-sys.path.insert(0, os.path.join(HERE, "..", ".."))
-
-import train_vl # noqa: E402
-
-
-class Experts(nn.Module):
- def forward(self, x):
- return x + 1
-
-
-class Block(nn.Module):
- def __init__(self):
- super().__init__()
- self.experts, self.shared = Experts(), Experts()
-
-
-def bind(module, name, fn): # liger_kernel.transformers.monkey_patch._bind_method_to_module
- module.__dict__[name] = fn.__get__(module, module.__class__)
-
-
-def test_only_the_routed_experts_get_their_own_forward_back():
- model = nn.Sequential(Block(), Block())
- for block in model:
- bind(block.experts, "forward", lambda self, x: x * 100)
- bind(block.experts, "_get_name", lambda self: "LigerExperts")
- bind(block.shared, "forward", lambda self, x: x * 7) # a SwiGLU patch: kept
- bind(block.shared, "_get_name", lambda self: "LigerQwen3MoeSwiGLUMLP")
- assert train_vl.restore_hf_experts(model) == 2
- x = torch.ones(2)
- for block in model:
- assert torch.equal(block.experts(x), x + 1)
- assert torch.equal(block.shared(x), x * 7)
- assert train_vl.restore_hf_experts(model) == 0
-
-
-def test_flag_defaults_to_liger():
- args = train_vl.build_parser().parse_args([])
- assert args.moe_experts == "liger"
- assert train_vl.build_parser().parse_args(["--moe-experts", "hf"]).moe_experts == "hf"
-
-
-def test_hf_experts_without_liger_is_refused():
- # without --liger nothing installs Liger's expert kernel: "hf" would silently do nothing
- parse = train_vl.build_parser().parse_args
- assert "--liger" in train_vl.experts_problem(parse(["--moe-experts", "hf"]))
- assert train_vl.experts_problem(parse(["--moe-experts", "hf", "--liger"])) is None
- assert train_vl.experts_problem(parse([])) is None
-
-
-def test_main_exits_on_hf_experts_without_liger(capsys):
- with pytest.raises(SystemExit):
- train_vl.main(["--moe-experts", "hf"])
- assert "--moe-experts hf" in capsys.readouterr().err
diff --git a/training/rdsp/tests/unit/test_train_vl_optimizer_flags.py b/training/rdsp/tests/unit/test_train_vl_optimizer_flags.py
deleted file mode 100644
index 1ede09fd5..000000000
--- a/training/rdsp/tests/unit/test_train_vl_optimizer_flags.py
+++ /dev/null
@@ -1,129 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-
-"""train_vl.py optimizer flags. --master-dtype bf16 sets DeepSpeed's two
-low-precision state keys and is refused wherever DeepSpeed would ignore them;
---master-dtype remainder asks the stage adapter for RemainderAdamW under the
-same conditions; --fused-adam asks PyTorch's AdamW for its fused kernel."""
-
-import os
-import sys
-
-import pytest
-
-HERE = os.path.dirname(os.path.abspath(__file__))
-sys.path.insert(0, os.path.join(HERE, "..", ".."))
-
-import train_vl # noqa: E402
-
-STAGES = ["--stages", "2", "--stage", "0:gpus=4,tp=4,zero=1", "--stage", "1:gpus=4,tp=4,zero=1"]
-
-
-def parse(*flags):
- return train_vl.build_parser().parse_args([*STAGES, *flags])
-
-
-def test_fp32_is_the_default_and_adds_nothing():
- args = parse()
- assert args.master_dtype == "fp32"
- bf16 = train_vl.ds_config(args)["bf16"]
- assert "bf16_master_weights_and_grads" not in bf16 and "bf16_optimizer_states" not in bf16
- assert train_vl.optimizer_problem(args) is None
-
-
-def test_bf16_sets_both_keys_and_leaves_grads_bf16():
- args = parse("--master-dtype", "bf16", "--grad-dtype", "bf16")
- conf = train_vl.ds_config(args)
- assert conf["bf16"]["bf16_master_weights_and_grads"] is True
- assert conf["bf16"]["bf16_optimizer_states"] is True
- assert "data_types" not in conf # gradients accumulate in the model's bf16
- assert train_vl.optimizer_problem(args) is None
-
-
-def test_remainder_asks_the_adapter_and_leaves_deepspeed_s_keys_alone():
- args = parse("--master-dtype", "remainder", "--grad-dtype", "bf16")
- conf = train_vl.ds_config(args)
- assert conf["rdsp_master_weights"] == "remainder"
- assert "bf16_master_weights_and_grads" not in conf["bf16"]
- assert "data_types" not in conf
- assert train_vl.optimizer_problem(args) is None
- assert "rdsp_master_weights" not in train_vl.ds_config(parse())
-
-
-@pytest.mark.parametrize("master", ["bf16", "remainder"])
-@pytest.mark.parametrize(
- "flags,needs",
- [
- ([], "--grad-dtype bf16"),
- (["--grad-dtype", "bf16", "--colocated-vision"], "replicated"),
- ],
-)
-def test_low_precision_masters_refused_where_deepspeed_would_keep_fp32(master, flags, needs):
- problem = train_vl.optimizer_problem(parse("--master-dtype", master, *flags))
- assert needs in problem and f"--master-dtype {master}" in problem
-
-
-@pytest.mark.parametrize("master", ["bf16", "remainder"])
-@pytest.mark.parametrize(
- "stage,needs",
- [
- ("1:gpus=4,tp=4,zero=0", "stage 1 has 0"),
- ("1:gpus=4,tp=4", "stage 1 has 0"), # inherits --zero's default 0
- ("1:gpus=4,tp=4,zero=1,offload=1", "offload"),
- ],
-)
-def test_low_precision_masters_need_zero_1_or_2_without_offload_on_every_stage(
- master, stage, needs
-):
- args = train_vl.build_parser().parse_args(
- [
- "--stages",
- "2",
- "--stage",
- "0:gpus=4,tp=4,zero=1",
- "--stage",
- stage,
- "--master-dtype",
- master,
- "--grad-dtype",
- "bf16",
- ]
- )
- assert needs in train_vl.optimizer_problem(args)
-
-
-def test_main_exits_before_loading_anything():
- with pytest.raises(SystemExit):
- train_vl.main([*STAGES, "--master-dtype", "bf16"])
-
-
-def test_fused_adam_is_off_by_default_and_passed_to_torch_adamw_when_asked():
- assert "fused" not in train_vl.ds_config(parse())["optimizer"]["params"]
- params = train_vl.ds_config(parse("--fused-adam"))["optimizer"]["params"]
- assert params["fused"] is True and params["torch_adam"] is True
- assert train_vl.optimizer_problem(parse("--fused-adam")) is None
- assert train_vl.optimizer_problem(parse("--fused-adam", "--grad-dtype", "bf16")) is None
-
-
-def test_fused_adam_refused_under_offload():
- args = train_vl.build_parser().parse_args(
- [
- "--stages",
- "2",
- "--stage",
- "0:gpus=4,tp=4,zero=1",
- "--stage",
- "1:gpus=4,tp=4,zero=1,offload=1",
- "--fused-adam",
- ]
- )
- assert "stage 1 offloads" in train_vl.optimizer_problem(args)
-
-
-def test_stage_key_recompute_blocks():
- (stage,) = parse().stage[:1]
- assert stage.recompute_blocks is None
- args = train_vl.build_parser().parse_args(
- ["--stages", "1", "--stage", "0:gpus=8,tp=2,recompute_blocks=24"]
- )
- assert args.stage[0].recompute_blocks == 24 and not args.stage[0].recompute
diff --git a/training/rdsp/tests/unit/test_train_vl_worker_env.py b/training/rdsp/tests/unit/test_train_vl_worker_env.py
deleted file mode 100644
index 5246bdaa4..000000000
--- a/training/rdsp/tests/unit/test_train_vl_worker_env.py
+++ /dev/null
@@ -1,60 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-# DeepSpeed Team
-
-"""train_vl.worker_env: the driver's settings Ray gives every worker of the job, so actors
-on a cluster started apart from the driver (`ray start` on each of two nodes) see them."""
-
-import os
-import sys
-
-HERE = os.path.dirname(os.path.abspath(__file__))
-sys.path.insert(0, os.path.join(HERE, "..", ".."))
-
-import train_vl # noqa: E402
-
-
-def test_passes_what_actors_read_and_nothing_else():
- env = {
- "RDSP_PROFILE": "1",
- "RDSP_P2P_TIMEOUT_S": "600",
- "NCCL_SOCKET_IFNAME": "^lo,docker",
- "FI_PROVIDER": "efa",
- "HF_HOME": "/home/ubuntu/hf",
- "PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True",
- "DS_BUILD_OPS": "0",
- "CUDA_HOME": "/usr/local/cuda-13.0",
- "LD_LIBRARY_PATH": "/opt/amazon/ofi-nccl/lib",
- "CUDA_VISIBLE_DEVICES": "0,1",
- "HOME": "/home/ubuntu",
- "PATH": "/usr/bin",
- "RAY_ADDRESS": "auto",
- }
- got = train_vl.worker_env(env)
- assert got == {
- k: env[k]
- for k in (
- "RDSP_PROFILE",
- "RDSP_P2P_TIMEOUT_S",
- "NCCL_SOCKET_IFNAME",
- "FI_PROVIDER",
- "HF_HOME",
- "PYTORCH_CUDA_ALLOC_CONF",
- "DS_BUILD_OPS",
- "CUDA_HOME",
- "LD_LIBRARY_PATH",
- )
- }
-
-
-def test_credentials_stay_on_the_driver():
- # Ray stores a job's runtime_env with the job, where others can read it
- env = {
- "HF_TOKEN": "hf_x",
- "HF_HUB_TOKEN": "hf_y",
- "HUGGING_FACE_HUB_TOKEN": "hf_z",
- "RDSP_API_KEY": "k",
- "TORCH_SECRET": "s",
- "HF_HOME": "/hf",
- "HF_HUB_OFFLINE": "1",
- }
- assert train_vl.worker_env(env) == {"HF_HOME": "/hf", "HF_HUB_OFFLINE": "1"}
diff --git a/training/rdsp/tests/unit/test_unused_grad_norm.py b/training/rdsp/tests/unit/test_unused_grad_norm.py
new file mode 100644
index 000000000..072bacef1
--- /dev/null
+++ b/training/rdsp/tests/unit/test_unused_grad_norm.py
@@ -0,0 +1,76 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+
+"""The ZeRO step without its unused gradient norm: the same weights, no norm computed. CPU, one
+rank, gloo; needs DeepSpeed."""
+
+import os
+
+import pytest
+import torch
+
+os.environ.setdefault("DS_ACCELERATOR", "cpu") # not the Mac's MPS
+deepspeed = pytest.importorskip("deepspeed")
+
+from ray_deepspeed_pipeline.deepspeed_adapter import ( # noqa: E402
+ _deepspeed_engine_factory,
+ _without_unused_grad_norm,
+)
+
+
+@pytest.fixture(scope="module", autouse=True)
+def gloo():
+ if deepspeed.accelerator.get_accelerator().device_name() != "cpu":
+ pytest.skip("DeepSpeed was already loaded on another accelerator (a Mac's GPU)")
+ os.environ.update(
+ MASTER_ADDR="127.0.0.1", MASTER_PORT="29553", RANK="0", WORLD_SIZE="1", LOCAL_RANK="0"
+ )
+ deepspeed.init_distributed(dist_backend="gloo")
+
+
+def _engine(clip=0.0, dtype="bf16"):
+ torch.manual_seed(0)
+ model = torch.nn.Sequential(torch.nn.Linear(8, 8), torch.nn.Linear(8, 4)).to(torch.bfloat16)
+ return _deepspeed_engine_factory(
+ model,
+ {
+ "train_micro_batch_size_per_gpu": 1,
+ "bf16": {"enabled": True},
+ "zero_optimization": {"stage": 1},
+ "gradient_clipping": clip,
+ "optimizer": {"type": "AdamW", "params": {"lr": 1e-2, "torch_adam": True}},
+ },
+ )
+
+
+def _train(engine, skip):
+ if skip:
+ _without_unused_grad_norm(engine.optimizer)
+ g = torch.Generator().manual_seed(1)
+ for _ in range(3):
+ out = engine(torch.randn(2, 8, generator=g, dtype=torch.bfloat16))
+ engine.backward(out.float().square().sum())
+ engine.step()
+ return [p.detach().float().clone() for p in engine.module.parameters()]
+
+
+def test_the_weights_are_the_same():
+ want, got = _train(_engine(), skip=False), _train(_engine(), skip=True)
+ assert all(torch.equal(a, b) for a, b in zip(want, got, strict=True))
+
+
+def test_clipping_keeps_the_norm():
+ engine = _engine(clip=1.0)
+ _without_unused_grad_norm(engine.optimizer)
+ assert "scaled_global_norm" not in vars(engine.optimizer)
+
+
+def test_without_clipping_it_is_skipped():
+ engine = _engine()
+ _without_unused_grad_norm(engine.optimizer)
+ assert float(engine.optimizer.scaled_global_norm()) == 0.0
+
+
+def test_another_optimizer_is_left_alone():
+ _without_unused_grad_norm(torch.optim.SGD([torch.nn.Parameter(torch.ones(1))], lr=0.1))
+ _without_unused_grad_norm(None)
diff --git a/training/rdsp/tests/unit/test_varlen_attention.py b/training/rdsp/tests/unit/test_varlen_attention.py
index a54c33cde..315db146c 100644
--- a/training/rdsp/tests/unit/test_varlen_attention.py
+++ b/training/rdsp/tests/unit/test_varlen_attention.py
@@ -21,7 +21,9 @@
from ray_deepspeed_pipeline import varlen_attention # noqa: E402
from ray_deepspeed_pipeline.varlen_attention import ( # noqa: E402
NAME,
+ PACKED,
register_if_used,
+ use_packed_vision_attention,
use_varlen_vision_attention,
)
@@ -116,6 +118,76 @@ def count(depth, varlen):
assert count(6, varlen=True) == count(2, varlen=True) <= 3
+# --vision-attn packed: SDPA itself, without the per-layer host reads
+
+
+@pytest.mark.parametrize("which", [slice(None), slice(0, 1)], ids=["three images", "one image"])
+def test_packed_sdpa_gives_the_same_features_and_gradients(which):
+ grid = images()[1][which]
+ pixels = images()[0][: int(grid.prod(-1).sum())]
+
+ def run_on(m):
+ out = m.visual(pixels, grid_thw=grid).pooler_output
+ out.square().sum().backward()
+ return out.detach(), [p.grad.clone() for p in m.visual.parameters()]
+
+ sdpa = model()
+ packed = copy.deepcopy(sdpa)
+ use_packed_vision_attention(packed)
+ assert {c._attn_implementation for c in varlen_attention._configs(packed)} == {PACKED}
+ (a, ga), (b, gb) = run_on(sdpa), run_on(packed)
+ assert torch.equal(a, b)
+ for x, y in zip(ga, gb):
+ assert torch.equal(x, y)
+
+
+@pytest.mark.parametrize("which", [slice(None), slice(0, 1)], ids=["three images", "one image"])
+def test_packed_sdpa_host_reads_do_not_grow_with_depth(which, monkeypatch):
+ reads = []
+ for name in ("item", "tolist"):
+ real = getattr(torch.Tensor, name)
+ monkeypatch.setattr(
+ torch.Tensor, name, lambda self, _real=real, _n=name: reads.append(_n) or _real(self)
+ )
+ grid = images()[1][which]
+ pixels = images()[0][: int(grid.prod(-1).sum())]
+
+ def count(depth):
+ m = model(depth)
+ use_packed_vision_attention(m)
+ reads.clear()
+ m.visual(pixels, grid_thw=grid)
+ return len(reads)
+
+ assert count(6) == count(2)
+
+
+def test_packed_sdpa_rejects_what_it_would_ignore():
+ q = torch.randn(1, 2, 4, 8)
+ cu = torch.tensor([0, 4])
+ packed = varlen_attention.packed_sdpa_forward
+ for bad in (
+ {"cu_seq_lens_q": None},
+ {"attention_mask": torch.ones(1, 1, 4, 4, dtype=torch.bool)},
+ {"dropout": 0.1},
+ ):
+ with pytest.raises(varlen_attention.ValidationError):
+ packed(None, q, q, q, **{"cu_seq_lens_q": cu, "max_length_q": 4, **bad})
+
+
+@pytest.mark.parametrize("use", ["use_varlen_vision_attention", "use_packed_vision_attention"])
+def test_stage_workers_register_both(monkeypatch, use):
+ from transformers import AttentionInterface
+
+ m = model(1)
+ getattr(varlen_attention, use)(m)
+ for name in (NAME, PACKED):
+ monkeypatch.delitem(AttentionInterface._global_mapping, name, raising=False)
+ register_if_used(m)
+ assert NAME in AttentionInterface._global_mapping
+ assert PACKED in AttentionInterface._global_mapping
+
+
def test_stage_workers_register_it_again(monkeypatch):
from transformers import AttentionInterface
@@ -132,4 +204,5 @@ def test_train_vl_flag():
import train_vl
assert train_vl.build_parser().parse_args([]).vision_attn == "same"
- assert train_vl.build_parser().parse_args(["--vision-attn", "varlen"]).vision_attn == "varlen"
+ for name in ("varlen", "packed"):
+ assert train_vl.build_parser().parse_args(["--vision-attn", name]).vision_attn == name
diff --git a/training/rdsp/tests/unit/test_vision.py b/training/rdsp/tests/unit/test_vision.py
index da7fea0fc..0cc7039df 100644
--- a/training/rdsp/tests/unit/test_vision.py
+++ b/training/rdsp/tests/unit/test_vision.py
@@ -43,6 +43,22 @@ def test_first_stage_encodes_its_first_images_and_the_rest_go_to_later_stages():
assert routes[2]["need"] == [] and routes[3]["need"] == []
+def test_first_stage_only_keeps_each_image_on_the_first_stage_cell_that_needs_it():
+ """The encoder stays on the first stage's GPUs, as a stage that holds it would, but
+ batches its images: each cell encodes its own rows' images and the other stages none."""
+ inputs = step_inputs([[1, 1]] * 4) # images 0..7 = (mb, row) in order
+ layout = VisionLayout(first=Grid(dp=2), world=4, first_stage_only=True)
+ routes = [route_images(inputs, layout, rank) for rank in range(4)]
+ assert [[image for image, *_ in r["own"]] for r in routes] == [
+ [0, 2, 4, 6],
+ [1, 3, 5, 7],
+ [],
+ [],
+ ]
+ assert routes[0]["need"] == [(0, 0, 0), (1, 2, 0), (2, 4, 0), (3, 6, 0)] # (mb, image, owner)
+ assert routes[2]["need"] == [] and routes[3]["need"] == []
+
+
def test_rows_without_images_are_skipped_and_tp_peers_all_receive():
inputs = step_inputs([[1, 0], [0, 1]])
layout = VisionLayout(first=Grid(dp=1, tp=2), world=2) # one stage: it encodes all
@@ -240,6 +256,24 @@ def test_vision_schedule_encodes_ahead_and_backpropagates_once_gradients_exist()
assert end == [5]
+def test_vision_schedule_encodes_and_backpropagates_chunks_of_microbatches():
+ """chunk=3 on 6 microbatches, 2 stages: each chunk's images in one encoder call before
+ the forward its first microbatch would have been encoded at (0-2 before forward 0, 3-5
+ before forward 1), and backpropagated in one call before the forward its last
+ microbatch would have been backpropagated at (0-2 before forward 4), or at the end."""
+ from ray_deepspeed_pipeline.vision import vision_schedule
+
+ ops = [(k, m, f"{k}{m}") for m in range(6) for k in ("forward", "backward")]
+ before, end = vision_schedule(ops, microbatches=set(range(6)), n_stages=2, chunk=3)
+ at = {ops[i][2]: v for i, v in before.items()}
+ assert at == {
+ "forward0": ([], [0, 1, 2]),
+ "forward1": ([], [3, 4, 5]),
+ "forward4": ([0, 1, 2], []),
+ }
+ assert end == [3, 4, 5]
+
+
def test_engine_encodes_and_backpropagates_microbatch_by_microbatch():
"""Two microbatches encoded in turn, then backpropagated in turn: the
same gradients as one batch, and only the images still waiting for their
diff --git a/training/rdsp/tests/unit/test_vocab_parallel.py b/training/rdsp/tests/unit/test_vocab_parallel.py
index 6ed668ab0..fe4b12eb7 100644
--- a/training/rdsp/tests/unit/test_vocab_parallel.py
+++ b/training/rdsp/tests/unit/test_vocab_parallel.py
@@ -8,6 +8,7 @@
import os
import tempfile
+import pytest
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
@@ -170,3 +171,42 @@ def test_tied_embedding_and_head_stay_one_parameter():
for rank in range(TP):
r = torch.load(os.path.join(d, f"r{rank}.pt"))
assert r["shared"] and r["params"] == 2 and r["grad"], r
+
+
+@pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16])
+@pytest.mark.parametrize("chunk", [1, 3, 1024])
+def test_the_unsharded_loss_is_cross_entropys_whatever_the_chunk(monkeypatch, dtype, chunk):
+ from ray_deepspeed_pipeline import vocab_parallel
+
+ monkeypatch.setattr(vocab_parallel, "_LOSS_CHUNK", chunk)
+ g = torch.Generator().manual_seed(3)
+ logits = (torch.randn(2, 9, 33, generator=g) * 4).to(dtype)
+ labels = torch.randint(0, 33, (2, 9), generator=g)
+ labels[0, 2:5] = -100
+ labels[1] = -100 # a whole row with nothing to learn
+ ours, theirs = logits.clone().requires_grad_(), logits.clone().requires_grad_()
+ got = next_token_loss_sum(ours, labels)
+ want = F.cross_entropy(
+ theirs[:, :-1].float().reshape(-1, 33),
+ labels[:, 1:].reshape(-1),
+ ignore_index=-100,
+ reduction="sum",
+ )
+ got.backward()
+ want.backward()
+ assert torch.allclose(got.float(), want.float(), atol=1e-4)
+ assert ours.grad.dtype is dtype
+ assert torch.allclose(
+ ours.grad.float(), theirs.grad.float(), atol=2e-2 if dtype is torch.bfloat16 else 1e-5
+ )
+
+
+def test_a_weighted_token_mean_scales_the_gradient_once():
+ logits = torch.randn(1, 5, 7).requires_grad_()
+ labels = torch.tensor([[1, 2, 3, 4, 5]])
+ total = next_token_loss_sum(logits, labels)
+ (total * 0.25).backward()
+ half = logits.grad.clone()
+ logits.grad = None
+ (next_token_loss_sum(logits, labels) * 0.25).backward()
+ assert torch.allclose(half, logits.grad)
diff --git a/training/rdsp/tests/unit/test_wire.py b/training/rdsp/tests/unit/test_wire.py
new file mode 100644
index 000000000..271bb297b
--- /dev/null
+++ b/training/rdsp/tests/unit/test_wire.py
@@ -0,0 +1,121 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+
+"""What a step's data is when it travels to the stage workers: raw arrays Ray hands over
+without copying, not pickled tensors (whose unpickling kept the first stage's GPUs idle at
+the start of every step)."""
+
+import pickle
+
+import numpy as np
+import pytest
+import torch
+
+from ray_deepspeed_pipeline.wire import from_wire, to_wire
+
+
+def step_data():
+ return {
+ "inputs": [
+ {"input_ids": torch.arange(12).view(3, 4), "pixel_values": torch.randn(5, 7)},
+ {"input_ids": torch.zeros(3, 4, dtype=torch.long), "pixel_values": torch.ones(2, 7)},
+ ],
+ "labels": [torch.tensor([[1, -100]]), None],
+ "vision": {"own": [(3, torch.randn(4, 2), torch.tensor([[1, 2, 2]]), [0, 1], 0)]},
+ "token_total": 17,
+ }
+
+
+def same(a, b):
+ if torch.is_tensor(a):
+ return torch.is_tensor(b) and a.dtype == b.dtype and torch.equal(a, b)
+ if isinstance(a, dict):
+ return list(a) == list(b) and all(same(a[k], b[k]) for k in a)
+ if isinstance(a, (list, tuple)):
+ return type(a) is type(b) and len(a) == len(b) and all(map(same, a, b))
+ return a == b
+
+
+def test_round_trip_keeps_structure_dtypes_and_values():
+ data = step_data()
+ assert same(data, from_wire(to_wire(data)))
+
+
+@pytest.mark.parametrize(
+ "dtype",
+ [torch.bfloat16, torch.float16, torch.float32, torch.float64, torch.int64, torch.bool],
+)
+@pytest.mark.parametrize("shape", [(), (0, 4), (3, 4)])
+def test_round_trip_of_every_dtype_and_shape(dtype, shape):
+ t = torch.ones(shape, dtype=dtype)
+ assert same(t, from_wire(to_wire(t)))
+
+
+def test_no_tensor_is_pickled_and_the_bytes_travel_out_of_band():
+ buffers = []
+ data = pickle.dumps(to_wire(step_data()), protocol=5, buffer_callback=buffers.append)
+ assert b"torch" not in data
+ assert sum(b.raw().nbytes for b in buffers) >= 5 * 7 * 4 + 2 * 7 * 4
+
+
+def test_a_slice_sends_its_own_bytes_only():
+ whole = torch.zeros(1000, 10)
+ buffers = []
+ pickle.dumps(to_wire(whole[:1]), protocol=5, buffer_callback=buffers.append)
+ assert sum(b.raw().nbytes for b in buffers) == 40
+
+
+def test_non_contiguous_tensors_travel_too():
+ t = torch.arange(6).view(2, 3).t()
+ assert same(t, from_wire(to_wire(t)))
+
+
+def test_tensors_that_need_grad_travel_as_plain_values():
+ t = torch.ones(2, requires_grad=True)
+ out = from_wire(to_wire({"x": t}))["x"]
+ assert torch.equal(out, torch.ones(2)) and not out.requires_grad
+
+
+def test_read_only_buffers_give_tensors_without_a_warning(recwarn):
+ buffers = []
+ data = pickle.dumps(to_wire(torch.ones(3)), protocol=5, buffer_callback=buffers.append)
+ frozen = [pickle.PickleBuffer(bytes(b.raw())) for b in buffers] # as Ray's shared memory is
+ out = from_wire(pickle.loads(data, buffers=frozen))
+ assert torch.equal(out, torch.ones(3))
+ assert not [w for w in recwarn if "not writable" in str(w.message)]
+
+
+def test_copy_gives_tensors_of_their_own():
+ array = np.ones(3, dtype=np.float32)
+ array.setflags(write=False)
+ wire = to_wire(torch.from_numpy(array.copy()))
+ out = from_wire(wire, copy=True)
+ out += 1
+ assert torch.equal(from_wire(wire), torch.ones(3))
+
+
+def test_what_is_already_plain_is_untouched():
+ for value in (None, 3, "x", [1, (2, None)], {"a": 1.5}):
+ assert from_wire(to_wire(value)) == value
+
+
+def test_a_stage_group_sends_no_tensors():
+ from ray_deepspeed_pipeline.stage_group import StageGroupClient
+
+ client = StageGroupClient([object(), object()], stage=0)
+ inputs = [{"input_ids": torch.arange(8).view(2, 4), "pixel_values": [torch.ones(3, 2)] * 2}]
+ labels = [torch.arange(8).view(2, 4)]
+
+ def tensors(x):
+ if torch.is_tensor(x):
+ return 1
+ if isinstance(x, dict):
+ x = x.values()
+ return sum(map(tensors, x)) if hasattr(x, "__iter__") and not isinstance(x, str) else 0
+
+ payloads = client._rank_payloads(inputs, labels)
+ assert [tensors(p) for p in payloads] == [0, 0]
+ second = from_wire(payloads[1])
+ assert torch.equal(second["inputs"][0]["input_ids"], torch.tensor([[4, 5, 6, 7]]))
+ assert torch.equal(second["inputs"][0]["pixel_values"], torch.ones(3, 2))
+ assert torch.equal(second["labels"][0], torch.tensor([[4, 5, 6, 7]]))
diff --git a/training/rdsp/tests/unit/test_worker_host.py b/training/rdsp/tests/unit/test_worker_host.py
new file mode 100644
index 000000000..dbf3d9e72
--- /dev/null
+++ b/training/rdsp/tests/unit/test_worker_host.py
@@ -0,0 +1,43 @@
+# SPDX-License-Identifier: Apache-2.0
+# DeepSpeed Team
+
+import gc
+
+from ray_deepspeed_pipeline import worker_host
+
+
+def test_parse_cpulist():
+ assert worker_host.parse_cpulist("0-3,8,10-11\n") == {0, 1, 2, 3, 8, 10, 11}
+ assert worker_host.parse_cpulist("") == set()
+
+
+def test_nothing_is_pinned_without_a_gpu_socket(monkeypatch):
+ monkeypatch.setattr(worker_host, "gpu_cpus", lambda: set())
+ assert not worker_host.pin_to_gpu_socket()
+ monkeypatch.setenv("RDSP_PIN_CPUS", "0")
+ assert not worker_host.pin_to_gpu_socket()
+
+
+def test_gpu_cpus_reads_the_gpus_sysfs_entry(monkeypatch, tmp_path):
+ class Properties:
+ pci_domain_id, pci_bus_id, pci_device_id = 0, 0x53, 0
+
+ monkeypatch.setattr(worker_host.torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(worker_host.torch.cuda, "get_device_properties", lambda i: Properties)
+ (tmp_path / "0000:53:00.0").mkdir()
+ (tmp_path / "0000:53:00.0" / "local_cpulist").write_text("0-47,96-143\n")
+ assert worker_host.gpu_cpus(str(tmp_path)) == set(range(48)) | set(range(96, 144))
+ assert worker_host.gpu_cpus(str(tmp_path / "none")) == set()
+
+
+def test_freeze_heap_freezes_and_can_be_switched_off(monkeypatch):
+ monkeypatch.setenv("RDSP_FREEZE_HEAP", "0")
+ before = gc.get_freeze_count()
+ worker_host.freeze_heap()
+ assert gc.get_freeze_count() == before
+ monkeypatch.delenv("RDSP_FREEZE_HEAP")
+ try:
+ worker_host.freeze_heap()
+ assert gc.get_freeze_count() > before
+ finally:
+ gc.unfreeze()
diff --git a/training/rdsp/train.py b/training/rdsp/train.py
index ade114a58..26ace826b 100644
--- a/training/rdsp/train.py
+++ b/training/rdsp/train.py
@@ -11,6 +11,7 @@
"""
import argparse
+import dataclasses
import itertools
import json
import time
@@ -25,6 +26,7 @@
_STAGE_KEYS = {
"gpus": "num_gpus",
+ "procs": "num_gpus", # the same on a CPU run: the stage's processes
"zero": "zero_stage",
"tp": "tp",
"sp": "sp",
@@ -34,8 +36,8 @@
def parse_stage(spec: str) -> StageOverride:
- """'1:gpus=2,tp=2' -> StageOverride(stage=1, num_gpus=2, tp=2). Keys: gpus,
- zero, tp, sp, ep, fold, recompute, offload, compile, compile_vision,
+ """'1:gpus=2,tp=2' -> StageOverride(stage=1, num_gpus=2, tp=2). Keys: gpus (procs on a CPU
+ run), zero, tp, sp, ep, fold, recompute, offload, compile, compile_vision,
recompute_blocks."""
index, _, fields = spec.partition(":")
kwargs = {"stage": int(index)}
@@ -51,14 +53,20 @@ def parse_stage(spec: str) -> StageOverride:
return StageOverride(**kwargs)
-def load_model(name: str, dtype: torch.dtype):
- model = transformers.AutoModelForCausalLM.from_pretrained(name, dtype=dtype)
- if model.get_output_embeddings().weight is model.get_input_embeddings().weight:
- # rdsp rejects parameters shared across stages
- head = model.get_output_embeddings()
- head.weight = torch.nn.Parameter(model.get_input_embeddings().weight.detach().clone())
- model.config.tie_word_embeddings = False
- return model
+def load_model(name: str, dtype: torch.dtype, stages: int):
+ """The model as an empty skeleton and its checkpoint folder: each stage reads only its own
+ weights from the checkpoint, so the driver never holds the whole model. A head tied to the
+ input embedding is untied when they could land on different stages."""
+ import accelerate
+ import huggingface_hub
+
+ config = transformers.AutoConfig.from_pretrained(name)
+ if stages > 1:
+ config.tie_word_embeddings = False
+ with accelerate.init_empty_weights():
+ model = transformers.AutoModelForCausalLM.from_config(config, dtype=dtype)
+ patterns = ["*.json", "*.safetensors", "*.txt", "*.model", "*.jinja"]
+ return model, huggingface_hub.snapshot_download(name, allow_patterns=patterns)
def token_stream(args, tokenizer):
@@ -121,8 +129,9 @@ def build_parser() -> argparse.ArgumentParser:
p.add_argument(
"--cuts",
default="",
- help="block indices where stages 1.. start, e.g. 9,18,27; "
- "'balanced' for cost-balanced cuts; default: even layer counts",
+ help="block indices where stages 1.. start, e.g. 9,18,27; 'balanced' for cuts by "
+ "parameter count; 'measured' to time every stage for a few steps first and re-cut "
+ "by their times; default: even layer counts",
)
p.add_argument(
"--stage",
@@ -155,25 +164,40 @@ def main(argv=None):
torch.manual_seed(args.seed)
ray.init(ignore_reinit_error=True)
dtype = torch.bfloat16 if args.dtype == "bf16" else torch.float32
- model = load_model(args.model, dtype)
+ model, weights = load_model(args.model, dtype, args.stages)
tokenizer = transformers.AutoTokenizer.from_pretrained(args.model)
- if args.cuts == "balanced":
+ if args.cuts in ("balanced", "measured"):
partition = rdsp.BalancedTransformerBlocks()
elif args.cuts:
partition = rdsp.ExplicitCuts(tuple(int(c) for c in args.cuts.split(",")))
else:
partition = rdsp.UniformTransformerBlocks()
- engine, _, _, _ = rdsp.initialize(
- model=model,
- config=ds_config(args),
- loss_fn=loss_fn,
- pipeline_config=rdsp.PipelineConfig(
- stages=args.stages, partition=partition, stage_overrides=tuple(args.stage)
- ),
- )
- del model # the stages hold their own copies
+
+ def build(partition, lr):
+ config = ds_config(args)
+ config["optimizer"]["params"]["lr"] = lr
+ engine, _, _, _ = rdsp.initialize(
+ model=model,
+ config=config,
+ loss_fn=loss_fn,
+ weights=weights,
+ pipeline_config=rdsp.PipelineConfig(
+ stages=args.stages, partition=partition, stage_overrides=tuple(args.stage)
+ ),
+ )
+ print(f"stages (blocks): {engine.stage_blocks}", flush=True)
+ return engine
data = microbatches(args, tokenizer)
+ if args.cuts == "measured": # time each stage at learning rate 0, then re-cut by the times
+ calibration = build(partition, lr=0.0)
+ try:
+ measured = calibration.measure_stages(data, steps=3, skip=1)
+ finally:
+ calibration.shutdown()
+ print(f"measured: {measured}", flush=True)
+ partition = dataclasses.replace(partition, measured=measured)
+ engine = build(partition, lr=args.lr)
tokens_per_step = args.microbatches * args.rows * args.seq
for step in range(args.steps):
start = time.perf_counter()
diff --git a/training/rdsp/train_vl.py b/training/rdsp/train_vl.py
index 2655b28b9..7206124f6 100644
--- a/training/rdsp/train_vl.py
+++ b/training/rdsp/train_vl.py
@@ -16,7 +16,7 @@
--rows 2 --microbatches 32 --stages 2 --cuts 16 \
--stage 0:gpus=4,tp=2,zero=1 --stage 1:gpus=4,tp=2,zero=1
-`exported:DIR` reads samples written by bench/common/export_bridge_batches.py
+`exported:DIR` reads samples written by bench/compare/lib/export_bridge_batches.py
(Megatron-Bridge's own SFT pipeline), one file per step, in order.
"""
@@ -25,6 +25,7 @@
import glob
import itertools
import json
+import math
import os
import random
import time
@@ -34,6 +35,8 @@
import ray_deepspeed_pipeline as rdsp
from ray_deepspeed_pipeline.config import MASTER_WEIGHTS_KEY, OPTIMIZER_GROUP_NUMEL_KEY
+from ray_deepspeed_pipeline.gated_norm import fuse_gated_norms
+from ray_deepspeed_pipeline.partition import vision_stage_gpus
from train import parse_stage
COLORS = ["red", "green", "blue", "yellow", "purple", "orange", "white", "black"]
@@ -188,12 +191,26 @@ def _padded_length(samples, pad_multiple: int, exported: int) -> int:
def token_loss_sum_liger(logits, labels):
"""token_loss_sum with Liger's cross entropy: computed in fp32 chunk by
chunk from bf16 logits, gradient written in place, so no fp32 copy of
- the (vocabulary-wide) logits."""
+ the (vocabulary-wide) logits. The per-token losses, in the logits' dtype,
+ are summed here in fp32: the sum in bf16 drops 0.2% of the total."""
from liger_kernel.transformers import LigerCrossEntropyLoss
- return LigerCrossEntropyLoss(ignore_index=-100, reduction="sum")(
+ per_token = LigerCrossEntropyLoss(ignore_index=-100, reduction="none")(
logits[:, :-1].reshape(-1, logits.shape[-1]), labels[:, 1:].reshape(-1).to(logits.device)
)
+ return per_token.float().sum()
+
+
+def sharded_loss_sum_liger(logits, labels):
+ """The loss of a stage whose output head may hold part of the vocabulary: next_token_loss_sum
+ on a shard, Liger's kernel where this rank holds the whole vocabulary (2 ms where PyTorch's
+ takes 10 for one 2,048-token row of 248k)."""
+ if getattr(logits, "vocab_shard", None) is not None:
+ return rdsp.next_token_loss_sum(logits, labels)
+ return token_loss_sum_liger(logits, labels)
+
+
+sharded_loss_sum_liger.takes_vocab_shards = True
def apply_liger(model):
@@ -210,6 +227,7 @@ def apply_liger(model):
cross_entropy=False,
fused_linear_cross_entropy=False,
)
+ fuse_gated_norms(model)
def restore_hf_experts(model) -> int:
@@ -243,7 +261,7 @@ def partition_policy(cuts: str, ratio):
"""--cuts as a partition policy. ratio() measures the vision encoder's cost
per text token from the first step; only 'balanced' (and 'measured',
whose calibration runs with the balanced cut) need it."""
- if cuts in ("balanced", "measured"):
+ if cuts in ("balanced", "measured", "auto"):
return rdsp.BalancedTransformerBlocks(vision_token_ratio=ratio())
if cuts in ("0,balanced", "0,measured"): # encoder alone on stage 0, decoder over the rest
return rdsp.BalancedTransformerBlocks(vision_stage=True)
@@ -275,10 +293,52 @@ def batches():
return dataclasses.replace(estimate, measured=measured)
+def vision_stage_layout(stages: list, k: int) -> list:
+ """The vision encoder alone on a stage of k GPUs, then the decoder on as many stages as the
+ other GPUs fill at the width (and settings) of the given equal stages."""
+ width = stages[0].num_gpus
+ count = (sum(s.num_gpus for s in stages) - k) // width
+ vision = dataclasses.replace(
+ stages[0], stage=0, num_gpus=k, tp=1, sp=1, ep=1, fold=False, recompute_blocks=None
+ )
+ template = stages[min(1, len(stages) - 1)]
+ return [vision] + [dataclasses.replace(template, stage=i + 1) for i in range(count)]
+
+
+def auto_policy(args, build, estimate, new_data):
+ """--cuts auto: time the given equal stages (balanced cut, learning rate 0); then give the
+ vision encoder a stage of its own, of the GPU count those times call for, and time again to
+ re-cut the decoder (0,measured). Rows per microbatch become a multiple of every stage's
+ data-parallel copies, keeping the rows a step. Without equal stages: measured cuts only."""
+ engine = build(estimate, ds_config(args, lr=0.0))
+ blocks = engine.stage_blocks[-1][1]
+ timed = calibrated_policy(args, engine, new_data(), estimate)
+ widths = {s.num_gpus for s in args.stage}
+ if len(args.stage) != args.stages or args.stages < 2 or len(widths) != 1:
+ return timed
+ total = sum(s.num_gpus for s in args.stage)
+ k = vision_stage_gpus(timed.measured, blocks, widths.pop(), total)
+ if k is None:
+ return timed
+ args.stage = vision_stage_layout(args.stage, k)
+ args.stages = len(args.stage)
+ decoder = args.stage[1]
+ rows = math.lcm(k, decoder.num_gpus // (decoder.tp * decoder.sp))
+ args.microbatches = max(args.rows * args.microbatches // rows, 2 * args.stages)
+ args.rows = rows
+ print(
+ f"vision stage: {k} GPUs, then {args.stages - 1} decoder stages; "
+ f"{rows} rows x {args.microbatches} microbatches",
+ flush=True,
+ )
+ vision = rdsp.BalancedTransformerBlocks(vision_stage=True)
+ return calibrated_policy(args, build(vision, ds_config(args, lr=0.0)), new_data(), vision)
+
+
def loss_function(args):
"""The stage loss for --loss / --liger / --sharded-loss."""
if args.sharded_loss:
- token_sum = rdsp.next_token_loss_sum
+ token_sum = sharded_loss_sum_liger if args.liger else rdsp.next_token_loss_sum
elif args.liger:
token_sum = token_loss_sum_liger
else:
@@ -312,10 +372,7 @@ def ds_config(args, lr: float | None = None) -> dict:
conf = {
"train_batch_size": args.rows * args.microbatches,
"gradient_accumulation_steps": args.microbatches,
- "bf16": {
- "enabled": True,
- **({"immediate_grad_update": False} if args.keep_bf16_grads else {}),
- },
+ "bf16": {"enabled": True},
# ZeRO's default 500M-element communication buckets cost ~2 GB each in
# fp32; smaller buckets change how gradients are batched, not the math
"zero_optimization": {
@@ -382,6 +439,17 @@ def worker_env(environ=None) -> dict:
}
+def ray_runtime_env(environ=None) -> dict:
+ """What ray.init() starts this job's workers with: worker_env(), and, when RDSP_NSIGHT
+ holds a JSON object of `nsys profile` options (Ray's _nsight runtime-env plugin), every
+ worker process under Nsight Systems; traces go to the Ray session's logs/nsight."""
+ environ = os.environ if environ is None else environ
+ env = {"env_vars": worker_env(environ)}
+ if environ.get("RDSP_NSIGHT"):
+ env["_nsight"] = json.loads(environ["RDSP_NSIGHT"])
+ return env
+
+
def optimizer_problem(args) -> str | None:
"""Why --master-dtype bf16/remainder or --fused-adam cannot apply as asked,
or None. DeepSpeed reads the bf16 states only in its ZeRO-1/2 optimizer,
@@ -398,7 +466,8 @@ def optimizer_problem(args) -> str | None:
flag = f"--master-dtype {args.master_dtype}"
if args.grad_dtype != "bf16":
return f"{flag} needs --grad-dtype bf16"
- if args.colocated_vision:
+ # the replicated encoder keeps fp32 master weights: as exact as the remainder master
+ if args.colocated_vision and args.master_dtype != "remainder":
return f"{flag}: the replicated encoder keeps fp32 states"
for s in range(args.stages):
o = overrides.get(s)
@@ -443,7 +512,9 @@ def build_parser() -> argparse.ArgumentParser:
help="'balanced', 'measured' (balanced, then re-cut by the stage "
"times and memory --calibration-steps profiled steps measure), "
"'0,balanced' (vision encoder alone on stage 0), '0,measured' (that, "
- "the decoder stages then re-cut as measured does), 'even', or e.g. 9,18",
+ "the decoder stages then re-cut as measured does), 'auto' (time equal stages, "
+ "then give the vision encoder a stage sized by the times, then 0,measured), "
+ "'even', or e.g. 9,18",
)
p.add_argument(
"--calibration-steps",
@@ -469,7 +540,7 @@ def build_parser() -> argparse.ArgumentParser:
p.add_argument(
"--dataset",
default="synthetic",
- help="synthetic, cord-v2, or exported:DIR (bench/common/export_bridge_batches.py)",
+ help="synthetic, cord-v2, or exported:DIR (bench/compare/lib/export_bridge_batches.py)",
)
p.add_argument(
"--loss",
@@ -534,11 +605,12 @@ def build_parser() -> argparse.ArgumentParser:
)
p.add_argument(
"--vision-attn",
- choices=("same", "varlen"),
+ choices=("same", "packed", "varlen"),
default="same",
- help="vision encoder attention: same as --attn, or varlen: PyTorch's "
- "variable-length flash attention, one kernel per layer for all "
- "images and no host sync per layer (CUDA)",
+ help="vision encoder attention: same as --attn; packed: SDPA without "
+ "reading the image lengths back from the GPU three times per layer; "
+ "varlen: PyTorch's variable-length flash attention, one kernel per "
+ "layer for all images and no such reads either (CUDA)",
)
p.add_argument(
"--max-pixels",
@@ -552,12 +624,6 @@ def build_parser() -> argparse.ArgumentParser:
help="train the input embedding and the output head as two matrices; "
"needed when a tied pair would land on different stages",
)
- p.add_argument(
- "--keep-bf16-grads",
- action="store_true",
- help="keep DeepSpeed's per-parameter bf16 gradients (accumulated into "
- "fp32 after each backward) instead of freeing each one as it lands",
- )
p.add_argument(
"--pad-per-microbatch",
action="store_true",
@@ -586,22 +652,11 @@ def build_parser() -> argparse.ArgumentParser:
action="store_true",
help="run the vision encoder on every GPU (rdsp.ColocatedVision)",
)
- p.add_argument(
- "--vision-per-microbatch",
- action="store_true",
- help="with --colocated-vision: encode and backpropagate images per "
- "microbatch inside the pipeline (less memory, can be slower)",
- )
p.add_argument(
"--vision-compile",
action="store_true",
help="with --colocated-vision: torch.compile the encoder's blocks",
)
- p.add_argument(
- "--vision-recompute",
- action="store_true",
- help="with --colocated-vision: recompute the encoder's blocks",
- )
p.add_argument("--steps", type=int, default=10)
p.add_argument("--lr", type=float, default=1e-5)
p.add_argument("--zero", type=int, default=0)
@@ -671,6 +726,10 @@ def new_data():
from ray_deepspeed_pipeline.varlen_attention import use_varlen_vision_attention
use_varlen_vision_attention(skeleton)
+ elif args.vision_attn == "packed":
+ from ray_deepspeed_pipeline.varlen_attention import use_packed_vision_attention
+
+ use_packed_vision_attention(skeleton)
from ray_deepspeed_pipeline.partition import vision_token_ratio
partition = partition_policy(args.cuts, ratio=lambda: vision_token_ratio(config, first))
@@ -682,7 +741,7 @@ def new_data():
apply_liger(skeleton)
if args.moe_experts == "hf":
restore_hf_experts(skeleton)
- ray.init(ignore_reinit_error=True, runtime_env={"env_vars": worker_env()})
+ ray.init(ignore_reinit_error=True, runtime_env=ray_runtime_env())
def build(partition, conf):
pipeline_config = rdsp.PipelineConfig(
@@ -690,13 +749,7 @@ def build(partition, conf):
partition=partition,
stage_overrides=tuple(args.stage),
colocated_vision=(
- rdsp.ColocatedVision(
- recompute=args.vision_recompute,
- compile=args.vision_compile,
- encode_per_microbatch=args.vision_per_microbatch,
- )
- if args.colocated_vision
- else None
+ rdsp.ColocatedVision(compile=args.vision_compile) if args.colocated_vision else None
),
prefetch=args.prefetch,
)
@@ -714,6 +767,10 @@ def build(partition, conf):
partition = calibrated_policy(
args, build(partition, ds_config(args, lr=0.0)), new_data(), partition
)
+ if args.cuts == "auto":
+ partition = auto_policy(args, build, partition, new_data)
+ data = new_data() # rows per microbatch may have changed
+ first = [next(data) for _ in range(args.microbatches)]
engine = build(partition, ds_config(args))
if reference is not None: