diff --git a/training/rdsp/.gitignore b/training/rdsp/.gitignore new file mode 100644 index 000000000..732c56160 --- /dev/null +++ b/training/rdsp/.gitignore @@ -0,0 +1,41 @@ +__pycache__/ +*.pyc +.venv/ +.pytest_cache/ +.ruff_cache/ +.cache/ +.DS_Store +*.egg-info/ +dist/ +build/ + +# raw run logs and profiles +bench/results/ + +# bench_oct10: the working folder of the October-November benchmark rounds +# (plans, queues, notes, raw logs, profiles). +bench_oct10/ + +# what the bench/ scripts write when they run stays local... +bench/**/logs*/* +bench/**/profiles*/ +bench/**/prep/ +bench/mimo_vs_rdsp/sweep/ +bench/mimo_vs_rdsp/convert.log +*.sqlite +*.nsys-rep +*.qdrep +*.pt.trace.json +*.dmon + +# benchmark logs and raw results stay local: docs/REPRODUCE.md names the log +# each run writes; the write-ups (*.md) are kept +bench/published/ +bench/blog_round/logs27b/ +bench/encoder_test/results/** +!bench/encoder_test/results/**/ +!bench/encoder_test/results/**/*.md +bench/torchtitan/results/data_check.txt + +# nCompass profiling plugin's working files +ncompass/ diff --git a/training/rdsp/CONTEXT.md b/training/rdsp/CONTEXT.md new file mode 100644 index 000000000..cf8b94c0b --- /dev/null +++ b/training/rdsp/CONTEXT.md @@ -0,0 +1,167 @@ +# rdsp + +Pipeline-parallel training in which one CPU process hands each GPU its work and every GPU trains its share of the model with DeepSpeed. This glossary fixes the words we use for rdsp and for comparing it with Megatron-Bridge and MegatronMIMO. + +## Language + +### Processes + +**Driver**: +The single CPU process that plans each training step and gives every GPU its work. It holds no model weights and no activations. +_Avoid_: controller, master, launcher + +**Stage worker**: +The Ray actor that owns one GPU and trains that GPU's part of one stage. +_Avoid_: worker, actor, rank (a rank is a number in a group, not the process) + +### Pipeline layout + +**Stage**: +A consecutive slice of the model, together with the GPUs that train it. The first stage can also hold the vision encoder, and the last stage holds the loss. +_Avoid_: partition, pipeline rank, module (MegatronMIMO uses "module" for a whole sub-model) + +**Stage world**: +The `torch.distributed` group of one stage's GPUs. Tensor and data parallelism happen inside it, and it does not know that other stages exist. +_Avoid_: process group, mesh + +**Cross-stage groups**: +The two NCCL groups, `fwd` and `bwd`, that span every GPU and carry only boundary tensors. +_Avoid_: P2P world, pipeline group + +**Boundary tensor**: +The activation sent forward to the next stage, or its gradient sent back, for one microbatch. +_Avoid_: message, payload + +**Cut**: +The number of decoder layers each stage holds, written in stage order, e.g. 13 | 19. +_Avoid_: split, partition, boundary + +**Balanced cut**: +rdsp's default cut. It gives each stage an equal share of the estimated compute, and that estimate includes the vision encoder. +_Avoid_: auto cut, smart cut + +**Measured cut**: +A balanced cut redone from what a few profiled steps measured: each stage's time per step, and its memory as a limit on how many layers it may gain. +_Avoid_: calibrated cut, tuned cut + +**Even cut**: +A cut with the same number of decoder layers on every stage. Megatron uses it by default, and it does not count the vision encoder. +_Avoid_: uniform split, default split + +### Vision placement + +**Shared first stage**: +The vision encoder runs on the first stage's GPUs, ahead of that stage's decoder layers. +_Avoid_: colocated, encoder on stage 0 + +**Vision-only stage**: +The vision encoder is a stage of its own and holds no decoder layers. +_Avoid_: non-colocated, separate encoder + +**Replicated encoder**: +Every GPU holds a copy of the vision encoder outside the pipeline. Each copy encodes a share of the images and sends the features to the first stage. +_Avoid_: colocated vision, colocated + +### Parallelism inside a stage + +**DP copy**: +One of a stage's data-parallel replicas. It holds the stage's full slice of the model (split across its TP GPUs) and trains on different rows from the other copies. +_Avoid_: replica, DP rank + +### Training step + +**Row**: +One training sample (an image, its prompt and its answer) as a single token sequence. +_Avoid_: sample, example, sequence + +**Step**: +One optimizer update, covering every row of the batch. +_Avoid_: iteration + +**Microbatch**: +The group of rows that moves through the pipeline as one unit. +_Avoid_: chunk, minibatch + +**Microbatch count**: +How many microbatches make up one step. It sets the size of the bubble. +_Avoid_: accumulation steps, number of microbatches + +**Microbatch size**: +The number of rows in one microbatch, counted across all DP copies of a stage. +_Avoid_: batch size, micro batch size per GPU + +**Job list**: +The ordered forwards and backwards that one stage runs in one step, delivered to it in a single call. +_Avoid_: op list, command list, schedule + +**1F1B**: +The job-list order in which a stage runs its warm-up forwards and then alternates one forward with one backward. +_Avoid_: interleaved schedule, PipeDream + +**Bubble**: +The share of a step during which a stage sits idle, waiting for a neighbouring stage. +_Avoid_: pipeline stall, idle time + +**Apply**: +The optimizer update at the end of a step. It starts on any stage only after every stage has finished all its backwards. +_Avoid_: optimizer step, update + +### Model + +**GDN layer**: +A Gated DeltaNet decoder layer: Qwen3.5's linear-attention layer type. Qwen3.5-4B has 24 of them next to 8 full-attention layers. +_Avoid_: linear layer, DeltaNet, SSM layer + +**Remainder master**: +Exact fp32 master weights kept as the bf16 weights plus the 16 bits the rounding dropped, 2 bytes per parameter instead of 4. +_Avoid_: bf16 master (that one is not exact), compressed master + +**Untied output layer**: +The last stage's own copy of the output-layer weight, which the original model shares with the input embedding on stage 0. +_Avoid_: lm head copy, duplicated embedding + +### Failure + +**Rebuild**: +Recovery that replaces every stage worker and reloads the last checkpoint, while the driver and the Ray cluster keep running. +_Avoid_: restart, failover, elastic recovery + +### Data and loss + +**Replayed data**: +The rows that Megatron-Bridge exported, given to rdsp in the same order and the same microbatch groups, so that both systems train on identical input. +_Avoid_: shared dataset, same data + +**Real token**: +A position that holds an actual token of the row: an image, prompt or answer token. +_Avoid_: valid token, non-pad token + +**Answer token**: +A real token from the row's answer. It is the only kind of token with a label, so it is the only kind that counts in the loss. +_Avoid_: caption token, supervised token, label token + +**Padding**: +Positions added after a row's last real token so that the rows in a microbatch share one length. They are computed, but they never count in the loss. +_Avoid_: pad tokens, filler + +**Positions per real token**: +The number of positions computed, divided by the number of real tokens. It measures how much compute goes to padding. +_Avoid_: padding ratio, efficiency + +**Token-mean loss**: +A step's loss taken as the plain average over every answer token in the step, whichever microbatch or GPU holds the token. +_Avoid_: per-token loss, global mean + +**Microbatch-mean loss**: +A step's training loss taken as the average of each rank-microbatch's own answer-token average: each data-parallel rank's share of a microbatch is averaged on its own. Tokens in rank-microbatches with fewer answer tokens count for more. The reported loss is still the token mean. +_Avoid_: per-microbatch loss, mean of means + +### Comparison + +**Recipe comparison**: +A benchmark with the same layout, data, batch, microbatch count, optimizer and loss on both systems. Each system keeps its own padding, cut and kernels. +_Avoid_: same settings, apples-to-apples, fair comparison + +**Equal-work comparison**: +A recipe comparison in which both systems also compute the same token positions. +_Avoid_: same settings, apples-to-apples diff --git a/training/rdsp/README.md b/training/rdsp/README.md new file mode 100644 index 000000000..dd1863114 --- /dev/null +++ b/training/rdsp/README.md @@ -0,0 +1,117 @@ +# rdsp: pipeline parallelism on Ray + DeepSpeed + +rdsp (`ray_deepspeed_pipeline`) splits a model into pipeline stages and gives each stage its own GPU count and parallel layout. You can split a Hugging Face vision-language model so the vision encoder gets its own stage, and train it from the HF checkpoint without converting it. + +![rdsp architecture. The driver cuts the model into stages and sends every GPU its schedule and batch. Each stage has its own group of GPUs, and every GPU is a Ray actor running a DeepSpeed engine. Activations go forward and gradients come back directly between the GPUs of neighbouring stages.](docs/images/architecture.png) + +Every stage is a group of Ray actors, one per GPU, each running a stock DeepSpeed engine. Stages pass activations and gradients to each other directly over NCCL; the driver only plans and schedules. + +## Results + +Qwen3.5 vision-language models on H100 GPUs, trained on CORD-v2. Median time per training step; lower is better. + +| Model | GPUs | rdsp | Megatron-Bridge | TorchTitan | +|---|---|---|---|---| +| Qwen3.5-35B-A3B (mixture of experts) | 16, two nodes | **6.38 s** | 8.67 s | 9.11 s | +| Qwen3.5-27B (dense) | 8, one node | **10.66 s** | 15.13 s | 13.16 s | + +- On the 35B that is 1.36× Megatron-Bridge's throughput and 1.43× TorchTitan's; on the 27B, 1.42× and 1.23×. With two rows per microbatch, the fastest setting for both pipelines on the 27B, rdsp is 1.05× Megatron-Bridge. +- On MegatronMIMO's own layouts, with one GPU for the vision encoder, rdsp runs at 0.99–1.09× MIMO's throughput. +- rdsp ran the 35B with the vision encoder on its own 4-GPU stage and six 2-GPU language stages, and the 27B as eight 1-GPU stages, each choosing how many of its layers to recompute. Megatron-Bridge used the layout of NVIDIA's H100 recipe on the 35B and rdsp's eight-stage split on the 27B. TorchTitan sharded over all GPUs, with expert parallelism on the 35B. + +One run per configuration. Settings and commands for each number: [docs/REPRODUCE.md](docs/REPRODUCE.md). Earlier Qwen3.5-2B and 4B results on 8 GPUs: [docs/BENCHMARK_RESULTS.md](docs/BENCHMARK_RESULTS.md). + +## Install + +Linux, CUDA GPUs, Python 3.12. On a fresh node: + +```bash +bash bench/setup_node.sh +``` + +This builds `~/venv` with torch, DeepSpeed at the commit every result was measured with, and rdsp, and pulls the container the Megatron comparisons run in. To install by hand, or without the container: [docs/GETTING_STARTED.md](docs/GETTING_STARTED.md#install). + +Importing `ray_deepspeed_pipeline` doesn't import Ray or DeepSpeed; only the stage actors do. + +## Quickstart + +```bash +./recipes/qwen35-2b-tp2pp2dp2.sh # Qwen3.5-2B on CORD-v2, 8 GPUs +./recipes/qwen35-2b-tp2pp2dp2.sh --steps 200 # extra flags override the recipe +``` + +`recipes/` has one script per benchmarked layout, plus a text-only Qwen3 recipe. [docs/GETTING_STARTED.md](docs/GETTING_STARTED.md) covers the flags, your own data, and common failures. + +## Python API + +```python +import ray, ray_deepspeed_pipeline as rdsp + +def count_tokens(labels): # tokens the loss is computed on + return int((labels[:, 1:] != -100).sum()) + +ray.init() +engine, _, _, _ = rdsp.initialize( + model=model, # HF model, built under accelerate.init_empty_weights() + weights="/path/to/hf/checkpoint", # each stage loads only its own tensors + config=ds_config, # DeepSpeed config dict + loss_fn=rdsp.TokenMeanLoss(rdsp.next_token_loss_sum, count_tokens), # mean over the step's tokens + pipeline_config=rdsp.PipelineConfig( + stages=2, + partition=rdsp.BalancedTransformerBlocks(vision_token_ratio=ratio), + stage_overrides=(rdsp.StageOverride(stage=0, num_gpus=4, tp=2, zero_stage=1), + rdsp.StageOverride(stage=1, num_gpus=4, tp=2, zero_stage=1)), + ), +) +loss = engine.train_batch(data_iter) # consumes exactly M (inputs, labels) entries +engine.save_checkpoint("ckpt/", tag="step100") +``` + +If the input embedding and output layer share a weight and land on different stages, untie them first (`train_vl.py --untie-embeddings`); on one stage they stay tied. Every public name, what it guarantees and what it raises are listed in [docs/CONTRACTS.md](docs/CONTRACTS.md). `train_vl.py` is a complete training script. + +## How it works + +- **Planning.** `rdsp.initialize` lowers the config into an immutable plan: where the model is cut, each stage's GPUs and DeepSpeed config, and a hash that binds checkpoints. Every check, including the cluster's GPU count, runs before any actor starts. +- **Stages.** Each stage runs the HF model's own `forward`. Blocks outside the stage pass their input through, and a hook injects what arrived from upstream. No per-architecture code is needed. +- **Step.** The driver hands each stage its 1F1B schedule, which interleaves forward and backward microbatches. Each stage applies its optimizer step only after every stage reports its backward done. +- **Failures.** A failure before any update raises `StepFailed`: weights are unchanged and a retry is exact. A failure during the update raises `PipelinePoisoned` until a checkpoint is loaded. + +Vision encoder placement, how the cuts are chosen, memory, and the reasoning behind the design: [docs/ENGINEERING.md](docs/ENGINEERING.md). + +## Model coverage + +| Builder | Models | Validation | +|---|---|---| +| `HFModelStage` | Any HF model with a `config`: Llama, Mistral, Qwen2/3/3.5, Qwen3-MoE, Mixtral, Gemma 1–3, Phi-3, OLMo2, Granite, Cohere, StarCoder2, StableLM, DeepSeek-V3, GLM-4/4-MoE/5.3, GPT-2, GPT-NeoX, Falcon, Bloom, Mamba, Qwen3-VL, Qwen3.5-VL | Pipeline loss equals the unsplit model's on CPU (`tests/integration/test_hf_families.py`). Qwen3, Qwen3-MoE and Qwen3.5-VL validated on GPU. | +| `CausalLMStage` | Llama, Qwen3, Qwen3-MoE | GPU-validated in every layout in CONTRACTS.md | +| `GenericSequentialStage` | Plain sequential models | CPU | + +TP inside a stage uses the model's AutoTP plan. Configs without one get a plan for the standard projection names. Qwen3-VL injects vision features into its first decoder blocks, so its encoder can't be colocated and the first cut must come after them. + +## Tests + +```bash +pytest -q # CPU: full runtime on Ray with a stub engine (~500 tests); GPU tests skip +ruff check . +``` + +The GPU tests (parity against the unsplit model, checkpoint round trip, rank-kill recovery) run on Modal: `scripts/modal_tests.py`. + +## Docs + +| | | +|---|---| +| [GETTING_STARTED](docs/GETTING_STARTED.md) | Install, terms, recipes, flags, your own data, common failures | +| [REPRODUCE](docs/REPRODUCE.md) | Rerun the benchmarks | +| [BENCHMARK_RESULTS](docs/BENCHMARK_RESULTS.md) | Qwen3.5-2B and 4B results, per-layout settings, what moved the numbers | +| [CONTRACTS](docs/CONTRACTS.md) | Public API guarantees, errors, supported layouts | +| [ENGINEERING](docs/ENGINEERING.md) | Design | + +## Limitations + +- **Scale.** Benchmarked on one 8-GPU node and on two 8× H100 nodes. Two nodes is the most it has run on. +- **Schedule.** 1F1B only, no interleaved stages. No global-norm gradient clipping: a nonzero `gradient_clipping` is rejected. +- **Weights.** No parameters tied across stages. +- **Colocated vision.** It matches the unsplit model. On 32 GB GPUs it needs encoder recompute and is slower; on 80 GB H100s it was the fastest Qwen3.5-4B layout. +- **Balanced cuts.** The cost model ignores communication and counts MoE experts in full, not by the active fraction. `ExplicitCuts` overrides it. +- **Checkpoints.** Node-local: they survive actor loss, not node loss. A stage that spans nodes needs shared storage. diff --git a/training/rdsp/bench/analyze.py b/training/rdsp/bench/analyze.py new file mode 100644 index 000000000..b6868e9c0 --- /dev/null +++ b/training/rdsp/bench/analyze.py @@ -0,0 +1,147 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team + +"""Turn modal_bench.py grid results (bench/results/*.json) into Markdown tables. + + python bench/analyze.py bench/results/.json [> table.md] + +Per cell: median / p90 step time over the measured steps, tokens/s, +tokens/s/GPU, MFU (one FLOP formula for both frameworks), pipeline +efficiency E = tokens/s(PP=p) / (p x tokens/s(PP=1, same system and s)), +the textbook bubble (p-1)/(m+p-1), and NVML peak memory (max over GPUs). +""" + +import json +import statistics +import sys +from collections import defaultdict + +H100_BF16_DENSE = 989e12 +L, H, Q, KV, FFN, V = 28, 1024, 2048, 1024, 3072, 151936 + + +def _flops(s: int) -> float: + """Training FLOPs per token, Megatron's convention: 3x the forward GEMMs, + causal core attention counted at half.""" + per_layer_gemm = 2 * (H * (Q + 2 * KV) + Q * H) + 2 * 3 * H * FFN # 31.46 MFLOP + lm_head = 2 * H * V # 311.16 MFLOP + core_attention = 2 * 2 * Q * s / 2 # per layer + return 3 * (L * per_layer_gemm + lm_head + L * core_attention) + + +def rows_per_microbatch(seq): + """Every grid cell has 2048 tokens per microbatch.""" + return 4 if seq == 512 else 1 + + +def summarize(records): + out = [] + for r in records: + c, res = r["cell"], r["result"] + steps = res.get("step_s") or [] + gpus = c["pp"] - 1 + c.get("last_stage_gpus", 1) + label = c["system"] + (f" ({c['tag']})" if c.get("tag") else "") + row = dict( + system=label, + pp=c["pp"], + m=c["m"], + seq=c["seq"], + gpus=gpus, + rep=c.get("rep", 0), + rc=r["rc"], + peak_gb=max(r["nvml_peak_bytes"].values(), default=0) / 1e9, + ) + if steps: + med = statistics.median(steps) + tokens = rows_per_microbatch(c["seq"]) * c["seq"] * c["m"] + tps = tokens / med + row.update( + median_s=med, + p90_s=sorted(steps)[int(0.9 * (len(steps) - 1))], + tok_s=tps, + tok_s_gpu=tps / gpus, + mfu=_flops(c["seq"]) * tps / (gpus * H100_BF16_DENSE), + ) + out.append(row) + return out + + +def with_efficiency(rows): + base = defaultdict(list) + for r in rows: + if r["pp"] == 1 and "tok_s" in r: + base[(r["system"], r["seq"])].append(r["tok_s"]) + for r in rows: + family = r["system"].split(" ")[0] + # each system vs its own PP=1 baseline; transport only matters at PP>1, + # so the RDT variants share the object-store PP=1 baseline + family = {"R-rdt": "R-os", "R-rdt-fused": "R-os-fused"}.get(family, family) + key = (family, r["seq"]) + if "tok_s" in r and base.get(key): + r["eff"] = r["tok_s"] / (r["pp"] * statistics.median(base[key])) + r["bubble_textbook"] = (r["pp"] - 1) / (r["m"] + r["pp"] - 1) + return rows + + +def table(rows): + hdr = ( + "| system | PP | GPUs | m | seq | step (median / p90) | tokens/s | tokens/s/GPU | MFU " + "| efficiency E | textbook bubble | peak GB |" + ) + lines = [hdr, "|" + "---|" * 12] + for r in sorted(rows, key=lambda r: (r["seq"], r["pp"], r["m"], r["system"])): + if "tok_s" not in r: + lines.append( + f"| {r['system']} | {r['pp']} | {r['gpus']} | {r['m']} | {r['seq']} " + f"| FAILED rc={r['rc']} | | | | | | {r['peak_gb']:.1f} |" + ) + continue + eff = f"{r['eff']:.2f}" if "eff" in r else "–" + lines.append( + f"| {r['system']} | {r['pp']} | {r['gpus']} | {r['m']} | {r['seq']} " + f"| {r['median_s'] * 1000:.0f} / {r['p90_s'] * 1000:.0f} ms | {r['tok_s']:,.0f} " + f"| {r['tok_s_gpu']:,.0f} | {100 * r['mfu']:.1f}% | {eff} " + f"| {r['bubble_textbook']:.2f} | {r['peak_gb']:.1f} |" + ) + return "\n".join(lines) + + +def ratios(rows): + """rdsp / Megatron throughput per (PP, m, seq).""" + by = {(r["system"], r["pp"], r["m"], r["seq"]): r for r in rows if "tok_s" in r} + lines = [ + "| PP | m | seq | R-os-fused / M-defaults | R-rdt-fused / M-defaults " + "| R-os / M-plain | R-rdt / R-os |", + "|---|---|---|---|---|---|---|", + ] + keys = sorted( + {(pp, m, seq) for (_, pp, m, seq) in by if pp > 1}, key=lambda k: (k[2], k[0], k[1]) + ) + + def ratio(num, den, pp, m, seq): + a, b = by.get((num, pp, m, seq)), by.get((den, pp, m, seq)) + return f"{a['tok_s'] / b['tok_s']:.2f}" if a and b else "–" + + for pp, m, seq in keys: + cols = [ + ratio(num, den, pp, m, seq) + for num, den in ( + ("R-os-fused", "M-defaults"), + ("R-rdt-fused", "M-defaults"), + ("R-os", "M-plain"), + ("R-rdt", "R-os"), + ) + ] + lines.append(f"| {pp} | {m} | {seq} | " + " | ".join(cols) + " |") + return "\n".join(lines) + + +if __name__ == "__main__": + records = [] + for path in sys.argv[1:]: + with open(path) as f: + records += json.load(f) + rows = with_efficiency(summarize(records)) + print(table(rows)) + print() + print(ratios(rows)) diff --git a/training/rdsp/bench/bench_hooks.py b/training/rdsp/bench/bench_hooks.py new file mode 100644 index 000000000..0cce779f9 --- /dev/null +++ b/training/rdsp/bench/bench_hooks.py @@ -0,0 +1,188 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team + +"""Stage builders and engine factories that rdsp_bench.py injects into rdsp. + +Imported inside the stage actors (rdsp_bench.py puts this directory on their +PYTHONPATH). The engine proxies wrap rdsp's own DeepSpeed engine factory +unmodified, so timing and profiling add no code to the measured path beyond +the proxy calls. +""" + +import json +import os +import time + +import torch + +from ray_deepspeed_pipeline.deepspeed_adapter import _deepspeed_engine_factory +from ray_deepspeed_pipeline.partition import build_causal_lm_stage + +OUT = os.environ.get("RDSP_BENCH_DIR", "/tmp/rdsp_bench") +WARMUP = int(os.environ.get("RDSP_BENCH_WARMUP", "10")) + + +def tagged_stage_builder(model, start, stop, names): + m = build_causal_lm_stage(model, start, stop, names) + m.bench_tag = f"blocks{start:02d}-{stop:02d}" + return m + + +class TimedEngine: + """Engine proxy: CUDA-event timing and NVTX ranges per forward, backward + and optimizer step. One host sync per optimizer step; one JSON line per + step in OUT. Peak-memory stats reset after WARMUP steps.""" + + def __init__(self, engine, tag): + self._e, self._tag, self._ops, self._step = engine, tag, [], 0 + os.makedirs(OUT, exist_ok=True) + self._f = open(f"{OUT}/{tag}.rank{os.environ.get('RANK', '0')}.jsonl", "a") + + def __getattr__(self, name): + if name.startswith("_"): + raise AttributeError(name) + return getattr(self._e, name) + + def _timed(self, kind, fn, *args): + s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True) + t = time.monotonic_ns() + torch.cuda.nvtx.range_push(f"{self._tag}.{kind}") + s.record() + out = fn(*args) + e.record() + torch.cuda.nvtx.range_pop() + self._ops.append((kind, t, s, e)) + return out + + def __call__(self, x, **kw): + return self._timed("fwd", lambda t: self._e(t, **kw), x) + + def backward(self, loss): + return self._timed("bwd", self._e.backward, loss) + + def step(self): + out = self._timed("opt", self._e.step) + torch.cuda.synchronize() + self._f.write( + json.dumps( + { + "tag": self._tag, + "pid": os.getpid(), + "step": self._step, + "ops": [(k, t, s.elapsed_time(e)) for k, t, s, e in self._ops], + "max_alloc": torch.cuda.max_memory_allocated(), + "max_reserved": torch.cuda.max_memory_reserved(), + } + ) + + "\n" + ) + self._f.flush() + self._ops.clear() + self._step += 1 + if self._step == WARMUP: + torch.cuda.reset_peak_memory_stats() + return out + + +def timed_engine_factory(stage_module, ds_config): + return TimedEngine( + _deepspeed_engine_factory(stage_module, ds_config), + getattr(stage_module, "bench_tag", "stage"), + ) + + +# Fused kernels, to match Megatron's default fusions. Liger replaces Qwen3's +# RMSNorm and SwiGLU MLP classes and its rotary function. The class swaps +# travel with the pickled stage modules, but the rotary patch is a module-level +# function in transformers, so every stage worker applies it too. + + +def apply_fusions(): + from liger_kernel.transformers import apply_liger_kernel_to_qwen3 + + apply_liger_kernel_to_qwen3( + rope=True, rms_norm=True, swiglu=True, cross_entropy=False, fused_linear_cross_entropy=False + ) + + +def fused_engine_factory(stage_module, ds_config): + apply_fusions() + return _deepspeed_engine_factory(stage_module, ds_config) + + +def fused_timed_engine_factory(stage_module, ds_config): + apply_fusions() + return timed_engine_factory(stage_module, ds_config) + + +# Kernel profile: same tool and window as megatron_hf_loop.py --prof_out. +PROF_START, PROF_STOP = 20, 30 # optimizer steps [20, 30): 10 steady-state steps + + +def kernel_table(prof): + """{kernel name: [calls, total device us]} from a torch.profiler run.""" + out = {} + for e in prof.key_averages(): + t = getattr(e, "self_device_time_total", None) + if t is None: + t = getattr(e, "self_cuda_time_total", 0) + if t and str(getattr(e, "device_type", "")).endswith("CUDA"): + out[e.key] = [e.count, t] + return out + + +class ProfiledEngine: + """Engine proxy: torch.profiler around optimizer steps [PROF_START, + PROF_STOP); writes the kernel table to OUT/prof_.json.""" + + def __init__(self, engine, tag): + self._e, self._tag, self._n, self._prof, self._t0 = engine, tag, 0, None, 0.0 + + def __getattr__(self, name): + if name.startswith("_"): + raise AttributeError(name) + return getattr(self._e, name) + + def __call__(self, x, **kw): + return self._e(x, **kw) + + def backward(self, loss): + return self._e.backward(loss) + + def step(self): + out = self._e.step() + self._n += 1 + if self._n == PROF_START: + torch.cuda.synchronize() + self._prof = torch.profiler.profile( + activities=[ + torch.profiler.ProfilerActivity.CPU, + torch.profiler.ProfilerActivity.CUDA, + ] + ) + self._prof.__enter__() + self._t0 = time.perf_counter() + elif self._n == PROF_STOP and self._prof is not None: + torch.cuda.synchronize() + wall = time.perf_counter() - self._t0 + self._prof.__exit__(None, None, None) + os.makedirs(OUT, exist_ok=True) + with open(f"{OUT}/prof_{self._tag}.json", "w") as f: + json.dump( + { + "steps": PROF_STOP - PROF_START, + "wall_s": wall, + "kernels": kernel_table(self._prof), + }, + f, + ) + self._prof = None + return out + + +def fused_prof_engine_factory(stage_module, ds_config): + apply_fusions() + return ProfiledEngine( + _deepspeed_engine_factory(stage_module, ds_config), + getattr(stage_module, "bench_tag", "stage"), + ) diff --git a/training/rdsp/bench/bridge_vs_rdsp/27b_tp1pp8dp1/results/nov21_images_per_pass.md b/training/rdsp/bench/bridge_vs_rdsp/27b_tp1pp8dp1/results/nov21_images_per_pass.md new file mode 100644 index 000000000..48a7ce2dd --- /dev/null +++ b/training/rdsp/bench/bridge_vs_rdsp/27b_tp1pp8dp1/results/nov21_images_per_pass.md @@ -0,0 +1,74 @@ +# 27B, eight stages of one H100: images per microbatch, and each side's best + +Qwen3.5-27B, TP1 x PP8 x DP1 on one 8× H100 node, 64 CORD-v2 rows a step (Megatron-Bridge's +export, replayed by rdsp), every row padded to 2,048, BF16 gradient accumulation. Settings +otherwise as the blog's runs (`scripts/run.sh`, `scripts/rdsp.sh`, `scripts/rdsp_tune.sh`). +Median of steps 6-50. Bridge runs at the cut rdsp measured for the same images per microbatch. +Logs in `../logs/`. + +The runs come from two machines of the same type: `*-nov21fix-*` logs from one, `*-nov21-*` logs +from the other. Compare numbers within one table. + +## Each side's best setting per images per microbatch, one machine + +| Images per microbatch | DeepSpeed (rdsp) | Megatron-Bridge | Faster | +|---|---|---|---| +| 1 | 10.66 s | 15.13 s | DeepSpeed 1.42x | +| 2 | **9.28 s** | **9.78 s** | DeepSpeed 1.05x | +| 4 | 11.33 s | 10.47 s | Bridge 1.08x | +| 8 | out of memory (stage 0, 15 GiB allocation) | out of memory (last stage) | neither fits | + +Logs: `rdsp-nov21fix-rows{1,2,4,8}-best.log`, `bridge-nov21fix-mbs{1,2,4,8}-best.log`. + +Each side's best overall is 2 per microbatch: DeepSpeed 9.28 s against Bridge 9.78 s, 1.05x. + +rdsp's setting is recompute per stage (`RC_PER`: blocks recomputed, counted at the calibration +cut): `6,8,7,7,6,5,3,0` at 1 and 2 per microbatch and `6,9,8,8,8,7,5,4` at 4. The calibration cut +gives stages 0-7 6, 9, 9, 9, 9, 9, 8 and 5 blocks, so at 1 and 2 per microbatch they keep 0, 1, 2, +2, 3, 4, 5 and 5 blocks' activations. At 8 per microbatch every block is recomputed. Bridge +recomputes every layer at every size; its lighter options did not fit (below). + +## Every layer recomputed on both, the other machine + +| Images per microbatch | DeepSpeed | Bridge | | +|---|---|---|---| +| 1 | 11.09 s | 14.79 s | DeepSpeed 1.33x | +| 2 | 10.03 s | 9.90 s | Bridge 1.01x | +| 4 | 11.24 s | 10.27 s | Bridge 1.09x | + +Logs: `rdsp-nov21-rows{1,2,4}.log`, `bridge-nov21-mbs{1,2,4}.log`. + +## What was tried (16-step trials at 2 per microbatch, steps 6-16) + +| Trial | Result | Log | +|---|---|---| +| rdsp, decoder blocks compiled (Liger off) | 11.36 s: 13% slower per stage (calibration 7.6 against 6.7 s) | `rdsp-nov21fix-rows2-compile.log` | +| rdsp, recompute 6 of 9 blocks on every stage | out of memory on stages 1-2 (7 and 6 microbatches in flight) | `rdsp-nov21fix-rows2-rc6.log` | +| rdsp, recompute per stage (`RC_PER=6,8,7,7,6,5,3,0`) | 9.45 s (50 steps: 9.28 s) | `rdsp-nov21fix-rows2-per1.log` | +| Bridge, `recompute_method=block` with 9 and 8 layers | out of memory on stage 0: the vision encoder takes the language config's recompute setting (`get_vision_model_config`) | `bridge-nov21fix-mbs2-block{9,8}.log` | +| Bridge, selective recompute | out of memory (stages 0-2) | `bridge-nov21fix-mbs2-selective.log` | + +Bridge's vision CUDA graphs cannot be turned on for Qwen3.5 in v0.6.0: the Qwen3.5 provider has +no `vision_cuda_graph_impl`. + +## Bridge at 1 per microbatch on four machines + +The same Bridge setting (every layer recomputed, rdsp's measured cut of that run) on four machines +of the same type: 14.34 s (`bridge-gap-cut1.log`), 14.45 s (`bridge-nov11.log`), 14.79 s +(`bridge-nov21-mbs1.log`) and 15.13 s (`bridge-nov21fix-mbs1-best.log`). + +## Why + +- 1 per microbatch: stage 0 (vision encoder + 1 layer) paces both. Bridge's encoder costs more per + image on the CPU: 173 against 114 ms per image with recompute (`../../../encoder_test/results.md`). +- 2 per microbatch: the language stages pace. rdsp's per-stage recompute lets late stages (fewer + microbatches in flight) keep activations. Bridge cannot recompute its language layers less + without its vision encoder also recomputing less, and that does not fit stage 0. +- 4 per microbatch: rdsp's `--profile` run with every block recomputed + (`../logs/rdsp-nov21fix-rows4-profile-all.log`, 16 steps) shows the busiest stage, stage 6 (10 + layers), at 7.38 s of an 11.4 s step. The 1F1B schedule needs 10.6 s at that stage, plus 0.25 s + for the optimizer step, so about 0.6 s is pipeline overhead; 3 of the 16 steps took 17-18 s. + Bridge at 10.47 s sits at about its floor. rdsp's measured cut leaves stage 7 at 5.42 s against + 7.38 s. +- 8 per microbatch: 8 microbatches for 8 stages, so the pipeline is idle 47% of each step; neither + fits in memory. diff --git a/training/rdsp/bench/bridge_vs_rdsp/27b_tp1pp8dp1/scripts/rdsp.sh b/training/rdsp/bench/bridge_vs_rdsp/27b_tp1pp8dp1/scripts/rdsp.sh new file mode 100755 index 000000000..2d53d3fdc --- /dev/null +++ b/training/rdsp/bench/bridge_vs_rdsp/27b_tp1pp8dp1/scripts/rdsp.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team +# 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/bridge_vs_rdsp/27b_tp1pp8dp1/scripts/rdsp_tune.sh b/training/rdsp/bench/bridge_vs_rdsp/27b_tp1pp8dp1/scripts/rdsp_tune.sh new file mode 100644 index 000000000..2d4528cdc --- /dev/null +++ b/training/rdsp/bench/bridge_vs_rdsp/27b_tp1pp8dp1/scripts/rdsp_tune.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team +# rdsp_tune.sh: rdsp.sh's 27B run (TP1 x PP8 x DP1, 8 x H100) with extra knobs, everything else as +# rdsp.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/bridge_vs_rdsp/27b_tp1pp8dp1/scripts/run.sh b/training/rdsp/bench/bridge_vs_rdsp/27b_tp1pp8dp1/scripts/run.sh new file mode 100755 index 000000000..1628cb0a9 --- /dev/null +++ b/training/rdsp/bench/bridge_vs_rdsp/27b_tp1pp8dp1/scripts/run.sh @@ -0,0 +1,78 @@ +#!/bin/bash +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team +# run.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/gap_round/scripts/prep.sh makes both). +# +# 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/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) +# -> profiles/pyspy-bridge-.txt, and the stage of each pid in +# 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; mkdir -p "$LOGS" +RUNS=$RDSP/bench/mimo/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/bridge_vs_rdsp/27b_tp4pp2dp1/scripts/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=$HERE/../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.sh" ${RDSP_ARGS:-}) 2>&1 | tee "$LOGS/rdsp${NAME:-}.log" ;; + *) sed -n 2,18p "$0"; exit 1 ;; +esac diff --git a/training/rdsp/bench/bridge_vs_rdsp/27b_tp4pp2dp1/scripts/meg_extra_bf16.txt b/training/rdsp/bench/bridge_vs_rdsp/27b_tp4pp2dp1/scripts/meg_extra_bf16.txt new file mode 100644 index 000000000..b10398aaf --- /dev/null +++ b/training/rdsp/bench/bridge_vs_rdsp/27b_tp4pp2dp1/scripts/meg_extra_bf16.txt @@ -0,0 +1 @@ +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/bridge_vs_rdsp/9b_tp4pp2dp1/scripts/rdsp.sh b/training/rdsp/bench/bridge_vs_rdsp/9b_tp4pp2dp1/scripts/rdsp.sh new file mode 100755 index 000000000..739f2f4d7 --- /dev/null +++ b/training/rdsp/bench/bridge_vs_rdsp/9b_tp4pp2dp1/scripts/rdsp.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team +# 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/bridge_vs_rdsp/9b_tp4pp2dp1/scripts/run.sh b/training/rdsp/bench/bridge_vs_rdsp/9b_tp4pp2dp1/scripts/run.sh new file mode 100755 index 000000000..935daa363 --- /dev/null +++ b/training/rdsp/bench/bridge_vs_rdsp/9b_tp4pp2dp1/scripts/run.sh @@ -0,0 +1,124 @@ +#!/bin/bash +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team +# run.sh : one step of the 9B TP4xPP2xDP1 comparison, on the H100 box, +# after bench/setup_node.sh. Logs go to ../logs (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 ../profiles +# backtrace like nsys, plus the Python call stack of every CPU-GPU sync +# (reports 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): 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; mkdir -p "$LOGS" +RUNS=$RDSP/bench/mimo/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=$HERE/../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.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 2,15p "$0"; exit 1 ;; +esac diff --git a/training/rdsp/bench/encoder_test/enc_bench.py b/training/rdsp/bench/encoder_test/enc_bench.py new file mode 100644 index 000000000..3f0fa3052 --- /dev/null +++ b/training/rdsp/bench/encoder_test/enc_bench.py @@ -0,0 +1,681 @@ +#!/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_test/grids.py b/training/rdsp/bench/encoder_test/grids.py new file mode 100644 index 000000000..0fbf46ce0 --- /dev/null +++ b/training/rdsp/bench/encoder_test/grids.py @@ -0,0 +1,40 @@ +#!/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 (bridge_vs_rdsp/9b_tp4pp2dp1/logs/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/encoder_test/results.md b/training/rdsp/bench/encoder_test/results.md new file mode 100644 index 000000000..507e3cb12 --- /dev/null +++ b/training/rdsp/bench/encoder_test/results.md @@ -0,0 +1,137 @@ +# Vision encoder alone on one H100: Megatron-Bridge (Transformer Engine) against Hugging Face + +The question: is Hugging Face's encoder cheaper per call than Megatron-Bridge's, which is built from +Transformer Engine modules, and why? + +## Setup + +- Model: the Qwen3.5-27B vision encoder (27 layers, width 1,152; the 9B's is the same but for the + merger's output), random weights, bf16, train mode. +- Bridge's encoder is built exactly as its Qwen3VLModel does (`enc_bench.py build_bridge`, + Megatron-Bridge v0.6.0, TE 2.18, NeMo 26.08 container). +- Hugging Face's uses SDPA attention, as the blog's rdsp runs did. It runs in rdsp's venv (torch + 2.13.0, transformers 5.17.0) and in the NeMo container (its torch, transformers 5.12.1). +- Images: 64 real CORD-v2 receipts through the Qwen3.5 processor capped at 1,000,000 pixels: 3,211 + patches per image on average, against 3,203 in the training rows (`grids.py`, `results/grids.log`, + `results/round2/export_grids.txt`). +- Time: the median of 3 passes over the 64 images, synchronized per call, no profiler. +- GPU work, kernels, syncs and the per-part split come from a separate profiled pass of 16 images. + The profiler slows the CPU side, so per-part CPU times are for comparison only. +- Hardware: round 1 on one H100 80GB (`results/hardware.txt`); round 2 on an 8× H100 node, four + jobs at a time, one GPU each (`results/round2/hardware4.txt`). + +## How to run + +Run from `bench/encoder_test`, with the Qwen3.5-27B config files downloaded (no weights needed) and +`HF_HUB_OFFLINE=1`. First the image grids: + +```bash +python grids.py results/grids.json 64 +``` + +Bridge runs in the NeMo container: + +```bash +C="docker run --gpus all --rm --ipc=host --shm-size=16g -v $HOME/hf:/root/.cache/huggingface \ + -v $HOME/rdsp:/rdsp -e HF_HOME=/root/.cache/huggingface -e HF_HUB_OFFLINE=1 \ + -w /rdsp/bench/encoder_test nvcr.io/nvidia/nemo:26.08" +$C python enc_bench.py --impl bridge --config Qwen/Qwen3.5-27B --images 1,2,4,8 \ + --grids results/grids.json --trace-dir results/traces --out results/bridge.json +``` + +Hugging Face runs in rdsp's venv: + +```bash +python enc_bench.py --impl hf --hf-attn sdpa --label hf-sdpa-rdsp --config Qwen/Qwen3.5-27B \ + --images 1,2,4,8 --grids results/grids.json --trace-dir results/traces --out results/hf-sdpa-rdsp.json +``` + +The other runs add flags to these two commands: + +| Run | Flags | +|---|---| +| Hugging Face in the container (`hf-sdpa-container`) | the Hugging Face command inside `$C`, `--modes fwd` | +| Every layer recomputed (`round2/*-rc`) | `--modes fwdbwd --recompute` | +| Timing repeats (`round2/*-r2`, `*-r3`) | `--profile-images 0` | +| Bridge's vision CUDA graphs (`round2/bridge-cg-*`) | `--images N --modes fwdbwd --cuda-graphs`, with `--recompute` for `bridge-cg-rc-*` | +| Hugging Face with per-layer CUDA graphs (`round2/hf-cg-*`, a prototype) | `--hf-attn varlen --hf-cuda-graphs --images N --modes fwdbwd` | +| The 35B-A3B encoder (`round2/*-35b`) | `--config Qwen/Qwen3.5-35B-A3B --images 1,8 --profile-images 0` | +| Bridge with the longest image length as an integer (`bridge-int-max-seqlen`) | `ENC_INT_MAX_SEQLEN=1`, `--images 1,8` | + +Each run writes its JSON (`--out`); `python summarize.py results/*.json` makes the tables in +`results/summary.md` and `results/round2/summary4.md`. `sync_stacks.py --grids results/grids.json` +(in the container) lists the lines that make the CPU wait for the GPU (`results/sync_stacks.txt`). + +## Every layer recomputed, as in the 27B training runs + +Per image, one image per call, forward and backward. Time is the median of three runs; GPU work +is from the profiled run. + +| | Bridge (TE) | Hugging Face, rdsp's venv | +|---|---|---| +| Time | 173 ms (172.3, 173.1, 175.6) | 114 ms (113.3, 114.8, 114.2) | +| GPU work | 73.8 ms | 62.4 ms | +| Time at 8 images per call | 75 ms (75.1, 74.6, 74.8) | 65 ms (64.6, 64.4, 64.9) | +| Time with Bridge's vision CUDA graphs | 78 ms (78.4, 78.5, 78.3) | | + +Files: `round2/bridge-rc*.json`, `round2/hf-sdpa-rdsp-rc*.json`, `round2/bridge-cg-rc-n1-r*.json`. +Megatron-Bridge v0.6.0 has no setting that turns these graphs on for Qwen3.5 in training. + +## Per image, one image per call, no recompute + +| | Bridge (TE) | Hugging Face, rdsp's venv | Hugging Face, NeMo container | +|---|---|---|---| +| Forward | 60.5 ms | 25.8 ms | 25.9 ms | +| Forward + backward | 123.0 ms | 74.7 ms | (cuDNN error in backward) | +| Forward GPU work | 18.5 ms | 15.5 ms | 15.6 ms | +| Forward GPU kernels | 1,238 | 782 | 798 | +| Forward CPU waits for the GPU | 131 | 94 | 88 | + +The same torch (container) gives Hugging Face the same time: the PyTorch version is not the cause. + +Round 2's repeats of these runs (`round2/bridge-r*`, `round2/hf-sdpa-rdsp-r*`) ran on a different +machine: forward + backward 115-117 ms for Bridge and 69-70 ms for Hugging Face. + +## Where the forward pass spends it, one image per call + +| Part | Kernels: Bridge | Kernels: HF | GPU ms: Bridge | GPU ms: HF | CPU ms traced: Bridge | CPU ms traced: HF | +|---|---|---|---|---|---|---| +| Attention kernel call | 215 | 27 | 5.2 | 4.3 | 21.7 | 3.5 | +| Linear layers (TE's fuse the layer norm) | 162 | 108 + 54 norm | 4.4 | 3.8 + 0.6 | 24.8 | 8.4 + 3.6 | +| Rotary position embedding | 648 | 378 | 5.4 | 4.6 | 22.6 | 11.2 | +| Rest of attention, MLP, layer, outside | 213 | 215 | 3.5 | 2.2 | 23.0 | 20.4 | +| Total | 1,238 | 782 | 18.5 | 15.5 | 92.0 | 47.1 | + +- Attention: TE's DotProductAttention runs 8 kernels and about 6x the CPU time per layer for the + same fused attention kernel. +- Attention waits: TE's settings check (`utils.py:320 if sf != of`) and its fused call each read a + value back from the GPU twice per layer (`results/sync_stacks.txt`), because Bridge passes the + longest image length as a GPU tensor (`seqlens.max()`). Passing it as an integer removes 108 of + 131 waits but saves only 1.7 ms (60.5 to 58.8 ms): the waits are not the main cost. +- Linear layers: TE's linear modules cost about twice the CPU time of nn.Linear plus nn.LayerNorm. +- Rotary: Megatron Core's rotary code runs 24 kernels per layer (cos and sin recomputed for query and + key in every layer, scale by 1.0, casts, a trailing concat); Hugging Face's 14. + +## More images per call, no recompute + +| Images per call | Bridge fwd | HF fwd | Bridge fwd+bwd | HF fwd+bwd | Ratio fwd+bwd | +|---|---|---|---|---|---| +| 1 | 60.5 | 25.8 | 123.0 | 74.7 | 1.65x | +| 2 | 35.4 | 20.7 | 76.8 | 57.7 | 1.33x | +| 4 | 23.9 | 17.7 | 61.0 | 52.6 | 1.16x | +| 8 | 21.9 | 16.6 | 57.1 | 50.5 | 1.13x | + +ms per image. At 8 images per call both are close to their GPU work (Bridge 48.9 ms, HF 45.4 ms +forward + backward); what is left is Bridge's extra GPU work (more, smaller kernels). + +## Other round-2 results + +- 35B-A3B encoder, forward + backward, one image per call: Bridge 118.0 ms, Hugging Face 71.0 ms + (`round2/*-35b.json`). +- Bridge's vision CUDA graphs without recompute: 61.4 ms at one image per call, but slower at more + images per call (77, 114 and 188 ms per image at 2, 4 and 8), because each graph pads every image + to one length (`round2/bridge-cg-n*.json`). +- rdsp's varlen vision attention: forward + backward 80.5 ms at one image per call, against SDPA's + 74.7 ms (`round2/hf-varlen-rdsp.json`; round 1's `results/hf-varlen-rdsp.log` failed to load it). +- Hugging Face with per-layer CUDA graphs, a prototype: 78 ms per image at one image per call + without recompute, 98 ms with it (`round2/hf-cg-*.json`). diff --git a/training/rdsp/bench/encoder_test/results/round2/summary4.md b/training/rdsp/bench/encoder_test/results/round2/summary4.md new file mode 100644 index 000000000..3995647c8 --- /dev/null +++ b/training/rdsp/bench/encoder_test/results/round2/summary4.md @@ -0,0 +1,148 @@ +## Environments + +- bridge-35b: {"torch": "2.13.0a0+8145d630e8.nv26.06", "transformers": "5.12.1", "python": "3.12.3", "gpu": "NVIDIA H100 80GB HBM3", "params": 446571248, "transformer_engine": "2.18.0+15288857"} +- bridge-cg-n1-r2: {"torch": "2.13.0a0+8145d630e8.nv26.06", "transformers": "5.12.1", "python": "3.12.3", "gpu": "NVIDIA H100 80GB HBM3", "params": 460730096, "transformer_engine": "2.18.0+15288857"} +- bridge-cg-n1-r3: {"torch": "2.13.0a0+8145d630e8.nv26.06", "transformers": "5.12.1", "python": "3.12.3", "gpu": "NVIDIA H100 80GB HBM3", "params": 460730096, "transformer_engine": "2.18.0+15288857"} +- bridge-cg-n1: {"torch": "2.13.0a0+8145d630e8.nv26.06", "transformers": "5.12.1", "python": "3.12.3", "gpu": "NVIDIA H100 80GB HBM3", "params": 460730096, "transformer_engine": "2.18.0+15288857"} +- bridge-cg-n2: {"torch": "2.13.0a0+8145d630e8.nv26.06", "transformers": "5.12.1", "python": "3.12.3", "gpu": "NVIDIA H100 80GB HBM3", "params": 460730096, "transformer_engine": "2.18.0+15288857"} +- bridge-cg-n4: {"torch": "2.13.0a0+8145d630e8.nv26.06", "transformers": "5.12.1", "python": "3.12.3", "gpu": "NVIDIA H100 80GB HBM3", "params": 460730096, "transformer_engine": "2.18.0+15288857"} +- bridge-cg-n8: {"torch": "2.13.0a0+8145d630e8.nv26.06", "transformers": "5.12.1", "python": "3.12.3", "gpu": "NVIDIA H100 80GB HBM3", "params": 460730096, "transformer_engine": "2.18.0+15288857"} +- bridge-r2: {"torch": "2.13.0a0+8145d630e8.nv26.06", "transformers": "5.12.1", "python": "3.12.3", "gpu": "NVIDIA H100 80GB HBM3", "params": 460730096, "transformer_engine": "2.18.0+15288857"} +- bridge-r3: {"torch": "2.13.0a0+8145d630e8.nv26.06", "transformers": "5.12.1", "python": "3.12.3", "gpu": "NVIDIA H100 80GB HBM3", "params": 460730096, "transformer_engine": "2.18.0+15288857"} +- bridge-rc-r2: {"torch": "2.13.0a0+8145d630e8.nv26.06", "transformers": "5.12.1", "python": "3.12.3", "gpu": "NVIDIA H100 80GB HBM3", "params": 460730096, "transformer_engine": "2.18.0+15288857"} +- bridge-rc-r3: {"torch": "2.13.0a0+8145d630e8.nv26.06", "transformers": "5.12.1", "python": "3.12.3", "gpu": "NVIDIA H100 80GB HBM3", "params": 460730096, "transformer_engine": "2.18.0+15288857"} +- bridge-rc: {"torch": "2.13.0a0+8145d630e8.nv26.06", "transformers": "5.12.1", "python": "3.12.3", "gpu": "NVIDIA H100 80GB HBM3", "params": 460730096, "transformer_engine": "2.18.0+15288857"} +- hf-sdpa-rdsp-35b: {"torch": "2.13.0+cu130", "transformers": "5.17.0", "python": "3.12.16", "gpu": "NVIDIA H100 80GB HBM3", "params": 446571248} +- hf-sdpa-rdsp-r2: {"torch": "2.13.0+cu130", "transformers": "5.17.0", "python": "3.12.16", "gpu": "NVIDIA H100 80GB HBM3", "params": 460730096} +- hf-sdpa-rdsp-r3: {"torch": "2.13.0+cu130", "transformers": "5.17.0", "python": "3.12.16", "gpu": "NVIDIA H100 80GB HBM3", "params": 460730096} +- hf-sdpa-rdsp-rc-r2: {"torch": "2.13.0+cu130", "transformers": "5.17.0", "python": "3.12.16", "gpu": "NVIDIA H100 80GB HBM3", "params": 460730096} +- hf-sdpa-rdsp-rc-r3: {"torch": "2.13.0+cu130", "transformers": "5.17.0", "python": "3.12.16", "gpu": "NVIDIA H100 80GB HBM3", "params": 460730096} +- hf-sdpa-rdsp-rc: {"torch": "2.13.0+cu130", "transformers": "5.17.0", "python": "3.12.16", "gpu": "NVIDIA H100 80GB HBM3", "params": 460730096} +- hf-varlen-rdsp: {"torch": "2.13.0+cu130", "transformers": "5.17.0", "python": "3.12.16", "gpu": "NVIDIA H100 80GB HBM3", "params": 460730096} + +## fwd: per image + +| Encoder | Images per call | Time (ms) | GPU busy (ms) | GPU share | Kernels | Syncs | Traced time (ms) | +|---|---|---|---|---|---|---|---| +| bridge-35b | 1 | 64.3 | | | | | | +| bridge-35b | 8 | 21.8 | | | | | | +| bridge-r2 | 1 | 63.9 | | | | | | +| bridge-r2 | 2 | 33.2 | | | | | | +| bridge-r2 | 4 | 23.7 | | | | | | +| bridge-r2 | 8 | 21.9 | | | | | | +| bridge-r3 | 1 | 63.2 | | | | | | +| bridge-r3 | 2 | 33.6 | | | | | | +| bridge-r3 | 4 | 23.8 | | | | | | +| bridge-r3 | 8 | 21.8 | | | | | | +| hf-sdpa-rdsp-35b | 1 | 26.2 | | | | | | +| hf-sdpa-rdsp-35b | 8 | 16.5 | | | | | | +| hf-sdpa-rdsp-r2 | 1 | 26.8 | | | | | | +| hf-sdpa-rdsp-r2 | 2 | 20.0 | | | | | | +| hf-sdpa-rdsp-r2 | 4 | 17.5 | | | | | | +| hf-sdpa-rdsp-r2 | 8 | 16.5 | | | | | | +| hf-sdpa-rdsp-r3 | 1 | 26.3 | | | | | | +| hf-sdpa-rdsp-r3 | 2 | 20.1 | | | | | | +| hf-sdpa-rdsp-r3 | 4 | 17.5 | | | | | | +| hf-sdpa-rdsp-r3 | 8 | 16.6 | | | | | | +| hf-varlen-rdsp | 1 | 26.4 | 15.4 | 58% | 782 | 94 | 50.5 | +| hf-varlen-rdsp | 2 | 21.1 | 14.8 | 70% | 424 | 47 | 27.7 | +| hf-varlen-rdsp | 4 | 17.9 | 14.5 | 81% | 228 | 24 | 18.9 | +| hf-varlen-rdsp | 8 | 16.7 | 14.4 | 86% | 130 | 12 | 16.6 | + +## fwdbwd: per image + +| Encoder | Images per call | Time (ms) | GPU busy (ms) | GPU share | Kernels | Syncs | Traced time (ms) | +|---|---|---|---|---|---|---|---| +| bridge-35b | 1 | 118.0 | | | | | | +| bridge-35b | 8 | 57.0 | | | | | | +| bridge-cg-n1-r2 | 1 | 61.6 | | | | | | +| bridge-cg-n1-r3 | 1 | 61.0 | | | | | | +| bridge-cg-n1 | 1 | 61.4 | 54.7 | 89% | 1,501 | 20 | 64.1 | +| bridge-cg-n2 | 2 | 77.1 | 71.7 | 93% | 764 | 17 | 78.3 | +| bridge-cg-n4 | 4 | 114.0 | 108.4 | 95% | 391 | 16 | 113.9 | +| bridge-cg-n8 | 8 | 188.1 | 183.6 | 98% | 205 | 15 | 188.2 | +| bridge-r2 | 1 | 116.8 | | | | | | +| bridge-r2 | 2 | 75.8 | | | | | | +| bridge-r2 | 4 | 60.4 | | | | | | +| bridge-r2 | 8 | 57.2 | | | | | | +| bridge-r3 | 1 | 115.2 | | | | | | +| bridge-r3 | 2 | 75.4 | | | | | | +| bridge-r3 | 4 | 61.0 | | | | | | +| bridge-r3 | 8 | 57.0 | | | | | | +| bridge-rc-r2 | 1 | 173.1 | | | | | | +| bridge-rc-r2 | 2 | 100.5 | | | | | | +| bridge-rc-r2 | 4 | 80.3 | | | | | | +| bridge-rc-r2 | 8 | 74.6 | | | | | | +| bridge-rc-r3 | 1 | 175.6 | | | | | | +| bridge-rc-r3 | 2 | 106.7 | | | | | | +| bridge-rc-r3 | 4 | 79.9 | | | | | | +| bridge-rc-r3 | 8 | 74.8 | | | | | | +| bridge-rc | 1 | 172.3 | 73.8 | 43% | 4,068 | 293 | 272.7 | +| bridge-rc | 2 | 109.4 | 69.2 | 63% | 2,049 | 154 | 141.0 | +| bridge-rc | 4 | 81.7 | 66.1 | 81% | 1,034 | 84 | 86.3 | +| bridge-rc | 8 | 75.1 | 64.5 | 86% | 526 | 49 | 72.1 | +| hf-sdpa-rdsp-35b | 1 | 71.0 | | | | | | +| hf-sdpa-rdsp-35b | 8 | 50.5 | | | | | | +| hf-sdpa-rdsp-r2 | 1 | 70.0 | | | | | | +| hf-sdpa-rdsp-r2 | 2 | 57.2 | | | | | | +| hf-sdpa-rdsp-r2 | 4 | 52.5 | | | | | | +| hf-sdpa-rdsp-r2 | 8 | 50.4 | | | | | | +| hf-sdpa-rdsp-r3 | 1 | 68.7 | | | | | | +| hf-sdpa-rdsp-r3 | 2 | 57.1 | | | | | | +| hf-sdpa-rdsp-r3 | 4 | 52.6 | | | | | | +| hf-sdpa-rdsp-r3 | 8 | 50.5 | | | | | | +| hf-sdpa-rdsp-rc-r2 | 1 | 114.8 | | | | | | +| hf-sdpa-rdsp-rc-r2 | 2 | 77.9 | | | | | | +| hf-sdpa-rdsp-rc-r2 | 4 | 68.0 | | | | | | +| hf-sdpa-rdsp-rc-r2 | 8 | 64.4 | | | | | | +| hf-sdpa-rdsp-rc-r3 | 1 | 114.2 | | | | | | +| hf-sdpa-rdsp-rc-r3 | 2 | 79.6 | | | | | | +| hf-sdpa-rdsp-rc-r3 | 4 | 68.5 | | | | | | +| hf-sdpa-rdsp-rc-r3 | 8 | 64.9 | | | | | | +| hf-sdpa-rdsp-rc | 1 | 113.3 | 62.4 | 55% | 3,088 | 175 | 194.4 | +| hf-sdpa-rdsp-rc | 2 | 80.9 | 60.4 | 75% | 1,646 | 88 | 105.4 | +| hf-sdpa-rdsp-rc | 4 | 68.9 | 58.7 | 85% | 893 | 44 | 72.7 | +| hf-sdpa-rdsp-rc | 8 | 64.6 | 57.5 | 89% | 517 | 22 | 84.1 | +| hf-varlen-rdsp | 1 | 80.5 | 49.4 | 61% | 2,467 | 94 | 122.2 | +| hf-varlen-rdsp | 2 | 59.0 | 47.7 | 81% | 1,308 | 47 | 68.7 | +| hf-varlen-rdsp | 4 | 52.9 | 46.3 | 87% | 711 | 24 | 51.9 | +| hf-varlen-rdsp | 8 | 51.0 | 45.4 | 89% | 412 | 12 | 48.5 | + +## fwd, 1 image per call: kernels per image, by part + +| Part | bridge-35b | bridge-cg-n1-r2 | bridge-cg-n1-r3 | bridge-cg-n1 | bridge-cg-n2 | bridge-cg-n4 | bridge-cg-n8 | bridge-r2 | bridge-r3 | bridge-rc-r2 | bridge-rc-r3 | bridge-rc | hf-sdpa-rdsp-35b | hf-sdpa-rdsp-r2 | hf-sdpa-rdsp-r3 | hf-sdpa-rdsp-rc-r2 | hf-sdpa-rdsp-rc-r3 | hf-sdpa-rdsp-rc | hf-varlen-rdsp | +|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| +| rotary | | | | | | | | | | | | | | | | | | | 378 | +| core_attn | | | | | | | | | | | | | | | | | | | 27 | +| linear | | | | | | | | | | | | | | | | | | | 108 | +| norm | | | | | | | | | | | | | | | | | | | 54 | +| attn_other | | | | | | | | | | | | | | | | | | | 27 | +| mlp_other | | | | | | | | | | | | | | | | | | | 27 | +| layer_other | | | | | | | | | | | | | | | | | | | 54 | +| outside | | | | | | | | | | | | | | | | | | | 107 | + +## fwd, 1 image per call: GPU ms per image, by part + +| Part | bridge-35b | bridge-cg-n1-r2 | bridge-cg-n1-r3 | bridge-cg-n1 | bridge-cg-n2 | bridge-cg-n4 | bridge-cg-n8 | bridge-r2 | bridge-r3 | bridge-rc-r2 | bridge-rc-r3 | bridge-rc | hf-sdpa-rdsp-35b | hf-sdpa-rdsp-r2 | hf-sdpa-rdsp-r3 | hf-sdpa-rdsp-rc-r2 | hf-sdpa-rdsp-rc-r3 | hf-sdpa-rdsp-rc | hf-varlen-rdsp | +|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| +| rotary | | | | | | | | | | | | | | | | | | | 4.57 | +| core_attn | | | | | | | | | | | | | | | | | | | 4.31 | +| linear | | | | | | | | | | | | | | | | | | | 3.79 | +| norm | | | | | | | | | | | | | | | | | | | 0.58 | +| attn_other | | | | | | | | | | | | | | | | | | | 0.04 | +| mlp_other | | | | | | | | | | | | | | | | | | | 0.53 | +| layer_other | | | | | | | | | | | | | | | | | | | 0.34 | +| outside | | | | | | | | | | | | | | | | | | | 1.27 | + +## fwd, 1 image per call: CPU ms (traced, forward thread, exclusive) per image, by part + +| Part | bridge-35b | bridge-cg-n1-r2 | bridge-cg-n1-r3 | bridge-cg-n1 | bridge-cg-n2 | bridge-cg-n4 | bridge-cg-n8 | bridge-r2 | bridge-r3 | bridge-rc-r2 | bridge-rc-r3 | bridge-rc | hf-sdpa-rdsp-35b | hf-sdpa-rdsp-r2 | hf-sdpa-rdsp-r3 | hf-sdpa-rdsp-rc-r2 | hf-sdpa-rdsp-rc-r3 | hf-sdpa-rdsp-rc | hf-varlen-rdsp | +|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| +| rotary | | | | | | | | | | | | | | | | | | | 11.40 | +| core_attn | | | | | | | | | | | | | | | | | | | 3.67 | +| linear | | | | | | | | | | | | | | | | | | | 8.87 | +| norm | | | | | | | | | | | | | | | | | | | 3.85 | +| attn_other | | | | | | | | | | | | | | | | | | | 11.53 | +| mlp_other | | | | | | | | | | | | | | | | | | | 2.05 | +| layer_other | | | | | | | | | | | | | | | | | | | 3.82 | +| outside | | | | | | | | | | | | | | | | | | | 4.60 | diff --git a/training/rdsp/bench/encoder_test/results/summary.md b/training/rdsp/bench/encoder_test/results/summary.md new file mode 100644 index 000000000..c6e5f38b0 --- /dev/null +++ b/training/rdsp/bench/encoder_test/results/summary.md @@ -0,0 +1,74 @@ +## Environments + +- bridge: {"torch": "2.13.0a0+8145d630e8.nv26.06", "transformers": "5.12.1", "python": "3.12.3", "gpu": "NVIDIA H100 80GB HBM3", "params": 460730096, "transformer_engine": "2.18.0+15288857"} +- hf-sdpa-container: {"torch": "2.13.0a0+8145d630e8.nv26.06", "transformers": "5.12.1", "python": "3.12.3", "gpu": "NVIDIA H100 80GB HBM3", "params": 460730096, "transformer_engine": "2.18.0+15288857"} +- hf-sdpa-rdsp: {"torch": "2.13.0+cu130", "transformers": "5.17.0", "python": "3.12.16", "gpu": "NVIDIA H100 80GB HBM3", "params": 460730096} + +## fwd: per image + +| Encoder | Images per call | Time (ms) | GPU busy (ms) | GPU share | Kernels | Syncs | Traced time (ms) | +|---|---|---|---|---|---|---|---| +| bridge | 1 | 60.5 | 18.5 | 31% | 1,238 | 131 | 92.8 | +| bridge | 2 | 35.4 | 17.5 | 49% | 631 | 72 | 49.1 | +| bridge | 4 | 23.9 | 16.8 | 70% | 325 | 43 | 26.7 | +| bridge | 8 | 21.9 | 16.3 | 75% | 171 | 29 | 21.4 | +| hf-sdpa-container | 1 | 25.9 | 15.6 | 60% | 798 | 88 | 49.9 | +| hf-sdpa-container | 2 | 20.9 | 15.0 | 72% | 454 | 44 | 28.0 | +| hf-sdpa-container | 4 | 18.2 | 14.6 | 80% | 261 | 22 | 19.4 | +| hf-sdpa-container | 8 | 17.1 | 14.4 | 84% | 165 | 11 | 17.3 | +| hf-sdpa-rdsp | 1 | 25.8 | 15.5 | 60% | 782 | 94 | 47.8 | +| hf-sdpa-rdsp | 2 | 20.7 | 14.9 | 72% | 424 | 47 | 27.3 | +| hf-sdpa-rdsp | 4 | 17.7 | 14.5 | 82% | 228 | 24 | 18.5 | +| hf-sdpa-rdsp | 8 | 16.6 | 14.3 | 86% | 130 | 12 | 16.5 | + +## fwdbwd: per image + +| Encoder | Images per call | Time (ms) | GPU busy (ms) | GPU share | Kernels | Syncs | Traced time (ms) | +|---|---|---|---|---|---|---|---| +| bridge | 1 | 123.0 | 56.4 | 46% | 2,880 | 185 | 171.9 | +| bridge | 2 | 76.8 | 52.6 | 69% | 1,455 | 100 | 92.8 | +| bridge | 4 | 61.0 | 50.1 | 82% | 737 | 57 | 62.0 | +| bridge | 8 | 57.1 | 48.9 | 86% | 378 | 35 | 54.7 | +| hf-sdpa-rdsp | 1 | 74.7 | 49.5 | 66% | 2,467 | 94 | 111.7 | +| hf-sdpa-rdsp | 2 | 57.7 | 47.7 | 83% | 1,308 | 47 | 64.8 | +| hf-sdpa-rdsp | 4 | 52.6 | 46.3 | 88% | 711 | 24 | 51.4 | +| hf-sdpa-rdsp | 8 | 50.5 | 45.4 | 90% | 412 | 12 | 48.2 | + +## fwd, 1 image per call: kernels per image, by part + +| Part | bridge | hf-sdpa-container | hf-sdpa-rdsp | +|---|---|---|---| +| rotary | 648 | 432 | 378 | +| core_attn | 215 | 27 | 27 | +| linear | 162 | 108 | 108 | +| norm | | 54 | 54 | +| attn_other | | 27 | 27 | +| mlp_other | 54 | 27 | 27 | +| layer_other | 108 | 54 | 54 | +| outside | 51 | 69 | 107 | + +## fwd, 1 image per call: GPU ms per image, by part + +| Part | bridge | hf-sdpa-container | hf-sdpa-rdsp | +|---|---|---|---| +| rotary | 5.40 | 4.82 | 4.58 | +| core_attn | 5.19 | 4.33 | 4.32 | +| linear | 4.41 | 3.80 | 3.82 | +| norm | | 0.58 | 0.58 | +| attn_other | | 0.04 | 0.04 | +| mlp_other | 1.46 | 0.52 | 0.52 | +| layer_other | 0.86 | 0.34 | 0.34 | +| outside | 1.14 | 1.21 | 1.27 | + +## fwd, 1 image per call: CPU ms (traced, forward thread, exclusive) per image, by part + +| Part | bridge | hf-sdpa-container | hf-sdpa-rdsp | +|---|---|---|---| +| rotary | 22.62 | 12.57 | 11.22 | +| core_attn | 21.70 | 3.52 | 3.47 | +| linear | 24.79 | 8.93 | 8.36 | +| norm | | 3.70 | 3.59 | +| attn_other | 4.68 | 11.17 | 10.59 | +| mlp_other | 3.35 | 2.02 | 1.90 | +| layer_other | 7.38 | 3.86 | 3.62 | +| outside | 7.52 | 3.54 | 4.35 | diff --git a/training/rdsp/bench/encoder_test/summarize.py b/training/rdsp/bench/encoder_test/summarize.py new file mode 100644 index 000000000..c9ab69444 --- /dev/null +++ b/training/rdsp/bench/encoder_test/summarize.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team + +"""summarize.py ...: markdown tables from enc_bench.py results (files without +results, e.g. grids.json, are skipped).""" + +import json +import sys + +PARTS = ( + "rotary", + "core_attn", + "linear", + "norm", + "attn_other", + "mlp_other", + "layer_other", + "outside", + "outside_encoder", + "backward", +) + + +def f(x, nd=1): + return "" if x is None else f"{x:,.{nd}f}" + + +runs = [] +for path in sys.argv[1:]: + data = json.load(open(path)) + if isinstance(data, dict) and "results" in data: + runs.append(data) + +print("## Environments\n") +for r in runs: + label = r["results"][0]["label"] if r["results"] else r["args"]["label"] + print(f"- {label}: {json.dumps(r['env'])}") + +for mode in ("fwd", "fwdbwd"): + print(f"\n## {mode}: per image\n") + print( + "| Encoder | Images per call | Time (ms) | GPU busy (ms) | GPU share | Kernels | Syncs | " + "Traced time (ms) |" + ) + print("|---|---|---|---|---|---|---|---|") + for r in runs: + for x in r["results"]: + if x["mode"] != mode: + continue + busy = x.get("gpu_busy_ms_per_image") + share = f"{busy / x['ms_per_image']:.0%}" if busy else "" + print( + f"| {x['label']} | {x['images_per_call']} | {f(x['ms_per_image'])} | {f(busy)} | " + f"{share} | {f(x.get('kernels_per_image'), 0)} | " + f"{f(x.get('syncs_per_image'), 0)} | {f(x.get('traced_ms_per_image'))} |" + ) + +for what, key, nd in ( + ("kernels", "kernels_by_part_per_image", 0), + ("GPU ms", "gpu_ms_by_part_per_image", 2), + ("CPU ms (traced, forward thread, exclusive)", "cpu_ms_by_part_per_image", 2), +): + print(f"\n## fwd, 1 image per call: {what} per image, by part\n") + print("| Part | " + " | ".join(r["results"][0]["label"] for r in runs if r["results"]) + " |") + print("|---|" + "---|" * len(runs)) + for part in PARTS: + cells = [] + for r in runs: + x = next( + (x for x in r["results"] if x["mode"] == "fwd" and x["images_per_call"] == 1), {} + ) + cells.append(f(x.get(key, {}).get(part), nd)) + if any(cells): + print(f"| {part} | " + " | ".join(cells) + " |") diff --git a/training/rdsp/bench/encoder_test/sync_stacks.py b/training/rdsp/bench/encoder_test/sync_stacks.py new file mode 100644 index 000000000..dfd2b7071 --- /dev/null +++ b/training/rdsp/bench/encoder_test/sync_stacks.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team + +"""sync_stacks.py --grids grids.json: which Python lines in Megatron-Bridge's vision encoder make +the CPU wait for the GPU. One image per call, forward; torch.cuda.set_sync_debug_mode("warn") +flags every synchronizing operation, and the warning's Python stack names the line. +Prints each distinct call site (the innermost frames outside torch) with its count per image.""" + +import argparse +import collections +import json +import traceback +import warnings + +import enc_bench +import torch + +ap = argparse.ArgumentParser() +ap.add_argument("--grids", required=True) +ap.add_argument("--config", default="Qwen/Qwen3.5-27B") +ap.add_argument("--images", type=int, default=4) +args = ap.parse_args() + +enc, hf_vision = enc_bench.build_bridge(args.config) +grids = json.load(open(args.grids))[: args.images] +calls = enc_bench.make_calls("bridge", enc, hf_vision, grids, 1, "cuda") +for c in calls[:2]: + enc_bench.run_call("bridge", enc, c, False) +torch.cuda.synchronize() + +sites = collections.Counter() + + +def record(message, category, filename, lineno, file=None, line=None): + frames = [ + f + for f in traceback.extract_stack()[:-1] + if "/torch/" not in f.filename + and "warnings" not in f.filename + and "sync_stacks.py" not in f.filename + and "enc_bench.py" not in f.filename + ] + site = " <- ".join( + f"{f.filename.split('site-packages/')[-1].split('dist-packages/')[-1]}:{f.lineno} {f.line}" + for f in reversed(frames[-4:]) + ) + sites[site] += 1 + + +warnings.showwarning = record +warnings.simplefilter("always") +torch.cuda.set_sync_debug_mode("warn") +for c in calls: + enc_bench.run_call("bridge", enc, c, False) +torch.cuda.set_sync_debug_mode("default") +torch.cuda.synchronize() +total = sum(sites.values()) +print(f"{total / len(calls):.1f} synchronizing operations per image\n") +for site, n in sites.most_common(20): + print(f"{n / len(calls):6.1f} per image\n " + site.replace(" <- ", "\n <- ") + "\n") diff --git a/training/rdsp/bench/gap_round/mimo/patch.diff b/training/rdsp/bench/gap_round/mimo/patch.diff new file mode 100644 index 000000000..21054e334 --- /dev/null +++ b/training/rdsp/bench/gap_round/mimo/patch.diff @@ -0,0 +1,24 @@ +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/gap_round/mimo/patch_mimo.py b/training/rdsp/bench/gap_round/mimo/patch_mimo.py new file mode 100644 index 000000000..77247e268 --- /dev/null +++ b/training/rdsp/bench/gap_round/mimo/patch_mimo.py @@ -0,0 +1,55 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team + +"""patch_mimo.py : MegatronMIMO's Qwen3.5 VL launcher with Megatron- +Bridge's memory settings, so the dense 27B fits on two nodes. Results from it are labeled "MIMO +with our memory settings"; MIMO's library itself is unchanged. + +Changes, each asserted to match exactly once in the container's copy (NeMo 26.08): + 1. precision-aware optimizer: bf16 main gradients, fp32 master weights stored as bf16 + 2-byte + remainders (Bridge's settings in our runs; the launcher fixes fp32 gradients and master) + 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 +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. +""" + +import sys + +path = sys.argv[1] +src = open(path).read() +EDITS = [ + ( + " optimizer_cfg.use_precision_aware_optimizer = False\n" + " optimizer_cfg.main_grads_dtype = torch.float32\n" + " optimizer_cfg.main_params_dtype = torch.float32\n", + " optimizer_cfg.use_precision_aware_optimizer = True\n" + " optimizer_cfg.main_grads_dtype = torch.bfloat16\n" + " optimizer_cfg.main_params_dtype = torch.float32\n" + " optimizer_cfg.store_param_remainders = True\n", + ), + (" grad_reduce_in_fp32=True,\n", " grad_reduce_in_fp32=False,\n"), + ( + ' cfg.mixed_precision = "bf16_mixed" if not args.fp32 else None\n', + " from megatron.bridge.training.mixed_precision import bf16_mixed as _bf16_mixed\n" + " _mp = _bf16_mixed()\n" + " _mp.grad_reduce_in_fp32 = False\n" + " cfg.mixed_precision = _mp if not args.fp32 else None\n", + ), + ( + ' if hasattr(standard_provider, "mtp_num_layers"):\n', + ' if os.environ.get("MIMO_RECOMPUTE") == "1":\n' + ' standard_provider.recompute_granularity = "full"\n' + ' standard_provider.recompute_method = "uniform"\n' + " standard_provider.recompute_num_layers = 1\n" + ' if hasattr(standard_provider, "mtp_num_layers"):\n', + ), +] +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) diff --git a/training/rdsp/bench/gap_round/scripts/medians.py b/training/rdsp/bench/gap_round/scripts/medians.py new file mode 100644 index 000000000..9a802d85d --- /dev/null +++ b/training/rdsp/bench/gap_round/scripts/medians.py @@ -0,0 +1,75 @@ +# 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/gap_round/scripts/one_node.sh b/training/rdsp/bench/gap_round/scripts/one_node.sh new file mode 100755 index 000000000..0e74c2765 --- /dev/null +++ b/training/rdsp/bench/gap_round/scripts/one_node.sh @@ -0,0 +1,73 @@ +#!/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/bridge_vs_rdsp/27b_tp1pp8dp1 +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 "$P8/logs/nvsmi-bridge-gap-$name.csv" env NAME="-gap-$name" \ + MEG_RC="$RC_ALL $(layout "$lay") $FAST $*" bash "$P8/scripts/run.sh" bridge +} +titan() { # titan + run "titan-27b-$1" 40 "$TL/nvsmi-gap-$1.csv" env NAME=-gap bash "$B/torchtitan/scripts/run.sh" run "$1" +} +mkdir -p "$P8/logs" "$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/scripts/run.sh" run qwen35_27b_cord_pp8_rc + run rdsp-27b-pp8 40 "$P8/logs/nvsmi-rdsp-gap.csv" env NAME=-gap \ + RDSP_ARGS="--master-dtype remainder --cuts measured" bash "$P8/scripts/run.sh" rdsp ;; + *) sed -n 2,9p "$0"; exit 1 ;; +esac +mark "ONE NODE DONE $1" diff --git a/training/rdsp/bench/gap_round/scripts/prep.sh b/training/rdsp/bench/gap_round/scripts/prep.sh new file mode 100755 index 000000000..c8715fbfd --- /dev/null +++ b/training/rdsp/bench/gap_round/scripts/prep.sh @@ -0,0 +1,58 @@ +#!/bin/bash +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team +# prep.sh, on node 1 (docs/REPRODUCE.md lists what must be in place): both nodes ready. +# 1. two_node_35b/scripts/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 two_node_35b's prep. Logs in ../prep/logs. +set -uo pipefail # no -e: each step checks its own exit code and reports which one failed +RDSP=~/rdsp +G=$RDSP/bench/gap_round +. ~/env2.sh +LOGS=$G/prep/logs; 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/two_node_35b/scripts/prep.sh" > "$LOGS/prep35.log" 2>&1 +grep -q "^=== PREP DONE" "$LOGS/prep35.log" || { mark "PREP FAILED 35B (prep/logs/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/mimo/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/gap_round/scripts/rdsp9.sh b/training/rdsp/bench/gap_round/scripts/rdsp9.sh new file mode 100644 index 000000000..6fc317a89 --- /dev/null +++ b/training/rdsp/bench/gap_round/scripts/rdsp9.sh @@ -0,0 +1,24 @@ +#!/bin/bash +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team +# rdsp9.sh, on node 1 with the two-node Ray cluster up (bench/two_node/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/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/two_node_35b/scripts/common.sh # RDSP_COMMON, rdsp +export LOGS=~/rdsp/bench/gap_round/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/gap_round/scripts/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/megatron_hf_loop.py b/training/rdsp/bench/megatron_hf_loop.py new file mode 100644 index 000000000..801ef6c22 --- /dev/null +++ b/training/rdsp/bench/megatron_hf_loop.py @@ -0,0 +1,284 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team + +"""Megatron-Core pipeline training from the same pretrained Hugging Face Qwen3 +weights and the same token file as rdsp_bench.py, for matched loss and +throughput comparisons. + + torchrun --standalone --nproc_per_node 4 megatron_hf_loop.py \ + --hf /cache/qwen3-0.6b-untied --data /cache/text_s512_b4_m8.pt --steps 300 --out x.json + +Weights are mapped by hand (no Megatron-Bridge): HF q/k/v are interleaved per +query group into Megatron's fused linear_qkv, gate/up stacked into linear_fc1, +norms into the TE layer-norm slots. Every Megatron parameter must be written +exactly once or the run aborts. +""" + +import argparse +import gc +import json +import os +import time + +import torch +import torch.nn.functional as F +from megatron.core import parallel_state +from megatron.core.distributed import DistributedDataParallel, DistributedDataParallelConfig +from megatron.core.distributed.finalize_model_grads import finalize_model_grads +from megatron.core.models.gpt.gpt_layer_specs import get_gpt_layer_with_transformer_engine_spec +from megatron.core.models.gpt.gpt_model import GPTModel +from megatron.core.optimizer import OptimizerConfig, get_megatron_optimizer +from megatron.core.pipeline_parallel.schedules import get_forward_backward_func +from megatron.core.tensor_parallel.random import model_parallel_cuda_manual_seed +from megatron.core.transformer.transformer_config import TransformerConfig +from safetensors.torch import load_file + +p = argparse.ArgumentParser() +p.add_argument("--hf", required=True) +p.add_argument("--data", required=True) +p.add_argument("--steps", type=int, default=300) +p.add_argument("--lr", type=float, default=1e-5) +p.add_argument("--out", required=True) +p.add_argument( + "--grad_bf16", + type=int, + default=0, + help="sum gradients across microbatches in bf16 (--grad-reduce-in-bf16), " + "as DeepSpeed ZeRO-0 bf16 does; Megatron's default sums in fp32", +) +p.add_argument( + "--ce_impl", + default="native", + choices=["native", "te"], + help="Megatron's fused cross-entropy implementation", +) +p.add_argument("--prof_out", default="", help="torch.profiler kernel table for steps [20, 30)") +p.add_argument("--layout", default="", help="Megatron layer layout, e.g. PP=8: 'Et*4|...|t*3,L'") +a = p.parse_args() + +H, L, HEADS, GROUPS, HD, FFN, V = 1024, 28, 16, 8, 128, 3072, 151936 + +torch.distributed.init_process_group("nccl") +local = int(os.environ["LOCAL_RANK"]) +torch.cuda.set_device(local) +pp = torch.distributed.get_world_size() +parallel_state.initialize_model_parallel(1, pp) +model_parallel_cuda_manual_seed(1234) +first, last = parallel_state.is_pipeline_first_stage(), parallel_state.is_pipeline_last_stage() + +X = torch.load(a.data) # [steps, m, b, s+1] token ids, the same file rdsp reads +_, M, B, S1 = X.shape +S = S1 - 1 + +cfg = TransformerConfig( + num_layers=L, + hidden_size=H, + ffn_hidden_size=FFN, + num_attention_heads=HEADS, + num_query_groups=GROUPS, + kv_channels=HD, + normalization="RMSNorm", + layernorm_epsilon=1e-6, + gated_linear_unit=True, + activation_func=F.silu, + add_bias_linear=False, + add_qkv_bias=False, + qk_layernorm=True, + hidden_dropout=0.0, + attention_dropout=0.0, + bf16=True, + params_dtype=torch.bfloat16, + pipeline_dtype=torch.bfloat16, + pipeline_model_parallel_size=pp, + pipeline_model_parallel_layout=a.layout or None, + # Megatron's standard fusions (pretrain_gpt.py defaults); rdsp runs the + # matching Liger kernels (RoPE, RMSNorm, SwiGLU, cross-entropy) and fused + # Adam. Weight-gradient accumulation fusion has no rdsp equivalent; + # Megatron keeps it. + apply_rope_fusion=True, + bias_activation_fusion=True, + cross_entropy_loss_fusion=True, + cross_entropy_fusion_impl=a.ce_impl, + gradient_accumulation_fusion=True, +) +model = GPTModel( + config=cfg, + transformer_layer_spec=get_gpt_layer_with_transformer_engine_spec(qk_layernorm=True), + vocab_size=V, + max_sequence_length=40960, + pre_process=first, + post_process=last, + share_embeddings_and_output_weights=False, + position_embedding_type="rope", + rotary_percent=1.0, + rotary_base=1000000, +).cuda() + +hf = load_file(os.path.join(a.hf, "model.safetensors")) +params = dict(model.named_parameters()) +written = set() + + +def put(name, tensor): + assert name in params, f"no Megatron parameter {name}" + assert params[name].shape == tensor.shape, (name, params[name].shape, tensor.shape) + with torch.no_grad(): + params[name].copy_(tensor.to(params[name].dtype)) + written.add(name) + + +if first: + put("embedding.word_embeddings.weight", hf["model.embed_tokens.weight"]) +if last: + put("decoder.final_layernorm.weight", hf["model.norm.weight"]) + put("output_layer.weight", hf["lm_head.weight"]) +per_group = HEADS // GROUPS +for i, layer in enumerate(model.decoder.layers): + g = layer.layer_number - 1 # global HF layer index + pre, loc = f"model.layers.{g}.", f"decoder.layers.{i}." + q = hf[pre + "self_attn.q_proj.weight"].view(GROUPS, per_group * HD, H) + k = hf[pre + "self_attn.k_proj.weight"].view(GROUPS, HD, H) + v = hf[pre + "self_attn.v_proj.weight"].view(GROUPS, HD, H) + put(loc + "self_attention.linear_qkv.weight", torch.cat([q, k, v], 1).reshape(-1, H)) + put(loc + "self_attention.linear_qkv.layer_norm_weight", hf[pre + "input_layernorm.weight"]) + put(loc + "self_attention.q_layernorm.weight", hf[pre + "self_attn.q_norm.weight"]) + put(loc + "self_attention.k_layernorm.weight", hf[pre + "self_attn.k_norm.weight"]) + put(loc + "self_attention.linear_proj.weight", hf[pre + "self_attn.o_proj.weight"]) + put( + loc + "mlp.linear_fc1.weight", + torch.cat([hf[pre + "mlp.gate_proj.weight"], hf[pre + "mlp.up_proj.weight"]], 0), + ) + put(loc + "mlp.linear_fc1.layer_norm_weight", hf[pre + "post_attention_layernorm.weight"]) + put(loc + "mlp.linear_fc2.weight", hf[pre + "mlp.down_proj.weight"]) +missing = set(params) - written +assert not missing, f"Megatron parameters with no HF weight: {sorted(missing)[:8]}" +# every HF layer lives on exactly one rank (catches a wrong layout / offset) +mine = torch.zeros(L, device="cuda") +for layer in model.decoder.layers: + mine[layer.layer_number - 1] += 1 +torch.distributed.all_reduce(mine) +assert bool((mine == 1).all()), f"layer coverage {mine.tolist()}" +print( + f"rank {torch.distributed.get_rank()}: layers " + f"{[layer.layer_number - 1 for layer in model.decoder.layers]}", + flush=True, +) +del hf + +ddp = DistributedDataParallel( + config=cfg, + ddp_config=DistributedDataParallelConfig( + grad_reduce_in_fp32=not a.grad_bf16, + overlap_grad_reduce=False, + use_distributed_optimizer=False, + ), + module=model, +) +opt = get_megatron_optimizer( + OptimizerConfig( + optimizer="adam", + lr=a.lr, + min_lr=a.lr, + weight_decay=0.0, + adam_beta1=0.9, + adam_beta2=0.999, + adam_eps=1e-8, + clip_grad=0.0, + bf16=True, + use_distributed_optimizer=False, + ), + [ddp], +) +# printed so each run's log records which gradient-summing precision it used +print(f"main_grad dtype: {next(p for p in model.parameters()).main_grad.dtype}", flush=True) +for group in opt.param_groups: + group["lr"], group["weight_decay"] = a.lr, 0.0 +cfg.finalize_model_grads_func = finalize_model_grads +cfg.no_sync_func = ddp.no_sync + +pos = torch.arange(S, device="cuda").unsqueeze(0).expand(B, -1) + + +def batches(step): + for k in range(M): + x = X[step, k] + yield x[:, :-1].contiguous().cuda(), x[:, 1:].contiguous().cuda() + + +def forward_step(it, mdl): + tokens, labels = next(it) + out = mdl(tokens, pos, None, labels=labels) # per-token CE on the last stage + + def loss_func(o): + loss = o.float().mean() # mean over this microbatch's tokens, like rdsp's loss_fn + # clone: Megatron divides `loss` by num_microbatches IN PLACE afterwards, + # and a detached view would share that storage (logged value /M) + return loss, {"lm loss": loss.detach().clone()} + + return out, loss_func + + +fb = get_forward_backward_func() +gc.disable() # Megatron's --manual-gc, as in the M-defaults pretrain_gpt.py runs +losses, times = [], [] +prof, t_prof = None, 0.0 +for step in range(a.steps): + if a.prof_out and step == 20: # same window and tool as bench_hooks.ProfiledEngine + torch.cuda.synchronize() + prof = torch.profiler.profile( + activities=[torch.profiler.ProfilerActivity.CPU, torch.profiler.ProfilerActivity.CUDA] + ) + prof.__enter__() + t_prof = time.perf_counter() + if prof is not None and step == 30: + torch.cuda.synchronize() + wall = time.perf_counter() - t_prof + prof.__exit__(None, None, None) + if torch.distributed.get_rank() == 0: + from bench_hooks import kernel_table + + with open(a.prof_out, "w") as f: + json.dump({"steps": 10, "wall_s": wall, "kernels": kernel_table(prof)}, f) + prof = None + ddp.zero_grad_buffer() + opt.zero_grad() + torch.cuda.synchronize() + t0 = time.perf_counter() + out = fb( + forward_step_func=forward_step, + data_iterator=batches(step), + model=ddp, + num_microbatches=M, + seq_length=S, + micro_batch_size=B, + forward_only=False, + ) + opt.step() + torch.cuda.synchronize() + times.append(time.perf_counter() - t0) + if last: + losses.append(sum(float(d["lm loss"]) for d in out) / M) + if step % 25 == 0: + print( + f"megatron step {step} loss {losses[-1]:.4f} {times[-1] * 1000:.0f} ms", flush=True + ) + +if last: + with open(a.out, "w") as f: + json.dump( + { + "system": "megatron", + "pp": pp, + "m": M, + "b": B, + "seq": S, + "layout": a.layout, + "grad_bf16": a.grad_bf16, + "ce_impl": a.ce_impl, + "loss": losses, + "step_s": times, + }, + f, + ) +torch.distributed.barrier() +torch.distributed.destroy_process_group() diff --git a/training/rdsp/bench/megatron_pretrain.sh b/training/rdsp/bench/megatron_pretrain.sh new file mode 100755 index 000000000..eb4c8ca6b --- /dev/null +++ b/training/rdsp/bench/megatron_pretrain.sh @@ -0,0 +1,69 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team +# Megatron-LM pretrain_gpt.py, Qwen3-0.6B shape, mock data. One benchmark cell. +# PP=2 M=8 SEQ=2048 VARIANT=plain ./megatron_pretrain.sh +# PP=4 M=16 SEQ=512 VARIANT=vpp ./megatron_pretrain.sh +# VARIANT: plain = optional fusions off, bf16 grad summing (matched to unfused rdsp) +# defaults = Megatron's standard fusions +# vpp = defaults + interleaved (virtual) pipeline stages +# local = Megatron's non-TransformerEngine layers +set -euo pipefail +PP=${PP:-2}; M=${M:-8}; SEQ=${SEQ:-2048}; VARIANT=${VARIANT:-plain} +ITERS=${ITERS:-60}; TIMING=${TIMING:-0} # TIMING=2 for instrumented runs +MEGATRON=${MEGATRON:-/opt/Megatron-LM} +MBS=$(( SEQ == 512 ? 4 : 1 )); GBS=$(( MBS * M )) # 2048 tokens per microbatch + +MODEL=( + --num-layers 28 --hidden-size 1024 --ffn-hidden-size 3072 + --num-attention-heads 16 --group-query-attention --num-query-groups 8 + --kv-channels 128 --qk-layernorm + --normalization RMSNorm --norm-epsilon 1e-6 --swiglu --disable-bias-linear + --position-embedding-type rope --rotary-base 1000000 --rotary-percent 1.0 + --untie-embeddings-and-output-weights --max-position-embeddings 40960 + --attention-dropout 0.0 --hidden-dropout 0.0 --init-method-std 0.02 + --seq-length "$SEQ" + --vocab-size 151936 --make-vocab-size-divisible-by 128 + --tokenizer-type NullTokenizer --mock-data +) +TRAIN=( + --micro-batch-size "$MBS" --global-batch-size "$GBS" --train-iters "$ITERS" + --optimizer adam --lr 1e-5 --min-lr 1e-5 --lr-decay-style constant --lr-warmup-iters 0 + --weight-decay 0.0 --adam-beta1 0.9 --adam-beta2 0.999 --adam-eps 1e-8 + --clip-grad 0.0 --bf16 --seed 1234 + --eval-iters 0 --eval-interval "$ITERS" --log-interval 1 --log-throughput + --timing-log-level "$TIMING" --timing-log-option all +) +PAR=( --tensor-model-parallel-size 1 --pipeline-model-parallel-size "$PP" --context-parallel-size 1 ) + +case "$VARIANT" in + plain) + IMPL=( --transformer-impl transformer_engine --attention-backend flash + --no-gradient-accumulation-fusion --no-bias-swiglu-fusion --no-rope-fusion + --no-bias-dropout-fusion --no-persist-layer-norm --no-masked-softmax-fusion + --grad-reduce-in-bf16 --no-overlap-p2p-communication ) ;; + defaults|vpp) + export CUDA_DEVICE_MAX_CONNECTIONS=1 + IMPL=( --transformer-impl transformer_engine --attention-backend auto + --cross-entropy-loss-fusion --manual-gc ) + if [[ "$VARIANT" == vpp ]]; then + if [[ "$PP" == 2 ]]; then IMPL+=( --num-virtual-stages-per-pipeline-rank 2 ) + else IMPL+=( --pipeline-model-parallel-layout "Et*4|t*3|t*3|t*4|t*3|t*4|t*4|t*3,L" ); fi + fi ;; + local) + IMPL=( --transformer-impl local --no-gradient-accumulation-fusion --grad-reduce-in-bf16 ) ;; +esac +# Explicit layer layout (e.g. PP=8 with 28 layers, which does not divide evenly) +if [[ -n "${LAYOUT:-}" ]]; then + IMPL+=( --pipeline-model-parallel-layout "$LAYOUT" ) +fi +# Balanced split (PP=4): the LM head is ~1/4 of the FLOPs, so the last stage gets 1 layer +if [[ "${BALANCED:-0}" == 1 && "$PP" == 4 ]]; then + IMPL+=( --pipeline-model-parallel-layout "Et*9|t*9|t*9|t,L" ) +fi + +cd "$MEGATRON" +exec torchrun --standalone --nproc_per_node "$PP" pretrain_gpt.py \ + "${MODEL[@]}" "${TRAIN[@]}" "${PAR[@]}" "${IMPL[@]}" +# Parse from stdout: "elapsed time per iteration (ms)", "throughput per GPU", +# "lm loss", and at TIMING=2 the per-rank forward-compute/backward-compute/*-send/*-recv. diff --git a/training/rdsp/bench/mimo/bench.sh b/training/rdsp/bench/mimo/bench.sh new file mode 100755 index 000000000..8966576fb --- /dev/null +++ b/training/rdsp/bench/mimo/bench.sh @@ -0,0 +1,94 @@ +#!/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 +# vision2 MegatronMIMO vs rdsp: vision DP2 on 2 GPUs, language TP2xDP2 (6 GPUs) +# langpp2 MegatronMIMO vs rdsp: vision on 1 GPU, language TP2xPP2 (5 GPUs) +# langtp4 MegatronMIMO vs rdsp: vision on 1 GPU, language TP4 (5 GPUs) +# mimo noncoloc vision2 langpp2 langtp4 +# +# 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 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,19p "$0"; exit 1; } +[ $# -gt 0 ] || usage +layouts=() +for arg in "$@"; do + case $arg in + all) layouts+=(noncoloc tp2 tp4 coloc) ;; + mimo) layouts+=(noncoloc vision2 langpp2 langtp4) ;; + noncoloc|tp2|tp4|coloc|vision2|langpp2|langtp4) 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 ;; + vision2|langpp2|langtp4) echo "$1-mimo" "$1-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" ;; + vision2) echo "qwen35-$SIZE-vision2-tp2dp2.sh" ;; + langpp2) echo "qwen35-$SIZE-vision1-tp2pp2.sh" ;; + langtp4) echo "qwen35-$SIZE-vision1-tp4.sh" ;; + esac +} + +failed=0 +run() { # run + echo "run LOGS=$1 $2" + [ -n "${DRY_RUN:-}" ] && return 0 + LOGS=$1 bash "$HERE/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 "$HERE/summarize.py" "$logs" --price "$PRICE" | tee "$logs/summary.txt" + fi +done +exit $failed diff --git a/training/rdsp/bench/mimo/export_bridge_batches.py b/training/rdsp/bench/mimo/export_bridge_batches.py new file mode 100644 index 000000000..cc51b3a0b --- /dev/null +++ b/training/rdsp/bench/mimo/export_bridge_batches.py @@ -0,0 +1,122 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team + +"""Export Megatron-Bridge's own SFT samples, for rdsp to train on the same data. + +Runs inside the NeMo container. Builds the training dataset exactly as a +Megatron-Bridge recipe does (same Hugging Face source and schema adapter, +same processor and image pixel limits, same collate, sequence length and +padding), then collates each sample alone in index order. With +dataloader_type="single" Megatron reads samples in that same order for any +data-parallel width, and a global microbatch is consecutive samples, so rdsp +reading these files in order sees the same rows in the same microbatches. + +Per sample it keeps what the Hugging Face model needs (input ids, attention +mask, mm_token_type_ids, pixels, image grid) and the labels in the Hugging +Face convention: unshifted, -100 where the loss mask is 0. Pixels are stored +in bf16, the dtype the model casts them to. One file per training step. + + python export_bridge_batches.py --out /workspace/cord_steps --steps 50 \\ + --recipe qwen35_vl_9b_sft_4gpu_h100_bf16_config \\ + model.seq_length=2048 dataset.seq_length=2048 train.global_batch_size=64 \\ + dataset.source.dataset_name=cord_v2 +""" + +import argparse +import json +import os +import sys + +import torch + +IGNORE = -100 + + +def to_rdsp_sample(batch: dict) -> dict: + """One collated row (batch of 1) from the Bridge Qwen-VL collate: its + labels are shifted left (label t is the target of position t), so the + target of position t moves to t + 1 for a loss that shifts itself.""" + shifted = batch["labels"].masked_fill(batch["loss_mask"] == 0, IGNORE) + labels = torch.full_like(shifted, IGNORE) + labels[:, 1:] = shifted[:, :-1] + visual = batch["visual_inputs"] + return { + "input_ids": batch["input_ids"].clone(), + "attention_mask": batch["attention_mask"].clone(), + "mm_token_type_ids": batch["mm_token_type_ids"].clone(), + "pixel_values": visual.pixel_values.to(torch.bfloat16), + "image_grid_thw": visual.image_grid_thw.clone(), + "labels": labels, + "tokens": int(batch["loss_mask"].sum()), + } + + +def save_step(out: str, step: int, samples: list) -> None: + os.makedirs(out, exist_ok=True) + torch.save(samples, os.path.join(out, f"step_{step:05d}.pt")) + + +def _bridge_config(recipe_name: str, overrides: list): + """The recipe's config with the training run's overrides applied.""" + bridge = os.environ.get("BRIDGE_ROOT", "/opt/Megatron-Bridge") + sys.path.insert(0, os.path.join(bridge, "scripts", "training")) + from recipe_runner import apply_cli_overrides, load_recipe + + cfg = apply_cli_overrides(load_recipe(recipe_name), overrides) + if getattr(cfg.dataset, "dataloader_type", "single") != "single": + raise SystemExit( + "set dataset.dataloader_type=single: other samplers reorder per data-parallel rank" + ) + return cfg + + +def _bridge_dataset(cfg, n_samples: int): + """The training dataset, built the way training builds it.""" + from megatron.bridge.data.base import DatasetBuildContext + from megatron.bridge.data.builders.direct_hf_sft import DirectHFSFTDatasetBuilder + + context = DatasetBuildContext(train_samples=n_samples, valid_samples=0, test_samples=0) + train, _, _ = DirectHFSFTDatasetBuilder(cfg.dataset).build(context) + return train + + +def main(argv=None): + p = argparse.ArgumentParser() + p.add_argument("--out", required=True) + p.add_argument("--recipe", required=True) + p.add_argument("--steps", type=int, default=50) + args, overrides = p.parse_known_args(argv) + + cfg = _bridge_config(args.recipe, overrides) + gbs = int(cfg.train.global_batch_size) + dataset = _bridge_dataset(cfg, args.steps * gbs) + stats = { + "steps": args.steps, + "global_batch": gbs, + "seq_length": int(cfg.dataset.seq_length), + "supervised_tokens": 0, + "real_tokens": 0, + "vision_tokens": 0, + "full_rows": 0, + } + for step in range(args.steps): + samples = [] + for i in range(step * gbs, (step + 1) * gbs): + example = dataset[i] + batch = dataset.collate_fn([example]) + sample = to_rdsp_sample(batch) + samples.append(sample) + stats["supervised_tokens"] += sample["tokens"] + stats["real_tokens"] += int(sample["attention_mask"].sum()) + stats["vision_tokens"] += int(sample["image_grid_thw"].prod(-1).sum()) // 4 + # a row filling the whole sequence may have been cut short + stats["full_rows"] += int(sample["attention_mask"][0, -1] == 1) + save_step(args.out, step, samples) + print(f"step {step}: {gbs} samples", flush=True) + with open(os.path.join(args.out, "stats.json"), "w") as f: + json.dump(stats, f, indent=1) + print(json.dumps(stats)) + + +if __name__ == "__main__": + main() diff --git a/training/rdsp/bench/mimo/nsys_breakdown.py b/training/rdsp/bench/mimo/nsys_breakdown.py new file mode 100644 index 000000000..c9a8c9aae --- /dev/null +++ b/training/rdsp/bench/mimo/nsys_breakdown.py @@ -0,0 +1,106 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team + +"""Per-GPU time per training step from an Nsight Systems trace: how long each +GPU computes, communicates and sits idle. The same table for Megatron and rdsp, +so their difference is visible kernel by kernel. + + nsys export --type sqlite -o run.sqlite run.nsys-rep + python nsys_breakdown.py run.sqlite --step-ms 7890 + +The window is the span of all kernels in the trace (runs.sh profiles a fixed +window of steady-state steps); --step-ms (the run's median step time) turns +its totals into per-step numbers. Busy time is the union of a GPU's kernel +intervals, so communication that overlaps compute is not counted twice; +category columns are each category's own kernel time. A GPU running the +decoder's linear-attention kernels is "language", any other "vision". +""" + +import argparse +import re +import sqlite3 + +CATEGORIES = ( # first match wins + ("all-reduce", r"nccl.*AllReduce"), + ("reduce-scatter", r"nccl.*ReduceScatter"), + ("all-gather", r"nccl.*AllGather"), + ("send/recv", r"nccl.*(SendRecv|Send|Recv)"), + ("other comm", r"nccl"), + ("linear attention", r"gated_delta|delta_rule|causal_conv1d"), + ("attention", r"flash|fmha|attention|sdpa"), + ("matmul", r"gemm|xmma|nvjet|cutlass|cublas|wgmma"), +) +COLUMNS = [name for name, _ in CATEGORIES] + ["other"] + + +def category(name: str) -> str: + for label, pattern in CATEGORIES: + if re.search(pattern, name, re.IGNORECASE): + return label + return "other" + + +def _union(intervals) -> int: + total, end = 0, None + for s, e in sorted(intervals): + if end is None or s > end: + total += e - s + end = e + elif e > end: + total += e - end + end = e + return total + + +def breakdown(path: str, step_ms: float) -> list[dict]: + """One dict per GPU: role, steps in the window, and per step: busy_ms, + idle_ms, kernels, and each category's ms.""" + db = sqlite3.connect(path) + rows = db.execute( + "SELECT k.deviceId, k.start, k.end, s.value FROM CUPTI_ACTIVITY_KIND_KERNEL k " + "JOIN StringIds s ON s.id = k.shortName" + ).fetchall() + db.close() + lo, hi = min(r[1] for r in rows), max(r[2] for r in rows) + steps = (hi - lo) / 1e6 / step_ms + out = [] + for device in sorted({r[0] for r in rows}): + mine = [r for r in rows if r[0] == device] + per = {c: 0 for c in COLUMNS} + for _, s, e, name in mine: + per[category(name)] += e - s + busy = _union((s, e) for _, s, e, _ in mine) + row = { + "device": device, + "steps": steps, + "role": "language" if per["linear attention"] else "vision", + "busy_ms": busy / 1e6 / steps, + "idle_ms": ((hi - lo) - busy) / 1e6 / steps, + "kernels": len(mine) / steps, + } + row.update({c: v / 1e6 / steps for c, v in per.items()}) + out.append(row) + return out + + +def main(argv=None) -> None: + p = argparse.ArgumentParser() + p.add_argument("sqlite") + p.add_argument("--step-ms", type=float, required=True, help="median step time of the run") + args = p.parse_args(argv) + rows = breakdown(args.sqlite, args.step_ms) + print( + f"{'gpu':>3} {'role':9} {'busy':>7} {'idle':>7} {'kernels':>8} " + + " ".join(f"{c:>16}" for c in COLUMNS) + + " (ms per step)" + ) + for r in rows: + print( + f"{r['device']:>3} {r['role']:9} {r['busy_ms']:>7.0f} {r['idle_ms']:>7.0f} " + f"{r['kernels']:>8.0f} " + " ".join(f"{r[c]:>16.0f}" for c in COLUMNS) + ) + print(f"window: {rows[0]['steps']:.1f} steps") + + +if __name__ == "__main__": + main() diff --git a/training/rdsp/bench/mimo/runs.sh b/training/rdsp/bench/mimo/runs.sh new file mode 100755 index 000000000..541d6afd7 --- /dev/null +++ b/training/rdsp/bench/mimo/runs.sh @@ -0,0 +1,223 @@ +#!/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 +# vision2-* (images DP2), langpp2-* (language TP2xPP2), langtp4-* (language TP4): +# more non-colocated MIMO layouts, each as -mimo | -rdsp +# 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/gap_round/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/gap_round/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/mimo/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" ;; + vision2-mimo) # language TP2 x DP2 on ranks 0-3, images DP2 on ranks 4-5 + mimo vision2-mimo 6 2 tp=2,pp=1,dp=2,rank_offset=0 tp=1,pp=1,dp=2,rank_offset=4 ;; + vision2-rdsp) + rdsp vision2-rdsp "qwen35-$SIZE-vision2-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:?}" ;; + langpp2-mimo) # language TP2 x PP2 on ranks 0-3, images on rank 4 + mimo langpp2-mimo 5 1 tp=2,pp=2,dp=1,rank_offset=0 tp=1,pp=1,dp=1,rank_offset=4 ;; + langpp2-rdsp) + rdsp langpp2-rdsp "qwen35-$SIZE-vision1-tp2pp2.sh" ;; + langtp4-mimo) # language TP4 on ranks 0-3, images on rank 4 + mimo langtp4-mimo 5 1 tp=4,pp=1,dp=1,rank_offset=0 tp=1,pp=1,dp=1,rank_offset=4 ;; + langtp4-rdsp) + rdsp langtp4-rdsp "qwen35-$SIZE-vision1-tp4.sh" ;; + 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/two_node/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/two_node/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/mimo/summarize.py b/training/rdsp/bench/mimo/summarize.py new file mode 100644 index 000000000..0ac2e2a09 --- /dev/null +++ b/training/rdsp/bench/mimo/summarize.py @@ -0,0 +1,81 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team + +"""Results table from bench/mimo/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/mimo 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"), + ("vision DP2 + language TP2xDP2", 6, "vision2-mimo", "vision2-rdsp"), + ("vision 1 GPU + language TP2xPP2", 5, "langpp2-mimo", "langpp2-rdsp"), + ("vision 1 GPU + language TP4", 5, "langtp4-mimo", "langtp4-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/mimo_vs_rdsp/scripts/run.sh b/training/rdsp/bench/mimo_vs_rdsp/scripts/run.sh new file mode 100755 index 000000000..7951512de --- /dev/null +++ b/training/rdsp/bench/mimo_vs_rdsp/scripts/run.sh @@ -0,0 +1,165 @@ +#!/bin/bash +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team +# run.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_vs_rdsp/9b_tp4pp2dp1/scripts/run.sh prep). +# +# 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 -> 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) -> /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 +# -> /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 +# -> /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) +export MODEL=Qwen3.5-9B +RUNS=$RDSP/bench/mimo/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 "$HERE/$layout/logs" + (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 "$HERE/$layout/logs/$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) + 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 "$HERE/convert.log" + sudo chown -R "$(id -u):$(id -g)" "$HOME/hf" "$HOME/mimo" ;; + mimo) mimo_run "$2" "${3:-50}" "$HERE/$2/logs" mimo ;; + sweep) mimo_run "$2" 15 "$HERE/sweep" "$2" || true ;; + rdsp) rdsp_run "$2" "${3:-50}" rdsp ;; + pyspy) + T=${TAG:-}; P=$HERE/$2/profiles$T; L=$HERE/$2/logs; mkdir -p "$P" "$L"; rm -f "$L/pyspy-mimo$T.log" "$L/pyspy-rdsp$T.log" + t0=$(date +%s); mimo_run "$2" 20 "$L" "pyspy-mimo$T" > /dev/null 2>&1 & + RUN=$! + steady "$L/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 "$L/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=$HERE/$2/profiles$T; L=$HERE/$2/logs; mkdir -p "$HOME/mimo/nsys" + NSYS_DELAY=$(cat "$P/steady-mimo.s") NSYS_DURATION=${NSYS_DURATION:-75} \ + mimo_run "$2" 20 "$L" "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=$HERE/$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 - "$HERE" "$2" <<'PY' +import glob, os, re, statistics, sys +here, lang = sys.argv[1], sys.argv[2] +logs = {f"9b_v1_{lang}": f"{here}/9b_v1_{lang}/logs/mimo.log"} +logs.update({os.path.basename(p)[:-4]: p for p in glob.glob(f"{here}/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/modal_bench.py b/training/rdsp/bench/modal_bench.py new file mode 100644 index 000000000..da8ec8e71 --- /dev/null +++ b/training/rdsp/bench/modal_bench.py @@ -0,0 +1,1059 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team + +"""rdsp vs Megatron: pipeline-parallel training throughput on Modal H100s. + +From the repo root: + + modal run bench/modal_bench.py # main grid, 1 repeat + modal run bench/modal_bench.py --reps 3 --only headline + modal run bench/modal_bench.py --only samebox # see main() for all modes + +Results are written to bench/results/ locally, one JSON file per run. + +One NGC image serves both frameworks (modal_smoke.py checks it). Methodology: +- GPUs are requested as `H100!` (Modal otherwise may substitute H200s) and + every container asserts the GPU name before doing any work. Identical work + still varied by up to ~20% between machines of the same chip, so the + comparisons that matter run both frameworks back to back in ONE container. +- Shapes run one after another: the workspace allows 10 concurrent GPUs. +- DeepSpeed ZeRO-0 bf16 sums microbatch gradients in bf16, Megatron in fp32 by + default; the `grad_bf16` runs match Megatron to rdsp's precision. + +Grid systems + M-plain Megatron-LM pretrain_gpt.py, optional fusions off + M-defaults pretrain_gpt.py with its standard fusions on + R-local rdsp (stage-local dispatch) + *-fused rdsp with Liger kernels matching Megatron's default fusions +Results recorded before 2026-09-26 also contain R-os / R-rdt cells: rdsp's +former driver-dispatched design (object store / Ray Direct Transport), since +removed from the package. +Model: Qwen3-0.6B shape (28 layers, untied), bf16, Adam lr 1e-5, no clipping, +no activation recomputation; 2048 tokens per microbatch (b=4 x 512 or b=1 x 2048). +""" + +import itertools +import json +import os +import random +import sys +import time +from pathlib import Path + +import modal + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from modal_smoke import image + +app = modal.App("rdsp-vs-megatron", image=image) +cache = modal.Volume.from_name("rdsp-bench-cache", create_if_missing=True) +hf_cache = modal.Volume.from_name("rdsp-hf-cache", create_if_missing=True) +KW = dict( + timeout=4 * 3600, + cpu=16, + memory=65536, + volumes={"/cache": cache, "/root/.cache/huggingface": hf_cache}, +) +BENCH = "/root/rdsp/bench" +HF = "/cache/qwen3-0.6b-untied" +RESULTS = Path(__file__).resolve().parent / "results" +WARMUP, STEPS = 10, 40 + + +# --- helpers that run inside the containers ----------------------------------- + + +def _sh(cmd): + import subprocess + + return subprocess.run(cmd, shell=True, capture_output=True, text=True) + + +def _require_h100(): + """Fail before spending if Modal handed out anything but H100s.""" + gpus = _sh("nvidia-smi --query-gpu=name --format=csv,noheader").stdout + names = [g for g in gpus.split("\n") if g.strip()] + assert names and all("H100" in g for g in names), f"not an H100 machine: {gpus}" + return gpus + + +def _install_rdsp(): + import subprocess + + subprocess.run(["pip", "install", "-e", "/root/rdsp"], check=True, capture_output=True) + + +def _load(path): + with open(path) as f: + return json.load(f) + + +def _tail(r, n=3000): + return (r.stdout + r.stderr)[-n:] + + +def _megatron_hf(nproc, data, steps, out, **flags): + """megatron_hf_loop.py on `nproc` GPUs; `flags` become --key 'value'.""" + extra = " ".join(f"--{k} '{v}'" for k, v in flags.items()) + return _sh( + f"cd {BENCH} && CUDA_DEVICE_MAX_CONNECTIONS=1 torchrun --standalone " + f"--nproc_per_node {nproc} megatron_hf_loop.py --hf {HF} --data {data} " + f"--steps {steps} --out {out} {extra}" + ) + + +def _rdsp(pp, m, data, steps, out, **flags): + """rdsp_bench.py with fused kernels, no warmup cut (callers drop warmup + steps when summarizing).""" + extra = " ".join(f"--{k} '{v}'" for k, v in flags.items()) + return _sh( + f"cd {BENCH} && python rdsp_bench.py --hf {HF} --pp {pp} --m {m} --seq 512 " + f"--steps {steps} --warmup 0 --data {data} --out {out} --fused 1 {extra}" + ) + + +def _megatron_checks(logs): + """The per-rank layer lists and main_grad dtype that megatron_hf_loop.py + prints: evidence of the layer split and gradient precision each run used.""" + return sorted( + { + line.strip() + for line in logs.splitlines() + if "main_grad dtype" in line or ": layers [" in line + } + ) + + +def _pick(path, keys): + return {k: v for k, v in _load(path).items() if k in keys} + + +# --- the grid: one cell per pretrain_gpt.py / rdsp_bench.py run --------------- + + +def _env_report(): + def run(cmd): + return _sh(cmd).stdout.strip() + + return { + "gpus": run("nvidia-smi --query-gpu=name,driver_version --format=csv,noheader"), + "topo": run("nvidia-smi topo -m"), + "versions": run( + 'python -c "import torch,deepspeed,ray,transformer_engine as te,' + "megatron.core as mc;print(torch.__version__,deepspeed.__version__," + 'ray.__version__,te.__version__,mc.__version__)"' + ), + } + + +def _nvml_peak(stop, peaks): + import pynvml + + pynvml.nvmlInit() + hs = [pynvml.nvmlDeviceGetHandleByIndex(i) for i in range(pynvml.nvmlDeviceGetCount())] + while not stop.is_set(): + for i, h in enumerate(hs): + peaks[i] = max(peaks.get(i, 0), pynvml.nvmlDeviceGetMemoryInfo(h).used) + time.sleep(0.05) + + +def _megatron_cell(c): + import re + + iters = WARMUP + STEPS + r = _sh( + f"cd {BENCH} && PP={c['pp']} M={c['m']} SEQ={c['seq']} ITERS={iters} " + f"VARIANT={c.get('variant', 'plain')} BALANCED={int(bool(c.get('balanced')))} " + f"LAYOUT='{c.get('layout', '')}' " + f"MEGATRON=/opt/Megatron-LM bash megatron_pretrain.sh" + ) + out = r.stdout + r.stderr + times = [ + float(x) / 1000 for x in re.findall(r"elapsed time per iteration \(ms\): ([\d.]+)", out) + ] + losses = [float(x) for x in re.findall(r"lm loss: ([\d.E+-]+)", out)] + # keep the lines that explain a failure (rank tracebacks), not just the + # launcher's generic epilogue + errs = [ + line + for line in out.splitlines() + if re.search(r"Error|error|Assert|assert|Traceback|out of memory", line) + ] + return ( + r.returncode, + {"step_s": times[WARMUP:], "loss": losses}, + "\n".join(errs[:60]) + "\n...\n" + out[-1500:], + ) + + +def _rdsp_cell(c): + b = 4 if c["seq"] == 512 else 1 + out_path = f"/tmp/rdsp_{os.getpid()}_{random.randrange(10**9)}.json" + r = _sh( + f"cd {BENCH} && python rdsp_bench.py --hf {HF} " + f"--pp {c['pp']} --m {c['m']} --seq {c['seq']} " + f"--steps {c.get('warmup', WARMUP) + c.get('steps', STEPS)} " + f"--warmup {c.get('warmup', WARMUP)} " + f"--data /cache/batches_s{c['seq']}_b{b}_m{c['m']}.pt " + f"--out {out_path} " + f"--cuts '{c.get('cuts', '')}' --last_stage_gpus {c.get('last_stage_gpus', 1)} " + f"--fused {int(bool(c.get('fused')))} " + f"--timed {int(bool(c.get('timed')))} --timeline {int(bool(c.get('timeline')))}" + ) + res = _load(out_path) if r.returncode == 0 and os.path.exists(out_path) else {} + return r.returncode, res, _tail(r) + + +def _summarize_profile(c, res): + """Compact profile summary computed in the container; the raw Ray + timeline and per-stage CUDA timings go to the cache volume.""" + from collections import defaultdict + + prof = res.pop("profile", None) + if not prof: + return None + os.makedirs("/cache/profile", exist_ok=True) + raw = f"/cache/profile/rdsp_pp{c['pp']}_m{c['m']}.json" + with open(raw, "w") as f: + json.dump(prof, f) + warm = c.get("warmup", WARMUP) + windows = prof.get("step_windows", [])[warm:] + n = max(len(windows), 1) + out = {"raw": raw, "measured_steps": len(windows)} + + # per stage: GPU busy time per step from CUDA events + stage_pid, gpu = {}, {} + for fname, recs in prof.get("stage_ops", {}).items(): + recs = [r for r in recs if r["step"] >= warm] + tot = defaultdict(float) + for r in recs: + for kind, _, ms in r["ops"]: + tot[kind] += ms + k = max(len(recs), 1) + gpu[fname] = {kind: round(v / k, 2) for kind, v in tot.items()} + if recs: + stage_pid[recs[0]["pid"]] = fname + out["gpu_ms_per_step_by_stage"] = gpu + + # Ray timeline within the measured steps: time per (process, event name) + lo = windows[0][0] * 1e6 if windows else 0 + hi = windows[-1][1] * 1e6 if windows else float("inf") + by = defaultdict(lambda: [0, 0.0]) + for e in prof.get("timeline", []): + if e.get("ph") != "X" or not (lo <= e.get("ts", 0) <= hi): + continue + key = (e.get("pid"), e.get("name"), e.get("cat")) + by[key][0] += 1 + by[key][1] += e.get("dur", 0) / 1000 + rows = sorted( + ((v[1] / n, v[0] / n, str(k[0]), str(k[1]), str(k[2])) for k, v in by.items()), reverse=True + ) + out["timeline_top"] = [ + { + "ms_per_step": round(ms, 2), + "count_per_step": round(cnt, 1), + "pid": pid, + "name": name, + "cat": cat, + } + for ms, cnt, pid, name, cat in rows[:40] + ] + out["stage_pids"] = {str(k): v for k, v in stage_pid.items()} + cache.commit() + return out + + +def run_cells(cells): + """Run grid cells in this container, in random order (unless profiling), + sampling NVML peak memory alongside each.""" + import threading + + _install_rdsp() + env = _env_report() + assert "H200" not in env["gpus"] and "H100" in env["gpus"], ( + f"not an H100 machine: {env['gpus']}" + ) + if not any(c.get("timeline") for c in cells): + random.shuffle(cells) + results = [] + for c in cells: + stop, peaks = threading.Event(), {} + th = threading.Thread(target=_nvml_peak, args=(stop, peaks), daemon=True) + th.start() + t0 = time.time() + fn = _megatron_cell if c["system"].startswith("M-") else _rdsp_cell + rc, res, tail = fn(c) + prof_summary = _summarize_profile(c, res) if res else None + stop.set() + th.join() + results.append( + { + "cell": c, + "rc": rc, + "wall_s": time.time() - t0, + "nvml_peak_bytes": peaks, + "result": res, + "profile_summary": prof_summary, + "tail": tail if rc else "", + "env": env, + } + ) + steps = res.get("step_s") or [] + med = f"{sorted(steps)[len(steps) // 2]:.3f}s" if steps else "n/a" + print(f"{c} rc={rc} median_step={med}", flush=True) + if rc or not steps: + print(f"--- failure tail ---\n{tail}", flush=True) + return results + + +@app.function(gpu="H100!:1", **KW) +def h100x1(cells): + return run_cells(cells) + + +@app.function(gpu="H100!:2", **KW) +def h100x2(cells): + return run_cells(cells) + + +@app.function(gpu="H100!:4", **KW) +def h100x4(cells): + return run_cells(cells) + + +@app.function(gpu="H100!:8", **KW) +def h100x8(cells): + return run_cells(cells) # also the 5-GPU capability cells (uses 5 of 8) + + +RUN = {1: h100x1, 2: h100x2, 4: h100x4, 8: h100x8} + + +# --- matched runs: same pretrained weights, same real text, same order -------- + +TEXT = "/cache/text_s512_b4_m8.pt" +LOSS_STEPS = 300 +TEXT16 = "/cache/text_s512_b4_m16.pt" # the same tokens regrouped: 150 steps x 16 microbatches +TEXT_B16 = "/cache/text_s512_b16_m4.pt" # the same tokens: 4 microbatches x 16 rows x 512 +TEXT_B16_M16 = "/cache/text_s512_b16_m16.pt" # 37 steps x 16 microbatches x 16 rows x 512 +PP8_LAYOUT = "Et*4|t*4|t*4|t*4|t*3|t*3|t*3|t*3,L" # = rdsp's uniform split at 8 stages + + +@app.function(**KW) +def prepare_text(): + """WikiText-103 (real text), tokenized with Qwen3's tokenizer, packed into + [steps, microbatches, rows, 513]; both frameworks read it identically.""" + import subprocess + + import torch + + if os.path.exists(TEXT): + return "cached" + subprocess.run(["pip", "install", "-q", "datasets"], check=True) + import datasets + import transformers + + tok = transformers.AutoTokenizer.from_pretrained(HF) + need = LOSS_STEPS * 8 * 4 * 513 + ds = datasets.load_dataset("Salesforce/wikitext", "wikitext-103-raw-v1", split="train") + ids, i = [], 0 + while len(ids) < need: + chunk = "".join(ds[i : i + 2000]["text"]) + ids.extend(tok(chunk)["input_ids"]) + i += 2000 + t = torch.tensor(ids[:need], dtype=torch.int64).view(LOSS_STEPS, 8, 4, 513) + torch.save(t, TEXT) + cache.commit() + return f"{need} tokens" + + +@app.function(**KW) +def prepare_text16(): + import torch + + if not os.path.exists(TEXT16): + x = torch.load(TEXT) + torch.save(x.reshape(x.shape[0] // 2, 16, *x.shape[2:]).clone(), TEXT16) + cache.commit() + return "ok" + + +def _ensure_b16_m16(): + import torch + + if not os.path.exists(TEXT_B16_M16): + x = torch.load(TEXT).reshape(-1, 513) + torch.save(x[: 37 * 256].reshape(37, 16, 16, 513).clone(), TEXT_B16_M16) + + +def _loss_compare( + pp, text=TEXT, steps=LOSS_STEPS, layout="", systems=("megatron", "rdsp"), grad_bf16=0 +): + """HF reference loss on step 0, then Megatron-Core and rdsp from the same + pretrained weights on the same batches, fusions on for both.""" + import subprocess + + import torch + + gpus = _require_h100() + _install_rdsp() + m = torch.load(text).shape[1] + out = {"pp": pp, "m": m, "text": text, "layout": layout, "gpu": gpus.split("\n")[0]} + # 1. reference: the plain HF model's loss on step 0's batch (no training) + ref = subprocess.run( + [ + "python", + "-c", + f""" +import torch, torch.nn.functional as F, transformers, json +m = transformers.AutoModelForCausalLM.from_pretrained( + '{HF}', dtype=torch.bfloat16, attn_implementation='sdpa').cuda().eval() +X = torch.load('{text}') +with torch.no_grad(): + ls = [F.cross_entropy(m(X[0, k][:, :-1].cuda()).logits.float().flatten(0, 1), + X[0, k][:, 1:].cuda().flatten()).item() for k in range(X.shape[1])] +print(json.dumps(sum(ls) / len(ls))) +""", + ], + capture_output=True, + text=True, + ) + out["grad_bf16"] = grad_bf16 + out["hf_step0_loss"] = ( + json.loads(ref.stdout.strip().splitlines()[-1]) + if ref.returncode == 0 + else ref.stderr[-2000:] + ) + # 2. Megatron-Core from the same HF weights, its standard fusions on + r = _megatron_hf(pp, text, steps, "/tmp/meg_loss.json", layout=layout, grad_bf16=grad_bf16) + logs = r.stdout + r.stderr + out["megatron_layers"] = [ + line for line in logs.splitlines() if ": layers [" in line or "main_grad dtype" in line + ] + out["megatron"] = ( + _load("/tmp/meg_loss.json") + if r.returncode == 0 + else { + "error": "\n".join( + line + for line in logs.splitlines() + if "rank0" in line or "Error" in line or "assert" in line + )[-4000:] + + "\n...\n" + + logs[-2000:] + } + ) + if "rdsp" not in systems: + out["rdsp"] = {"error": "skipped"} + return out + # 3. rdsp: same weights, data, optimizer, matching fused kernels + r = _rdsp(pp, m, text, steps, "/tmp/rdsp_loss.json") + out["rdsp"] = _load("/tmp/rdsp_loss.json") if r.returncode == 0 else {"error": _tail(r, 4000)} + out["rdsp"].pop("profile", None) + out["rdsp"].pop("executed", None) + return out + + +def _same_box(pp, layout="", steps=60): + """Megatron fp32-summing, Megatron bf16-summing and rdsp, back to back in + ONE container on pinned H100s, same weights/data/kernels/steps.""" + _require_h100() + _install_rdsp() + q = ( + "nvidia-smi --query-gpu=index,name,pci.bus_id,clocks.max.sm,power.limit," + "temperature.gpu --format=csv,noheader" + ) + out = { + "pp": pp, + "m": 16, + "steps": steps, + "layout": layout, + "gpus": _sh(q).stdout, + "topo": _sh("nvidia-smi topo -m").stdout, + "order": ["megatron_fp32", "megatron_bf16", "rdsp"], + } + for name, bf16 in (("megatron_fp32", 0), ("megatron_bf16", 1)): + r = _megatron_hf(pp, TEXT16, steps, f"/tmp/{name}.json", layout=layout, grad_bf16=bf16) + out[name] = _load(f"/tmp/{name}.json") if r.returncode == 0 else {"error": _tail(r)} + out[name + "_check"] = _megatron_checks(r.stdout + r.stderr) + r = _rdsp(pp, 16, TEXT16, steps, "/tmp/rdsp.json") + out["rdsp"] = _load("/tmp/rdsp.json") if r.returncode == 0 else {"error": _tail(r)} + out["rdsp"].pop("profile", None) + out["rdsp"].pop("executed", None) + out["gpus_after"] = _sh(q).stdout + return out + + +@app.function(gpu="H100!:1", **KW) +def gpubound_x1(): + """GPU-bound regime: 8,192-token microbatches. Megatron (native CE, TE CE) + and rdsp back to back on one pinned H100, bf16 gradient summing on all, + 60 steps each; steps 20-29 profiled (excluded from timing).""" + import glob + import shutil + + import torch + + gpus = _require_h100() + if not os.path.exists(TEXT_B16): + x = torch.load(TEXT) # [300, 8, 4, 513] -> consecutive rows regrouped + torch.save(x.reshape(-1, x.shape[-1]).reshape(150, 4, 16, x.shape[-1]).clone(), TEXT_B16) + _install_rdsp() + out = { + "gpu": gpus.strip(), + "b": 16, + "m": 4, + "seq": 512, + "steps": 60, + "order": ["megatron_native_ce", "megatron_te_ce", "rdsp"], + } + for name, ce in (("megatron_native_ce", "native"), ("megatron_te_ce", "te")): + r = _megatron_hf( + 1, + TEXT_B16, + 60, + f"/tmp/{name}.json", + grad_bf16=1, + ce_impl=ce, + prof_out=f"/tmp/{name}_prof.json", + ) + out[name] = ( + dict(_load(f"/tmp/{name}_prof.json"), **_load(f"/tmp/{name}.json")) + if r.returncode == 0 + else {"error": _tail(r)} + ) + shutil.rmtree("/tmp/rdsp_bench", ignore_errors=True) + r = _rdsp(1, 4, TEXT_B16, 60, "/tmp/rdsp.json", b=16, prof=1) + files = glob.glob("/tmp/rdsp_bench/prof_*.json") + out["rdsp"] = ( + dict(_load(files[0]), **_pick("/tmp/rdsp.json", ("step_s", "loss", "b", "m"))) + if r.returncode == 0 and files + else {"error": _tail(r)} + ) + return out + + +def _gpubound_pipe(pp, layout=""): + """Large-microbatch pipeline run: Megatron (TE CE, bf16 summing) and rdsp + back to back on one pinned-H100 machine; 36 steps, timing only.""" + _require_h100() + _ensure_b16_m16() + _install_rdsp() + out = { + "pp": pp, + "b": 16, + "m": 16, + "seq": 512, + "steps": 36, + "layout": layout, + "gpus": _sh("nvidia-smi --query-gpu=index,name --format=csv,noheader").stdout, + "order": ["megatron_te_ce", "rdsp"], + } + r = _megatron_hf( + pp, TEXT_B16_M16, 36, "/tmp/meg.json", grad_bf16=1, ce_impl="te", layout=layout + ) + out["megatron_te_ce"] = _load("/tmp/meg.json") if r.returncode == 0 else {"error": _tail(r)} + out["megatron_te_ce_check"] = _megatron_checks(r.stdout + r.stderr) + r = _rdsp(pp, 16, TEXT_B16_M16, 36, "/tmp/rdsp.json", b=16) + out["rdsp"] = ( + _pick("/tmp/rdsp.json", ("step_s", "loss", "stage_tags")) + if r.returncode == 0 + else {"error": _tail(r)} + ) + return out + + +HETERO = [ # (name, system, pp, cuts or layout, last-stage GPUs) + ("megatron_4_balanced", "megatron", 4, "Et*9|t*9|t*9|t,L", 1), + ("rdsp_4_balanced", "rdsp", 4, "9,18,27", 1), + ("megatron_5_balanced", "megatron", 5, "Et*7|t*7|t*7|t*6|t,L", 1), + ("rdsp_5_balanced", "rdsp", 5, "7,14,21,27", 1), + ("rdsp_4_stages_5_gpus", "rdsp", 4, "8,16,24", 2), # the head stage on 2 GPUs +] + + +@app.function(gpu="H100!:8", **KW) +def hetero_x8(): + """Does giving the head stage a second GPU beat the best uniform layouts? + Large microbatches, one pinned-H100 machine, back to back.""" + _require_h100() + _ensure_b16_m16() + _install_rdsp() + out = { + "gpus": _sh("nvidia-smi --query-gpu=index,name --format=csv,noheader").stdout, + "b": 16, + "m": 16, + "seq": 512, + "steps": 36, + "order": [h[0] for h in HETERO], + "configs": HETERO, + } + for name, system, pp, spec, last in HETERO: + path = f"/tmp/{name}.json" + if system == "megatron": + r = _megatron_hf(pp, TEXT_B16_M16, 36, path, grad_bf16=1, ce_impl="te", layout=spec) + out[name] = _load(path) if r.returncode == 0 else {"error": _tail(r)} + out[name + "_check"] = _megatron_checks(r.stdout + r.stderr) + else: + r = _rdsp(pp, 16, TEXT_B16_M16, 36, path, b=16, cuts=spec, last_stage_gpus=last) + out[name] = ( + _pick(path, ("step_s", "loss", "stage_tags", "last_stage_gpus", "b")) + if r.returncode == 0 + else {"error": _tail(r)} + ) + return out + + +FEWMB = [ # (name, data, microbatches, cuts, last-stage GPUs): rdsp only, same machine + ("m4_5_stages", TEXT_B16, 4, "7,14,21,27", 1), + ("m4_head_on_2_gpus", TEXT_B16, 4, "7,14,21", 2), + ("m16_5_stages", TEXT_B16_M16, 16, "7,14,21,27", 1), + ("m16_head_on_2_gpus", TEXT_B16_M16, 16, "7,14,21", 2), +] + + +@app.function(gpu="H100!:8", **KW) +def fewmb_x8(): + """Uneven stages vs a plain 5th stage at 4 and 16 microbatches, one pinned + H100 machine. Prediction (stated before running): 2-GPU head stage wins, + ~1.14x at 4 microbatches, ~1.05x at 16, minus its gradient all-reduce.""" + import torch + + _require_h100() + x = torch.load(TEXT).reshape(-1, 513) + if not os.path.exists(TEXT_B16): + torch.save(x.reshape(150, 4, 16, 513).clone(), TEXT_B16) + _ensure_b16_m16() + _install_rdsp() + out = { + "gpus": _sh("nvidia-smi --query-gpu=index,name --format=csv,noheader").stdout, + "order": [f[0] for f in FEWMB], + "configs": FEWMB, + } + for name, data, m, cuts, last in FEWMB: + pp = len(cuts.split(",")) + 1 + path = f"/tmp/{name}.json" + r = _rdsp(pp, m, data, 36, path, b=16, cuts=cuts, last_stage_gpus=last) + out[name] = ( + _pick(path, ("step_s", "loss", "stage_tags", "last_stage_gpus", "m", "b")) + if r.returncode == 0 + else {"error": _tail(r)} + ) + return out + + +@app.function(gpu="H100!:4", **KW) +def gpubound_x4(): + return _gpubound_pipe(4) + + +@app.function(gpu="H100!:8", **KW) +def gpubound_x8(): + return _gpubound_pipe(8, PP8_LAYOUT) + + +@app.function(gpu="H100!:1", **KW) +def profile_x1(): + """Kernel profile of matched-precision Megatron and rdsp, one pinned H100, + same tool (torch.profiler) and window (steps 20-29) on both.""" + import glob + + gpus = _require_h100() + _install_rdsp() + out = {"gpu": gpus.strip()} + r = _megatron_hf(1, TEXT16, 31, "/tmp/meg.json", grad_bf16=1, prof_out="/tmp/meg_prof.json") + out["megatron"] = ( + dict(_load("/tmp/meg_prof.json"), step_s=_load("/tmp/meg.json")["step_s"]) + if r.returncode == 0 + else {"error": _tail(r)} + ) + r = _rdsp(1, 16, TEXT16, 31, "/tmp/rdsp.json", prof=1) + files = glob.glob("/tmp/rdsp_bench/prof_*.json") + out["rdsp"] = ( + dict(_load(files[0]), step_s=_load("/tmp/rdsp.json")["step_s"]) + if r.returncode == 0 and files + else {"error": _tail(r)} + ) + return out + + +@app.function(gpu="H100!:1", **KW) +def samebox_x1(): + return _same_box(1, steps=100) # longer: Megatron's 1-GPU step time drifts over ~70 steps + + +@app.function(gpu="H100!:4", **KW) +def samebox_x4(): + return _same_box(4) + + +@app.function(gpu="H100!:8", **KW) +def samebox_x8(): + return _same_box(8, PP8_LAYOUT) + + +@app.function(gpu="H100!:4", **KW) +def loss_compare(): # 4 stages, 8 microbatches, 300 steps + return _loss_compare(4) + + +@app.function(gpu="H100!:1", **KW) +def matched_x1(): + return _loss_compare(1, TEXT16, 150) + + +@app.function(gpu="H100!:1", **KW) +def megatron_bf16_x1(): # Megatron only, gradients summed in bf16 like rdsp + return _loss_compare(1, TEXT16, 150, systems=("megatron",), grad_bf16=1) + + +@app.function(gpu="H100!:4", **KW) +def megatron_bf16_x4(): + return _loss_compare(4, TEXT16, 150, systems=("megatron",), grad_bf16=1) + + +@app.function(gpu="H100!:8", **KW) +def megatron_bf16_x8(): + return _loss_compare(8, TEXT16, 150, PP8_LAYOUT, systems=("megatron",), grad_bf16=1) + + +@app.function(gpu="H100!:4", **KW) +def matched_x4(): + return _loss_compare(4, TEXT16, 150) + + +@app.function(gpu="H100!:8", **KW) +def matched_x8(): + return _loss_compare(8, TEXT16, 150, PP8_LAYOUT) + + +@app.function(**KW) +def prepare(): + """Untied Qwen3-0.6B checkpoint and the random-token grid files, once.""" + import torch + import transformers + + if not os.path.exists(f"{HF}/config.json"): + m = transformers.AutoModelForCausalLM.from_pretrained( + "Qwen/Qwen3-0.6B", dtype=torch.bfloat16 + ) + m.lm_head.weight = torch.nn.Parameter(m.model.embed_tokens.weight.detach().clone()) + m.config.tie_word_embeddings = False + m.save_pretrained(HF) + transformers.AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B").save_pretrained(HF) + for s, m_ in itertools.product((512, 2048), (4, 8, 16)): + b = 4 if s == 512 else 1 + path = f"/cache/batches_s{s}_b{b}_m{m_}.pt" + if not os.path.exists(path): + g = torch.Generator().manual_seed(0) + torch.save(torch.randint(0, 151936, (8, m_, b, s + 1), generator=g), path) + cache.commit() + hf_cache.commit() + + +def grid(only: str): + """Cells for a grid run; the cell dicts are recorded with each result.""" + if only == "context": + return [ + # Megatron as people run it (fusions on): full grid plus its own + # PP=1 baselines for pipeline efficiency + *[ + {"system": "M-defaults", "variant": "defaults", "pp": 1, "m": 8, "seq": seq} + for seq in (512, 2048) + ], + *[ + {"system": "M-defaults", "variant": "defaults", "pp": pp, "m": m, "seq": seq} + for pp in (2, 4) + for m in (4, 8, 16) + for seq in (512, 2048) + ], + # balanced split: move layers off the head-heavy last stage + { + "system": "R-local", + "pp": 4, + "m": 8, + "seq": 512, + "cuts": "9,18,27", + "tag": "balanced", + }, + {"system": "M-plain", "pp": 4, "m": 8, "seq": 512, "balanced": True, "tag": "balanced"}, + # a second GPU for the last stage (5 GPUs): not expressible in Megatron + { + "system": "R-local", + "pp": 4, + "m": 8, + "seq": 512, + "last_stage_gpus": 2, + "tag": "capability", + "shape": 8, + }, + ] + if only == "local": + return [ + {"system": "R-local-fused", "fused": True, "pp": pp, "m": 16, "seq": 512, "shape": 8} + for pp in (8, 4) + ] + if only == "profile": + # one 8-GPU container: rdsp at 8 stages, then 4 for contrast + base = { + "system": "R-local-fused", + "fused": True, + "m": 16, + "seq": 512, + "timed": True, + "timeline": True, + "warmup": 5, + "steps": 10, + "shape": 8, + } + return [dict(base, pp=8), dict(base, pp=4)] + if only == "pp8-megatron": + return [c for c in grid("pp8") if c["system"] == "M-defaults"] + if only == "pp8": + # 8 stages; 28 layers split 4-4-4-4-3-3-3-3 on both sides (rdsp's uniform split) + return [ + { + "system": "M-defaults", + "variant": "defaults", + "pp": 8, + "m": 16, + "seq": 512, + "layout": PP8_LAYOUT, + }, + {"system": "R-local-fused", "fused": True, "pp": 8, "m": 16, "seq": 512}, + ] + if only == "fused-smoke": + return [ + {"system": "R-local-fused", "fused": True, "pp": 2, "m": 4, "seq": 512}, + {"system": "R-local", "pp": 2, "m": 4, "seq": 512}, + ] + if only == "fused": + cells = [ + {"system": "R-local-fused", "fused": True, "pp": 1, "m": 8, "seq": seq} + for seq in (512, 2048) + ] + cells += [ + {"system": "R-local-fused", "fused": True, "pp": pp, "m": m, "seq": seq} + for pp, m, seq in itertools.product((2, 4), (4, 8, 16), (512, 2048)) + ] + return cells + if only == "smoke": + return [ + {"system": "M-plain", "pp": 2, "m": 4, "seq": 512}, + {"system": "R-local", "pp": 2, "m": 4, "seq": 512}, + ] + if only not in ("", "headline"): + raise ValueError(f"unknown mode {only!r}") + # main grid ("" or "headline" = m=8 only), fusions off on both sides + cells = [] + for seq in (512, 2048): # PP=1 baselines (pipeline efficiency denominators) + cells += [ + {"system": "M-plain", "pp": 1, "m": 8, "seq": seq}, + {"system": "R-local", "pp": 1, "m": 8, "seq": seq}, + ] + for sysname, pp, m, seq in itertools.product( + ("M-plain", "R-local"), (2, 4), (4, 8, 16), (512, 2048) + ): + if only == "headline" and m != 8: + continue + cells.append({"system": sysname, "pp": pp, "m": m, "seq": seq}) + return cells + + +# --- local entrypoint ----------------------------------------------------------- + + +def _save(prefix, obj, indent=None): + RESULTS.mkdir(parents=True, exist_ok=True) + path = RESULTS / f"{prefix}{time.strftime('%Y%m%d-%H%M%S')}.json" + with open(path, "w") as f: + json.dump(obj, f, indent=indent) + return path + + +def _stats(step_s, skip=10): + """(median, p10, p90) step time after dropping the first `skip` steps.""" + t = sorted(step_s[skip:]) + return t[len(t) // 2], t[len(t) // 10], t[9 * len(t) // 10] + + +def _print_row(name, x, tokens_per_step, width): + """One timing line for a result dict with step_s and loss, or its error.""" + if "step_s" not in x: + print(f" {name} FAILED:", x.get("error", "")[-2500:]) + return False + med, p10, p90 = _stats(x["step_s"]) + print( + f" {name:{width}s} median {med * 1000:6.0f} ms = " + f"{tokens_per_step / med / 1000:6.1f}k tok/s " + f"(p10 {p10 * 1000:.0f}, p90 {p90 * 1000:.0f}) " + f"loss {x['loss'][0]:.4f} -> {x['loss'][-1]:.4f}" + ) + return True + + +def _print_loss_run(r, names): + print(f"--- {r['pp']} GPU(s), {r['gpu']}: HF step-0 loss {r['hf_step0_loss']}") + for line in r.get("megatron_layers", []): + print(" ", line.strip()[-120:]) + for name in names: + x = r[name] + if "loss" not in x: + print(f" {name} FAILED:", x.get("error", "")[-3000:]) + continue + med = _stats(x["step_s"])[0] + print( + f" {name}: step0 {x['loss'][0]:.4f} last {x['loss'][-1]:.4f} " + f"median {med * 1000:.0f} ms = {r['m'] * 4 * 512 / med / 1000:.1f}k tok/s" + ) + + +@app.local_entrypoint() +def main(reps: int = 1, only: str = ""): + """--only picks the run: a grid name (see grid()), or one of loss, matched, + samebox, samebox1, meg-bf16-{1,4,8}, profile1, gpubound1, gpubound48, + hetero, fewmb.""" + prepare.remote() + if only == "loss": + print("text:", prepare_text.remote()) + res = loss_compare.remote() + path = _save("loss_", res) + print("HF reference step-0 loss:", res["hf_step0_loss"]) + for name in ("megatron", "rdsp"): + r = res[name] + if "loss" in r: + med = _stats(r["step_s"])[0] + print( + f"{name}: step0 {r['loss'][0]:.4f} step{len(r['loss']) - 1} " + f"{r['loss'][-1]:.4f} median step {med * 1000:.0f} ms" + ) + else: + print(name, "FAILED:", r.get("error", "")[-1500:]) + print("->", path) + return + if only == "fewmb": + r = fewmb_x8.remote() + path = _save("fewmb_", r) + print(r["gpus"].strip()) + for name, _data, m, _cuts, _last in r["configs"]: + x = r[name] + if _print_row(name, x, m * 16 * 512, 20): + print(f" {x.get('stage_tags')} last_gpus={x.get('last_stage_gpus')}") + print("->", path) + return + if only == "hetero": + r = hetero_x8.remote() + path = _save("hetero_", r) + print(r["gpus"].strip()) + for name, _system, pp, _spec, last in r["configs"]: + x = r[name] + if _print_row(f"{name} ({pp + last - 1} GPUs)", x, 16 * 16 * 512, 32): + print(f" {x.get('stage_tags', '')} b={x.get('b', '')}") + for c in r.get(name + "_check", []): + print(" ", c[-100:]) + print("->", path) + return + if only == "gpubound48": + res = [] + for fn in (gpubound_x8, gpubound_x4): # one at a time: 10-GPU workspace limit + r = fn.remote() + res.append(r) + print(f"=== {r['pp']} GPUs, one container ===\n{r['gpus'].strip()}") + for name in r["order"]: + _print_row(name, r[name], 16 * 16 * 512, 16) + for c in r.get("megatron_te_ce_check", []): + print(" ", c[-110:]) + print(" rdsp stages:", r["rdsp"].get("stage_tags")) + print("->", _save("gpubound48_", res)) + return + if only == "gpubound1": + r = gpubound_x1.remote() + path = _save("gpubound1_", r) + print("GPU:", r["gpu"]) + for name in r["order"]: + x = r[name] + if "step_s" not in x: + print(name, "FAILED:", x.get("error", "")[-2500:]) + continue + # steps 20-30 carry the profiler + t = sorted(x["step_s"][10:20] + x["step_s"][31:]) + med = t[len(t) // 2] + kernel_ms = ( + sum(v[1] for k, v in x["kernels"].items() if not k.startswith("##")) + / 1e3 + / x["steps"] + ) + print( + f" {name:20s} median {med * 1000:5.0f} ms = {32768 / med / 1000:5.1f}k tok/s " + f"| GPU kernels {kernel_ms:4.0f} ms/step " + f"| loss {x['loss'][0]:.4f} -> {x['loss'][-1]:.4f}" + ) + print("->", path) + return + if only == "profile1": + r = profile_x1.remote() + path = _save("profile1_", r) + print("GPU:", r["gpu"]) + for name in ("megatron", "rdsp"): + x = r[name] + if "kernels" not in x: + print(name, "FAILED:", x.get("error", "")[-2500:]) + continue + busy = sum(v[1] for v in x["kernels"].values()) / 1e6 + print( + f"{name}: window {x['wall_s']:.2f} s for 10 steps, kernel time {busy:.2f} s, " + f"{len(x['kernels'])} distinct kernels" + ) + print("->", path) + return + if only in ("samebox", "samebox1"): + res = [] + # one at a time: 10-GPU workspace limit + for fn in (samebox_x1,) if only == "samebox1" else (samebox_x8, samebox_x4): + r = fn.remote() + res.append(r) + print(f"=== {r['pp']} GPUs, one container ===") + print(r["gpus"].strip()) + for name in r["order"]: + x = r[name] + if _print_row(name, x, 16 * 2048, 14): + s = x["step_s"] + h = len(s) // 2 + print( + f" halves: steps 10-{h - 1} median " + f"{sorted(s[10:h])[(h - 10) // 2] * 1000:.0f} ms, " + f"steps {h}-{len(s) - 1} median " + f"{sorted(s[h:])[(len(s) - h) // 2] * 1000:.0f} ms" + ) + for c in r.get(name + "_check", []): + print(" ", c[-110:]) + print("->", _save("samebox_", res)) + return + if only in ("meg-bf16-1", "meg-bf16-4", "meg-bf16-8"): + fn = {"1": megatron_bf16_x1, "4": megatron_bf16_x4, "8": megatron_bf16_x8}[only[-1]] + r = fn.remote() + path = _save(f"{only}_", r) + _print_loss_run(r, ("megatron",)) + print("->", path) + return + if only == "matched": + # 1, 4 and 8 GPUs; same weights and text (16 microbatches x 2048 tokens + # per step at every size), fusions on for both. 8+1 GPUs first, then 4. + print("text:", prepare_text.remote(), prepare_text16.remote()) + h8, h1 = matched_x8.spawn(), matched_x1.spawn() + res = [h1.get(), h8.get(), matched_x4.remote()] + path = _save("matched_", res) + for r in res: + _print_loss_run(r, ("megatron", "rdsp")) + print("->", path) + return + cells = grid(only) + all_results = [] + for shape in (1, 2, 4, 8): # one shape at a time: 10-GPU workspace limit + mine = [c for c in cells if c.get("shape", c["pp"]) == shape] + if not mine: + continue + for rep in range(reps): + all_results.extend(RUN[shape].remote([dict(c, rep=rep) for c in mine])) + path = _save("", all_results, indent=1) + print(f"{len(all_results)} cells -> {path}") diff --git a/training/rdsp/bench/modal_smoke.py b/training/rdsp/bench/modal_smoke.py new file mode 100644 index 000000000..588fe68e6 --- /dev/null +++ b/training/rdsp/bench/modal_smoke.py @@ -0,0 +1,129 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team + +"""Check that the shared NGC benchmark image works for both frameworks. + + modal run bench/modal_smoke.py # from the repo root + modal run bench/modal_smoke.py --only megatron # Megatron PP=2 run only + +Checks: + 1. the image builds and CUDA works on Modal's driver + 2. Megatron-Core, TransformerEngine, DeepSpeed (pinned), Ray and rdsp import + 3. pretrain_gpt.py knows the Qwen3 flags (--kv-channels, --qk-layernorm) + 4. rdsp's Qwen3-0.6B two-stage acceptance test passes in this image + 5. a 20-iteration Megatron PP=2 mock-data run completes +""" + +from pathlib import Path + +import modal + +REPO = Path(__file__).resolve().parents[1] +NGC = "nvcr.io/nvidia/pytorch:25.10-py3" +MCORE_TAG = "core_v0.19.2" +DS_REV = "53a2ac44fb664bea838df3981ba4366b91643070" + +image = ( + modal.Image.from_registry(NGC) + .env( + { + "PIP_CONSTRAINT": "", + "DS_BUILD_OPS": "0", + "TOKENIZERS_PARALLELISM": "false", + "HF_HOME": "/root/.cache/huggingface", + # lets containers import bench modules (modal_bench imports this file) + "PYTHONPATH": "/root/rdsp/bench", + } + ) + .run_commands( + f"git clone --depth 1 --branch {MCORE_TAG} " + "https://github.com/NVIDIA/Megatron-LM.git /opt/Megatron-LM", + "pip install --no-build-isolation -e /opt/Megatron-LM", + # 25.10 ships an nvidia-resiliency-ext without __version__, which + # Megatron probes at import; it is optional (async checkpointing only) + "pip uninstall -y nvidia-resiliency-ext", + "pip install 'transformers==5.16.1' accelerate safetensors einops " + "'ray[default]==2.58.0' cloudpickle nvidia-ml-py pytest cupy-cuda13x", + # --no-deps: liger's triton pin would replace NGC's triton, which + # breaks torch 2.9's inductor (Megatron-defaults torch.compile path) + "pip install --no-deps liger-kernel", + f"pip install --no-build-isolation git+https://github.com/deepspeedai/DeepSpeed.git@{DS_REV}", + ) + .add_local_dir( + REPO, + "/root/rdsp", + ignore=[".venv", "**/__pycache__", ".pytest_cache", "uv.lock", ".cache", "bench/results"], + ) +) +app = modal.App("rdsp-bench-smoke", image=image) +hf_cache = modal.Volume.from_name("rdsp-hf-cache", create_if_missing=True) + + +def _sh(cmd: str) -> tuple[int, str]: + import subprocess + + r = subprocess.run(cmd, shell=True, capture_output=True, text=True) + return r.returncode, (r.stdout + r.stderr)[-6000:] + + +@app.function( + gpu="H100:2", timeout=3600, cpu=16, memory=65536, volumes={"/root/.cache/huggingface": hf_cache} +) +def smoke(): + results = {} + results["nvidia-smi"] = _sh("nvidia-smi --query-gpu=name,driver_version --format=csv") + results["imports"] = _sh( + 'python -c "import torch, transformer_engine, megatron.core, deepspeed, ray; ' + "print(torch.__version__, torch.version.cuda, torch.cuda.is_available(), " + "transformer_engine.__version__, megatron.core.__version__, deepspeed.__version__, " + 'ray.__version__)"' + ) + results["flags"] = _sh( + "cd /opt/Megatron-LM && python pretrain_gpt.py --help 2>&1 | " + "grep -E -- '--kv-channels|--qk-layernorm|" + "--pipeline-model-parallel-layout' | head" + ) + results["rdsp_install"] = _sh("pip install -e /root/rdsp") + results["rdsp_acceptance"] = _sh( + "cd /root/rdsp && python -m pytest -q -x " + "tests/integration/test_two_stage_baseline.py 2>&1 | tail -5" + ) + results["megatron_pp2"] = _sh( + "cd /root/rdsp/bench && PP=2 M=4 SEQ=512 ITERS=20 VARIANT=plain " + "MEGATRON=/opt/Megatron-LM bash megatron_pretrain.sh 2>&1 | " + "grep -E 'elapsed time per iteration|lm loss|Error|error' | tail -8" + ) + hf_cache.commit() + return results + + +@app.function( + gpu="H100:2", timeout=1800, cpu=16, memory=65536, volumes={"/root/.cache/huggingface": hf_cache} +) +def megatron_only(extra: str = ""): + import subprocess + + r = subprocess.run( + f"cd /root/rdsp/bench && PP=2 M=4 SEQ=512 ITERS=20 VARIANT=plain " + f"MEGATRON=/opt/Megatron-LM {extra} bash megatron_pretrain.sh", + shell=True, + capture_output=True, + text=True, + ) + out = r.stdout + r.stderr + keep = [ + line + for line in out.splitlines() + if "[rank0]" in line or "elapsed time" in line or "lm loss" in line + ] + return r.returncode, "\n".join(keep[-60:]) or out[-8000:] + + +@app.local_entrypoint() +def main(only: str = ""): + if only == "megatron": + code, out = megatron_only.remote() + print(out, f"\nexit {code}") + return + for k, (code, out) in smoke.remote().items(): + print(f"===== {k} (exit {code})\n{out}") diff --git a/training/rdsp/bench/rdsp_bench.py b/training/rdsp/bench/rdsp_bench.py new file mode 100644 index 000000000..4b714168d --- /dev/null +++ b/training/rdsp/bench/rdsp_bench.py @@ -0,0 +1,208 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team + +"""Train one rdsp benchmark cell on the local GPUs and write its results as JSON. + + python rdsp_bench.py --pp 4 --m 16 --seq 512 --data --out + +Assembles the pipeline the same way as the Qwen3-0.6B GPU acceptance test. +--data is a [steps, m, b, s+1] token tensor shared with the Megatron runs. +""" + +import argparse +import json +import os +import time + +import ray +import torch +import torch.nn.functional as F +import transformers +from bench_hooks import ( + apply_fusions, + fused_engine_factory, + fused_prof_engine_factory, + fused_timed_engine_factory, + tagged_stage_builder, + timed_engine_factory, +) + +import ray_deepspeed_pipeline as rdsp +from ray_deepspeed_pipeline.compiler import lower +from ray_deepspeed_pipeline.config import StageOverride +from ray_deepspeed_pipeline.coordinator import PipelineCoordinator +from ray_deepspeed_pipeline.engine import RayPipelineEngine +from ray_deepspeed_pipeline.stage_group import create_stage_clients + + +def loss_fn(out, labels): + return F.cross_entropy(out.float().reshape(-1, out.shape[-1]), labels.reshape(-1)) + + +p = argparse.ArgumentParser() +for name, typ, default in [ + ("hf", str, "/cache/qwen3-0.6b-untied"), + ("pp", int, 2), + ("m", int, 8), + ("seq", int, 2048), + ("steps", int, 60), + ("warmup", int, 10), + ("data", str, None), + ("out", str, None), + ("cuts", str, ""), + ("last_stage_gpus", int, 1), + ("timeline", int, 0), + ("timed", int, 0), + ("fused", int, 0), + ("prof", int, 0), + ("b", int, 0), +]: + p.add_argument(f"--{name}", type=typ, default=default) +a = p.parse_args() +b = a.b or (4 if a.seq == 512 else 1) # rows per microbatch: 2048 tokens by default +# a stage with k GPUs splits every microbatch's rows k ways (data parallel +# inside the stage), so the microbatch needs a multiple of k rows +b = max(b, a.last_stage_gpus) if b % a.last_stage_gpus else b +os.environ["RDSP_BENCH_WARMUP"] = str(a.warmup) +if a.timed: # fresh per-stage timing files for this run + import shutil + + shutil.rmtree(os.environ.get("RDSP_BENCH_DIR", "/tmp/rdsp_bench"), ignore_errors=True) + +ray.init( + include_dashboard=False, + log_to_driver=False, + runtime_env={ + "env_vars": { + "PYTHONPATH": os.path.dirname(os.path.abspath(__file__)), + "RDSP_BENCH_WARMUP": str(a.warmup), + } + }, +) +if a.fused: + apply_fusions() # before model construction: fused norm/MLP classes + from liger_kernel.transformers import LigerCrossEntropyLoss + + _fused_ce = LigerCrossEntropyLoss() + + def loss_fn(out, labels): # fused CE: no fp32 copy of the [tokens, vocab] logits + return _fused_ce(out.reshape(-1, out.shape[-1]), labels.reshape(-1)) + + +model = transformers.AutoModelForCausalLM.from_pretrained(a.hf, dtype=torch.bfloat16) +assert model.lm_head.weight is not model.model.embed_tokens.weight # untied checkpoint + +ds = { + "train_micro_batch_size_per_gpu": b, + "gradient_accumulation_steps": a.m, + "train_batch_size": b * a.m, + "optimizer": { + "type": "AdamW", + "params": { + "lr": 1e-5, + "betas": [0.9, 0.999], + "eps": 1e-8, + "weight_decay": 0.0, + "torch_adam": True, + **({"fused": True} if a.fused else {}), + }, + }, + "zero_optimization": {"stage": 0}, + "bf16": {"enabled": True}, + "gradient_clipping": 0.0, + "steps_per_print": 10**9, +} +part = ( + rdsp.ExplicitCuts(tuple(int(c) for c in a.cuts.split(","))) + if a.cuts + else rdsp.UniformTransformerBlocks() +) +overrides = ( + (StageOverride(stage=a.pp - 1, num_gpus=a.last_stage_gpus),) if a.last_stage_gpus > 1 else () +) +plan = lower( + model, + rdsp.PipelineConfig(stages=a.pp, partition=part, microbatches=a.m, stage_overrides=overrides), + ds, +) +# Clean throughput runs use rdsp's own engine factory (None); --timed 1 adds +# the CUDA-event proxy (one host sync per step) for per-stage busy times. +if a.fused: + factory = ( + fused_prof_engine_factory + if a.prof + else fused_timed_engine_factory + if a.timed + else fused_engine_factory + ) +else: + factory = timed_engine_factory if a.timed else None +clients = create_stage_clients( + model, plan, loss_fn, use_gpu=True, stage_builder=tagged_stage_builder, engine_factory=factory +) +engine = RayPipelineEngine(PipelineCoordinator(plan, clients)) +del model # the driver holds no weights + +X = torch.load(a.data) # [steps, m, b, s+1]; labels are the inputs shifted by one + + +def mbs(step): + return iter( + [ + ( + X[step % X.shape[0], k][:, :-1].contiguous(), + X[step % X.shape[0], k][:, 1:].contiguous(), + ) + for k in range(a.m) + ] + ) + + +times, losses, windows = [], [], [] +for step in range(a.steps): + t0, w0 = time.perf_counter(), time.time() + losses.append(float(engine.train_batch(data_iter=mbs(step)))) + times.append(time.perf_counter() - t0) + windows.append((w0, time.time())) # epoch seconds, to align with the Ray timeline + +profile = {} +if a.timeline: + ray.timeline(filename=a.out + ".timeline.json") + with open(a.out + ".timeline.json") as f: + profile["timeline"] = json.load(f) + profile["step_windows"] = windows +if a.timed: + import glob + + time.sleep(1) # let the actors' last JSON lines reach disk + stage_ops = {} + bench_dir = os.environ.get("RDSP_BENCH_DIR", "/tmp/rdsp_bench") + for path in glob.glob(os.path.join(bench_dir, "*.jsonl")): + with open(path) as f: + stage_ops[os.path.basename(path)] = [json.loads(line) for line in f] + profile["stage_ops"] = stage_ops +order = ( + {c.stage: [ray.get(act.executed_commands.remote()) for act in c.actors] for c in clients} + if a.timeline + else None +) +with open(a.out, "w") as f: + json.dump( + { + "system": "rdsp", + "fused": a.fused, + "pp": a.pp, + "m": a.m, + "seq": a.seq, + "b": b, + "cuts": a.cuts, + "last_stage_gpus": a.last_stage_gpus, + "stage_tags": [f"blocks{s.block_start:02d}-{s.block_stop:02d}" for s in plan.stages], + "step_s": times[a.warmup :], + "loss": losses, + "executed": order, + "profile": profile, + }, + f, + ) +ray.shutdown() diff --git a/training/rdsp/bench/results/all_cells.md b/training/rdsp/bench/results/all_cells.md new file mode 100644 index 000000000..bfaa1ca35 --- /dev/null +++ b/training/rdsp/bench/results/all_cells.md @@ -0,0 +1,102 @@ +| system | PP | GPUs | m | seq | step (median / p90) | tokens/s | tokens/s/GPU | MFU | efficiency E | textbook bubble | peak GB | +|---|---|---|---|---|---|---|---|---|---|---|---| +| M-defaults | 1 | 1 | 8 | 512 | 1149 / 1207 ms | 14,256 | 14,256 | 5.4% | 1.00 | 0.00 | 22.9 | +| M-plain | 1 | 1 | 8 | 512 | 1074 / 1086 ms | 15,255 | 15,255 | 5.8% | 1.00 | 0.00 | 20.7 | +| R-os | 1 | 1 | 8 | 512 | 778 / 787 ms | 21,064 | 21,064 | 8.0% | 1.00 | 0.00 | 23.7 | +| R-os-fused | 1 | 1 | 8 | 512 | 695 / 706 ms | 23,584 | 23,584 | 8.9% | 1.00 | 0.00 | 19.5 | +| M-defaults | 2 | 2 | 4 | 512 | 396 / 400 ms | 20,713 | 10,357 | 3.9% | 0.73 | 0.20 | 16.2 | +| M-plain | 2 | 2 | 4 | 512 | 397 / 416 ms | 20,645 | 10,323 | 3.9% | 0.68 | 0.20 | 14.1 | +| R-os | 2 | 2 | 4 | 512 | 337 / 359 ms | 24,327 | 12,164 | 4.6% | 0.58 | 0.20 | 14.7 | +| R-os-fused | 2 | 2 | 4 | 512 | 328 / 334 ms | 24,975 | 12,487 | 4.7% | 0.53 | 0.20 | 11.8 | +| R-rdt | 2 | 2 | 4 | 512 | 294 / 321 ms | 27,826 | 13,913 | 5.3% | 0.66 | 0.20 | 15.6 | +| R-rdt-fused | 2 | 2 | 4 | 512 | 292 / 300 ms | 28,103 | 14,051 | 5.3% | 0.60 | 0.20 | 12.6 | +| M-defaults | 2 | 2 | 8 | 512 | 697 / 704 ms | 23,515 | 11,757 | 4.5% | 0.82 | 0.11 | 16.2 | +| M-plain | 2 | 2 | 8 | 512 | 693 / 724 ms | 23,656 | 11,828 | 4.5% | 0.78 | 0.11 | 14.1 | +| R-os | 2 | 2 | 8 | 512 | 520 / 568 ms | 31,483 | 15,742 | 6.0% | 0.75 | 0.11 | 14.7 | +| R-os-fused | 2 | 2 | 8 | 512 | 557 / 583 ms | 29,428 | 14,714 | 5.6% | 0.62 | 0.11 | 11.8 | +| R-rdt | 2 | 2 | 8 | 512 | 539 / 595 ms | 30,390 | 15,195 | 5.8% | 0.72 | 0.11 | 15.6 | +| R-rdt-fused | 2 | 2 | 8 | 512 | 487 / 501 ms | 33,645 | 16,822 | 6.4% | 0.71 | 0.11 | 12.6 | +| M-defaults | 2 | 2 | 16 | 512 | 1382 / 1414 ms | 23,703 | 11,851 | 4.5% | 0.83 | 0.06 | 16.3 | +| M-plain | 2 | 2 | 16 | 512 | 1290 / 1358 ms | 25,408 | 12,704 | 4.8% | 0.83 | 0.06 | 14.1 | +| R-os | 2 | 2 | 16 | 512 | 998 / 1094 ms | 32,832 | 16,416 | 6.2% | 0.78 | 0.06 | 14.7 | +| R-os-fused | 2 | 2 | 16 | 512 | 1031 / 1076 ms | 31,796 | 15,898 | 6.0% | 0.67 | 0.06 | 11.8 | +| R-rdt | 2 | 2 | 16 | 512 | 970 / 1030 ms | 33,794 | 16,897 | 6.4% | 0.80 | 0.06 | 15.6 | +| R-rdt-fused | 2 | 2 | 16 | 512 | 873 / 899 ms | 37,524 | 18,762 | 7.1% | 0.80 | 0.06 | 12.6 | +| M-defaults | 4 | 4 | 4 | 512 | 317 / 322 ms | 25,855 | 6,464 | 2.5% | 0.45 | 0.43 | 14.6 | +| M-plain | 4 | 4 | 4 | 512 | 296 / 307 ms | 27,643 | 6,911 | 2.6% | 0.45 | 0.43 | 12.6 | +| R-os | 4 | 4 | 4 | 512 | 284 / 306 ms | 28,820 | 7,205 | 2.7% | 0.34 | 0.43 | 12.2 | +| R-os-fused | 4 | 4 | 4 | 512 | 307 / 326 ms | 26,668 | 6,667 | 2.5% | 0.28 | 0.43 | 10.2 | +| R-rdt | 4 | 4 | 4 | 512 | 276 / 288 ms | 29,651 | 7,413 | 2.8% | 0.35 | 0.43 | 13.1 | +| R-rdt-fused | 4 | 4 | 4 | 512 | 271 / 277 ms | 30,210 | 7,552 | 2.9% | 0.32 | 0.43 | 10.8 | +| M-defaults | 4 | 4 | 8 | 512 | 505 / 521 ms | 32,447 | 8,112 | 3.1% | 0.57 | 0.27 | 14.6 | +| M-plain | 4 | 4 | 8 | 512 | 493 / 505 ms | 33,254 | 8,313 | 3.2% | 0.54 | 0.27 | 12.6 | +| M-plain (balanced) | 4 | 4 | 8 | 512 | 455 / 466 ms | 36,005 | 9,001 | 3.4% | 0.59 | 0.27 | 13.9 | +| R-os | 4 | 4 | 8 | 512 | 429 / 449 ms | 38,201 | 9,550 | 3.6% | 0.45 | 0.27 | 12.2 | +| R-os (balanced) | 4 | 4 | 8 | 512 | 492 / 532 ms | 33,273 | 8,318 | 3.2% | 0.39 | 0.27 | 13.1 | +| R-os (capability) | 4 | 5 | 8 | 512 | 490 / 525 ms | 33,416 | 6,683 | 2.5% | 0.40 | 0.27 | 12.0 | +| R-os-fused | 4 | 4 | 8 | 512 | 488 / 514 ms | 33,541 | 8,385 | 3.2% | 0.36 | 0.27 | 10.4 | +| R-rdt | 4 | 4 | 8 | 512 | 442 / 461 ms | 37,060 | 9,265 | 3.5% | 0.44 | 0.27 | 13.6 | +| R-rdt (balanced) | 4 | 4 | 8 | 512 | 447 / 467 ms | 36,692 | 9,173 | 3.5% | 0.44 | 0.27 | 15.2 | +| R-rdt (capability) | 4 | 5 | 8 | 512 | 473 / 493 ms | 34,632 | 6,926 | 2.6% | 0.41 | 0.27 | 13.5 | +| R-rdt-fused | 4 | 4 | 8 | 512 | 432 / 447 ms | 37,931 | 9,483 | 3.6% | 0.40 | 0.27 | 11.3 | +| M-defaults | 4 | 4 | 16 | 512 | 909 / 929 ms | 36,044 | 9,011 | 3.4% | 0.63 | 0.16 | 13.4 | +| M-plain | 4 | 4 | 16 | 512 | 814 / 843 ms | 40,256 | 10,064 | 3.8% | 0.66 | 0.16 | 12.6 | +| R-os | 4 | 4 | 16 | 512 | 789 / 826 ms | 41,509 | 10,377 | 3.9% | 0.49 | 0.16 | 12.2 | +| R-os-fused | 4 | 4 | 16 | 512 | 813 / 847 ms | 40,298 | 10,074 | 3.8% | 0.43 | 0.16 | 10.4 | +| R-rdt | 4 | 4 | 16 | 512 | 721 / 768 ms | 45,442 | 11,360 | 4.3% | 0.54 | 0.16 | 13.6 | +| R-rdt-fused | 4 | 4 | 16 | 512 | 752 / 767 ms | 43,546 | 10,886 | 4.1% | 0.46 | 0.16 | 11.3 | +| M-defaults | 1 | 1 | 8 | 2048 | 1097 / 1114 ms | 14,937 | 14,937 | 6.5% | 1.00 | 0.00 | 22.9 | +| M-plain | 1 | 1 | 8 | 2048 | 1054 / 1070 ms | 15,545 | 15,545 | 6.7% | 1.00 | 0.00 | 20.6 | +| R-os | 1 | 1 | 8 | 2048 | 803 / 820 ms | 20,403 | 20,403 | 8.8% | 1.00 | 0.00 | 23.7 | +| R-os-fused | 1 | 1 | 8 | 2048 | 715 / 723 ms | 22,904 | 22,904 | 9.9% | 1.00 | 0.00 | 19.5 | +| M-defaults | 2 | 2 | 4 | 2048 | 399 / 410 ms | 20,516 | 10,258 | 4.4% | 0.69 | 0.20 | 16.2 | +| M-plain | 2 | 2 | 4 | 2048 | 389 / 412 ms | 21,056 | 10,528 | 4.6% | 0.68 | 0.20 | 14.0 | +| R-os | 2 | 2 | 4 | 2048 | 322 / 346 ms | 25,413 | 12,706 | 5.5% | 0.62 | 0.20 | 14.7 | +| R-os-fused | 2 | 2 | 4 | 2048 | 317 / 327 ms | 25,864 | 12,932 | 5.6% | 0.56 | 0.20 | 11.8 | +| R-rdt | 2 | 2 | 4 | 2048 | 295 / 327 ms | 27,803 | 13,901 | 6.0% | 0.68 | 0.20 | 15.6 | +| R-rdt-fused | 2 | 2 | 4 | 2048 | 273 / 288 ms | 30,052 | 15,026 | 6.5% | 0.66 | 0.20 | 12.6 | +| M-defaults | 2 | 2 | 8 | 2048 | 730 / 774 ms | 22,445 | 11,223 | 4.9% | 0.75 | 0.11 | 16.3 | +| M-plain | 2 | 2 | 8 | 2048 | 667 / 696 ms | 24,556 | 12,278 | 5.3% | 0.79 | 0.11 | 14.0 | +| R-os | 2 | 2 | 8 | 2048 | 534 / 596 ms | 30,686 | 15,343 | 6.6% | 0.75 | 0.11 | 14.7 | +| R-os-fused | 2 | 2 | 8 | 2048 | 558 / 567 ms | 29,378 | 14,689 | 6.4% | 0.64 | 0.11 | 11.8 | +| R-rdt | 2 | 2 | 8 | 2048 | 554 / 590 ms | 29,555 | 14,777 | 6.4% | 0.72 | 0.11 | 15.6 | +| R-rdt-fused | 2 | 2 | 8 | 2048 | 499 / 520 ms | 32,843 | 16,421 | 7.1% | 0.72 | 0.11 | 12.6 | +| M-defaults | 2 | 2 | 16 | 2048 | 1367 / 1386 ms | 23,965 | 11,983 | 5.2% | 0.80 | 0.06 | 16.2 | +| M-plain | 2 | 2 | 16 | 2048 | 1338 / 1392 ms | 24,484 | 12,242 | 5.3% | 0.79 | 0.06 | 14.0 | +| R-os | 2 | 2 | 16 | 2048 | 1091 / 1173 ms | 30,041 | 15,020 | 6.5% | 0.74 | 0.06 | 14.7 | +| R-os-fused | 2 | 2 | 16 | 2048 | 982 / 1006 ms | 33,377 | 16,689 | 7.2% | 0.73 | 0.06 | 11.8 | +| R-rdt | 2 | 2 | 16 | 2048 | 1009 / 1072 ms | 32,477 | 16,238 | 7.0% | 0.80 | 0.06 | 15.6 | +| R-rdt-fused | 2 | 2 | 16 | 2048 | 917 / 931 ms | 35,732 | 17,866 | 7.7% | 0.78 | 0.06 | 12.6 | +| M-defaults | 4 | 4 | 4 | 2048 | 305 / 314 ms | 26,863 | 6,716 | 2.9% | 0.45 | 0.43 | 13.4 | +| M-plain | 4 | 4 | 4 | 2048 | 297 / 313 ms | 27,541 | 6,885 | 3.0% | 0.44 | 0.43 | 12.4 | +| R-os | 4 | 4 | 4 | 2048 | 302 / 320 ms | 27,128 | 6,782 | 2.9% | 0.33 | 0.43 | 12.2 | +| R-os-fused | 4 | 4 | 4 | 2048 | 313 / 326 ms | 26,195 | 6,549 | 2.8% | 0.29 | 0.43 | 10.2 | +| R-rdt | 4 | 4 | 4 | 2048 | 264 / 276 ms | 31,022 | 7,756 | 3.4% | 0.38 | 0.43 | 13.1 | +| R-rdt-fused | 4 | 4 | 4 | 2048 | 268 / 274 ms | 30,616 | 7,654 | 3.3% | 0.33 | 0.43 | 10.8 | +| M-defaults | 4 | 4 | 8 | 2048 | 487 / 492 ms | 33,636 | 8,409 | 3.6% | 0.56 | 0.27 | 14.6 | +| M-plain | 4 | 4 | 8 | 2048 | 483 / 499 ms | 33,935 | 8,484 | 3.7% | 0.55 | 0.27 | 12.4 | +| R-os | 4 | 4 | 8 | 2048 | 426 / 451 ms | 38,454 | 9,614 | 4.2% | 0.47 | 0.27 | 12.2 | +| R-os-fused | 4 | 4 | 8 | 2048 | 495 / 517 ms | 33,120 | 8,280 | 3.6% | 0.36 | 0.27 | 10.4 | +| R-rdt | 4 | 4 | 8 | 2048 | 410 / 435 ms | 39,918 | 9,979 | 4.3% | 0.49 | 0.27 | 13.6 | +| R-rdt-fused | 4 | 4 | 8 | 2048 | 429 / 436 ms | 38,193 | 9,548 | 4.1% | 0.42 | 0.27 | 11.3 | +| M-defaults | 4 | 4 | 16 | 2048 | 845 / 862 ms | 38,795 | 9,699 | 4.2% | 0.65 | 0.16 | 14.6 | +| M-plain | 4 | 4 | 16 | 2048 | 848 / 876 ms | 38,644 | 9,661 | 4.2% | 0.62 | 0.16 | 12.4 | +| R-os | 4 | 4 | 16 | 2048 | 722 / 748 ms | 45,394 | 11,349 | 4.9% | 0.56 | 0.16 | 12.2 | +| R-os-fused | 4 | 4 | 16 | 2048 | 801 / 831 ms | 40,899 | 10,225 | 4.4% | 0.45 | 0.16 | 10.4 | +| R-rdt | 4 | 4 | 16 | 2048 | 755 / 795 ms | 43,408 | 10,852 | 4.7% | 0.53 | 0.16 | 13.6 | +| R-rdt-fused | 4 | 4 | 16 | 2048 | 751 / 770 ms | 43,607 | 10,902 | 4.7% | 0.48 | 0.16 | 11.3 | + +| PP | m | seq | R-os-fused / M-defaults | R-rdt-fused / M-defaults | R-os / M-plain | R-rdt / R-os | +|---|---|---|---|---|---|---| +| 2 | 4 | 512 | 1.21 | 1.36 | 1.18 | 1.14 | +| 2 | 8 | 512 | 1.25 | 1.43 | 1.33 | 0.97 | +| 2 | 16 | 512 | 1.34 | 1.58 | 1.29 | 1.03 | +| 4 | 4 | 512 | 1.03 | 1.17 | 1.04 | 1.03 | +| 4 | 8 | 512 | 1.03 | 1.17 | 1.15 | 0.97 | +| 4 | 16 | 512 | 1.12 | 1.21 | 1.03 | 1.09 | +| 2 | 4 | 2048 | 1.26 | 1.46 | 1.21 | 1.09 | +| 2 | 8 | 2048 | 1.31 | 1.46 | 1.25 | 0.96 | +| 2 | 16 | 2048 | 1.39 | 1.49 | 1.23 | 1.08 | +| 4 | 4 | 2048 | 0.98 | 1.14 | 0.99 | 1.14 | +| 4 | 8 | 2048 | 0.98 | 1.14 | 1.13 | 1.04 | +| 4 | 16 | 2048 | 1.05 | 1.12 | 1.17 | 0.96 | diff --git a/training/rdsp/bench/setup_node.sh b/training/rdsp/bench/setup_node.sh new file mode 100755 index 000000000..c5bddda3f --- /dev/null +++ b/training/rdsp/bench/setup_node.sh @@ -0,0 +1,33 @@ +#!/bin/bash +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team +# Fresh Linux GPU node -> ready to run recipes/ and bench/mimo/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/checks/compare_mrope.py b/training/rdsp/bench/torchtitan/checks/compare_mrope.py new file mode 100644 index 000000000..d010a3c91 --- /dev/null +++ b/training/rdsp/bench/torchtitan/checks/compare_mrope.py @@ -0,0 +1,42 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team + +"""TorchTitan's M-RoPE positions (saved by checks/tt_data_check.py) against Hugging +Face's Qwen3_5Model.get_rope_index on the same exported rows, real tokens only +(padding positions never feed a real token: attention is causal). + + .venv/bin/python rdsp/bench/torchtitan/checks/compare_mrope.py +""" + +import glob +import os +import sys + +import huggingface_hub +import torch +import transformers + +saved = torch.load(sys.argv[1], weights_only=False) +rows = torch.load(sorted(glob.glob(os.path.join(sys.argv[2], "step_*.pt")))[0], weights_only=False) +path = huggingface_hub.snapshot_download("Qwen/Qwen3.5-27B", allow_patterns=["*.json"]) +config = transformers.AutoConfig.from_pretrained(path) +with torch.device("meta"): + model = transformers.Qwen3_5Model(config) +for i, (s, row) in enumerate(zip(saved, rows)): + assert torch.equal(s["input_ids"], row["input_ids"][0]) + pos, _ = model.get_rope_index( + row["input_ids"], + row["mm_token_type_ids"], + image_grid_thw=row["image_grid_thw"], + attention_mask=row["attention_mask"], + ) + hf = pos[:, 0, :].T.cpu() # (S, 3) + real = row["attention_mask"][0].bool() + tt = s["tt_mrope"].to(hf.dtype) + diff = (hf[real] - tt[real]).abs().max().item() + print( + f"row {i}: {int(real.sum())} real tokens, image grid {row['image_grid_thw'].tolist()}, " + f"max |HF - TorchTitan| position difference {diff}" + ) + assert diff == 0, f"row {i}: positions differ" +print("OK: M-RoPE positions identical on every real token") diff --git a/training/rdsp/bench/torchtitan/checks/make_fake_export.py b/training/rdsp/bench/torchtitan/checks/make_fake_export.py new file mode 100644 index 000000000..b40e758d0 --- /dev/null +++ b/training/rdsp/bench/torchtitan/checks/make_fake_export.py @@ -0,0 +1,78 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team + +"""A small export in the format of bench/mimo/export_bridge_batches.py, built with the +real Qwen3.5 Hugging Face processor: random images of varying sizes, a chat prompt and +an answer, labels on the last 12 real tokens (Hugging Face convention: unshifted, -100 +elsewhere; any known mask serves the check), every row padded to 2048. Row i's answer +names i, so order can be checked. + + .venv/bin/python rdsp/bench/torchtitan/checks/make_fake_export.py [steps] +""" + +import os +import sys + +import huggingface_hub +import numpy as np +import torch +import transformers +from PIL import Image + +SEQ, ROWS = 2048, 64 +out = sys.argv[1] +steps = int(sys.argv[2]) if len(sys.argv) > 2 else 2 +path = huggingface_hub.snapshot_download( + "Qwen/Qwen3.5-27B", allow_patterns=["*.json", "*.txt", "*.jinja"] +) +processor = transformers.AutoProcessor.from_pretrained(path) +pad = processor.tokenizer.convert_tokens_to_ids("<|endoftext|>") +rng = np.random.default_rng(0) +os.makedirs(out, exist_ok=True) +for step in range(steps): + samples = [] + for r in range(ROWS): + i = step * ROWS + r + h, w = (int(x) for x in rng.integers(48, 200, size=2)) + image = Image.fromarray(rng.integers(0, 255, size=(h, w, 3), dtype=np.uint8)) + prompt = [ + { + "role": "user", + "content": [ + {"type": "image", "image": image}, + {"type": "text", "text": "Read the receipt."}, + ], + } + ] + full = prompt + [ + {"role": "assistant", "content": [{"type": "text", "text": f"row {i}: total {i * 7}"}]} + ] + f = processor.apply_chat_template( + full, tokenize=True, return_dict=True, return_tensors="pt" + ) + ids = f["input_ids"][0] + n = ids.shape[0] + start = n - 12 + input_ids = torch.full((1, SEQ), pad, dtype=ids.dtype) + input_ids[0, :n] = ids + attention_mask = torch.zeros((1, SEQ), dtype=torch.long) + attention_mask[0, :n] = 1 + labels = torch.full((1, SEQ), -100, dtype=ids.dtype) + labels[0, start:n] = ids[start:n] + mm = f.get("mm_token_type_ids") + mm_ids = torch.zeros((1, SEQ), dtype=torch.long) + if mm is not None: + mm_ids[0, :n] = mm[0] + samples.append( + { + "input_ids": input_ids, + "attention_mask": attention_mask, + "mm_token_type_ids": mm_ids, + "pixel_values": f["pixel_values"].to(torch.bfloat16), + "image_grid_thw": f["image_grid_thw"].clone(), + "labels": labels, + "tokens": int((labels != -100).sum()), + } + ) + torch.save(samples, os.path.join(out, f"step_{step:05d}.pt")) +print(f"wrote {steps} steps x {ROWS} rows to {out}; processor {path}") diff --git a/training/rdsp/bench/torchtitan/checks/tt_data_check.py b/training/rdsp/bench/torchtitan/checks/tt_data_check.py new file mode 100644 index 000000000..706e43b87 --- /dev/null +++ b/training/rdsp/bench/torchtitan/checks/tt_data_check.py @@ -0,0 +1,76 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team + +"""CPU check of cord_data.py through TorchTitan's own loader and MultiModalCollator: +every microbatch against the exported row it came from. Saves the first rows' M-RoPE +positions for checks/compare_mrope.py (Hugging Face's get_rope_index). + + PYTHONPATH=rdsp/bench/torchtitan /bin/python \\ + rdsp/bench/torchtitan/checks/tt_data_check.py +""" + +import glob +import os +import sys + +import cord_data +import torch +from torchtitan.components.loss import IGNORE_INDEX +from torchtitan.components.tokenizer import MultiModalTokenizer + +export, hf, out = sys.argv[1:4] +# torchtitan/models/qwen3_5/flavors.py QWEN3_5_SPECIAL_TOKENS (importing the model +# package pulls GPU-only kernels) +SPECIAL = { + "image_token": "<|image_pad|>", + "video_token": "<|video_pad|>", + "vision_start_token": "<|vision_start|>", + "vision_end_token": "<|vision_end|>", + "pad_token": "<|endoftext|>", +} +tokenizer = MultiModalTokenizer.Config(**SPECIAL).build(tokenizer_path=hf) +loader = cord_data.exported_dataloader(export).build( + dp_world_size=1, + dp_rank=0, + tokenizer=tokenizer, + max_context_length=2048, + num_tokens_per_microbatch=2048, +) +rows = [ + r + for p in sorted(glob.glob(os.path.join(export, "step_*.pt"))) + for r in torch.load(p, weights_only=False) +] +saved, n = [], 0 +for mb, row in zip(loader, rows): + ids, hf_labels = row["input_ids"][0], row["labels"][0] + assert torch.equal(mb.input.flatten(), ids), f"row {n}: input differs" + want = torch.full_like(ids, IGNORE_INDEX) + want[:-1] = hf_labels[1:] + assert torch.equal(mb.labels.flatten(), want), f"row {n}: labels differ" + kw = mb.model_kwargs + assert torch.equal(kw["pixel_values"], row["pixel_values"]), f"row {n}: patches differ" + assert torch.equal(kw["grid_thw"], row["image_grid_thw"]), f"row {n}: grid differs" + assert int(mb.loss_token_counts) == int((hf_labels[1:] != IGNORE_INDEX).sum()), ( + f"row {n}: count" + ) + assert not bool(mb.padding_mask.any()), f"row {n}: unexpected padding" + assert kw["special_tokens"]["image_id"] == tokenizer.image_id + if n < 8: + saved.append( + { + "input_ids": ids, + "image_grid_thw": row["image_grid_thw"], + "attention_mask": row["attention_mask"][0], + "tt_mrope": kw["mrope_positions"], + } + ) + n += 1 +assert n == len(rows), f"loader gave {n} microbatches for {len(rows)} rows" +torch.save(saved, out) +m = saved[0]["tt_mrope"] +print( + f"OK: {n} microbatches = {len(rows)} exported rows, in order; inputs, shifted labels, " + f"patches, grids, loss-token counts all equal. mrope_positions shape {tuple(m.shape)}, " + f"image_id {tokenizer.image_id}, pad_id {tokenizer.pad_id}" +) diff --git a/training/rdsp/bench/torchtitan/checks/tt_dp_check.py b/training/rdsp/bench/torchtitan/checks/tt_dp_check.py new file mode 100644 index 000000000..e10bfcc13 --- /dev/null +++ b/training/rdsp/bench/torchtitan/checks/tt_dp_check.py @@ -0,0 +1,63 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team + +"""CPU check: with data parallelism 2 (layout C3), TorchTitan's loader on rank r gives +microbatch k = exported row 2k + r, so each step trains on the same 64 consecutive rows +as Megatron-Bridge (global microbatch k = rows 2k, 2k + 1). Also builds the C3 configs. + + PYTHONPATH=rdsp/bench/torchtitan EXPORTED= HF_ASSETS= \\ + /bin/python rdsp/bench/torchtitan/checks/tt_dp_check.py +""" + +import glob +import os + +import cord_data +import cord_qwen35 +import torch +from torchtitan.components.tokenizer import MultiModalTokenizer + +export, hf = os.environ["EXPORTED"], os.environ["HF_ASSETS"] +SPECIAL = { + "image_token": "<|image_pad|>", + "video_token": "<|video_pad|>", + "vision_start_token": "<|vision_start|>", + "vision_end_token": "<|vision_end|>", + "pad_token": "<|endoftext|>", +} +tokenizer = MultiModalTokenizer.Config(**SPECIAL).build(tokenizer_path=hf) +rows = [ + r + for p in sorted(glob.glob(os.path.join(export, "step_*.pt"))) + for r in torch.load(p, weights_only=False) +] +for rank in (0, 1): + loader = cord_data.exported_dataloader(export, data_parallel=2).build( + dp_world_size=2, + dp_rank=rank, + tokenizer=tokenizer, + max_context_length=2048, + num_tokens_per_microbatch=2048, + ) + it = iter(loader) + for k in range(len(rows) // 2): + mb = next(it) + assert torch.equal(mb.input.flatten(), rows[2 * k + rank]["input_ids"][0]), (rank, k) + print( + f"rank {rank}: microbatches 0-{len(rows) // 2 - 1} = exported rows " + f"{rank}, {rank + 2}, ..., {len(rows) - 2 + rank}" + ) +for name in ("qwen35_27b_cord_tp4dp2", "qwen35_27b_cord_tp4dp2_rc"): + c = getattr(cord_qwen35, name)() + p, t = c.parallelism, c.training + accumulation = t.num_tokens_per_train_step // (t.num_tokens_per_microbatch_per_dp_rank * 2) + recompute = type(c.activation_checkpoint).__name__ if c.activation_checkpoint else None + print( + f"{name}: dp_shard {p.data_parallel_shard_degree} TP {p.tensor_parallel_degree} " + f"PP {p.pipeline_parallel_degree} SP {p.enable_sequence_parallel} " + f"| tokens/microbatch {t.num_tokens_per_microbatch_per_dp_rank} " + f"tokens/step {t.num_tokens_per_train_step} -> accumulation {accumulation} " + f"| recompute {recompute} " + f"| loader repeat {c.dataloader.repeat} shuffle {c.dataloader.shuffle}" + ) +print("OK") diff --git a/training/rdsp/bench/torchtitan/cord_data.py b/training/rdsp/bench/torchtitan/cord_data.py new file mode 100644 index 000000000..3bb5c3af5 --- /dev/null +++ b/training/rdsp/bench/torchtitan/cord_data.py @@ -0,0 +1,135 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team + +"""Megatron-Bridge's exported CORD-v2 rows as a TorchTitan dataset (see cord_qwen35.py). + +Source, processor and collator only: no model or kernel code, so the data path runs +and is tested on a CPU. +""" + +import glob +import os +import threading +from dataclasses import dataclass +from typing import Any + +import numpy as np +import torch +from torchtitan.components.data import GrainDataLoader, SampleProcessor, SingleDatasetConfig +from torchtitan.components.data.multimodal.mm_collator import MultiModalCollator +from torchtitan.components.data.types import DatasetBuildContext +from torchtitan.components.loss import IGNORE_INDEX +from torchtitan.config import Configurable + +ROWS_PER_STEP = int(os.environ.get("ROWS", "64")) # rows of 2048 per step: 64, 128 on two nodes + + +class ExportedStepsSource(Configurable): + """Rows of an export directory in training order: step file by step file, row + by row. A step file (one training step's rows) is loaded once and kept while + its rows are read.""" + + @dataclass(kw_only=True, slots=True) + class Config(Configurable.Config): + directory: str + rows_per_step: int = ROWS_PER_STEP + data_parallel: int = 1 + """TorchTitan gives data-parallel rank r the r-th contiguous slice of the + dataset; Megatron gives it row r of each group of `data_parallel` consecutive + rows. With data_parallel = d, index i serves row (i % n) * d + i // n (n = rows + / d), so rank r's slice is rows r, r + d, r + 2d, ... and each microbatch holds + the same d consecutive rows as Megatron's.""" + + def __init__(self, config: Config) -> None: + self.paths = sorted(glob.glob(os.path.join(config.directory, "step_*.pt"))) + if not self.paths: + raise FileNotFoundError(f"no step_*.pt files in {config.directory}") + self.rows = config.rows_per_step + self.dp = config.data_parallel + if (len(self.paths) * self.rows) % self.dp: + raise ValueError( + f"{len(self.paths) * self.rows} rows do not split over {self.dp} ranks" + ) + self._lock = threading.Lock() + self._cached: tuple[int, list] | None = None + + def __len__(self) -> int: + return len(self.paths) * self.rows + + def _step(self, step: int) -> list: + with self._lock: + if self._cached is None or self._cached[0] != step: + samples = torch.load(self.paths[step], weights_only=False) + if len(samples) != self.rows: + raise ValueError( + f"{self.paths[step]}: {len(samples)} rows, expected {self.rows}" + ) + self._cached = (step, samples) + return self._cached[1] + + def __getitem__(self, index: int) -> dict[str, Any]: + shard, offset = divmod(index, len(self) // self.dp) + step, row = divmod(offset * self.dp + shard, self.rows) + return self._step(step)[row] + + +def exported_row_to_sample(row: dict[str, Any]) -> dict[str, Any]: + """One exported row (batch of 1, Hugging Face conventions) as a TorchTitan + multimodal sample: input = all exported tokens, label t = target of input t, + and one (patches, grid) pair per image in the row.""" + ids = row["input_ids"][0] + hf_labels = row["labels"][0] + labels = torch.full_like(ids, IGNORE_INDEX) + labels[:-1] = hf_labels[1:] + grids = row["image_grid_thw"] + patches = torch.split(row["pixel_values"], grids.prod(-1).tolist()) + return { + "input_ids": ids, + "labels": labels, + "positions": torch.arange(ids.shape[0]), + "pixel_values": list(zip(patches, grids)), + } + + +class ExportedRowProcessor(SampleProcessor): + """exported_row_to_sample as a dataset processor (no randomness).""" + + @dataclass(kw_only=True, slots=True) + class Config(SampleProcessor.Config): + pass + + def __init__(self, config: Config, *, context: DatasetBuildContext) -> None: + del config, context + + def __call__(self, sample: dict[str, Any], rng: np.random.Generator) -> dict[str, Any]: + del rng + return exported_row_to_sample(sample) + + +class ExportedRowCollator(MultiModalCollator): + """MultiModalCollator whose images arrive already patched, as (patches, grid) + pairs: they are concatenated in order instead of patchified.""" + + @dataclass(kw_only=True, slots=True) + class Config(MultiModalCollator.Config): + pass + + def collate_images(self, all_images: list) -> tuple[torch.Tensor, torch.Tensor]: + patches = torch.cat([p for p, _ in all_images]) + grids = torch.stack([g for _, g in all_images]) + return patches, grids + + +def exported_dataloader(directory: str, data_parallel: int = 1) -> GrainDataLoader.Config: + """Bridge's rows in Bridge's order, no shuffle. One pass without data parallelism; + with it TorchTitan requires repeat (the trainer's step count ends the run, and a + run of all exported steps never wraps).""" + return GrainDataLoader.Config( + dataset=SingleDatasetConfig( + source=ExportedStepsSource.Config(directory=directory, data_parallel=data_parallel), + processor=ExportedRowProcessor.Config(), + ), + collator=ExportedRowCollator.Config(build_mrope_positions=True), + shuffle=False, + repeat=data_parallel > 1, + ) diff --git a/training/rdsp/bench/torchtitan/cord_qwen35.py b/training/rdsp/bench/torchtitan/cord_qwen35.py new file mode 100644 index 000000000..a6a886add --- /dev/null +++ b/training/rdsp/bench/torchtitan/cord_qwen35.py @@ -0,0 +1,472 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team + +"""TorchTitan on the rows Megatron-Bridge exported: Qwen3.5 on CORD-v2. + +Bridge's SFT rows, exported by bench/mimo/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: + +- labels: the export keeps Hugging Face's (label t is token t; the loss shifts); + TorchTitan's label t is the target of input t, so label t = exported label t + 1, + and the last input has none. +- images: the export holds the processor's patches; TorchTitan's collator patchifies + image tensors itself, so cord_data.ExportedRowCollator takes the patches as they are. + TorchTitan's Hugging Face parity test reads both with one layout + (scripts/checkpoint_conversion/numerical_tests_qwen3_5.py, the rearrange pattern + "(t bh bw m n) (c pt ph pw)"). + +Each row is one document of 2048 positions (padding included, causal), as rdsp runs +it with --drop-padding-mask. The data path (cord_data.py) is checked on a CPU against +the export and Hugging Face's M-RoPE positions: checks/, results/data_check.txt. + +Run from a TorchTitan checkout (read at 3c36a77; no change to it), on 8 GPUs: + + 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. +""" + +import os + +from cord_data import ROWS_PER_STEP, exported_dataloader +from torchtitan.components.checkpointer import CheckpointManager +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.parallelism import ParallelismConfig +from torchtitan.distributed.activation_checkpoint import FullAC, RegionAC +from torchtitan.models.common.config_utils import decoder_vocab_size +from torchtitan.models.qwen3_5 import QWEN3_5_SPECIAL_TOKENS, build_model_config +from torchtitan.observability.metrics import MetricsProcessor +from torchtitan.trainer import Trainer + +SEQ = int(os.environ.get("SEQ", "2048")) # 4096 for NVIDIA's published SFT setup + + +def qwen35_27b_cord_tp4pp2() -> Trainer.Config: + """Qwen3.5-27B, TP4 x PP2 x DP1 on 8 GPUs, the equal-work settings of the + Bridge and rdsp runs: 64 rows of 2048 tokens per step, 1 row per microbatch, + 1F1B, layers split 32 | 32 with the vision encoder on stage 0 (TorchTitan's + default split), token-mean loss over the step, AdamW lr 1e-5 constant, betas + 0.9/0.95, eps 1e-8, no weight decay, no clipping, no warm-up, fp32 master + weights and Adam moments, no recompute.""" + parallelism = ParallelismConfig( + data_parallel_shard_degree=1, + tensor_parallel_degree=4, + enable_sequence_parallel=True, # TorchTitan's default + pipeline_parallel_degree=2, + pipeline_parallel_schedule="1F1B", + num_pp_microbatches=ROWS_PER_STEP, + ) + model_config = build_model_config("27B", seq_len=SEQ, parallelism=parallelism) + return Trainer.Config( + model=model_config, + parallelism=parallelism, + hf_assets_path=os.environ["HF_ASSETS"], + tokenizer=MultiModalTokenizer.Config(**QWEN3_5_SPECIAL_TOKENS), + dataloader=exported_dataloader(os.environ["EXPORTED"]), + loss=ChunkedLossWrapper.Config( + loss_fn=CrossEntropyLoss.Config(global_vocab_size=decoder_vocab_size(model_config)), + ), + optim=Optim.Config( + optimizer=OptimizersContainer.Config( + optimizers=[ + AdamW.Config( + pattern=r".*", + lr=1e-5, + betas=(0.9, 0.95), + eps=1e-8, + weight_decay=0.0, + fused=True, + moment_dtype="parameter", + ) + ] + ), + lr_scheduler=LRSchedulersContainer.Config(warmup_steps=0, decay_ratio=0.0), + # 0 would scale every gradient by 0; inf leaves them unchanged + max_norm=float("inf"), + ), + training=TrainingConfig( + num_tokens_per_microbatch_per_dp_rank=SEQ, + num_tokens_per_train_step=-1, # one row per PP microbatch: 64 rows a step + max_context_length=SEQ, + steps=int(os.environ.get("STEPS", "50")), + dtype="float32", + mixed_precision_param="bfloat16", + mixed_precision_reduce="float32", + disable_cuda_graphs=True, # image sizes vary from row to row + ), + checkpointer=CheckpointManager.Config(initial_load_in_hf=True, load_only=True), + activation_checkpoint=None, + metrics=MetricsProcessor.Config(log_freq=1), + ) + + +def qwen35_27b_cord_tp4pp2_rc() -> Trainer.Config: + """qwen35_27b_cord_tp4pp2 with every block recomputed (TorchTitan's FullAC), for + when the plain layout runs out of memory.""" + config = qwen35_27b_cord_tp4pp2() + config.activation_checkpoint = FullAC.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: + """config on another layout (and model flavor): the model rebuilt for it, Bridge's rows + dealt to the data-parallel copies as Megatron deals them, ROWS_PER_STEP rows of 2048 + tokens a step.""" + config.parallelism = parallelism + config.model = build_model_config(flavor, seq_len=SEQ, parallelism=parallelism) + config.loss = ChunkedLossWrapper.Config( + loss_fn=CrossEntropyLoss.Config(global_vocab_size=decoder_vocab_size(config.model)) + ) + 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, + ) + + +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() + return config + + +def qwen35_27b_cord_fsdp16_rc() -> Trainer.Config: + """Two nodes: FSDP over all 16 GPUs (dp_shard 16), every block recomputed (FullAC), as + qwen35_27b_cord_fsdp8_rc on one node. Run with ROWS=128: 8 accumulation steps of one row + per GPU per step, the rows dealt to the 16 copies as Megatron deals them.""" + config = _with_layout( + qwen35_27b_cord_tp4pp2(), + ParallelismConfig( + data_parallel_shard_degree=16, + tensor_parallel_degree=1, + ), + data_parallel=16, + ) + config.activation_checkpoint = FullAC.Config() + return config + + +def _without_router_balancing_loss(config: Trainer.Config) -> Trainer.Config: + """No load-balancing loss on the experts' router, as in the Bridge and rdsp runs: the + systems each define it differently (TorchTitan's flavor sets a batch-wise one at 1e-3), + so only "none" is the same everywhere. The loss is cross-entropy alone.""" + for layer in config.model.layers: + if getattr(layer, "moe", None) is not None: + layer.moe.router.aux_loss = None + return config + + +def qwen35_35b_a3b_cord_fsdp16() -> Trainer.Config: + """Qwen3.5-35B-A3B (mixture of experts: 256 experts, 8 per token, plus a shared expert) + on two nodes: FSDP over all 16 GPUs, no expert parallelism, so each GPU holds 1/16 of + every expert's weights and each layer is gathered whole before it runs. Run with ROWS=128 + and HF_ASSETS at the 35B-A3B snapshot: 8 accumulation steps of one row per GPU per step. + No router load-balancing loss. No recompute: a fit check.""" + return _without_router_balancing_loss( + _with_layout( + qwen35_27b_cord_tp4pp2(), + ParallelismConfig( + data_parallel_shard_degree=16, + tensor_parallel_degree=1, + ), + data_parallel=16, + flavor="35B-A3B", + ) + ) + + +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 + weights are FSDP-split over the 2 nodes, everything else over all 16 GPUs. The model is + built for the EP layout (the flavor reads it). No router load-balancing loss. No + recompute: a fit check.""" + return _without_router_balancing_loss( + _with_layout( + qwen35_27b_cord_tp4pp2(), + ParallelismConfig( + data_parallel_shard_degree=16, + tensor_parallel_degree=1, + expert_parallel_degree=8, + ), + data_parallel=16, + flavor="35B-A3B", + ) + ) + + +def qwen35_35b_a3b_cord_fsdp16_ep8_rc() -> Trainer.Config: + """qwen35_35b_a3b_cord_fsdp16_ep8 with every block recomputed (FullAC; the all-to-alls + are replayed in the backward pass).""" + config = qwen35_35b_a3b_cord_fsdp16_ep8() + config.activation_checkpoint = FullAC.Config() + return config + + +def _bf16_reduce(config: Trainer.Config) -> Trainer.Config: + """Gradients reduce-scattered in bf16 instead of fp32, as Megatron-Bridge and rdsp send + theirs (TorchTitan still accumulates the microbatches in fp32). Half the bytes of each + gradient reduce-scatter.""" + config.training.mixed_precision_reduce = "bfloat16" + 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()) + + +def qwen35_27b_cord_fsdp16_bf16() -> Trainer.Config: + """Two nodes, FSDP over all 16 GPUs, no recompute, gradients reduced in bf16 (ROWS=128). + Half the state per GPU of FSDP8, so it may fit where FSDP8 without recompute did not.""" + return _bf16_reduce( + _with_layout( + qwen35_27b_cord_tp4pp2(), + ParallelismConfig( + data_parallel_shard_degree=16, + tensor_parallel_degree=1, + ), + data_parallel=16, + ) + ) + + +def qwen35_27b_cord_fsdp16_ffnrc_bf16() -> Trainer.Config: + """qwen35_27b_cord_fsdp16_bf16 with only each block's MLP recomputed (RegionAC).""" + config = qwen35_27b_cord_fsdp16_bf16() + config.activation_checkpoint = RegionAC.Config( + save_regions=["*"], recompute_regions=["feed_forward.*"] + ) + return config + + +def qwen35_27b_cord_fsdp16_rc_bf16() -> Trainer.Config: + """qwen35_27b_cord_fsdp16_rc with gradients reduced in bf16.""" + 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) + + +def _module_split(cut: tuple[int, ...]) -> list[list[str]]: + """Per-stage module names for a layer cut: the vision encoder and embedding on the first + stage, the final norm and output layer on the last.""" + parts, start = [], 0 + for i, n in enumerate(cut): + names = [f"layers.{j}" for j in range(start, start + n)] + start += n + if i == 0: + names = ["vision_encoder", "tok_embeddings"] + names + if i == len(cut) - 1: + names += ["norm", "lm_head"] + parts.append(names) + return parts + + +def _from_dcp(config: Trainer.Config) -> Trainer.Config: + """Weights from a DCP copy of the Hugging Face checkpoint (TT_DCP, made with TorchTitan's + scripts/checkpoint_conversion/convert_from_hf.py): TorchTitan's Qwen3.5 HF loader needs the + embedding or the output layer on every pipeline stage (state_dict_adapter.py from_hf), so a + middle stage of 3 or more stages cannot load the HF files.""" + config.checkpointer = CheckpointManager.Config( + initial_load_in_hf=False, + initial_load_path=os.environ["TT_DCP"], + load_only=True, + initial_load_model_only=True, + ) + 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, + ) + config.activation_checkpoint = FullAC.Config() + return _from_dcp(_bf16_reduce(config)) + + +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.""" + config = _with_layout( + qwen35_27b_cord_tp4pp2(), + ParallelismConfig( + data_parallel_shard_degree=2, + 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, + ) + config.activation_checkpoint = FullAC.Config() + return _from_dcp(_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()) diff --git a/training/rdsp/bench/torchtitan/scripts/run.sh b/training/rdsp/bench/torchtitan/scripts/run.sh new file mode 100755 index 000000000..e3cf88cb7 --- /dev/null +++ b/training/rdsp/bench/torchtitan/scripts/run.sh @@ -0,0 +1,25 @@ +#!/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 scripts/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/scripts/run2.sh b/training/rdsp/bench/torchtitan/scripts/run2.sh new file mode 100755 index 000000000..d56885a21 --- /dev/null +++ b/training/rdsp/bench/torchtitan/scripts/run2.sh @@ -0,0 +1,39 @@ +#!/bin/bash +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team +# run2.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/two_node/both.sh, which +# sets NNODES, NODE_RANK and MASTER_ADDR: +# bash bench/two_node/both.sh bash bench/torchtitan/scripts/run2.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: run2.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/../../../bench/two_node/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/scripts/setup_box.sh b/training/rdsp/bench/torchtitan/scripts/setup_box.sh new file mode 100755 index 000000000..91c43bedd --- /dev/null +++ b/training/rdsp/bench/torchtitan/scripts/setup_box.sh @@ -0,0 +1,20 @@ +#!/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/bench/two_node/both.sh b/training/rdsp/bench/two_node/both.sh new file mode 100755 index 000000000..12199c643 --- /dev/null +++ b/training/rdsp/bench/two_node/both.sh @@ -0,0 +1,40 @@ +#!/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/mimo/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-