Repository navigation
Conversation
## Summary * Add `get_accelerator().pin_empty()` / `pin_empty_like()` so the repeating `pin_memory(torch.empty(...), make_copy=False)` idiom from deepspeedai#8256 lives in one place ([review note](deepspeedai#8256 (comment))). * Helpers take a shape and dtype only (zero-element template), so neither backend allocates a full-size pageable buffer before page-locking. * Route ZeRO-1/2 `offload_states` hp/lp pins, `offload_optimizer_states`, and the SuperOffload worker grad buffer through the helper. ## Test plan * `pre-commit run --files` on touched paths * `pytest tests/unit/v1/accelerator/test_accelerator.py tests/unit/v1/pin_memory/test_offload_route.py tests/unit/v1/pin_memory/test_pin_memory.py` — **37 passed**, 5 skipped (CPU host; GPU-only offload-route cases skipped) Made with [Cursor](https://cursor.com) --------- Signed-off-by: tunji-ruwase_snow <tunji.ruwase@snowflake.com> Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: Ma, Guokai <guokai.ma@gmail.com>
…peedai#8259) ## Description `is_nfs_path()` reads the fs type from the second column of the second `df` output row. With BusyBox `df` and a device name longer than ~20 characters (common on AWS, where the EBS device is derived from the volume id), the device wraps onto its own line, the row has a single field, and the `[1]` lookup raises `IndexError`. Since the check runs while printing an informational NFS warning during `import deepspeed`, that exception kills the whole import in BusyBox-based containers. I changed the call to `df -PT` so POSIX output keeps every filesystem on one line (BusyBox and coreutils both honour `-P` with `-T`), and made the parse treat a short or malformed row as not-NFS instead of raising, so any other unexpected `df` output just skips the warning. ## Testing - `pytest -q tests/unit/ops/transformer/inference/test_matmul_ext.py` — new mocked regression test covering the wrapped-device case passes, and fails with IndexError on the old parsing - `pre-commit run --files deepspeed/ops/transformer/inference/triton/matmul_ext.py tests/unit/ops/transformer/inference/test_matmul_ext.py` — all hooks pass - mocked POSIX `nfs4` row is still detected as NFS, so real NFS warnings keep working Fixes deepspeedai#8249 --------- Signed-off-by: Atirna <288419661+atirna@users.noreply.github.com>
…eta (deepspeedai#8241) ## What this does Fixes deepspeedai#8231. `tp_shard` kept `num_kv_heads` / `num_attention_heads` / `n_embd` / `tp_grain_size` as **process-wide mutable globals**, written during AutoTP replacement. A second AutoTP model loaded into the same process overwrote them, so the first model's later sharding / gather / checkpoint conversion silently read the wrong values — making it unsafe to run more than one AutoTP model per process (teacher/student, online distillation, RL actor + reference). This moves that state onto a per-model `AutoTPMeta`, computed once from the model config and threaded through every sharding helper and TP layer, so each model carries its own kv-head / grain state. ## Stacking / merge order **Depends on deepspeedai#8185** (AutoTP uneven sharding). This branch is based on deepspeedai#8185's head and is opened as **draft** until deepspeedai#8185 lands — GitHub will drop deepspeedai#8185's commits from this diff automatically once it merges. Please **merge after deepspeedai#8185**. ## Changes - `AutoTPMeta` dataclass + `from_model_config` (single source for kv-head / attn-head / hidden extraction); `get_shard_size(_list)` take it as a required arg; tp_shard globals + `set_*` / `get_*` removed. - AutoTP threads `tp_meta` from `__init__` through every TP layer and fused-QKV helper. - Ulysses sequence parallelism gets its own `_ulysses_num_kv_heads`, decoupled from AutoTP (the AutoTP↔Ulysses coupling is gone; Ulysses's own multi-model case is left for a separate change). - Inference engine builds one `meta` per model (`_autotp_meta`) and threads it through the alibi head-sharding helpers; `_get_model_head_count` / `_get_model_kv_head_count` deleted. - kv-head / attn-head attribute lists unified behind `_kv_head_count_from` / `_attention_head_count_from` (covers chatglm, falcon, llama-class, dbrx, legacy `n_head_kv`). ## Tests Validated on 4×RTX 4080 (nccl) against deepspeedai#8185: full AutoTP / SP / checkpoint suite passes (127 passed); remaining failures are pre-existing env issues (transformers/HF network `client has been closed`, torch 2.12 `ProcessGroupGloo.perform_nocolor_split`, a cuda/cpu device-mismatch), each confirmed failing on the deepspeedai#8185 baseline too. `test_two_models_do_not_clobber_each_others_meta` is the direct regression test for deepspeedai#8231. --------- Signed-off-by: Guokai Ma <guokai.ma@intel.com> Signed-off-by: Ma, Guokai <guokai.ma@intel.com>
`DeepSpeedCPUAdam` has hand-vectorized AVX2 and AVX-512 implementations, but AArch64 systems currently use the scalar fallback. This leaves CPU optimizer performance on NVIDIA Grace and other SVE-capable Arm CPUs below the available memory and vector throughput, which directly affects ZeRO-Offload workloads. ## Summary - add a vector-length-agnostic ARM SVE path for FP32 `DeepSpeedCPUAdam` - retain the scalar fallback for unsupported data types and non-SVE Arm CPUs ## Performance Three warmup steps, ten timed steps per trial, median of three trials, FP32 parameters/states. | Parameters | Scalar CPU-Adam | SVE CPU-Adam | Speedup | |---:|---:|---:|---:| | 1B | 0.163 s | 0.125 s | 1.30x | | 2B | 0.322 s | 0.215 s | 1.50x | | 4B | 0.755 s | 0.487 s | 1.55x | --------- Signed-off-by: Xinyu Lian <lian7@illinois.edu> Co-authored-by: Ma, Guokai <guokai.ma@gmail.com>
…erator (deepspeedai#8335) ## Summary Closes the remaining gap in the Apple Silicon support series (deepspeedai#8293, deepspeedai#8300, deepspeedai#8303, deepspeedai#8307): none of the MPS paths were exercised by CI — every MPS-gated test skips on Linux runners, so regressions could only be caught on a developer's Mac. ### macOS CI workflow (`mps-torch-latest.yml`) Runs the MPS-green unit test subset on GitHub's arm64 macOS runners (`macos-15`), which expose a working MPS device: - `unit/ops/adam/test_adamw.py` — Metal/foreach FusedAdam vs fp32-math reference, CPU Adam configs incl. ZeRO-Offload - `unit/comm/test_dist.py` — gloo CPU-staging for collectives and P2P (`TestMpsStagedP2P`) - `unit/runtime/test_ds_config_dict.py` — config-driven `deepspeed.initialize` + training steps **Designed not to interfere with existing CI:** - PR triggers are scoped via `paths:` to MPS-relevant files (`accelerator/**`, `op_builder/mps/**`, `csrc/mps/**`, `deepspeed/comm/**`, the two test dirs, and the workflow itself) — the check does not even appear on unrelated PRs. - Separate workflow, own concurrency group with cancel-in-progress, hard `timeout-minutes: 45`. - Not a required check (that's a branch-protection setting; nothing here changes it), so even a red run cannot block merges of non-macOS work. - Nightly `schedule` + `workflow_dispatch` for coverage between touching PRs. ### torch floor check `MPS_Accelerator.__init__` now fails with a clear message on torch older than 2.3, where the `torch.mps` memory queries ZeRO depends on (`recommended_max_memory`) do not exist — previously this surfaced as a bare `AttributeError` deep inside ZeRO's flatten logic. Feature-detected rather than version-parsed. (The Metal FusedAdam kernel already degrades gracefully on torch without `compile_shader`.) ## Validation - The workflow's exact pytest command passes locally on an M5 Max (macOS 26.3, torch 2.13): 65 passed, 23 skipped (multi-device), 1m54s — comfortably inside the runner budget. - Guard verified both ways: normal construction unaffected; with `recommended_max_memory` hidden, construction raises the explicit `ValueError`. --------- Signed-off-by: PKUWZP <zhipeng.rainbowserie@gmail.com>
…speedai#8213) ## What this adds An optional DeepEP transport for the AutoEP expert all-to-all, selected by environment variable and defaulting to the existing NCCL path. ```bash DEEPSPEED_AUTOEP_COMM_BACKEND=nccl # default, unchanged behaviour DEEPSPEED_AUTOEP_COMM_BACKEND=deepep DEEPSPEED_AUTOEP_COMM_SMS=<n> # default 12 ``` ## Why The expert all-to-all is the largest single cost in an AutoEP step. Replaying routing captured from real SFT runs on 16 H100s across two nodes: | Routing | Skew (max receive / mean) | NCCL | DeepEP | Speedup | |---|---|---|---|---| | math, last step | 3.01 | 99.72 ms | 48.02 ms | 2.08x | | code, last step | 2.56 | 100.52 ms | 47.91 ms | 2.10x | | code, worst step | 5.09 | 115.75 ms | 46.40 ms | 2.49x | Two things are worth separating. Roughly half the gain is deduplication: DeepEP sends a token once per destination rank rather than once per selected expert, which is worth about 1.29x on its own and could in principle be done without changing transport. Its kernels account for the remaining 1.61x, and they are also where the skew immunity comes from — at the most imbalanced step recorded, NCCL degrades to 115.8 ms while DeepEP stays flat. In whole training steps, with the same model, data and step count and only the backend changed: ``` nccl: step=454.01 ms payload all-to-all=142.92 ms (31.5% of the step) deepep: step=370.74 ms payload all-to-all= 29.68 ms ( 8.0% of the step) end-to-end: 1.225x (18.3% of the step removed) ``` ## Why DeepEP v2 only This wraps `ElasticBuffer`, the v2 API. The legacy v1 `Buffer` is deliberately not supported: - v1 carries data over NVSHMEM and IBGDA rather than NCCL, which needs either the `NVreg_EnableStreamMemOPs` driver parameter or the GDRCopy `/dev/gdrdrv` device. Neither is present on the cluster this was developed against, and both require administrator action rather than configuration. - v1's published internode bandwidth is markedly lower — 43 GB/s at EP16 against 153 GB/s intranode — and the node boundary is exactly the cost this change exists to reduce. v2's hierarchical NVLink plus RDMA path targets that case directly. - v2 can reuse existing NCCL communicators, which matters in a training step that already has ZeRO and data-parallel groups on the fabric. The backend name is `deepep` rather than `deepep_v2`: it names the library, and nothing about it would have to change if v1 were ever added. ## Choosing the SM budget Communication competes with the expert GEMM for SMs, so the default was chosen by sweeping whole training steps rather than the collective in isolation: | Comm SMs | Step time | |---|---| | 8 | 340 ms | | **12** | **311 ms** | | 16 | 353 ms | | 24 | 360 ms | | 32 | 391 ms | At 8 the collective itself degrades; above 12 the step grows because communication takes SMs the rest of the step was using. Tuning this from 24 to 12 moved the end-to-end result from 1.126x to 1.225x. ## Scope and safety `git diff -w` removes zero lines from the shipped path: the existing NCCL code is unchanged and only moves into an `else` branch. `deep_ep` is imported only when the backend is selected, so installations without it are unaffected, and an unparsable backend value warns and falls back rather than breaking a path nobody opted into. DeepEP also requires NCCL 2.30.4 or newer for GIN, which not every cluster has, so a missing package explains what it needs instead of failing deep inside buffer construction. DeepEP replaces more than the two collectives. It takes tokens before top-k expansion and replicates them itself, groups arrivals by expert for the grouped GEMM, and reduces the weighted sum in its combine, so the expansion and reduction around the collectives are replaced as well. Its backward pass has no separate entry points: the gradient of a combine is a dispatch and the gradient of a dispatch is a combine, both replayed against the handle the forward dispatch produced. ## Limitations The DeepEP path is disabled with a warning when folded tensor parallelism is active (`tp_size > 1`). Folded TP partitions assignments across lanes and restores them by assignment metadata, which a transport whose combine returns token-major rows cannot satisfy. Such layers fall back to the NCCL path rather than silently producing wrong output. ## Testing 13 unit tests cover backend selection (default, empty, unknown, SM budget), the preflight checks, and gradient shape conformance. Correctness was verified on 16 H100s across two nodes for every routing scenario above, including a forward-and-backward round trip through all four payload collectives. Follow-up work, kept out of this PR so each change stands on its own: communication/compute overlap (measured 1.11x, composes with this) and deduplication on the NCCL path (1.29x, needs no new dependency). --------- Signed-off-by: yh0903 <helloyu0903@gmail.com> Co-authored-by: Hongwei Chen <33092912+hwchen2017@users.noreply.github.com> Co-authored-by: Ma, Guokai <guokai.ma@gmail.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…eepspeedai#8349) ## Problem `TritonSelfAttention.forward` had a fallback branch that called `self.ds_compute_attention(...)`, reachable only when `alibi is not None` or when the caller passed `use_triton_attention=False`. The call site misspelled the keyword as `toke_idx=`, so the branch raised `TypeError: ds_compute_attention() got an unexpected keyword argument 'toke_idx'` on every entry — i.e. it had never executed. ## Fix Per @delock's review, the branch is dead rather than broken, so it is removed instead of repaired: - delete `TritonSelfAttention.ds_compute_attention` - drop the now-unused `SoftmaxContextOp` import and `self.score_context_func` - drop the `use_triton_attention=True` parameter from `forward` (grep over the repo finds no other reference to it — `attention.py` was the only file) - the remaining `alibi is not None` case now raises `NotImplementedError("TritonSelfAttention does not support alibi")` Net `-37/+2` in one file. `minus_inf` is kept — it is still used by the Triton kernel at `attention.py:300`. `python -m py_compile` and `pyflakes` are clean on the result (the one `pyflakes` note, `v_offset` assigned but never used at line 255, is pre-existing in the Triton kernel and untouched here). 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Anai-Guo <antai12232931@outlook.com> Signed-off-by: Tai An <antai12232931@outlook.com> Co-authored-by: Ma, Guokai <guokai.ma@gmail.com>
## Summary Extend the opt‑in HybridEngineRollout profiling with: - prefill_forward_ms - decode_forward_ms - generation_overhead_ms - num_decode_forwards Accelerator events are recorded around top‑level model forwards without synchronizing every decode step. Existing profiling fields and rollout behavior remain unchanged. For CUDA graph generation, forward timings are reported as unavailable because graph replay bypasses model forward hooks. Follow‑up to deepspeedai#8197. ## Validation - Focused rollout tests: 25 passed, 1 skipped - Changed‑file pre‑commit hooks: passed - py_compile: passed - git diff --check: passed ## GPU Environment - GPU: NVIDIA RTX A4500, 20,470 MiB - Driver: 570.195.03 - CUDA: 12.8 - PyTorch: 2.9.1+cu128 - Transformers: 4.40.2 - Model: facebook/opt‑6.7b - Dtype: FP16 - World size: 1 - ZeRO stage: 0 - Batch size: 1 - Samples per prompt: 4 - Prompt length: 512 - Warmup: 5 - Iterations: 20 - Response Length: 32 | Metric | Baseline | Shared prefill | Change | |---|---|---|---| | Prefill forward | 438.91 ms | 130.15 ms | -70.35% | | Decode forward | 863.04 ms | 865.98 ms | +0.34% | | Generation overhead | 9.60 ms | 14.19 ms | +47.72% | | Generation | 1311.55 ms | 1010.32 ms | -22.97% | | Total | 1312.11 ms | 1010.90 ms | -22.96% | | Throughput | 97.55 tok/s | 126.62 tok/s | +29.80% | | Peak memory | 13144.63 MiB | 13178.63 MiB | +34 MiB | The measurements show that shared prefill reduces prefill latency by about 70%, while decode latency remains nearly unchanged. Thank you for reviewing! --------- Signed-off-by: nathon-lee <leejianwoo@gmail.com> Co-authored-by: Ma, Guokai <guokai.ma@gmail.com>
Under DeepCompile's ZeRO-3, a module parameter can be empty (while partitioned) and full-sized `param.data` (while gathered). Dynamo could recompile the graph when the status changes. The eager fallback added in deepspeedai#8059 gathers ZeRO-3 parameters for frames that Dynamo skips, which made these temporary state changes visible during tracing. deepspeedai#8157 prevented one parameter lookup performed during guard evaluation from triggering a gather. However, Dynamo could still build tensor guards from the parameter's temporary gathered or partitioned representation, and `ZeROOrderedDict` could still read the current ds_status while Dynamo was compiling. This PR makes Dynamo's graph reuse check compare the parameter's identity and logical properties, including its type, dispatch keys, dtype, device, layout, `requires_grad`, `ds_id`, and `ds_shape`. It does not make the check depend on the temporary `param.data` shape or `ds_status`. As the result, DeepCompile can keep Dynamo's existing tensor checks unchanged for non-ZeRO tensors. When DeepCompile supplies a full-sized placeholder during tracing, it now looks up the corresponding module parameter before building the check. It also returns parameters from `ZeROOrderedDict` during compilation without reading `ds_status`. Signed-off-by: Masahiro Tanaka <mtanaka@anyscale.com> Co-authored-by: Masahiro Tanaka <mtanaka@anyscale.com>
…edai#8269) Fixes deepspeedai#8248. ### The change `init_process_group` now asks a small resolver instead of inlining the condition: ```python device_id = get_init_process_group_device_id(world_size) if device_id is not None: kwargs.update(device_id=device_id) ``` `DEEPSPEED_SET_DEVICE_ID` overrides the decision, parsed by a new `get_env_flag` helper: | Value | Effect | |---|---| | `1` / `true` / `yes` / `on` | always bind | | `0` / `false` / `no` / `off` | never bind | | unset | the default above: bind iff `world_size > 1` | | anything else | warn and ignore, so the default still decides | Multi-rank behaviour is unchanged. ### Tests `tests/unit/comm/test_dist.py` --------- Signed-off-by: pengdurice <pengduhit@gmail.com>
`add_tuning_arguments` declares `--warmup_min_ratio` and
`--cos_min_ratio` for
WarmupCosineLR, but `get_config_from_args` routed every schedule that is
not
`LRRangeTest` or `OneCycle` through `override_warmupLR_params`. So both
flags
were parsed and then dropped, and the config came back carrying the
WarmupLR
parameters instead:
```
$ parser = add_tuning_arguments(argparse.ArgumentParser())
$ args = parser.parse_args(["--lr_schedule", "WarmupCosineLR",
"--warmup_min_ratio", "0.1", "--cos_min_ratio", "0.05"])
$ get_config_from_args(args)
({'type': 'WarmupCosineLR',
'params': {'warmup_min_lr': 0, 'warmup_max_lr': 0.001,
'warmup_num_steps': 1000, 'warmup_type': 'log'}}, None)
```
Both ratios are gone, and building the scheduler from what is left
fails,
because `WarmupCosineLR` has no min/max lr at all:
```
TypeError: WarmupCosineLR.__init__() got an unexpected keyword argument 'warmup_min_lr'
```
`WARMUP_MIN_RATIO` and `COS_MIN_RATIO` were already defined next to the
other
config keys, so only the plumbing was missing.
`get_lr_from_config` had the mirror-image problem: it falls through to
`lr_params[WARMUP_MAX_LR]` for anything that is not `LRRangeTest` or
`OneCycle`. For WarmupCosineLR that returned an unrelated WarmupLR
default on
a CLI-built config, and raised `KeyError: 'warmup_max_lr'` on a config
actually written for this schedule. WarmupCosineLR scales each param
group's
own lr by a ratio, so there is no learning rate in its params to read,
and it
now says so instead.
The JSON config path was never affected:
`engine._configure_lr_scheduler`
calls `scheduler(optimizer, **scheduler_params)` straight from the
config
file, so `"scheduler": {"type": "WarmupCosineLR", "params":
{"warmup_min_ratio": 0.1}}`
has always worked. Only the `add_tuning_arguments` CLI helper is fixed
here.
Other schedules are untouched. `LRRangeTest`, `OneCycle`, `WarmupLR` and
`WarmupDecayLR` produce the same params and the same
`get_lr_from_config`
answer as before, and `test_other_schedules_keep_their_config_params`
pins
that.
**Not included**, so as to keep this to one thing: `TOTAL_NUM_STEPS` is
defined but unused, and neither `WarmupDecayLR` nor `WarmupCosineLR` can
be
built from `get_config_from_args` output alone because both need
`total_num_steps`, which has no CLI flag. Callers pass it themselves
today.
Happy to add that separately if you would like it plumbed.
## Tests
`tests/unit/runtime/test_lr_schedulers.py` gains three plain
(non-distributed)
tests next to the existing ones:
- `test_warmup_cosine_lr_config_from_args_carries_the_ratios`
- `test_warmup_cosine_lr_has_no_lr_in_its_config_params`
- `test_other_schedules_keep_their_config_params`
DeepSpeed does not build on this machine (macOS, no CUDA), so I ran the
three
new test bodies against the unmodified `lr_schedules.py` from master and
against the patched one, loading the module directly:
```
before: 2 failed, 1 passed
(KeyError: 'warmup_max_lr', and the ratios missing from the config)
after: 3 passed
```
The one that passes on both sides is the no-regression control.
`yapf --style .style.yapf --diff` is clean on both changed files, and
neither
adds a line over the 119 column limit.
Signed-off-by: Vineeth Sai <vineethsai4444@gmail.com>
Co-authored-by: Olatunji Ruwase <tunji.ruwase@snowflake.com>
…eedai#8306) Fixes deepspeedai#7947. ## Problem `Loading.is_load_module()` in `auto_tp.py` gates whether a leaf module's parameters get loaded from a raw state dict during AutoTP-based checkpoint loading (both call sites — `auto_tp.py` and `replace_module.py` — use it the same way). It matches by an exact class-name allowlist that gets a new entry each time a model family ships its own RMSNorm class, but Qwen3.5's classes were never added. `Qwen3_5RMSNorm`, `Qwen3_5RMSNormGated` (dense), `Qwen3_5MoeRMSNorm` and `Qwen3_5MoeRMSNormGated` (MoE) each own a `weight` `nn.Parameter`, same shape as every other listed `*RMSNorm` class — without an allowlist entry, `is_load_module()` returns `False` for them and that weight is never loaded from the checkpoint, silently left at its random init value instead. ## Verification Verified against the real modeling code (transformers 5.3.0, the version reported in the issue): built a small `Qwen3_5TextModel` and confirmed `Qwen3_5RMSNorm`/`Qwen3_5RMSNormGated` instances only carry a `weight` parameter, matching the pattern of the already-listed `LlamaRMSNorm` et al. Confirmed the MoE variants carry the same single `weight` parameter. **Deliberately not adding `Qwen3_5TextRotaryEmbedding`**: it carries no parameters, only two buffers (`inv_freq`, `original_inv_freq`), and both call sites already load any child's buffers unconditionally (`if len(child._buffers) != 0`) regardless of `is_load_module()` — so listing it would be a no-op, not a functional fix. (Happy to add it anyway for consistency with the codebase's existing `Phi3RotaryEmbedding`/`YuanRotaryEmbedding` entries if maintainers prefer explicitness over strict minimality here — wasn't sure which this repo's convention favors.) ## Test `tests/unit/module_inject/test_auto_tp_is_load_module.py` (new). Uses name-matched dummy `nn.Module` stand-ins rather than real `transformers` classes, since `is_load_module()` matches by class name only and the dev requirement (`transformers>=4.51.3`) predates Qwen3.5 — importing the real classes would make the test depend on a newer transformers than the repo's own pinned minimum. Covers all four new allowlist entries plus one negative case for an unrelated class name. ``` $ pytest tests/unit/module_inject/test_auto_tp_is_load_module.py -v ... 5 passed in 1.70s ``` `pre-commit run --files deepspeed/module_inject/auto_tp.py tests/unit/module_inject/test_auto_tp_is_load_module.py` (yapf, flake8, check-license, codespell) is clean. --- Prepared with AI assistance under my review; the root cause, the parameter-vs-buffer distinction behind the RotaryEmbedding decision, and the test were verified locally before opening this PR. --------- Signed-off-by: promptsmith1990 <319963136+promptsmith1990@users.noreply.github.com> Co-authored-by: promptsmith1990 <319963136+promptsmith1990@users.noreply.github.com> Co-authored-by: Ma, Guokai <guokai.ma@gmail.com>
…pspeedai#8305) ## Problem [deepspeedai#6694](deepspeedai#6694) added a `free_data` flag so the ZeRO-3 leaf-module fast-sharding path could partition a parameter *without* calling `free_param()` on it, and then release the buffer itself after the whole submodule was done (`param.data = empty_buffer`), avoiding a per-parameter synchronisation. The flag was added to all three signatures, but the two intermediate hops pass the literal `True` instead of the value they were given: ```python def partition(param_list=None, hierarchy=0, has_been_updated=False, free_data=True): ... self._partition(param_list, has_been_updated=has_been_updated, free_data=True) # not free_data def _partition(self, param_list, force=False, has_been_updated=False, free_data=True): ... self._partition_param(param, has_been_updated=has_been_updated, free_data=True) # not free_data ``` So `free_data=False` never reaches the only place that reads it: ```python # _partition_param if free_data: free_param(param) ``` Consequences: - The `if free_data:` guard is unreachable as `False`; `free_param()` always runs. - `PartitionedParameterCoordinator.release_sub_module()` computes `free_data = not z3_leaf_module(submodule) or not self.fast_sharding_for_leaf_module` and threads it through `__release_param()` -> `param.partition(free_data=free_data)`, but the buffer is freed anyway. The fast path enabled by `stage3_module_granularity_threshold > 0` is a no-op, and the `param.data = empty_buffer` that follows just overwrites an already-freed tensor. Reproducible directly on the parameter API (single process, CPU): ```python with deepspeed.zero.Init(): l = torch.nn.Linear(6, 3, bias=False) l.weight.all_gather() print(l.weight.numel()) # 18 l.weight.partition(free_data=False) print(l.weight.numel()) # 0 <- expected 18 ``` ## Fix Pass `free_data` down at both hops. Two lines; no signature or default changes, so the default path (`free_data=True`) is byte-for-byte the same as before. ## Test Added `TestPartitionWithoutFreeingData` to `tests/unit/runtime/zero/test_zero_context.py` (`world_size=1`), next to the existing `TestZeroGatheredParametersFree`. It gathers a parameter, calls `partition(free_data=False)` and asserts `param.data` survives, then gathers again and calls plain `partition()` to assert the default still frees. ``` # new test against the unpatched source 1 failed, 2 passed (TestZeroGatheredParametersFree and TestMiCSGatheredParametersFree are the controls) # after the fix 3 passed ``` Whole-file and feature-path controls, clean tree vs patched: ``` tests/unit/runtime/zero/ (whole directory) clean: 1 failed, 57 passed, 250 skipped patched: 1 failed, 58 passed, 250 skipped (net difference is exactly the new test) tests/unit/v1/zero/test_zero_activation_checkpoint_lifecycle.py (parametrises module_granularity_threshold) clean: 9 passed, 2 xfailed patched: 9 passed, 2 xfailed ``` The one failure is the same on both sides, `test_zero_nesting_init.py::TestNestedParallelInit::test_nested_parallel_init`, and is unrelated to this change. `yapf --style .style.yapf -d` is clean on both files. `flake8 --config .flake8` reports the same two pre-existing `F824 global reuse_buffers` warnings before and after; nothing new. Signed-off-by: Vineeth Sai <vineethsai4444@gmail.com> Co-authored-by: Olatunji Ruwase <tunji.ruwase@snowflake.com>
`deepspeed.comm.barrier` exposes `device_ids`, but the wrapper drops it. This PR forwards `device_ids` to communication backends. Signed-off-by: Masahiro Tanaka <mtanaka@anyscale.com> Co-authored-by: Masahiro Tanaka <mtanaka@anyscale.com>
## Symptom
The flops profiler reports **zero macs for a depthwise transposed
convolution**, and under-counts every other grouped one. Bias flops are
wrong for every strided transposed convolution.
```python
import torch
from deepspeed.profiling.flops_profiler import FlopsProfiler
for m in [torch.nn.ConvTranspose2d(4, 6, 4, stride=2, padding=1),
torch.nn.ConvTranspose2d(4, 4, 3, stride=2, padding=1, output_padding=1, groups=4),
torch.nn.ConvTranspose2d(6, 6, 2, stride=2, groups=3)]:
x = torch.randn(2, m.in_channels, 8, 8)
p = FlopsProfiler(m); p.start_profile(); y = m(x); p.stop_profile()
print(m.groups, p.get_total_macs(), p.get_total_flops()); p.end_profile()
```
| layer | macs reported | macs | flops reported | flops |
| --- | --- | --- | --- | --- |
| `ConvTranspose2d(4, 6, 4, stride=2, padding=1)` | 49152 | 49152 |
98496 | 101376 |
| `ConvTranspose2d(4, 4, 3, stride=2, padding=1, output_padding=1,
groups=4)` | **0** | 4608 | 32 | 11264 |
| `ConvTranspose2d(6, 6, 2, stride=2, groups=3)` | **0** | 6144 | 64 |
15360 |
## Root cause
Two independent problems in `_conv_trans_flops_compute`.
**1. The per-group filter count is divided by `groups` twice.** A
transposed-convolution weight is `[in_channels, out_channels // groups,
*kernel]`, not `[out_channels, in_channels // groups, *kernel]` as for a
forward convolution. So `weight.shape[1]` is already `out_channels //
groups`, and
```python
out_channels = weight.shape[1]
...
filters_per_channel = out_channels // groups
```
yields `out_channels // groups ** 2`. For a depthwise layer that is `1
// groups`, which floors to `0`, so `conv_per_position_macs` and the
whole layer collapse to zero.
**2. The output shape uses the forward-convolution formula.** A
transposed convolution inverts it, and `output_padding` was accepted by
the signature but never read:
```python
output_dim = (input_dim + 2 * paddings[idx] - (dilations[idx] * (kernel_dims[idx] - 1) + 1)) // strides[idx] + 1
```
The bias is added once per output element, so `bias_flops = out_channels
* batch_size * prod(output_dims)` inherits the error. For a stride-2
layer the formula returns roughly `input_dim / stride` where the real
output is `input_dim * stride`, so the bias term comes out about 16x too
small in 2D.
The three lines that recomputed `paddings`/`strides`/`dilations` as
2-tuples immediately after the loop were dead, and hardcoded 2D for a
helper that also serves `conv_transpose1d` and `conv_transpose3d`, so
they go with the fix.
## Fix
Read `filters_per_channel` straight off `weight.shape[1]` and recover
`out_channels` by multiplying it back up, and compute the output shape
with the transposed-convolution formula, including `output_padding`.
The mac convention is unchanged: a transposed convolution scatters every
input element across the kernel, so `active_elements_count` stays based
on `input_dims`.
## Test
`tests/unit/profiling/flops_profiler/test_flops_profiler.py::test_conv_transpose_flops`,
parametrized over `groups` in 1/2/4 and `(stride, padding,
output_padding)` in (1, 0, 0)/(2, 1, 1). It checks both counts against
the shapes torch itself produced, so the expected values are not a copy
of the implementation.
Against master: **6 failed, 2 passed** (`assert 0 == 9216` for the
depthwise cases). With the fix: **8 passed**.
```
$ pytest unit/profiling/flops_profiler/test_flops_profiler.py -m sequential
8 passed, 2 deselected
$ pytest unit/profiling/flops_profiler/test_flops_profiler.py
2 passed, 8 deselected
```
Manually checked beyond what the test parametrizes, all matching torch:
`ConvTranspose1d`, `ConvTranspose3d`, `dilation=2`, and `bias=False`.
---------
Signed-off-by: Vineeth Sai <vineethsai4444@gmail.com>
…8324) ## Symptom The flops profiler counts an elementwise `mul`/`add` over the wrong shape whenever the two operands differ in rank, which is exactly the common case of scaling or shifting an activation by a per-feature vector. ```python import torch from deepspeed.profiling.flops_profiler import FlopsProfiler class Elementwise(torch.nn.Module): def forward(self, lhs, rhs): return torch.mul(lhs, rhs) for lhs_shape, rhs_shape in [((2, 3, 4), (4,)), ((4,), (2, 3, 4)), ((8,), (2, 8)), ((3, 4), (4,))]: model = Elementwise() lhs, rhs = torch.randn(*lhs_shape), torch.randn(*rhs_shape) prof = FlopsProfiler(model) prof.start_profile(); out = model(lhs, rhs); prof.stop_profile() print(lhs_shape, rhs_shape, prof.get_total_flops(), out.numel()) prof.end_profile() ``` | operands | elements touched | flops reported | | --- | --- | --- | | `[2, 3, 4] * [4]` | 24 | 48 | | `[4] * [2, 3, 4]` | 24 | 48 | | `[8] * [2, 8]` | 16 | 64 | | `[3, 4] * [4]` | 12 | 16 | | `[2, 3, 4] * [2, 3, 4]` | 24 | 24 | | `[4, 1, 7] * [1, 5, 7]` | 140 | 140 | ## Root cause `_elementwise_flops_compute` builds the result shape by walking both operands from index 0 and padding the shorter one on the *right*: ```python for i in range(max_dim): in_i = input.shape[i] if i < dim_input else 1 ot_i = other.shape[i] if i < dim_other else 1 ``` Broadcasting lines shapes up from the *trailing* dimension and pads on the left. For `[2, 3, 4]` against `[4]` the loop pairs 2 with 4, then 3 with the pad, then 4 with the pad, producing `[4, 3, 4]` rather than `[2, 3, 4]`. Equal ranks are handled correctly, which is why this is easy to miss: the shape only comes out wrong when the ranks differ, and it can land either high or low depending on which dimensions get paired up. It happens to be right by coincidence when the mispaired dimensions have the same product, e.g. `[16] * [32, 16]` gives `[16, 32]`. The counter backs `torch.mul`, `torch.Tensor.mul`, `torch.add` and `torch.Tensor.add`. ## Fix `torch.broadcast_shapes` returns the result shape directly, so the hand-rolled loop goes. The two non-tensor branches above it are unchanged, and a 0-dim tensor operand still resolves to the other operand's shape. ## Test `tests/unit/profiling/flops_profiler/test_flops_profiler.py::test_elementwise_broadcast_flops`, parametrized over four mismatched-rank pairs and two matched-rank pairs (one of them exercising a size-1 dimension). The expected value is `result.numel()` from the tensor torch actually produced, so it is not a restatement of the implementation. Against master: **4 failed, 4 passed** (`assert 48 == 24`, `assert 64 == 16`, `assert 16 == 12`). With the fix: **8 passed**. ``` $ pytest unit/profiling/flops_profiler/test_flops_profiler.py -m sequential 8 passed, 2 deselected $ pytest unit/profiling/flops_profiler/test_flops_profiler.py 2 passed, 8 deselected ``` Also checked by hand and matching torch: a python scalar operand, `Tensor.mul`, `torch.add`, a 0-dim tensor operand, and a scalar in the first position. Independent of deepspeedai#8323, which fixes `_conv_trans_flops_compute` in the same file. The two touch different functions and do not overlap. Signed-off-by: Vineeth Sai <vineethsai4444@gmail.com> Signed-off-by: Masahiro Tanaka <tanaka.masahiro@gmail.com> Co-authored-by: Masahiro Tanaka <tanaka.masahiro@gmail.com>
…type annotations (deepspeedai#8336) This PR addresses deepspeedai#8330 by replacing the internal assertion in `replace_with_policy` with a clear `ValueError` when both `replace_with_kernel_inject=True` and `enable_cuda_graph=True` are requested for a model whose policy does not support CUDA graphs. Changes: - `deepspeed/module_inject/replace_module.py`: raise an actionable `ValueError` instead of asserting. - `tests/unit/inference/test_inference_config.py`: add a regression test using a tiny Llama model that verifies the new error message. - `deepspeed/compile/custom_ops/tp_collectives.py`: replace `list[int]` annotations with `typing.List[int]` so `import deepspeed` works on PyTorch 2.6+ (the new regression test needs this to import cleanly). The regression test was verified on a single H100 with: ``` PYTHONPATH=tests/unit pytest tests/unit/inference/test_inference_config.py::TestInferenceCudaGraphConfig::test_cuda_graph_with_kernel_inject_raises -m inference -v ``` --------- Signed-off-by: Chakshu Dhannawat <chakshu.dhannawat1@gmail.com>
…eepspeedai#8329) `DeepSpeedConfig` keeps the dict it is handed by reference: ```python if isinstance(config, dict): self._param_dict = config ``` deepspeedai#8289 established that parsing must not write back into it — the caller owns that dict and may reuse it after initialization. The elasticity branch still does, two lines above the comment that says otherwise: ```python self._param_dict[TRAIN_BATCH_SIZE] = final_batch_size self._param_dict[TRAIN_MICRO_BATCH_SIZE_PER_GPU] = micro_batch_size self._param_dict[GRADIENT_ACCUMULATION_STEPS] = gradient_accu_steps # Pass a copy so that user json is unmodified, e.g. for logging self._initialize_params(copy.copy(self._param_dict)) ``` A caller that enables elasticity gets three keys back that it never set. `print_user_config()` dumps `self._param_dict`, so it then reports them as though the user had written them. **It also makes the dict unparseable a second time.** The elasticity path rejects those keys in the input unless `ignore_non_elastic_batch_info` is set: ``` One or more batch related parameters were found in your ds_config (...). These parameters *will not be used* since elastic training is enabled ... ``` The first parse succeeds and injects them; the second parse of the same dict trips that guard, and its message asks the user to remove three keys they never wrote. ### The fix Collect the overrides and apply them to the copy. All three are top-level keys, so the existing shallow copy keeps them off the caller's dict. ### Test `DeepSpeedConfig(config_dict)` twice on an elasticity config, with `ignore_non_elastic_batch_info` left out so the guard is live: before ``` parse 1 OK, caller dict gained: ['gradient_accumulation_steps', 'train_batch_size', 'train_micro_batch_size_per_gpu'] parse 2 FAILED: ElasticityConfigError One or more batch related parameters were found in your ds_config ... ``` after ``` parse 1 OK, caller dict gained: nothing parse 2 OK ``` Parsed values are unchanged either way (`train_batch_size=4 micro=2 gas=2`), so this only removes the write-back. `test_elasticity_leaves_caller_config_untouched` sits next to deepspeedai#8289's `test_max_grad_norm_leaves_caller_config_untouched` and covers both symptoms. On master it fails at ``` AssertionError: assert {'elasticity', 'train_batch_size', 'train_micro_batch_size_per_gpu', 'gradient_accumulation_steps'} == {'elasticity'} ``` ``` tests/unit/runtime/test_ds_config_dict.py 27 passed, 5 skipped tests/unit/elasticity/test_elastic.py 23 passed, 3 skipped yapf --diff / flake8 clean ``` --------- Signed-off-by: alanhuangyoo <alanhuangyoo@gmail.com> Signed-off-by: Masahiro Tanaka <tanaka.masahiro@gmail.com> Co-authored-by: Masahiro Tanaka <tanaka.masahiro@gmail.com>
…ai#8334) ## Symptom The curriculum schedule can start below the `min_difficulty` it is configured with, and for one pair the tutorial itself recommends it starts at **0**. ```python from deepspeed.runtime.data_pipeline.curriculum_scheduler import CurriculumScheduler def sched(min_d, step): return CurriculumScheduler({ "min_difficulty": min_d, "max_difficulty": 1024, "schedule_type": "fixed_linear", "schedule_config": {"total_curriculum_step": 100, "difficulty_step": step}, }) for min_d, step in [(8, 8), (8, 16), (64, 16), (1, 8), (10, 8)]: s = sched(min_d, step) print(min_d, step, [s.get_difficulty(i) for i in range(6)]) ``` | `min_difficulty` | `difficulty_step` | first six steps | | --- | --- | --- | | 8 | 8 | `[8, 16, 24, 32, 48, 56]` | | **8** | **16** | **`[0, 16, 16, 32, 48, 48]`** | | 64 | 16 | `[64, 64, 80, 80, 96, 112]` | | **1** | **8** | **`[0, 8, 16, 24, 40, 48]`** | | **10** | **8** | **`[8, 16, 24, 40, 48, 56]`** | `min_difficulty=8` with `difficulty_step=16` is not a contrived pair. The tutorial recommends "starting with `min_difficulty` at 8 (million-scale models) or 64 (billion-scale models)" and separately "we usually set [`difficulty_step`] to 8 (for FP16 data) or 16 (for INT8 data)". A million-scale model on INT8 data lands on exactly that combination, and its first training step gets a sequence length of 0. ## Root cause `__fixed_root_get_difficulty`, which serves both `fixed_linear` (root degree 1) and `fixed_root`, floors the interpolated value to a multiple of `difficulty_step` and then clamps only the top: ```python next_difficulty -= (next_difficulty % s_state[CURRICULUM_LEARNING_SCHEDULE_DIFFICULTY_STEP]) next_difficulty = min(next_difficulty, self.state[CURRICULUM_LEARNING_MAX_DIFFICULTY]) ``` At step 0 the interpolation is exactly `min_difficulty`, so the floor subtracts `min_difficulty % difficulty_step` and there is nothing to stop it going under. The tutorial's own formula for this schedule is `((step/total)**(1/root_degree)) * (max_difficulty - min_difficulty) + min_difficulty`, which starts at `min_difficulty`. ## Fix Clamp the bottom the way the top already is, one line. This does not introduce a new exception to the "difficulty is a multiple of `difficulty_step`" rule: the existing top clamp already returns `max_difficulty` verbatim when it is not a multiple. With `max_difficulty=1000` and `difficulty_step=16` the schedule returns 1000, not 992, once it runs out. Both endpoints being the configured values rather than multiples of the step is the behaviour this function already has at one end. `__fixed_discrete_get_difficulty` picks from an explicit list and is untouched. ## Test Two tests in `tests/unit/runtime/test_data_efficiency.py`, both plain CPU tests rather than `DistributedTest`, since `CurriculumScheduler` needs neither an accelerator nor a process group: - `test_curriculum_never_starts_below_min_difficulty`, parametrized over `fixed_linear` and `fixed_root` and over five `(min_difficulty, difficulty_step)` pairs including the tutorial's own recommendations, checks the first twenty steps stay within `[min_difficulty, max_difficulty]`. - `test_curriculum_endpoints_are_the_configured_values` pins both ends with a `max_difficulty` that is not a multiple of `difficulty_step`. Its top-end assertion passes on master too, which is what makes it the control for the argument above. Against master: **7 failed, 4 passed, 6 skipped** (`assert 0 >= 8`, `assert 8 >= 10`, `assert 0 == 8`). With the fix: **11 passed, 6 skipped**. The 6 skipped are the file's pre-existing `DistributedTest` cases, which need 2 GPUs; a pristine checkout reports the same 6 skips and nothing else. yapf and flake8 clean, with yapf making no changes to either file. --------- Signed-off-by: Vineeth Sai <vineethsai4444@gmail.com>
## Summary - Add an opt-in AutoEP `combine_impl="fused_weighted_sum"` path while keeping the existing eager weighted reduction as the default. - Restore `[tokens * top_k, hidden]` expert rows directly to `[batch, sequence, hidden]` in one Triton pass with FP32 weighting and accumulation, including expert-row and routing-score gradients. - Fail fast for unsupported CUDA/dtype/score/AutoTP/expert-TP configurations, preserve higher-order autograd through a differentiable fallback, and document the experimental path. ## Performance - Canonical-shape H100 microbenchmark: 2.98x forward and 1.87x forward+backward, saving about 0.215 ms per layer. - Qwen3-30B-A3B, 48 layers, EP16, 2x8 H100: pooled median improved by 0.97%, with a 95% CI of `[-1.12%, +3.02%]`; this is not yet a statistically conclusive end-to-end win. - Peak reserved memory decreased by 96 MiB, matching the removed 64 MiB FP32 weighted intermediate and 32 MiB assignment buffer. - The experimental expert reorder was removed after launch-amortized measurements showed no benefit, so this PR changes only the weighted restore. ## Testing Done - [x] Local code review completed - [x] Unit tests added/updated - [x] Integration tests pass - [x] Manual testing performed - Repository pre-commit hooks passed for all nine changed files. - H100 fused token-op suite: 23 passed, including top-k 2/4/6/8, non-power-of-two hidden sizes, input-contract validation, forward/backward parity, and double backward. - H100 configuration tests: 5 passed for standard, folded AutoTP, expert tensor parallelism, and score-application validation. - Full-step eager/fused parity: 3 passed, covering loss, output, input gradients, router/expert gradients, optimizer parameter deltas, activation checkpointing on/off, EP2, and local experts. - Earlier final restore-only sweep: 121 kernel/config tests passed before the additional review-driven safety cases were added. --------- Signed-off-by: yh0903 <helloyu0903@gmail.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Hongwei Chen <33092912+hwchen2017@users.noreply.github.com>
…dai#8383) Running the unit tests from a source checkout — one that was not `pip install`ed, so `git_version_info_installed.py` does not exist — fails before any test body runs: ``` FAILED unit/runtime/zero/test_zero_tensor_fragment.py::TestTensorFragmentSet::test_zero_fragments[none-1-local-dtype0] - KeyError: 'nccl_version' ``` `setup.py:292` writes five keys: ```python torch_info = { "version": torch_version, "bf16_support": bf16_support, "cuda_version": cuda_version, "nccl_version": nccl_version, "hip_version": hip_version, } ``` and the fallback in `deepspeed/git_version_info.py:22` lists three: ```python torch_info = {'version': "0.0", "cuda_version": "0.0", "hip_version": "0.0"} ``` `tests/unit/util.py` reads `nccl_version` on the way into `bf16_required_version_check`: ```python if torch_info['nccl_version'] == '0.0': # Use runtime NCCL version if available ``` The `"0.0"` is a sentinel — the reader's own comment says so, and `version`, `cuda_version` and `hip_version` all carry it for exactly that reason. `nccl_version` was left out, so instead of taking the runtime-detection branch the lookup raises. ## The change Add the missing key with the same sentinel the other three use, so the reader takes the fallback it was written to take. Not adding `bf16_support`, the other key `setup.py` writes and this dict omits: nothing reads it off `torch_info` today (`get_accelerator().is_bf16_supported()` is used instead), and there is no established sentinel for a bool the way `"0.0"` is for a version. Happy to add it if you would rather the two dicts match key-for-key. ## Verification Reproduced on both a CPU checkout and 2×H100: ``` # upstream/master, source checkout >>> from unit.util import bf16_required_version_check; bf16_required_version_check() KeyError: 'nccl_version' # this branch >>> bf16_required_version_check() False # no CUDA on that box, which is the correct answer ``` On 2 GPUs, `unit/runtime/zero/test_zero_tensor_fragment.py`: ``` master 19 failures, all KeyError: 'nccl_version' this branch 0 occurrences of nccl_version anywhere in the log ``` The failures that remain in my environment are all `Unable to JIT load the {cpu_adam,fused_adam} op due to ninja not being installed` — a missing build tool on that box, unrelated to this change and present identically before and after. ``` yapf==0.40.0 --diff (no diff) ``` --------- Signed-off-by: alanhuangyoo <alanhuangyoo@gmail.com> Co-authored-by: Ma, Guokai <guokai.ma@gmail.com>
## Motivation AI coding agents increasingly submit tests alongside features, and a recurring failure mode of such contributions is tests coupled to the implementation rather than the contract: - asserting private method return values or exact internal strings, - re-implementing the logic under test as the test's own reference, - mocks that stand in for internals instead of a documented collaborator contract. Such tests pass trivially, break on harmless refactors (or worse, survive bugs they should catch), and give false coverage confidence. ## What this PR adds A `### Test discipline` section to the agent guidelines (`AGENTS.md` + `CLAUDE.md`, kept in sync as the file header requires) with operational rules: 1. A test is well-formed only if a different correct implementation of the same contract passes it. 2. Name the concrete incorrect behavior a test would catch before writing it; if none can be named, do not write it. 3. Assert observable outcomes through public/stable interfaces; white-box pinning only for specific fixed bugs, justified in a comment. 4. Anchor to an external oracle or an independently derived reference instead of re-implementing the logic under test. 5. Mocks must stand in for a collaborator's documented contract (schema, protocol), never for internals of the module under test. The rules are deliberately example-free to keep the guide lean. --------- Signed-off-by: Ma, Guokai <guokai.ma@intel.com>
`DeepSpeedStaticCache` preallocates its KV buffers with `hidden_size // num_attention_heads`. Models that set `head_dim` explicitly (Qwen3, Gemma, Llama 4) break that identity, so the buffers get the wrong last dimension and the prefill copy in `_generate_graph` dies before the graph is ever captured: ``` RuntimeError: The size of tensor a (16) must match the size of tensor b (32) at non-singleton dimension 3 ``` Now it reads `head_dim` off the config and falls back to the division when the attribute is missing or None (older configs set it to None). To reproduce on CPU: a tiny Qwen3 with `hidden_size=64`, `num_attention_heads=4`, `head_dim=32`, prefilled through the HF `StaticCache` the way `_generate_graph` does, then the copy loop at `hybrid_engine_rollout.py:346` verbatim. The prefill cache comes back `(1, 2, 8, 32)` and `DeepSpeedStaticCache` allocates `(1, 2, 8, 16)`. With `head_dim=16` the same script is fine on both sides, which is why nothing has caught this so far. Two tests in `tests/unit/runtime/rollout/`. The `head_dim` one fails on master. No GPU on this machine, so the capture and replay path itself is not exercised, only the allocation and the copy that feeds it. Signed-off-by: Ehsan Barkhordar <realbarkhordar@gmail.com> Co-authored-by: Ma, Guokai <guokai.ma@gmail.com>
…dai#8398) ## Problem `TestMultipleModels::test_zero_optimizer`, `TestSimpleMoE`, `TestMoE`, `TestPRMoE`, and `TestMOETensorParallel` hardcode `"fp16": {"enabled": True}` in their DeepSpeed configs. The engine's sanity check then raises: ``` ValueError: Type fp16 is not supported on your device. ``` on any accelerator whose `is_fp16_supported()` is false. On CPU that maps to the AVX512-FP16 capability of the host, and GitHub's `ubuntu-24.04` runners are hardware-heterogeneous: **the same test passes on one runner and fails on the next** (observed directly in deepspeedai#8381 — 146 failures appeared on one runner generation and none on another, with identical code). ## Change Skip these tests via a capability query: ```python @pytest.mark.skipif(not get_accelerator().is_fp16_supported(), reason="fp16 is not supported on this accelerator") ``` - capability only, no accelerator-name matching; - mirrors the existing bf16 skip precedent in `tests/unit/v1/zero/test_zero_user_backward.py`; - deliberately a **skip** rather than silently running bf16 — these tests exist to cover the fp16 paths. ## Validation Validated as part of the multi-rank CPU CI experiment in deepspeedai#8381: the 146 hardware-lottery failures became deterministic skips, zero regressions on previously-passing tests. Signed-off-by: Guokai Ma <guokai.ma@intel.com>
## Problem
`tests/unit/v1/zero/test_zero_user_backward.py` builds torch DDP
**reference** models (the known-good baseline that ZeRO results are
compared against) at five sites:
```python
model_ddp = DDP(model_ddp, device_ids=[rank], output_device=rank)
```
`device_ids=[rank]` assumes rank ↔ GPU index. torch's DDP contract only
allows `device_ids`/`output_device` for single-device GPU modules; **CPU
modules live on one shared device and must omit them**, so multi-rank
CPU runs died inside the DDP constructor with:
```
ValueError: DistributedDataParallel device_ids and output_device arguments only work with single-device/multiple-device GPU modules or CPU modules, ...
```
## Change
Route all five sites through one helper:
```python
def wrap_ddp_reference(model, device, rank):
# Only indexed devices take device_ids/output_device; CPU modules live on one shared device.
if torch.device(device).type == 'cpu':
return DDP(model)
return DDP(model, device_ids=[rank], output_device=rank)
```
Design notes:
- the condition restates the exact precondition torch's own DDP
constructor enforces, in torch's device vocabulary — it follows the
model's actual device rather than the global accelerator configuration;
- a single helper means new reference-model sites cannot forget the
branch (the first fix round in deepspeedai#8381 missed 4 of the 5 sites for exactly
this reason);
- GPU behavior is unchanged.
## Validation
Validated as part of the multi-rank CPU CI experiment in deepspeedai#8381: all
DDP-constructor failures were eliminated (the file's few remaining
failures there are unrelated — see the triage table in that PR), zero
regressions vs the same-commit baseline.
Signed-off-by: Guokai Ma <guokai.ma@intel.com>
…eepspeedai#8397) ## Problem `get_accelerator().current_device()` returns a **device index** on GPU backends (`torch.cuda.current_device()` → int), but on CPU it returns the `LOCAL_RANK` environment value — a plain **string** like `'1'`. Two test-side consumers fed that value straight into tensor/device placement: - `reduce_boolean_flags` in `tests/unit/common.py` (backbone of `allclose_on_all_ranks`, the "all ranks succeed or fail together" check) - 15 call sites in `tests/unit/v1/autotp/test_autotp_training.py` On CPU this fails immediately with `RuntimeError: Invalid device string: '1'` — before the first collective even runs. ## Change - Use `current_device_name()`, which returns a full device string on every backend (`'cpu'`, `'cuda:N'`, `'mps:0'`, …) and is equivalent to the index on GPU backends. - In `reduce_boolean_flags`, carry the flag in a 1-dim tensor: gloo rejects 0-dim inputs to `all_gather_into_tensor` (NCCL tolerates them), so the previous form would have failed on the very next line. ## Validation Validated as part of the multi-rank CPU CI experiment in deepspeedai#8381 (same-commit baseline comparison): this failure class disappeared, zero regressions on previously-passing tests. --------- Signed-off-by: Guokai Ma <guokai.ma@intel.com> Signed-off-by: Ma, Guokai <guokai.ma@intel.com>
…ai#8316) Fixes deepspeedai#8291. ## What breaks `single_all_to_all` decides whether a model does uneven-head sequence parallelism by asking whether the process-wide `tp_shard` head count is set: ```python if get_num_kv_heads() is not None or (num_heads % seq_world_size != 0 and not scatter_idx < 2): ``` AutoTP writes that same slot on every injection (`replace_module.py:306`, `engine.py:770`), so it is not only a second Ulysses model that clobbers the first — a single AutoTP model anywhere in the process is enough. `uneven_heads_all2all` then splits against that value, and `get_shard_size_list` falls back to the same global internally, so threading a value without also passing `num_kv_heads=` explicitly would not have been enough. A 12-head model on sp=4 should hand every rank 3 heads. With a leftover `num_kv_heads=3`: ``` 12 heads, sp=4 clean process -> [3, 3, 3, 3] after AutoTP set kv=3 -> [4, 4, 4, 0] ``` Driving it through `DistributedAttention` on 4 gloo ranks, upstream `6e3bd087f`: ``` clean process rank0: local_attn got 3 heads ids=[0, 1, 2] backward OK rank1: local_attn got 3 heads ids=[3, 4, 5] backward OK rank2: local_attn got 3 heads ids=[6, 7, 8] backward OK rank3: local_attn got 3 heads ids=[9, 10, 11] backward OK after an AutoTP model ran first (no output — rank 3 gets an empty tensor and the forward hangs in the output all-to-all) ``` Same script with this branch applied, both cases: ``` rank0: local_attn got 3 heads ids=[0, 1, 2] backward OK rank1: local_attn got 3 heads ids=[3, 4, 5] backward OK rank2: local_attn got 3 heads ids=[6, 7, 8] backward OK rank3: local_attn got 3 heads ids=[9, 10, 11] backward OK ``` ## The change `DistributedAttention` holds the count, either from a new `num_kv_heads` argument or read off its own key tensor, and only when it does not divide evenly — claiming one otherwise would push every model onto the uneven kernels. It threads the value through `_SeqAllToAll` into `single_all_to_all` and `uneven_heads_all2all`, and `backward` restores it from `ctx`, which is the piece the gather direction cannot recover from tensor shapes. The value is the **KV** head count, taken from the key tensor rather than the query tensor. That is what the `tp_shard` slot held, and it is what the partition has to follow: under GQA a query head must land on the rank holding its KV head. Q=6 / KV=3 over sp=2 divides evenly on the query side, so reading the query would give [3, 3] and split group 1 across two ranks; the KV side gives [2, 1] and therefore [4, 2]. Thanks to @FU-max-boop for catching that on the issue - my first revision had exactly this bug. `get_shard_size_list` is called with `num_kv_heads` set explicitly so its module-level default cannot reintroduce the leak. Callers that reach `single_all_to_all` directly, Megatron-DeepSpeed among them, pass nothing and keep the old behaviour including the `set_num_kv_heads` publish on first use. A sentinel separates "not supplied" from a deliberate `None`, which now means "splits evenly, take the fast path". This is independent of deepspeedai#8241 — it touches only `deepspeed/sequence/layer.py` and does not depend on `AutoTPMeta` — but the two overlap in intent, and I am happy to rebase on it if that lands first. ## Tests New `tests/unit/sequence_parallelism/test_ulysses_multiple_models.py`, shaped after the multi-model AutoTP test in deepspeedai#8241: - two `DistributedAttention` instances at 3 and 5 heads over sp=2 — the first still splits `[2, 1]` after the second has run forward and backward - a 6-head model over sp=2 with a leftover `num_kv_heads=3` — this is the case above, and it hangs on master - GQA, Q=6 / KV=3 over sp=2 - splits [4, 2], matching master - the explicit `num_kv_heads` argument ``` $ LOCAL_SIZE=2 pytest unit/sequence_parallelism/test_ulysses_multiple_models.py 4 passed in 21.65s $ LOCAL_SIZE=2 pytest unit/sequence_parallelism/ unit/module_inject/test_tp_shard.py 31 passed in 97.39s ``` Run on CPU, so `cpu-torch-latest` picks them up rather than only the GPU workflows. --------- Signed-off-by: alanhuangyoo <alanhuangyoo@gmail.com> Co-authored-by: Ma, Guokai <guokai.ma@gmail.com>
…ing (deepspeedai#8403) The `modal-torch-latest` GPU job is killed at its 75-minute cap before the suite finishes. On master this now happens in roughly half the runs (e.g. runs `33622520807`, `33600515110`, `33533630019`, `33526004564`), each annotated by GitHub with `The job has exceeded the maximum execution time of 1h15m0s`. **The test suite is not what grew.** Phase timings extracted from the job logs: | run | provisioning | env setup | pytest | tests | |---|---|---|---|---| | 08-22 12:53 | 0.1m | 6.0m | 37.5m | 1150 passed | | 08-24 05:12 | 0.1m | 6.3m | 41.1m | 1159 passed | | 08-29 00:40 | 0.2m | 6.2m | 39.3m | 1194 passed | | 08-31 08:45 | 7.9m | 6.4m | 48.8m | — | | 08-31 14:11 | 10.8m | 6.8m | 44.5m | — | | 09-01 11:47 | **17.8m** | 6.6m | 48.4m | 1241 passed | | 09-02 04:00 | **22.0m** | 4.8m | 38.5m | 1241 passed | pytest stayed in its usual 38-49 min band for a near-identical test count (1150 -> 1241, +8%). The entire regression is in **Modal sandbox provisioning: ~0.1 min -> 18-22 min since 2026-08-31**. ## What this PR changes This only restores the margin that regression consumed: - outer GitHub job budget: 75 -> 90 min - inner Modal sandbox lifetime: 3600 -> 4200s (60 -> 70 min) The sandbox clock starts when the container starts, so it has to cover env setup plus pytest, which has already been observed at 55 min - only 5 minutes of headroom under the old 3600s value. Both limits are raised together so the inner one does not become the new binding constraint. `ci/test_torch_latest.py` pins both values as a guard against unreviewed changes to the CI configuration, so the two assertions are updated in the same commit. ## Note: the provisioning regression is not addressed here It still needs investigation on the Modal side. Ruled out from the repo side: - image name unchanged: `pytorch/pytorch:2.10.0-cuda12.8-cudnn9-devel`, preset table untouched since deepspeedai#8016 (2026-05-19) - modal client pinned at `modal==1.2.6` - sandbox kwargs unchanged since deepspeedai#8170 The modal client prints no build output during the wait, which points at scheduling/capacity for `l40s:2` rather than an image pull. Concurrency of our own runs does not correlate (2 concurrent -> 0.9 min, 1 concurrent -> 17.8 min). Confirming this requires the Modal dashboard for app `deepspeedai-torch-latest-ci`. If provisioning keeps growing, 90 minutes will be consumed the same way, so the underlying cause is worth tracking separately. Signed-off-by: Ma, Guokai <guokai.ma@intel.com>
## Summary Fix AutoEP replacement silently dropping `e_score_correction_bias` when Hugging Face models register it as a buffer or place it somewhere other than the router module expected by the preset. The parser now records the bias owner's actual path inside each MoE layer. Replacement then copies the bias while preserving whether it is an `nn.Parameter` or registered buffer, including the buffer's persistence setting. The implementation supports locations such as: - `gate` - the MoE block itself - `router` - nested modules such as `gate.moe_statics` Ambiguous layers containing more than one `e_score_correction_bias` are rejected rather than selecting one silently. Unsupported non-parameter/non-buffer values produce a warning. ## Validation - Full AutoEP unit test file: `103 passed` - All pre-commit hooks passed - Tested with a real Transformers 5.15.1 `DeepseekV3MoE` - GPU validation environment: - NVIDIA GeForce RTX 5090 - PyTorch 2.8.0+cu128 - Transformers 5.15.1 - DeepSpeed 0.19.6 - The replacement preserved the CUDA registered buffer and its value - Native and EP2 replacement routing selected the same experts - Single-GPU full MoE forward comparison had a maximum absolute difference of `0.0` The available validation machine has one GPU, so a multi-GPU collective/ZeRO-3 end-to-end run was not performed. Fixes deepspeedai#8358 Signed-off-by: poorpaper <43514747+poorpaper@users.noreply.github.com>
## Problem `CUDAOpBuilder.nvcc_args()` only passes `-std=c++20` to nvcc when CUDA is 12.5+; on CUDA 13.x it falls back to `-std=c++17`. PyTorch >= 2.12 headers require C++20, so building DeepSpeed CUDA ops against CUDA 13 + torch >= 2.12 fails: ``` torch/include/torch/csrc/api/include/torch/all.h:5:2: error: #error C++20 or later compatible compiler is required to use PyTorch. torch/include/ATen/ATen.h:5:2: error: #error C++20 or later compatible compiler is required to use ATen. torch/include/c10/util/intrusive_ptr.h(775): error: namespace "std" has no member "strong_ordering" ... error: command '/usr/bin/ccache' failed with exit code 255 ``` Note that `cxx_args()` already selects `-std=c++20` for torch >= 2.12 (see deepspeedai#8238), so only the nvcc path is broken. ## Fix Extend the C++20 condition in `nvcc_args()` to also cover CUDA 13+: ```python if (cuda_major == 12 and cuda_minor >= 5) or cuda_major >= 13: ``` ## Verification Built DeepSpeed from source (`DS_BUILD_OPS=1 pip install .`) with CUDA 13.3, PyTorch 2.14.0, gcc-13: the build fails before this change with the errors above and completes successfully with it. Signed-off-by: Frank Tin <frank@bheu.net>
…edai#8583) ## Why `HybridEngineRollout.generate` selects the continuous path whenever `SamplingConfig.continuous_batch_size` is set, before any shared-prefill logic runs. With `HybridEngineRolloutConfig.use_shared_prefill=True`, that flag was therefore ignored with no error. This PR rejects the combination explicitly, matching the approach already taken for CUDA graph capture on the continuous path. Fixes deepspeedai#8458. ## Scope - `HybridEngineRollout._validate_continuous_inputs`: raise `ValueError` when `use_shared_prefill` is enabled. - `docs/code-docs/source/inference-engine.rst`: document that shared prefill and continuous batching cannot be combined. Out of scope: implementing shared-prefill semantics inside continuous batching. ## Tradeoffs Rejection over a compatible shared-prefill continuous mode. Continuous batching already requires `n_samples_per_prompt=1`, so shared prefill has no clear benefit there today. ## Blast Radius Only the experimental continuous path changes, and only when shared prefill is also requested. Default `generate()` and shared-prefill-only configs are unchanged. ## Verification Before the fix, `_validate_continuous_inputs` accepted `use_shared_prefill=True` with `continuous_batch_size=1` (silent ignore). After the fix it raises `ValueError: continuous batching does not support shared prompt prefill`. ``` TRANSFORMERS_NO_TF=1 PYTHONPATH=. python3 -m pytest tests/unit/runtime/rollout/test_hybrid_engine_rollout.py -q # 32 passed, 1 skipped ``` Signed-off-by: Chandan Kumar <cml.codes@gmail.com>
# AutoEP: a registry of expert activations, checked against the model at detection time ## Problem `GroupedExperts` computes `silu(gate) * up` in all three of its paths, and nothing in AutoEP checks which form the source model uses. That was true for every model family with a built-in preset, and it is not true in general. A scan of the 51 experts classes in transformers 5.15.1 (50 model families; regex over the modeling files, then each non-default row verified by hand in the source): | expert MLP form | families | examples | |---|---|---| | `silu(gate) * up` | 42 | Mixtral, Qwen2/3/3.5-MoE, DeepSeek-V2/V3/V3.2, GLM-4 MoE, GLM-DSA, Kimi-style `inkling`, Granite, OLMoE, Jamba, Mistral-4, ... | | `gelu_tanh(gate) * up` | 2 | Gemma-4, Diffusion-Gemma | | `silu(clamp(gate)) * clamp(up)`, limit 10 | 1 | DeepSeek-V4 | | `(clamp(up) + 1) * clamp(gate) * sigmoid(1.702 * clamp(gate))`, limit 7 | 3 | GPT-OSS, MiniMax-M3, OpenAI privacy filter | | `relu(up)^2`, no gate projection | 1 | Nemotron-H (different weight layout; out of scope here) | | not resolved from the config defaults | 1 | LFM2-MoE | `hidden_act` cannot be used to tell them apart: the configs of DeepSeek-V4, GPT-OSS and MiniMax-M3 all say `silu`. Each of the non-default families is replaced by AutoEP today with no error and no warning, through the custom `moe_layer_pattern` path, and the replaced layer then computes a different function. Measured on CPU with one real block against a deep copy of itself (`master` `4e394422a`, hidden 64, 8 experts, top-2): | block | how it was given to AutoEP | weight std | relative error of the AutoEP layer | |---|---|---|---| | `MiniMaxM3VLSparseMoeBlock` | custom `moe_layer_pattern` (its names are the custom defaults) | 0.02 | **0.8057** | | same | same | 0.5 | **0.2929** | | `GptOssMLP` | custom pattern + `router_pattern="router"` | 0.02 | **1.0084** (activation, plus dropped biases and the interleaved layout) | MiniMax-M3 is one model. DeepSeek-V4 is the reason to make the form a first-class, extensible part of AutoEP rather than a special case, and the next family will bring its own form. ## The change **`deepspeed/moe/ep_experts.py`: the registry** - `ExpertActivation`: `fn(gate, up, alpha, limit)` in plain PyTorch, an optional `fused_fn` with the same signature, `uses_alpha` / `uses_limit`, and `gate_fn`, the elementwise function the form applies to `gate` when it is `gate_fn(gate) * up` (used by the check below; `None` for `swiglu_oai`, which is not such a product). - `EXPERT_ACTIVATIONS`: `swiglu` (with the existing fused Triton kernel as `fused_fn`), `geglu_tanh`, `swiglu_clamped`, `swiglu_oai`. `register_expert_activation(name, fn, ...)` adds a form; a duplicate name is an error. - `apply_expert_activation(gate, up, activation, alpha, limit, fused)`. The three expert paths take `activation, alpha, limit` and call it; the for-loop path passes `fused=False`, so it stays in plain PyTorch and on CPU exactly as before. `GroupedExperts.__init__` takes the three values and rejects an unknown name at construction. - Default `"swiglu"`: no behaviour change for any existing preset. **`auto_ep_presets/base.py`, `auto_ep_config.py`, `auto_ep_presets/registry.py`: the name travels with the preset** - `MoEModelPreset` and `MoELayerSpec` gain `expert_activation`, `expert_activation_alpha`, `expert_activation_limit`. `AutoEPConfig` gains `expert_activation: str | None` (None = the preset's). The `expert_parallel.expert_activation` key is parsed, validated against the registry, counted as a custom field, applied by `apply_config_overrides`, and used by `_build_custom_preset`. **`auto_ep.py`: the preset names the form, the model is checked against it** `_resolve_expert_activation` runs once per detected layer: 1. `_detect_clamped_swiglu` looks for a clamp limit: `swiglu_limit` / `swiglu_alpha` on the experts module, the model config or its text config (MiniMax-M3, GPT-OSS), or a numeric `limit` / `alpha` on the experts module (DeepSeek-V4, GPT-OSS). A limit with a form that does not clamp is an error. For a clamping form, the model's limit and alpha replace the preset's. 2. `_gate_activation_matches` evaluates the experts' `act_fn`, when there is one, on a probe vector and compares it numerically with the `gate_fn` of every registered form. An `act_fn` that does not match the named form is an error (Gemma-4's `gelu_pytorch_tanh` under a `swiglu` preset; an activation nobody registered). 3. Setting `expert_activation` in the config is taken as a decision and switches both checks off. The errors name the registered forms and the model families that use them. Nothing is guessed from the model: the name comes from the preset or the user, the model can only contradict it. **`auto_ep_layer.py`**: passes the three spec fields to `GroupedExperts`. **`docs/_pages/config-json.md`**: the new key, next to the other custom-preset keys. ## Tests New file `tests/unit/v1/moe/test_autoep_expert_activation.py`, same style as `test_autoep_unit.py`. 35 cases; 27 run on CPU in one process, 8 need an accelerator. | group | what it checks, and the wrong behaviour it would catch | |---|---| | `TestApplyExpertActivation` | hand-computed values for the three non-default forms (clamp hits `gate` from above only and `up` on both sides; `alpha` and `limit` honoured); every pair of forms differs; equality with `MiniMaxM3VLExperts._apply_gate`, `DeepseekV4Experts._apply_gate` and transformers' `_default_apply_gate` with `silu` and `gelu_pytorch_tanh`; unknown names rejected in the call, the layer and the config; a form registered at runtime is usable in the call, the layer, config validation and a custom preset, and a duplicate name is refused | | `TestGroupedExpertsActivation` | for-loop path against a dense per-expert reference, forward and input gradient, every registered form, with an expert that has zero tokens; **accelerator:** the `torch._grouped_mm` and Triton grouped-GEMM paths (packed rows, fused kernel) match the for-loop path in output, input gradient and the three weight gradients, every form; the for-loop path never reaches the Triton kernel | | `TestPresetAndConfig` | every built-in preset is `swiglu`; the config key reaches a custom preset and overrides a built-in one without changing the registered preset | | `TestExpertActivationDetection` | a plain model is unchanged; a clamp limit on the experts (`swiglu_limit`, or `limit` + `alpha`) or on the config is refused under a plain preset; explicit `swiglu` is kept; `alpha` and `limit` come from the model; the DeepSeek-V4 shape (limit, no alpha) is refused with `swiglu_clamped` named, and accepted with it set; `gelu_tanh` experts are refused under a plain preset and accepted with `geglu_tanh`; `silu` experts pass; an `act_fn` matching no registered form is refused unless the user chooses | | `TestMiniMaxM3ThroughCustomPattern` | a real `MiniMaxM3VLSparseMoeBlock` given through the custom pattern, as a user does before a preset exists: without the key it is refused; with `expert_activation="swiglu_oai"` the replaced block matches a deep copy of the original, forward and input gradient, at weight std 0.02 and 0.5 (0.5 drives pre-activations past the clamp) | `test_preset_registry_core_contracts` in `test_autoep_unit.py` is unchanged: this PR adds no preset. Results, all measured on this branch: | where | environment | `test_autoep_expert_activation.py` | `test_autoep_unit.py` | `test_autoep_grad_parity.py` | `ops/triton_ops/test_swiglu_triton.py` | |---|---|---|---|---|---| | login node, CPU, one process | torch 2.9.1, transformers 5.15.0 | 27 passed, 8 skipped (accelerator cases) | 184 passed, 6 skipped | not run (needs 4 devices) | not run | | H200 node, Slurm jobs 34594 (4 GPUs) and 34598 (1 GPU) | torch 2.9.1+cu128, transformers 5.15.0, Triton 3.5.1 | **35 passed** (job 34598) | **190 passed** (job 34594) | **23 passed, 8 skipped** (the regional-compile parity cases need `DEEPSPEED_RUN_H100_TESTS=1`), 2 min 41 s (job 34594) | 37 passed (job 34594; kernel unchanged, it is the `swiglu` fused path) | The accelerator test went through two tolerance fixes on the way: `out.sum().backward()` hands `torch._grouped_mm` an expanded all-ones gradient with zero strides, which it refuses (real training never does that; the test now uses a random dense upstream gradient), and an elementwise absolute tolerance is wrong for bf16 sums, because the fused kernel rounds once after fp32 math and the eager ops round per op, and a matmul then sums those rounded values. A direct probe of the fused kernel against eager `silu(gate) * up` on the H200 (8 shapes from (5, 7) to (1024, 4096), bf16 and fp32, forward and both gradients) stays within one bf16 ulp and is exact in fp32; the test's absolute tolerance is now set from the compared tensor's largest magnitude. `pre-commit run --files` on the changed files: yapf, flake8, codespell, check-torchdist, check-torchcuda pass. `check-license` reports the new test file only because the hook uses `git grep`, which skips untracked files; the header is the same as `test_autoep_unit.py`'s. Signed-off-by: pengdurice <pengduhit@gmail.com>
## What breaks
`DeepSpeedEngine._backward_prologue()` / `_backward_epilogue()` enter
the ZeRO DeepCompile backward hooks whenever DeepCompile is active,
exempting only the AutoTP compile pass:
```python
if self.is_deepcompile_active() and not self.compile_autotp():
deepcompile_backward_prologue(self.is_gradient_accumulation_boundary())
```
With `compile.passes: ["autosp"]`, `engine.compile()` installs the
AutoSP backend and marks DeepCompile active, so every backward calls
`deepcompile_backward_prologue()`. That calls
`get_deepcompile_handle()`, which loads (and JIT-builds on first use)
the DeepCompile native extension, then calls `start_backward()` on it.
AutoSP never initializes that runtime (`dc.init()` is only called on the
ZeRO DeepCompile path), so on CUDA this silently loads an unused
extension, and on accelerators that cannot build it, backward fails.
`allreduce_gradients()` already uses `uses_parallelization_pass_only()`
(AutoSP or AutoTP) for the same decision; the backward hooks were missed
when that helper was introduced.
## Fix
Use `uses_parallelization_pass_only()` in both the backward prologue and
epilogue checks. The AutoTP behavior is unchanged.
## Tests
Added
`TestAutoSPEngineBackward::test_backward_skips_zero_deepcompile_hooks`
in `tests/unit/v1/compile/test_compile_autosp.py`. It builds a ZeRO-0
engine with `compile.passes: ["autosp"]`, marks DeepCompile active as
`engine.compile()` would, makes `get_deepcompile_handle()` and the
post-backward hooks raise, and runs forward/backward/step.
| | result |
|---|---|
| master | FAILED (`RuntimeError: AutoSP backward must not load the ZeRO
DeepCompile runtime`) |
| this PR | PASSED |
Also ran locally: `tests/unit/compile/test_zero3_grad_dtype.py`,
`tests/unit/compile/test_backend.py`, and the rest of
`tests/unit/v1/compile/test_compile_autosp.py` (all IR-level tests
pass). The end-to-end `TestAutoSPCompile` cases fail identically on
master and this branch in my environment (torch 2.13, transformers 5.17)
during Dynamo tracing of the forward pass, before backward is reached,
so they are unrelated to this change.
Signed-off-by: Jin, Youzhi <youzhi.jin@intel.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Implements `DualPipeV` from `DeepSeek` team Part of deepspeedai#7100. This adds DualPipeV, the V-shaped schedule from [DualPipe](https://github.com/deepseek-ai/DualPipe), as an opt-in alternative to 1F1B. Existing pipeline users are not affected. A model opts in by building a `DualPipeVModule` instead of a `PipelineModule`. ```python from deepspeed.pipe import DualPipeVModule net = DualPipeVModule(layers=layers, num_stages=4, loss_fn=loss_fn) engine, _, _, _ = deepspeed.initialize(config=config, model=net, model_parameters=net.parameters()) loss = engine.train_batch() ``` ## Changes - Adds `DualPipeVModule`, which cuts the model into `2P` stages and builds stages `r` and `2P-1-r` on rank `r`. - Adds `DualPipeVEngine`, a child of `PipelineEngine`. It replaces only the send and receive methods with batched `isend`/`irecv`. - Adds `DualPipeVSchedule`, which follows the eight steps of the reference `dualpipev.py`. - Adds `P2POp` and `batch_isend_irecv` to `deepspeed.comm`. - `PipelineEngine` gets three small hook methods for the schedules and the loss rank, and `PipelineModule` reads `self.num_stages` when partitioning. Neither changes 1F1B behaviour. - Tests for the schedule protocol, and an end-to-end test against an unpartitioned `nn.Sequential`. I also tried it using a small experiment on Kaggle's 2 T4 using [this scipt](https://gist.github.com/phoeenniixx/245535be06ae731d2a8329590f43dca1). See the results [here](https://www.kaggle.com/code/arian32/notebook561d1e71d8) | schedule | step time (s) | samples/s | peak mem rank 0 (MB) | peak mem rank 1 (MB) | final loss | |---|---|---|---|---|---| | 1F1B (PipelineModule) | 0.465 | 68.9 | 621 | 525 | 1.000726 | | DualPipeV (DualPipeVModule) | 0.439 | 72.9 | 761 | 909 | 1.000726 | ## Limitations - `gradient_accumulation_steps` must be at least twice the number of pipeline ranks. - `dynamic_shape`, `pipe_partitioned`, `grad_partitioned` and boolean attention masks are not supported. - No forward/backward overlap and no deferred weight gradients yet, so the speedup is smaller than in the DualPipe README. ## Follow-ups If this approach is accepted, I plan to raise follow-up PRs for: - The bidirectional DualPipe schedule. It can reuse parts of `DualPipeVEngine` (maybe move the common parts to a common base class in future?) and needs a second `steps()` generator plus data loading and loss on both end ranks. - Forward/backward overlap and the zero-bubble weight-gradient split. - Tutorial and API reference docs. --------- Signed-off-by: Aryan Saini <116151399+phoeenniixx@users.noreply.github.com>
deepspeedai#8627) Fixes deepspeedai#8626 Ships the NPU counterparts of the three op builders that deepspeedai#8054 added for SUPA in op_builder/supa/. ## Summary Adds op_builder/npu/fused_lion.py (NPUFusedLion), op_builder/npu/fused_lamb.py (NPUFusedLamb), and op_builder/npu/quantizer.py (NPUQuantizer + QuantizerBuilder), registered in op_builder/npu/__init__.py. Previously the three names resolved to NotImplementedBuilder on NPU, so "optimizer": {"type": "Lion"|"Lamb"} and zero_quantized_weights / zero_quantized_gradients all crashed at engine initialization with ValueError: This op had not been implemented on NPU backend. — reproduced on hardware. All three are pure-torch stateless modules with the same interface shape as the SUPA backend (Add Biren SUPA accelerator support deepspeedai#8054) and the same per-parameter op contract as the CUDA kernels; nothing to compile, no kernel code. The quantizer matches the Zero++ wire format bit for bit (truncation toward zero, clamp to [-2**(b-1), 2**(b-1)-1], stored 1/scale per group) and includes the qgZ int4 swizzle_quant / quantized_reduction pair (signed two's-complement nibble packing, two-stage all-to-all layout). ## Implementation notes NPUFusedLion implements the sign update with the c==0 -> +lr branch and multiplicative weight decay. NPUFusedLamb implements the full per-parameter semantics (trust ratio clamped by max/min coefficients, bias correction, both eps modes, zero-norm fallbacks). Both use chained in-place updates, following torch_npu's NpuFusedLamb form: on 910B4 this is ~26% (Lion) / ~17% (Lamb) faster per step than the equivalent explicit two-step arithmetic (128 params, 162M elems). Lion agrees with the explicit form bitwise; Lamb agrees to 1 ulp, and its exp_avg/exp_avg_sq are bit-identical to torch_npu.optim.NpuFusedLamb under equivalent semantics (an independent cross-check). NPUQuantizer covers quantize / dequantize / dequantize_fp32 for the hpZ int8 path and swizzle_quant / quantized_reduction for the qgZ int4 path. The int8/int4 types only ever appear as communication payloads (quantize -> move bytes -> dequantize); training compute stays fp16/bf16. Docstrings record the native-operator upgrade points: torch_npu's npu_quantize family rounds half-to-even and exposes no truncation mode today, so a native kernel can be swapped in later without changing the contract. ## Performance (Ascend 910B4, median of 5 runs, chained in-place vs the original explicit two-step form) | Operation | Config | Before | After | Speedup | | --- | --- | --- | --- | --- | | FusedLamb | 128 params, 162M elems, fp32 states | 127.0 ms | 112.6 ms | 1.13x | | FusedLion | 128 params, 162M elems, fp32 states | 64.3 ms | 49.1 ms | 1.31x | | quantize | 1M elems, 1024 groups | 0.50 ms | 0.39 ms | 1.28x | | quantize | 8M elems, 1024 groups | 0.50 ms | 0.39 ms | 1.27x | | quantize | 64M elems, 1024 groups | 4.82 ms | 4.76 ms | 1.01x | | dequantize | 64M elems, 1024 groups | 1.21 ms | 1.12 ms | 1.08x | The optimizers are called per parameter, matching the per-parameter op contract of the CUDA kernels; quantize/dequantize timings cover the hpZ bucket size range. At 64M elements the quantize path is bandwidth-bound and the forms are equivalent (1.01x). Validation on Ascend 910B4 (CANN 8.5.0, torch 2.9.0+cpu, torch_npu 2.9.0.post7, 4x Ascend 910B4, aarch64) - Lion 20 steps 1.1281 -> 0.6392; LAMB 20 steps 1.1281 -> 1.1196; a 5-step Lion engine run is bitwise-equal to a manual oracle loop. - LAMB cross-checked against torch_npu.optim.NpuFusedLamb (equivalent semantics: eps_mode 1, no bias correction): exp_avg/exp_avg_sq bit-identical after 10 steps, params within 1 ulp. - hpZ ZeRO-3 2-rank 8 steps: the quantized path fires on the training loop, quantized on/off loss trajectories overlap (final gap 1.7e-4), per-rank weight-fetch payload 33152 B -> 16592 B (-50.0%). - Benchmark (2 ranks, intra-node): pure-torch quantize/dequantize throughput 12.3-28.6 / 32.1-91.7 GB/s (8-537 MB tensors); intra-node HCCL all_gather 4.7-16.2 GB/s (2-537 MB per rank); computed break-even communication bandwidth 14.4 GB/s. ## Test plan - pre-commit run --files on the touched paths: yapf, flake8, check-torchdist, check-license, codespell all pass. - Contract tests for the three modules (bitwise comparison against independent numpy oracles) pass on CPU without any accelerator. They are maintained out of tree, following the existing convention that no vendor ships vendor-specific test files in-tree (HPU/XPU/MLU/SUPA have none). - Real-device on Ascend 910B4: Lion/LAMB convergence, Lion engine-vs-oracle bitwise parity, LAMB-vs-NpuFusedLamb cross-check, and the hpZ payload measurement reported above. ## Known limitation fp32/fp64 division on Ascend is approximate (1 ulp off on ~5% of values), so the stored quantizer scales can differ from a correctly rounded computation by 1 ulp. This is bounded and safe: every rank in a run computes the same value, the 1-ulp scale error (~1e-7 relative) is five orders below the quantization error (~1e-2), and the wire format is transient (checkpoints store unquantized weights). --------- Signed-off-by: Zizhao Tang <1601677496@qq.com>
…epspeedai#8679) Fix compatibility failures in the Triton transformer-inference kernels without changing kernel math or autotune configurations: • Inline the packed FlashAttention masking constant to avoid accessing a non-constexpr module global during JIT compilation. • Update both 2D and 4D MatMul pruning callbacks to accept launch keywords such as grid , and query device properties through triton.runtime.driver.active.utils . • Add 2D MatMul autotuning regressions using fresh autotuners, so cached configurations or earlier skip_autotune() calls cannot hide pruning failures. Signed-off-by: Hongwei Chen <hongweichen@microsoft.com> Co-authored-by: Ma, Guokai <guokai.ma@gmail.com>
## Summary `SamplingConfig` exposes `top_k`, but `HybridEngineRollout` did not forward it to Transformers generation. As a result, sampling callers could not apply their configured top-k limit and the default non-positive setting could fall through to Transformers' own behavior. This PR: - forwards `top_k` when `HybridEngineRollout` uses random sampling; - treats `top_k <= 0` as disabled by passing Transformers its disabled value; - preserves greedy generation, CUDA graph capture, and continuous batching behavior; - removes the unused local top-p sampler, since rollout sampling delegates to Transformers. ## Validation - verifies top-k forwarding during random sampling; - verifies prompt expansion for multiple samples; - verifies EOS padding and the `eos_token_id=None` ZeRO lockstep contract; - verifies disabled `top_k` values (`-1` and `0`); - focused regression tests: 4 passed; - Changed-file pre-commit checks: passed Thank you for your review. Signed-off-by: nathon-lee <leejianwoo@gmail.com>
…dai#8684) ## Description Every fp16-config test that reaches `deepspeed.initialize` crashes its sanity check (`Type fp16 is not supported on your device.`) on accelerators whose `is_fp16_supported()` is false. On CPU that maps to the AVX512-FP16 capability of the host, and GitHub's `ubuntu-24.04` runners are hardware-heterogeneous, so these tests flip between failure and skip depending on which runner they land on. deepspeedai#8398 added the first skipifs; the multi-rank CPU run in deepspeedai#8381 flushed out six more files: | File | Shape of the gap | |---|---| | `checkpoint/test_universal_checkpoint.py` | fp16 parametrizations fail **inside the baseline DistributedFixture's distributed run** — pytest reports a setup **ERROR** for every dependent test (48 on the multi-rank run) instead of a skip | | `v1/zero/test_zero_coalesce_grad_reduction.py` | `TestCoalesceFP16` forces an fp16 config | | `runtime/test_no_sync_ctxt.py` | dtype=float16 parametrizations of three methods; stages 2/3 additionally never reach their expected no_sync AssertionError on such hosts | | `checkpoint/test_moe_checkpoint.py` | whole class hardcodes fp16 | | `runtime/zero/test_zero_offloadpp.py` | `TestZeroPartialOffloadConfigSweep` hardcodes fp16 | | `checkpoint/test_pipeline.py` | fp16 enabled for zero_stage > 0; only that parametrization skips, zero_stage=0 keeps running | With this PR, **every fp16-config test in the suite guards on `is_fp16_supported()`** — the capability gap is a skip, not a failure, on any accelerator. ## Validation (executed on real hardware) - 20-core x86_64 CPU without AVX512-FP16, gloo, 2-4 ranks (`LOCAL_SIZE=2/4`) - Before: 18 failures + 48 setup ERRORs across these files on the multi-rank CPU run - After: every affected parametrization skips; adjacent non-fp16 parametrizations keep passing (e.g. pipeline zero_stage=0 runs to completion) - Full-suite evidence in deepspeedai#8381: the multi-rank CPU run went 8 failures -> 0 with these guards Sibling PRs from the same series: deepspeedai#8397, deepspeedai#8398, deepspeedai#8399, deepspeedai#8407, deepspeedai#8409, deepspeedai#8559, deepspeedai#8648. Signed-off-by: Guokai Ma <guokai.ma@intel.com>
Consolidate the reviewed documentation fixes, typo corrections, and small runtime cleanups from the original PRs below. **Credit to @simpleqt for the original contributions.** The cherry-picked commits preserve the original authorship and sign-offs. This PR combines the valid changes, avoids duplicate edits, and adjusts changes that no longer match the current code or documentation. - Fix broken tutorial links, documentation anchors, and Python API references. - Correct parameter names, missing argument documentation, duplicated words, and garbled text in docstrings, comments, and documentation. - Simplify identical branches in the checkpoint writer and ZenFlow gradient-copy path, restore the gradient assertion, and remove the checkpoint writer's unconditional debug print. - Additionally, repair the remaining ZeRO-3 Offload tutorial link so it points to the current ZeRO-3/ZeRO-Infinity section. ## Original PRs | Original PR | Change incorporated | | --- | --- | | [deepspeedai#8445](deepspeedai#8445) | Restore the non-None gradient assertion and remove the duplicated ZenFlow gradient-copy branch. | | [deepspeedai#8446](deepspeedai#8446) | Remove identical checkpoint-writer branches and the unconditional constructor debug print. | | [deepspeedai#8449](deepspeedai#8449) | Point CONTRIBUTING's installation link to `README.md#installation`. | | [deepspeedai#8450](deepspeedai#8450) | Include only the `max_norm` documentation; omit the obsolete `use_graph` entry. | | [deepspeedai#8545](deepspeedai#8545) | Both scheduling-docstring corrections are covered by deepspeedai#8599, so they are included only once. | | [deepspeedai#8546](deepspeedai#8546) | Correct the "Add a new workflow" anchor in `TEST_SELECTION.md`. | | [deepspeedai#8593](deepspeedai#8593) | Correct the two 1Cycle tutorial links to `/tutorials/one-cycle/`. | | [deepspeedai#8594](deepspeedai#8594) | Retain the two valid URL case corrections in the ZeRO-3 Offload post; handle its final tutorial link separately as described below. | | [deepspeedai#8595](deepspeedai#8595) | Correct the Megatron example to use `deepspeed.checkpointing.get_cuda_rng_tracker`. | | [deepspeedai#8596](deepspeedai#8596) | Correct `deepspeed.com.log_summary` to `deepspeed.comm.log_summary`. | | [deepspeedai#8597](deepspeedai#8597) | Point the AutoTP supported-models link to the correct Read the Docs page and anchor. | | [deepspeedai#8598](deepspeedai#8598) | Align the `fp_quantize` docstring's parameter names with its signature. | | [deepspeedai#8599](deepspeedai#8599) | Remove duplicated words and garbled fragments in scheduling docstrings, runtime comments, and documentation. | ## Integration adjustments - **deepspeedai#8450:** `use_graph` was removed by [deepspeedai#8579](deepspeedai#8579), so only the still-applicable `max_norm` documentation is retained. - **deepspeedai#8594:** Its proposed final destination, `/tutorials/zero-offload/`, teaches ZeRO stage 2 optimizer offloading. Instead, this PR separately updates the ZeRO-3 tutorial link to [Training trillion-scale models with ZeRO-Infinity](https://www.deepspeed.ai/tutorials/zero/#training-trillion-scale-models-with-zero-infinity), which documents stage 3 and CPU parameter/optimizer offloading. - **deepspeedai#8545 and deepspeedai#8599:** The overlapping scheduling-docstring fixes are incorporated through deepspeedai#8599 rather than duplicated. --------- Signed-off-by: simpleqt <89645338+simpleqt@users.noreply.github.com> Signed-off-by: Hongwei Chen <hongweichen@microsoft.com> Co-authored-by: simpleqt <89645338+simpleqt@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Follow up deepspeedai#8381 Fix 3 FAILED `unit/v1/ops/muon/test_per_head_muon_accelerator.py` in https://github.com/deepspeedai/DeepSpeed/actions/runs/35675316100/job/106580600974?pr=8381 @delock --------- Signed-off-by: Jin, Youzhi <youzhi.jin@intel.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: pengdurice <pengduhit@gmail.com>
…i#8694) `DeepSpeedCPUAdam(amsgrad=True)` silently runs plain Adam. The CPU kernel has no AMSGrad path, so the flag is stored in the param group and never read. With `"amsgrad": true` in the optimizer config, `FusedAdam` raises, but turning on `offload_optimizer` swaps in CPU Adam and the run trains with a different algorithm and no warning. Fix: reject `amsgrad` in `add_param_group`, the same way `FusedAdam` and `FusedLamb` do. That covers the constructor, the engine's config path, ZenFlow's subclass and groups added later. `__del__` now skips the C++ destroy when construction failed, so the error isn't followed by an `AttributeError`. Test: `test_cpu_adam_rejects_amsgrad` fails on master (DID NOT RAISE) and passes with the fix. `tests/unit/ops/adam/` and the Muon partial-training tests pass: 158 passed, 14 skipped. Signed-off-by: Vineeth Sai <vineethsai4444@gmail.com>
…dai#8665) ## What breaks `_FPDTGPUAttentionImpl_` (the non-offloading FPDT attention, used when `cpu_offloading=False` or when there is a single attention chunk) allocates its K/V gradient accumulators with the **query** shape: ```python dk = [torch.zeros(global_q[0].shape, ...) for _ in range(num_chunks)] dv = [torch.zeros(global_q[0].shape, ...) for _ in range(num_chunks)] ``` With grouped-query attention (`num_key_value_heads < num_attention_heads`) the K/V chunks carry fewer heads than Q. The per-block `dk_this`/`dv_this` are already allocated from the K/V shapes, so they are accumulated into buffers with the wrong head count, and after the reverse all-to-all the projected K/V gradient no longer fits the K/V slice of the QKV weight. Backward fails, e.g. with 8 query heads, 2 KV heads, head_dim 32 and sp=2: ``` RuntimeError: The size of tensor a (64) must match the size of tensor b (256) at non-singleton dimension 0 ``` The offloading implementation (`_FPDTGPUOffloadingAttentionImpl_`) already allocates these buffers from `global_k`/`global_v`, so only the non-offloading path is affected. MHA is unaffected because Q and K/V shapes coincide. ## Fix Allocate `dk`/`dv` from the K/V chunk shapes, matching the offloading implementation. ## Tests Added `TestFPDTAttentionGQABackward` in `tests/unit/v1/sequence_parallelism/test_ulysses.py` (world size 2, `num_kv_heads` in {2, 4, 8} with 8 query heads). It runs the non-offloading implementation on load-balanced FPDT shards and compares the output and the input, QKV weight and QKV bias gradients against a full-sequence fp32 causal attention reference. Previously only the offloading implementation's forward output was tested; this is the first backward check for FPDT attention. Like the existing FPDT test, it requires flash-attn and is skipped otherwise. Local results (2x RTX 5090 D, torch 2.13 + CUDA 13.0, flash-attn 2.8.3.post1 built from source): | | kv=2 (GQA) | kv=4 (GQA) | kv=8 (MHA) | |---|---|---|---| | master | FAILED | FAILED | PASSED | | this PR | PASSED | PASSED | PASSED | On master the GQA cases fail in backward with the shape mismatch above. With the fix, in fp16, the largest gradient deviation from the fp32 reference is ~0.07 on values up to ~150 (QKV bias grad of V). Signed-off-by: Jin, Youzhi <youzhi.jin@intel.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Masahiro Tanaka <81312776+tohtana@users.noreply.github.com>
…#8675) ## What breaks AutoSP shards the sequence across the SP ranks, and the Q/K/V all-to-all trades heads for sequence (`[B, N, S/P, H] -> [B, N/P, S, H]`). So the sequence length and the head counts must both be divisible by `sequence_parallel_size`. Neither is checked. Reproduced on 2 ranks (sp=2) with a small SDPA model compiled through `apply_autosp` + Inductor (the default AutoSP backend), torch 2.13: | case | master | |---|---| | 4 query heads, 1 KV head (GQA) | runs; **Q/K/V projection gradients are exactly 0** | | 3 query heads | `RuntimeError: shape '[2, (s38//2), 24]' is invalid for input of size 32*((s38//2))` at compile time | | sequence length 15 | `AssertionError: expected size 2==2, stride 224==240 at dim=0; ... expected size 14==15 ...` in `autosp::all_to_all` | | sequence length 15, eager backend | runs; the last token is silently dropped | The GQA case is the worst one. For KV heads, the all-to-all reshapes `N` heads into `N // P = 0` heads per rank. Under Inductor this yields an empty attention output and training continues without error, while attention does not learn: ``` rank0: OK loss=4.1853 k.grad.norm=0 v.grad.norm=0 q.grad.norm=0 ``` For the sequence length, every rank takes `S // P` tokens, so `S % P` tokens are dropped. The fake all-to-all restores the full symbolic `S` afterwards, which is where the Inductor stride assertion comes from. ## Fix - **Heads**: `pass_insert_attention_all_to_all` checks the query, key and value head counts of every SDPA call. They are checked separately because with GQA the K/V heads can be fewer than the query heads. The `autosp::all_to_all` op also checks the head count before the collective, since it can be called outside the pass. - **Sequence length**: the length is a dynamic dimension, so it can only be checked when the graph runs. `create_shard_offsets` inserts an `aten._assert_scalar` on `S % P == 0` next to the shard offsets. That is the op Dynamo itself emits for runtime asserts, and unlike `torch._assert` it is not stripped under `python -O`. - **Docs**: the AutoSP note in `training.rst` now states both requirements. With the fix, the same cases give: ``` ValueError: AutoSP requires the number of key heads (1) to be divisible by sequence_parallel_size (2) ValueError: AutoSP requires the number of query heads (3) to be divisible by sequence_parallel_size (2) RuntimeError: AutoSP requires the sequence length to be divisible by sequence_parallel_size (2) ``` Divisible lengths reuse the compiled graph as before. For example, after compiling with S=16, S=32 runs without a recompile, and S=15 and S=17 raise the error above. ## Tests `TestAutoSPDivisibilityValidation` in `tests/unit/v1/compile/test_compile_autosp.py` contains plain pytest tests that run IR-level passes with a mocked `sp_size`: | test | master | this PR | |---|---|---| | `test_shard_offsets_for_divisible_sequence_length[16, 32]` | PASSED | PASSED | | `test_shard_offsets_reject_non_divisible_sequence_length` | FAILED | PASSED | | `test_rejects_non_divisible_attention_heads[mha]` (3 query heads) | FAILED | PASSED | | `test_rejects_non_divisible_attention_heads[gqa]` (4 query heads, 1 KV head) | FAILED | PASSED | | `test_accepts_grouped_query_attention_with_divisible_heads` (4 query heads, 2 KV heads) | PASSED | PASSED | | `test_all_to_all_rejects_non_divisible_heads_before_the_collective` | FAILED | PASSED | The existing IR-level tests in the same file also pass (29 passed). Signed-off-by: Jin, Youzhi <youzhi.jin@intel.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…peedai#8674) ## What breaks AutoSP keeps its SP/DP process groups in a process-global registry (`deepspeed/compile/custom_ops/sp_dp_registry.py`). The compiled graph reads `sp_size()` and `get_group()` from it **at runtime**, inside the `autosp::all_to_all` op and the sharding offsets. ### 1. A different mesh silently reuses the stale groups `populate_registry()` returns early once any mesh is registered: ```python if GROUP_REGISTRY.get('is_reg', False): return ``` If a second AutoSP compilation in the same process (e.g. another engine) requests a different `sequence_parallel_size`, it keeps the first mesh without warning. The graph is then sharded and exchanged with the old SP size, while the engine's own data-parallel groups follow the new config. On 4 ranks, `populate_registry(2, 2)` followed by `populate_registry(4, 1)` gives, on master: ``` rank0: requested sp=4, registry sp_size()=2 group size=2 rank1: requested sp=4, registry sp_size()=2 group size=2 rank2: requested sp=4, registry sp_size()=2 group size=2 rank3: requested sp=4, registry sp_size()=2 group size=2 ``` Rebuilding the groups is not an option either, since graphs already compiled for the first mesh would then pick up the new SP size at runtime. So a changed mesh now raises a `RuntimeError`. Re-registering the same mesh still reuses the existing groups. ### 2. A mesh smaller than the world size fails later with a `KeyError` `apply_autosp()` only asserted `sp_size * dp_size <= world_size`. With a smaller mesh, ranks outside it have no SP group. On 4 ranks with `(sp, dp) = (2, 1)`: ``` rank0: group size=2 rank1: group size=2 rank2: KeyError: 1 rank3: KeyError: 1 ``` `populate_registry()` now requires `sp_size * dp_size == world_size` and raises a `ValueError` before creating any group. The check was moved from `apply_autosp()` into `populate_registry()` so that every caller gets it. The engine derives `dp_size = world_size // sp_size` in `extract_mesh_size()`, so case 2 is only reachable when `apply_autosp()` / `populate_registry()` are called directly. Case 1 is reachable through the engine. ## Tests In `tests/unit/v1/compile/test_compile_autosp.py`: - `TestAutoSPMeshValidation::test_rejects_changed_mesh`: an already-registered `(2, 2)` mesh rejects `(4, 1)` and keeps its SP/DP sizes. - `TestAutoSPMeshValidation::test_rejects_mesh_not_covering_world[2-1, 1-2]`: a mesh that does not cover a world of 4 raises before any process group is created. - `TestAutoSPMeshRegistry::test_same_mesh_is_reused` (4 ranks, real process groups): registering the same mesh twice keeps the same group objects. The rejection tests are plain pytest tests with `get_world_size` mocked, not `DistributedTest`s. When `pytest.raises` fails inside a `DistributedTest` worker it raises a `BaseException`, which hangs the worker pool instead of reporting the failure. | | master | this PR | |---|---|---| | `test_rejects_changed_mesh` | FAILED | PASSED | | `test_rejects_mesh_not_covering_world[2-1]` | FAILED | PASSED | | `test_rejects_mesh_not_covering_world[1-2]` | FAILED | PASSED | | `test_same_mesh_is_reused` | PASSED | PASSED | The rest of the IR-level tests in `test_compile_autosp.py` pass as well (26 passed). --------- Signed-off-by: Jin, Youzhi <youzhi.jin@intel.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
…rad norm (deepspeedai#8635) `FP16_Optimizer.step` builds two gradient-norm inputs, and the two consumers expect different things: - the non-expert list goes to `get_flattened_grad_norm`, which filters on `p.grad` and reads `p.grad.data`, so it expects **parameters**; - the expert list goes to `get_norm_with_moe_layers` → `get_global_norm_of_tensors`, which reads each tensor's own data, and whose docstring asks for **gradient tensors**. Both lists were filled with the FP32 master parameter `self.fp32_groups_flat[i]`. That is correct for the first consumer and wrong for the second, so the expert contribution to the global norm was the expert **weight** norm rather than the expert gradient norm. With the default `gradient_clipping=1.0`, that inflates the norm and shrinks the clip scale applied to every gradient, including non-expert ones. The fix passes `grads_groups_flat[i]` to the expert list. `BF16_Optimizer` (`self.fp32_groups_gradients[i][j]`) and `FP16_UnfusedOptimizer` (`split_params_grads_into_shared_and_expert_params`) already take the expert norm from gradients and are not affected. ### Test `TestMoEFP16GradientNorm::test_expert_weight_values_do_not_affect_gradient_norm` trains a small MoE model with fp16 and ZeRO stage 0, which selects `FP16_Optimizer`. It sets every gradient to the same fixed value, scales only the expert weights by 100, and requires the norm reported by `engine.get_global_grad_norm()` to be exactly unchanged. It also checks that the norm is above the default clipping threshold of 1.0, so that clipping acts on it. H100 80GB, torch 2.10 (CUDA 13.0): | Source | Result | |---|---| | test only, unmodified master | fails: `Scalars are not equal!` | | test + fix | passes | These runs predate the rebase onto current master, which does not touch either file. The test needs fp16, so CPU runners skip it. Signed-off-by: yh0903 <helloyu0903@gmail.com>
Restore now takes this rank's shard from the map the layer published, which is the same piece list conversion uses run in the opposite direction. That completes the symmetry §7 of `affine_ir_spec.md` describes and that conversion has had since deepspeedai#8385: until now the two sides described the same layout in two different ways, and could disagree. Follows deepspeedai#8519 (layers emit the map) and deepspeedai#8575 (GPTBigCode and Yuan describe themselves). ### This one is not additive The map lives on the parameter, built by this job's layer. It is `M_t` — it describes the topology being restored into, regardless of how the source checkpoint was converted. So the new path is taken for **every** AutoTP restore, not only for checkpoints that were converted through a map. A parameter whose layer published no map falls back to the existing category keys unchanged. That is the correct reading of the spec rather than a shortcut: §6.1 keeps `M_t` out of the file precisely because the restoring job derives it from its own layers. But it does mean the blast radius here is wider than the three PRs before it, so the equivalence is worth checking rather than assuming. I ran `tests/unit/checkpoint/` and `tests/unit/runtime/tensor_parallel/` (385 tests) against this branch and against upstream master in a separate worktree. The failing set is **identical by name**, not merely the same count — 75 failed, 187 passed either way, all of them FusedAdam JIT, fp16-on-CPU, or the pre-existing `st_st_size` typo in `test_convert_checkpoint.py`. ### The tests are built to discriminate `test_restore_prefers_the_map_over_the_category_keys` gives one parameter deliberately contradictory geometry: the category keys describe a plain dim-0 split, so rank 0 would take the first half, while the map hands rank 0 the second half. Which half rank 0 receives says which side of the metadata restore actually consulted. This matters because the old path covers the same layouts correctly. Without a discriminating case the map branch could be deleted and every existing test would stay green. I checked: removing the branch fails that test, while `test_restore_falls_back_when_no_map_was_published` keeps passing. ### Validation 112 passed on CPU/gloo (`DS_ACCELERATOR=cpu LOCAL_SIZE=4`): the affine suite, the resume matrix, the coverage test, `tests/unit/runtime/tensor_parallel/`, and deepspeedai#8544's AutoEP affine suite, which this now sits on top of after the rebase. ### Scale powers Restore resolves a partition once per state file, so each state takes its own power of a piece's scale. The power table lives in affine.py as SCALE_POWER_BY_STATE — ds_to_universal.py had its own copy since deepspeedai#8519, so conversion and restore now read one definition rather than two that could drift. This also reaches the refusal built for scaled optimizer states, which only triggers on a non-parameter power. No layer emits a scaled map today, so it is ahead of the path rather than behind it. Related: deepspeedai#8252, deepspeedai#8230. cc @delock --------- Signed-off-by: Achyuthan Sivasankar <achyuthan.sivasankar@gmail.com>
…eepspeedai#8678) ## Summary - Keep `combine_impl="fused_weighted_sum"` opt-in and change only its forward scheduling: one Triton program handles a whole token, walking the hidden dimension in up to 1024-column chunks instead of launching a program per token and 256-column tile. The backward kernel and its row/score gradients are unchanged. - Preserve the existing routing, expert reorder, collectives, grouped GEMM and top-k semantics. The default combine path is unaffected. ## Numerical contract - Each row value and routing score are multiplied in FP32, the top-k products accumulate in FP32 in a fixed slot order, and the output is cast to the row dtype once. FP contraction is disabled so the product rounds before addition. Hidden-tail loads/stores are masked; non-power-of-two top-k requires no padded loads; token and source-row address arithmetic uses int64. - **Not bitwise unchanged versus eager:** eager's top-k reduction may sum FP32 products in a different order. The existing operator and model parity tolerances are unchanged; repeated fused calls are deterministic on fixed inputs. The backward implementation is unchanged. - Measured step-0 loss was 13.237928 → 13.237917 at 8k and 13.276934 → 13.276920 at 16k. These are **step-0 observations, not upper bounds on differences at later training steps**. No long-run convergence claim is made. ## Testing Done - Previously validated on NVIDIA H100: **241 passed**, including fused restore and AutoEP unit coverage. The operator tests compare forward, row gradients and routing-score gradients against the eager weighted sum. Existing separate model parity tests cover gradients through the router and experts; they were not rerun here. The wide-hidden test covers 2048 columns and a 1030-column tail with top-k 6, plus repeated-run determinism. - New focused FP32 cancellation case: **1 passed, 0 skipped** on one NVIDIA H100 80GB HBM3 (torch 2.10, CUDA 13.0, Triton 3.6). It checks that the product is rounded before it is added, including a non-power-of-two top-k and a 1030-column hidden tail. As a negative control, allowing FP contraction makes this same case fail. The negative-control change is not in this PR; existing tolerances were not relaxed. - Changed-files pre-commit checks passed. ## Performance and attribution Within the same NVIDIA H100 allocation, at top-k 8 and hidden 2048, the restore forward fell from about **0.60 → 0.105 ms** per call at 8k tokens, and **1.20 → 0.20 ms** at 16k. The complete AutoEP native-path old/new comparison (two repeats per arm, identical setup apart from this forward change) is the primary E2E evidence: | Sequence | AutoEP before | AutoEP after | Difference | | --- | ---: | ---: | ---: | | 8192 | 2547.53 ms | 2500.44 ms | −47.1 ms (−1.85%) | | 16384 | 5244.91 ms | 5145.86 ms | −99.1 ms (−1.89%) | Peak allocated and reserved memory did not increase. On this allocation, the remaining AutoEP/Megatron step-time gaps were about 0.43%/0.61% at 8k/16k; those numbers are context, **not** evidence that Transformer Engine's unpermute has identical semantics. Its unpermute does not apply the routing weights, so no direct kernel-to-kernel speedup is claimed. This PR's code is independent of deepspeedai#8671 and changes different files. The **reported E2E baseline already includes deepspeedai#8671's gather-based reorder**, so those timings should not be compared with runs that omit it. No new full E2E or convergence run was required for this focused forward review. 🤖 Generated with [GitHub Copilot CLI](https://docs.github.com/copilot/github-copilot-cli) --------- Signed-off-by: yh0903 <helloyu0903@gmail.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
## Motivation The master full suite on `modal-torch-latest` grew from ~52 to ~70 minutes within a month and keeps climbing ~7-8 min/week, repeatedly exhausting its Sandbox/job time budgets (the 3600 -> 4200 -> 5400s raises are chasing the growth). This PR adds a scheduled nightly full-suite run with automated, noise-free failure triage, so master landings no longer pay the full-suite cost on every push and nightly regressions are reported without flooding the tracker. ## Changes **1. Nightly full-suite run; no master push trigger** - A `schedule` (cron, daily `0 10 * * *`) run always executes the full suite on master; this is the only event whose failures feed automated regression triage. - The `push` trigger is dropped: master receives no direct pushes (the merge queue lands every entry, and each `merge_group` run already tested the merged tree). Cross-entry interaction regressions are what the nightly full suite exists to catch. - `concurrency` group now includes `github.event_name` so a nightly run and merge-queue runs don't cancel each other. **2. Controller classifies its own failures (`ci/torch_latest.py`)** - `infra` (exit 75): the Sandbox never got a GPU instance — no test ran, no candidate information. - `timeout` (exit 124): the Sandbox lifetime budget was exhausted mid-run (classified just inside the nominal budget, with a 120s grace for server-side kills). - `test` (exit 1): everything else, raised with a full traceback as before. - Each class prints a `DS_CI_FAILURE_CLASS=<class>` sentinel line that survives into job logs even when the job is killed before exiting. **3. Nightly triage (`nightly-triage.yml`, `ci/nightly_classify.sh`, `ci/nightly_report.sh`)** - Triggered by `workflow_run` on completed `modal-torch-latest` runs, filtered to scheduled master runs only; all script checkouts are pinned to the SHA the nightly actually ran (`github.event.workflow_run.head_sha`), so the classifier and the sentinel protocol it parses come from the same revision even if master moved on overnight. - **green** → move the `nightly-last-green` tag to the tested SHA (persistent good endpoint for future range work; operational failure days simply leave it in place). - **infra** → no-op (capacity problem, no candidate information). - **timeout** → open an issue (the suite outgrew its Sandbox budget; consider shard-splitting or raising it). - **unknown** → open an issue (no sentinel: the run died before the controller could classify itself — checkout, setup, or a job kill). Kept distinct from timeout instead of guessing. - **test failures** → open an issue listing the failing test files (parsed from the nightly log). - All reports go through `ci/nightly_report.sh`: labeled `nightly-triage`, and a recurring regression with the same stable title comments on the existing open issue instead of filing a duplicate (titles are deliberately SHA-free; the per-night SHA and run link go in the body). **4. Housekeeping**: refreshed stale self-tests that no longer matched master (sandbox timeout 4200 -> 5400 left behind by deepspeedai#8571, merge-group trusted-ref expression, the baked-image `FakeImage` chain, and the removed `reinstall Torch packages` runtime command). `ci/test_torch_latest.py` is 24/24 green; pre-commit passes on all changed files. ## Known limitations - The nightly run doubles as an upstream-drift sentinel (it installs transformers from git `main`); red nightlies caused by upstream drift are reported as ordinary test failures, and the issue text keeps the run link for human judgment. - Triage routes on the sentinel protocol of the nightly SHA; a controller change to that protocol requires this PR's self-tests (`ci/test_torch_latest.py`) to be updated in the same change. --------- Signed-off-by: Ma, Guokai <guokai.ma@intel.com>
…8655) Under fp16, Muon parameters barely train with ZeRO-1/2/3 unless the optimizer is offloaded. Newton-Schulz returns the same update at any loss scale, but the step then treats it like a scaled gradient: `unscale_and_clip_grads` divides it by the loss scale, and the global norm takes it as scaled too. So a Muon parameter moves by 1/loss_scale of its update, 1/65536 with the default dynamic loss scaler. On 2×H20, the norm of one Muon step on a small model, static loss scale 1 vs 1024, no clipping: | | scale 1 | scale 1024 | |---|---|---| | ZeRO-1/2/3, master | 4.47e-2 | 4.37e-5 | | ZeRO-1/2/3, this PR | 4.47e-2 | 4.47e-2 | | ZeRO-1/2/3 with CPU offload, master | 4.47e-2 | 4.47e-2 | And 60 steps of a small regression with the default fp16 config (dynamic loss scale, clipping 1.0), ZeRO-1 and ZeRO-3 alike: | | loss at step 0 → 59 | |---|---| | bf16 | 0.403 → 0.295 | | fp16, master | 0.403 → 0.385 | | fp16, this PR | 0.403 → 0.295 | It's the same with gradient accumulation (gas=2: bf16 and this PR 0.362 → 0.320, master 0.362 → 0.418), and with an initial scale of 2^30 that overflows for the first steps this PR trains normally afterwards with no NaN. The CPU-offload path from deepspeedai#8464 already handles this: it unscales before Newton-Schulz and scales the update back before the norm. Without offload the update sits in the fp16 gradient buffers, where scaling it back up could overflow, so this does it after the cast to fp32, for the norm and before `unscale_and_clip_grads`. In the 2^30 run the dynamic scaler settles at 2^22, so scaling the update up in fp16 would overflow it. The momentum keeps the scaled gradient as before, which in fp16 keeps small gradients out of the subnormal range. An invalid group norm stays at its -1 sentinel. bf16 and fp32 have a loss scale of 1 and don't reach the new code. `TestMuonLossScaling`, next to the offload test, checks ZeRO-1/2/3 with clipping on: on master the update under scale 1024 is 3e-3 of the one under 1, here they match. The Muon tests, the fp16 dynamic loss scale tests and the ZeRO cases of `test_fp16.py` pass on 2×H20 (294 passed, 8 skipped). Not covered: ZenFlow and SuperOffload, which have their own step. Also, with fp16 the momentum is in scaled units here but unscaled under offload, so a universal checkpoint moved between the two would carry it off by the loss scale; that was already the case before this. --------- Signed-off-by: alanhuangyoo <alanhuangyoo@gmail.com>
Add Fengchun Hua ([hipudding](https://github.com/hipudding), Huawei) to the TSC committers list. Signed-off-by: PKUWZP <zhipeng.rainbowserie@gmail.com>
## Summary - Add experimental `expert_parallel.row_weighting_impl="fused"` for the AutoEP DeepEP route at both `score_apply="pre"` and `"post"` boundaries. The default `"auto"` still resolves to the existing eager expression; unsupported configurations fail explicitly rather than falling back. - The Triton operator multiplies each received row by its FP32 routing weight, rounds at the same BF16/FP16 boundary, and leaves routing, expert GEMM, DeepEP combine, and the top-k reduction unchanged. - In a prior within-allocation H200 A/B screen, fused row weighting reduced median step time by 2.10% (four repeats, 95% CI 0.075%-3.45%). Peak allocated memory differed by 192 KiB and peak reserved memory was 510 MiB higher; the latter is an observation, not an explained or accepted memory improvement. ## Numerical semantics - The forward and row gradients use eager's FP32 products and rounding. The routing-weight gradient sums the same FP32 products in another order, so bitwise equality with eager is not expected. Against an FP64 reference at 4096 x 2048, fused/eager maximum absolute errors were 1.77e-5/1.49e-5 and maximum relative errors were 8.5e-5/2.9e-4; neither order is consistently more accurate. - The model regression snapshots retained routing-score, router-gate, full-parameter, and input gradients **after `engine.backward()` and before `engine.step()` clips gradients**, using `||fused - eager||_2 / ||eager||_2 <= 2e-2` for each checked tensor/group. Same-seed eager/eager controls were bit-exact; the largest previously measured native fused/eager model-gradient relative L2 was 5.6e-3 (reentrant checkpointing), leaving about 3.6x headroom. Near-zero gradient sign flips can cause learning-rate-scale differences in Adam's first parameter update, so coordinate-wise update equality is not used as the native-path gate. ## Testing Done - [x] Local code review completed. - [x] Unit and GPU-gated operator tests cover default selection, fail-fast inputs, score boundaries, forward/row-gradient parity, and the unmodified fused weight reduction against FP64 with an FP32 tree-sum error bound. The previously run GPU operator checks are reused; they are not a substitute for the model-level test. - [x] Native-backward distributed BF16 model tests: **2 passed, 0 skipped** (`pre` and `post`) on 4 ranks of an 8-GPU NVIDIA H100 80GB HBM3 node. Neither case replaces `d_weights`; both check exact routes and normalized errors through routing scores, router gate, all model parameters, and model input. The separate summation-order-matched attribution controls remain in place. - [x] Reviewer follow-up: only explicit eager/fused comparisons use `lr=1e-2`; the original default/cleanup/legacy cases retain `lr=1e-4`. A targeted run on 4 ranks of an 8-GPU NVIDIA H100 80GB HBM3 node passed **7/7, 0 skipped**: three config-scope cases, both cleanup/legacy cases, and eager/fused comparisons at both score boundaries. - [x] Changed-files pre-commit checks passed for all ten files touched by this PR. - A prior broad run accidentally used a stale validation bundle and did not exercise the two native-backward cases; it reported 72 passed and one legacy non-reentrant checkpoint/optimizer-delta mismatch. That legacy case passed in the targeted rerun after restoring its original learning rate. Full-suite pass is **not** claimed from the broad run. ## Dependencies and scope - The cached-layout repair (deepspeedai#8636) and independent MoE gradient-norm fix (deepspeedai#8635) have merged into upstream `master`. The GPU tests used an earlier pinned source with both corrections applied separately; neither is included in this PR. The norm fix applies to `FP16_Optimizer`, which is also used by some BF16 configurations. The new model-level gradient gate reads gradients **before** this wrapper's norm/clipping in `engine.step()`. - The integrated DeepEP route currently accepts BF16 rows. The operator also supports FP16 rows, but is CUDA/Triton-only, requires contiguous `[N, H]` rows and FP32 `[N, 1]` weights, and does not support ROCm or non-DeepEP/EP=1 routes. DeepEP v2 requires a compatible NCCL build with GIN support. --------- Signed-off-by: yh0903 <helloyu0903@gmail.com> Co-authored-by: pengdurice <pengduhit@gmail.com>
# AutoEP: MiniMax-M3 preset
## What
A built-in preset `minimax_m3` for MiniMax-M3 (`model_type =
"minimax_m3_vl_text"`, transformers >= 5.15.0).
MiniMax-M3 is 425.9 B parameters, 25.7 B active: 60 layers, the first 3
dense, the other 57 with 128
experts, top-4, and one shared expert. With the preset,
`expert_parallel: {"enabled": true, "autoep_size": N}`
is the whole configuration; nothing has to be spelled out.
| preset field | value | where it comes from |
|---|---|---|
| MoE block, router, experts, shared expert | `model.layers.N.mlp`,
`gate`, `experts`, `shared_experts` | `MiniMaxM3VLSparseMoeBlock` |
| expert weights | fused 3-D `gate_up_proj` / `down_proj` |
`MiniMaxM3VLExperts` |
| expert and top-k counts | `num_local_experts` / `num_experts_per_tok`
on the model config | `MiniMaxM3VLTextConfig` (128 / 4) |
| scoring | sigmoid, applied after the experts, selected top-k weights
normalised | `MiniMaxM3VLTopKRouter` |
| selection bias | `gate.e_score_correction_bias` (a buffer, as in
DeepSeek-V3) | found by the existing bias-path resolution |
| routed output scale | `routed_scaling_factor` = 2.0 | read from the
model config by the existing code |
| expert activation | `swiglu_oai`, alpha 1.702, limit 7.0 | preset; the
model's `swiglu_alpha` / `swiglu_limit` override it at detection |
| router logits | recorded at the model level as
`OutputRecorder(MiniMaxM3VLTopKRouter, index=0)`, the raw logits | same
pattern as Mixtral, so the adapter is a
`TransformersTopLevelRouterLogitsAdapter` |
| version gate | transformers >= 5.15.0, checked when the model type is
MiniMax's | adapter opts in |
| composite `minimax_m3_vl` (vision + text) | refused with a note to
pass the text backbone | `unsupported_hf_model_type_notes` |
| `load_balance_coeff` | defaults to `None`; a non-null value is
rejected, as for DeepSeek-V3 | `autoep_config_defaults`,
`supports_expert_bias=False` |
## Trained at scale: the full MiniMax-M3 on 65,536-token books, 4 nodes
of 8 H200
This preset is the configuration under which the real MiniMax-M3
checkpoint fine-tuned on real
65,536-token sequences. The run used the preset before it was committed;
the preset fields, the
`swiglu_oai` form with alpha 1.702 / limit 7.0, and the config keys are
the ones in this PR.
Setup: 4 nodes of 8 H200 (32 ranks), all 60 layers, the real checkpoint
(795.5 GiB in 59 safetensors
shards, streamed in one tensor at a time in 791 s), 426.2B parameters of
which 413.1B are expert weights.
`expert_parallel: {"enabled": true, "autoep_size": 4}`: 8 expert groups
of 4 ranks, each rank holding 32
experts that ZeRO-3 shards 8 ways across the expert-data-parallel group.
`fused_weighted_sum` combine,
ZeRO-3 with the optimizer state offloaded to host memory, activation
checkpointing with the checkpoint
inputs on host, tiled loss (64 shards over the 200,064-token
vocabulary), micro-batch 1 per rank = one
whole PG-19 book of 65,536 tokens per rank, learning rate 1e-6, 1
warm-up + 2 measured steps. torch
2.8.0+cu126, transformers 5.15.1. Attention ran through a harness-side
gather over each query's selected
keys, because the stock transformers path materialises a `[1, 64, S, S]`
block mask and stops at 14,336
tokens on a 141 GB card; that module is outside this PR.
| step | loss (rank 0's book) | grad norm | step time | rank 0 peak
allocated |
|---|---|---|---|---|
| 1 (warm-up) | 0.0153 (the King James Bible) | 0.98 | 361.0 s | 89.1
GiB |
| 2 | 0.8592 | 1.18 | 296.1 s | 90.6 GiB |
| 3 | 1.0754 | 1.23 | 292.3 s | 90.6 GiB |
Measured average 294.22 s per step = 7,128 tokens/s over the 32 ranks.
Memory: rank 0 peak 90.57 GiB
allocated / 109.78 GiB reserved; the highest rank 102.07 GiB allocated /
126.24 GiB reserved of 139.80.
Host memory 1.87 TB per node, most of it the offloaded optimizer state.
The losses are a trained model's losses on real text (0.015 on a text
every corpus contains, 0.86 and
1.08 on two other pre-1919 books), against 13.44 with random weights on
the same setup. That is the
end-to-end check of everything the preset describes: the conversion of
the checkpoint's per-expert
`w1`/`w3`/`w2` into AutoEP's fused expert layout, the sigmoid router
with the fp32 selection bias,
`routed_scaling_factor` 2.0, the shared expert, and the clamped
activation. With standard SwiGLU in
place of `swiglu_oai` the replaced block differs from the model's own by
0.41 mean absolute (correlation
0.74), so the activation form is what makes this loss a real loss.
Why expert parallel 4 and not 32: real router weights route far more
unevenly than random ones. Over all
57 MoE layers of this run, the busiest of the 4 ranks in an expert group
received 1.09 to 2.22 times the
mean number of rows (median 1.36; the worst is layer 54, 581,906 rows on
one rank against 262,144 own
rows). The same counts grouped as expert parallel 32 give a median of
4.20 and a maximum of 7.84 times
the mean, and at that skew the busiest rank runs out of memory at this
length:, same setup with
expert parallel 32, failed in the step-1 forward on one rank with a
single 11.96 GiB temporary for
1,045,081 routed rows inside the expert activation, 129.50 GiB already
in use. AutoEP has no capacity
limit, so the busiest rank sets the memory ceiling; a smaller expert
group spreads each expert set over
more ranks, at the cost of a per-layer all-gather of the local experts
(32 experts x 113 MB at expert
parallel 4).
## Why a preset
Without it, MiniMax-M3 runs through the custom `moe_layer_pattern` path
with six keys (`score_func`,
`score_apply`, `route_norm`, `has_shared_experts`,
`shared_experts_pattern`, `expert_activation`), and a
user who omits `expert_activation` is stopped by the registry PR's check
rather than silently trained on
`silu(gate) * up`. The preset makes the model type enough, records the
facts above in one place, and
switches on the version gate for it. The run above is this
configuration.
## Files
| file | change |
|---|---|
| `deepspeed/module_inject/auto_ep_presets/minimax_m3.py` | new: the
preset and `MiniMaxM3PresetAdapter` |
| `deepspeed/module_inject/auto_ep_presets/registry.py` | registers the
module |
| `docs/_pages/config-json.md`, `docs/code-docs/source/autoep.rst` |
`minimax_m3` in the preset list and the version table |
| `tests/unit/v1/moe/autoep_test_utils.py` | `tiny_minimax_m3_config` |
| `tests/unit/v1/moe/test_autoep_unit.py` | registry contract extended;
`test_hf_minimax_m3_causal_lm_matches_autoep_with_router_logits`;
`test_minimax_m3_adapter_guards` |
| `tests/unit/v1/moe/test_autoep_expert_activation.py` | the
block-parity test now runs through the preset as well as the custom
pattern; "every preset is swiglu" becomes "every preset names its form"
|
## Tests
| test | what it checks, and the wrong behaviour it would catch |
|---|---|
| `test_preset_registry_core_contracts` | `minimax_m3` registered;
`minimax_m3_vl_text` resolves to it; the composite `minimax_m3_vl`
carries a note naming the text backbone |
| `test_minimax_m3_adapter_guards` | a mock model of type
`minimax_m3_vl_text` is detected as `minimax_m3` with `swiglu_oai`; an
installed transformers below 5.15.0 is refused with the version named
(the gate is switched on for this preset; an unregistered adapter would
silently skip it); the composite type is refused with the note |
| `test_hf_minimax_m3_causal_lm_matches_autoep_with_router_logits` | a
tiny `MiniMaxM3VLForCausalLM` (1 layer, 4 experts, top-2),
state-matched, native against AutoEP: loss, the recorded router logits,
and the auxiliary load-balancing loss agree at rtol 1e-5 (the recorder
retarget and the raw-logit capture mode are what make the last two
agree) |
| `TestMiniMaxM3Block.test_replaced_block_matches_hf_block[preset-*]` |
a real `MiniMaxM3VLSparseMoeBlock` found from the model type alone, no
config keys: family `minimax_m3`, activation `swiglu_oai` with 1.702 /
7.0 from the model, and the replaced block matches a deep copy of the
original, forward and input gradient, at weight std 0.02 and 0.5 |
| `TestMiniMaxM3Block.*[custom_pattern-*]`,
`test_custom_pattern_without_the_key_is_refused` | the custom-pattern
route from the registry PR, kept for a model type AutoEP does not know
yet |
Results, all on this branch:
| where | environment | `test_autoep_expert_activation.py` |
`test_autoep_unit.py` | `test_autoep_grad_parity.py` |
|---|---|---|---|---|
| CPU, one process | torch 2.9.1, transformers 5.15.0 | 29 passed, 8
skipped (accelerator cases) | 186 passed, 6 skipped | not run (needs 4
devices) |
| H200 node, 4 GPUs | torch 2.9.1+cu128, transformers 5.15.0, Triton
3.5.1 | **37 passed** | **192 passed** | **23 passed, 8 skipped** (the
regional-compile parity cases need `DEEPSPEED_RUN_H100_TESTS=1`), 2 min
44 s |
`pre-commit run --files` on the changed files: yapf, flake8, codespell,
check-torchdist, check-torchcuda
pass; `check-license` reports the new preset file only because the hook
uses `git grep`, which skips
untracked files.
Signed-off-by: pengdurice <pengduhit@gmail.com>
…speedai#8671) ## Summary AutoEP's native collective path (`comm_backend="comm"`, NCCL all-to-all) puts each rank's received rows into expert-major order before the grouped GEMM, and back afterwards, with `permute_by_local_expert` and `unpermute_by_local_expert`. The `autoep_size=1` path uses the same two functions. Both moved every routed row more often than needed: - **`permute_by_local_expert`:** - appended a zero row to the received rows with `torch.vstack`, a full copy, before indexing the padded expert-major buffer; - its backward was an accumulating `index_put`, i.e. a sort plus atomic adds. - **`unpermute_by_local_expert`:** zero-filled an `[N + 1, H]` buffer, then scattered into it with an elementwise `index_put`. On CUDA with Triton, both directions are now gathers: | Direction | Forward | Backward | |---|---|---| | permute | a Triton row gather that writes zero rows where `generate_permute_indices` marked padding (`-1`) | `index_select` through the inverse permutation | | unpermute | `index_select` through the inverse permutation | the same padded row gather | **Scope.** - This is a local, on-rank change to the expert reorder. - The all-to-alls send and receive the same rows in the same order, so communication volume is unchanged, and no communication/computation overlap is added. - `generate_permute_indices` is unchanged, and the DeepEP backend does not call these functions. - There is no switch: the gathers replace the previous code for 2-D CUDA tensors when Triton is available, because their results are equal to it (see Numerics). Other tensors keep the previous code. ## Permutation contract `generate_permute_indices` sends each received row to exactly one slot of the padded expert-major buffer and marks every other slot `-1`. The gathers rely on that one-to-one mapping: - **Permute forward:** writes each output row once: the row mapped to its slot, or zeros at a padding slot. - **Inverse permutation:** a scatter of slot positions into scratch of `N + N_padded` entries. Each padding slot goes to its own entry past `N`, so no entry is written twice, and every row's entry is written. - **Unpermute forward:** reads each row's slot through the inverse; padding rows are never read. - **Backward:** each direction's backward is the other gather. A row's gradient is that of the one slot it occupied, not a sum, and padding slots get zero gradient. Both backwards are autograd functions themselves, so double backward goes through the same pair. - **Top-k:** each received row is one (token, expert) assignment. Summing a token's top-k expert outputs, in the combine, and accumulating its top-k gradients, in the backward of the routed gather `x[token_indices // top_k]`, stay in the surrounding code, unchanged. These helpers are therefore not a general gather/scatter. `permute_rows`, `unpermute_rows` and `inverse_permutation` require the valid entries to be a complete one-to-one permutation of the rows, and do not check it; the docstrings say so. Both callers meet the requirement, because the counts sum to the number of rows: - with expert parallelism, each all-to-all receives exactly the row sums of the exchanged counts; - with `autoep_size=1`, the `T × top_k` routed rows are sorted by expert, and the counts are per expert. The previous code tolerated counts that sum to fewer rows (the rows left out came back as zeros); the gathers do not. The row gather reads its index by linear offset, so it now makes the index contiguous first, as it already did the source rows. ## Numerics The gathers only move data. Outputs, gradients and double-backward gradients equal the previous implementation's under `torch.equal`, which does not distinguish `+0.0` from `-0.0`. We also compared bit patterns on H100, in bf16, fp16 and fp32, with inputs and upstream gradients of which a quarter were `-0.0`: - Both outputs and the unpermute gradient are bitwise identical to the previous implementation's. - The permute gradient differs only where the upstream gradient is `-0.0`. The previous backward accumulated it into a zero-filled buffer, giving `+0.0`, whereas the gather passes `-0.0` through. ## Validation **Unit tests** (below): the earlier H100 validation passed these 27 tests and the existing `tests/unit/v1/moe/test_autoep_unit.py` (217 tests). The review follow-up additionally validates all 27 reorder cases with plain, forked and xdist-forked execution. **Local token movement**, one rank's work for one MoE layer, on one H100: - Shape: T tokens, top-8 of 128 experts, EP16 (8 local experts), hidden 2048. - The all-to-alls are replaced by the identity and the experts by a scalar multiply, so only the local work is timed. - Each iteration runs a no-grad forward, a grad forward and a backward, as under reentrant activation checkpointing. - The whole local chain is timed; only the reorder differs between the two columns. | T | Before | After | Saving × 48 layers | |---|---|---|---| | 8192 | 7.04 ms | 5.12 ms | −92 ms | | 16384 | 13.53 ms | 9.58 ms | −190 ms | At T=8192, per grad forward, the permute goes from 0.44 to 0.27 ms and the unpermute from 0.71 to 0.21 ms. **End to end**, Qwen3-30B-A3B training with AutoEP: - 16× H100, expert parallel 16, 48 layers, micro-batch 1, BF16, ZeRO stage 1, reentrant activation checkpointing, and a fixed routing, so both arms route identically. - `comm_backend="comm"` with `combine_impl="fused_weighted_sum"` and `async_split_plan=true`. - Both arms also carry other opt-in kernels under review: fused RMSNorm (deepspeedai#8645, deepspeedai#8664), fused RoPE (deepspeedai#8663), chunked loss (deepspeedai#8653) and BF16 gradient release (deepspeedai#8654). The arms differ only in this PR. - Both arms ran on the same 16 GPUs in mirrored order, two runs each. | Sequence | Before | After | Change | |---|---|---|---| | 8192 | 2649.4 ms | 2554.3 ms | −95.2 ms (−3.6%) | | 16384 | 5434.6 ms | 5244.5 ms | −190.2 ms (−3.5%) | - Each arm's two runs agree within 5 ms. - The end-to-end saving matches the local estimate scaled to 48 layers (−92 and −190 ms). - Peak memory and the step-0 loss are identical in both arms. These numbers come from one model, two sequence lengths, one GPU type and one parallel layout. The saving scales with the rows each rank reorders, so its share of the step depends on the configuration. Small shapes are not guaranteed to improve in every direction: a review microbenchmark on RTX PRO 4500 found slower forwards at 8,192 rows × hidden 1,025, while both backwards improved. This PR does not add a shape-dependent dispatch heuristic. The local and end-to-end numbers were measured with this PR's first commit. The later commits add `index.contiguous()`, a no-op for the contiguous indices both callers pass, and change docstrings and tests. The forked-runner review follow-up changes only test execution, not the runtime implementation. ## Tests `tests/unit/v1/moe/test_autoep_permute_rows.py`, 27 tests: 26 need CUDA and Triton, and 1 runs on the host. All compare against the previous zero-row-and-index implementation with `torch.equal`: - forward and backward of both reorders: - bf16 and fp32; - hidden 2048, 100 and 1; - source-major `[ep, E_local]` counts with and without empty experts, and aggregated `[E_local]` counts; - fp16 and bf16 rows read through a column-strided view, with column-major upstream gradients, in both directions, including the output strides; - double backward of both reorders; - a round trip with zero padding; - zero tokens; - the row gather with both padding encodings, through a contiguous and a strided index; - host tensors keeping the previous code. Results: - 1× NVIDIA H100 80GB HBM3, Python 3.12, torch 2.10 (CUDA 13.0), Triton 3.6.0: 27 passed, and 217 together with `tests/unit/v1/moe/test_autoep_unit.py`. - The same 27 tests against this PR's first commit, the code the timings used: 26 passed. The strided-index case failed, because that commit read the index as if contiguous. - CPU, torch 2.14: 1 passed, 26 skipped. - Forked-runner review regression on H100, torch 2.10 (CUDA 13.0), Triton 3.6.0: plain pytest, `pytest --forked` and `pytest -n 4 --forked` each pass all 27 cases, with no skips and no bad-fork errors. In the same environment, the previous tests fail under `--forked` (26 failed, 1 host case passed), reproducing the reported issue. - CPU review regression, torch 2.14: `--forked` and `-n 4 --forked` each give 1 passed, 26 skipped. - `pre-commit run --files` on the changed files: passed. ## CI - `cpu-torch-latest` runs the host test and skips the rest. - The test file is under `tests/unit/v1`, in the scope of both AWS and Modal GPU CI; Modal executes the selected GPU tests when the PR enters the merge queue. - `aws-torch-latest` uses `pytest -n 4 --forked`. The GPU cases now use `DistributedTest` with `world_size=1`, launching clean workers even when CUDA was touched while importing DeepSpeed during collection. These local operator tests do not need a process group (`init_distributed=False`). CUDA availability is checked by the runner during test execution, not by this file's collection-time skip condition. The host case remains an ordinary test, and all 27 cases and their numerical assertions are unchanged. ## Not covered - ROCm: PyTorch reports ROCm devices as `cuda`, so the gathers would be used there, as the existing Triton index generation is. Neither was tested on ROCm here. - Inputs that break the permutation contract. It is not checked; both callers meet it by construction. - `torch.compile` of the MoE layer itself. AutoEP's regional compilation keeps that layer eager, and the path already launched Triton kernels there. - Models, sequence lengths, hardware and parallel layouts other than the ones above. --------- Signed-off-by: yh0903 <helloyu0903@gmail.com> Co-authored-by: pengdurice <pengduhit@gmail.com>
…es (deepspeedai#8702) ## Description Two latent bugs in Ulysses SP, both backend-independent (neither is CPU-specific — the CPU/gloo multi-rank run in deepspeedai#8381 is simply what surfaced them), plus test adaptations so the file can also run on non-CUDA accelerators. ### 1. `register_with_transformers` rejected every string model path `deepspeed/runtime/sequence_parallel/ulysses_sp.py` compared `core_attn_implementation` against the config's `_attn_implementation` even when the caller passed a **model path string**: ```python hf_model_config = AutoConfig.from_pretrained(model_name_or_path) # string branch model_attn_implementation = getattr(hf_model_config, "_attn_implementation", None) if model_attn_implementation is not None and model_attn_implementation != core_attn_implementation: raise ValueError(...) ``` In transformers, `_attn_implementation` is a **property resolved at model load time** — `from_pretrained` resolves which implementation the runtime can actually use and writes it back to the config. A bare `AutoConfig` never goes through that resolution, so the property returns its fallback value for "unresolved": ``` AutoConfig.from_pretrained(path)._attn_implementation -> eager (fallback, not a choice) AutoModelForCausalLM.from_pretrained(path).config._attn... -> sdpa (resolved) ``` So every string-path caller asking for `sdpa`/`flex_attention`/FA2 was rejected with a spurious mismatch against `'eager'`. The check is only meaningful for a config that was resolved, i.e. when the caller handed us a constructed model (or a PEFT wrapper exposing `.config`); scope it to that case. The comparison expression itself is unchanged, and `TestUlyssesSPHFAttnImplMismatch` (which passes a model object) still raises as intended. ### 2. `UlyssesSPDataLoaderAdapter` used a 0-dim tensor in `all_gather` ```python seqlen = torch.tensor(n, ...) # 0-dim seqlens = [torch.zeros(1, ...) for _ in range(sp_world_size)] # shape (1,) dist.all_gather(seqlens, seqlen, group=self.sp_group) ``` `c10d.all_gather` requires each receive tensor to have the same size as the send tensor. NCCL moves flattened bytes and tolerates the mismatch; gloo validates shapes and rejects it (`ProcessGroupGloo::allgather: invalid tensor size at index 0 (expected (), got (1))`). Send a 1-element tensor to match. ### 3. Tests - `TestUlyssesSPHFFlexAttention` needs the CUDA flex kernel -> skip on non-CUDA accelerators (same guard idiom as `tests/unit/util.py`, the nvme/triton CUDA-only tests). - `TestUlyssesSPHFPEFT`: the mock attached a **bare** `AutoConfig`, whose `_attn_implementation` is the unresolved `'eager'` — so this test failed on every backend, not just CPU. Give the mock the load-resolved value a real PEFT wrapper carries (the sibling `TestUlyssesSPHFAttnImplMismatch` in the same file already sets it the same way). - `TestUlyssesSPHFDisableInEval` pinned its tensors/models to `cuda:<rank>` although it runs sdpa and nothing in it is CUDA-specific. Use `get_accelerator().current_device_name()` like the rest of the file (on CUDA that is exactly `cuda:<rank>`, since the test harness sets the device per rank in `tests/unit/common.py`), so the test runs on any backend instead of erroring. ## Validation Hardware: 20-core x86_64 CPU without AVX512-FP16, gloo backend, 2 ranks (`LOCAL_SIZE=2`), transformers 4.51.3, torch 2.13. - `tests/unit/ulysses_alst/test_ulysses_sp_hf.py`: **5 passed, 2 skipped** (flex skipped by the new guard). The sdpa classes pass end to end including their numerical-parity assertions; before the fix they died at registration. - `TestUlyssesSPHFDisableInEval` now actually **executes** on CPU rather than being skipped. - `TestUlyssesSPHFAttnImplMismatch` still raises the expected `ValueError` (the mismatch check is preserved where a resolved config exists). - Full multi-rank CPU CI in deepspeedai#8381: this file went from 5 failures to 0, with the overall job green. (`TestUlyssesSPHFHubKernel` is not exercised by the version pin above — it needs the `lazy_import_flash_attention` API from a newer transformers; it passes in CI, which installs transformers from git main.) Sibling PRs from the same series: deepspeedai#8397, deepspeedai#8398, deepspeedai#8399, deepspeedai#8407, deepspeedai#8409, deepspeedai#8559, deepspeedai#8648, deepspeedai#8684. --------- Signed-off-by: Guokai Ma <guokai.ma@intel.com> Co-authored-by: pengdurice <pengduhit@gmail.com>
…deepspeedai#8632) ## Summary Harden gradient storage lifetime and stream ordering for ZeRO-1/2 with optimizer offload (`cpu` or `nvme`). These protections are always on for offload and have no configuration options. They address ownership and synchronization risks found while debugging NaNs under CPU offload. ## Changes - **Oversized-gradient ownership:** gradients larger than `reduce_bucket_size` are cloned into independent storage before reduction. Reduction and the D2H offload copy then read the clone. - **Producer readiness:** every bucket producer records an event, including oversized gradients. Reduction waits on all of them, with or without `overlap_comm`. - **Bucket reuse:** a contiguous IPG buffer records a reuse event when its consumer finishes, and later producers wait on it before writing into that buffer again. - **Stream lifetimes:** gradient tensors are `record_stream`'d on the streams that consume them. - **Offload copy ordering:** successive CPU-gradient writes are ordered across streams. Pending offload copies are waited on before CPU accumulator reloads, `step()`, `reset_cpu_buffers`, checkpoint loading (legacy and universal), and `destroy()`. - The existing `overlap_comm` barrier (compute stream waits on the reduction stream) is kept. The new events only add ordering on top of it. ## Scope - **Covered:** ZeRO-1 and ZeRO-2 with `offload_optimizer` set to `cpu` or `nvme`. Both stages use the same `reduce_independent_p_g_buckets_and_remove_grads` → `copy_grads_in_partition` D2H path, and offload already forces `contiguous_gradients`. Pipeline parallelism and DeepCompile are not excluded. - **Not covered:** ZenFlow, which overrides reduction and offload copies with its own ordering. A warning is logged when ZenFlow is combined with offload. - **Unchanged:** non-offloaded paths and ZeRO-3. Reduction thresholds, communication dtypes, and accumulation semantics are also unchanged. ## Cost Oversized gradients add one gradient-sized allocation and copy. Event tracking adds synchronization overhead and can extend storage lifetimes. ## Tests `tests/unit/v1/zero/test_zero2_gradient_safety.py`: - Unit tests for oversized-copy independence, producer and reuse waits, cross-stream CPU write ordering, the pageable-accumulator wait (default path, no accumulation flag), and waits before step, reset, and checkpoint load. - A constructor matrix covering stage, contiguous, and offload device (cpu, nvme, none). - Two-rank training against an independent full-batch reference: ZeRO-1/2, with and without offload, `overlap_comm`, and `contiguous_gradients=false`. - A CUDA stream-handoff test for oversized producers. Ran locally (macOS, CPU accelerator, 2 ranks): 35 passed, 2 skipped (the CUDA-only tests). A multi-GPU NCCL run of offload + overlap is still pending. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Jeff Rasley <jeff.rasley@snowflake.com> Signed-off-by: Jeff Rasley <jeffra45@gmail.com> Signed-off-by: tunji-ruwase_snow <tunji.ruwase@snowflake.com> Co-authored-by: Jeff Rasley <jeff.rasley@snowflake.com> Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Co-authored-by: tunji-ruwase_snow <tunji.ruwase@snowflake.com> Co-authored-by: Cursor <cursoragent@cursor.com>
…eepspeedai#8730) ## Summary - `cpu-torch-latest` installs Transformers from git `main`. `StaticCache` now reads `config.per_layer_config` before choosing layer types. - The three continuous-generation tests used a `SimpleNamespace` cache config, so that read raised `AttributeError`. Real `PreTrainedConfig` objects already have this property. - The fakes now return a one-element `per_layer_config`, which Transformers treats as full attention. ## Test plan - [ ] `cpu-torch-latest` unit tests, especially the three continuous-generation cases - [ ] Local run could not reproduce the CI Transformers SHA; this machine's Transformers fails later on `Cache.update(cache_position=...)` Made with [Cursor](https://cursor.com) Signed-off-by: tunji-ruwase_snow <tunji.ruwase@snowflake.com> Co-authored-by: Cursor <cursoragent@cursor.com>
…eepspeedai#8663) ## Summary Adds an opt-in fused Triton kernel for Hugging Face's split-half rotary position embedding, `apply_rotary_pos_emb`, as used by Llama-, Mistral-, Qwen- and DeepSeek-V3-style models: ```python from deepspeed.ops.triton_ops.fused_rotary_pos_emb import replace_rotary_pos_emb patched = replace_rotary_pos_emb(model) # number of modeling modules patched; 1 for Qwen3-30B-A3B ``` The eager function, `q * cos + rotate_half(q) * sin`, runs several elementwise kernels, each reading and writing the whole query or key tensor, and its backward does the same again. The fused kernel reads and writes each tensor once per pass and applies each position's `cos`/`sin` to all of that position's heads. Nothing changes unless `replace_rotary_pos_emb` is called. ## Semantics and safety - **Process-wide patch.** Attention layers look `apply_rotary_pos_emb` up in their modeling module, so the installer replaces it there. The replacement applies to every model of that architecture in the process, not only to `model`. Calling it again is a no-op, and `restore_rotary_pos_emb()` undoes it. - **Which modules.** A modeling module is patched only if all of these hold: - one of the model's submodules is defined in it; - it is listed in `SUPPORTED_ROTARY_MODULES` (Llama, Mistral, Mixtral, Qwen2, Qwen2-MoE, Qwen3, Qwen3-MoE, DeepSeek-V3); - its `apply_rotary_pos_emb` and `rotate_half` still have the split-half expression's code: the same bytecode, names, constants and defaults, whatever their docstrings. Constants are compared because bytecode refers to them by index: a `rotate_half` that splits at a quarter, or along another axis, otherwise has the same bytecode. Several architectures define functions of the same name that rotate part of the head dimension or add casts (for example Phi-3 and OLMo-2). A module whose functions differ is left alone with a warning. This includes transformers releases whose `apply_rotary_pos_emb` still takes `position_ids`, such as 4.51. - **Fallback.** For any input the kernel does not cover, the patched function runs the original eager function and warns once. Uncovered inputs are: - dtypes other than bf16/fp16, or mixed dtypes; - tensors not on one CUDA device; - an odd head dimension, one over 512, or one without unit stride; - shapes whose batch, sequence or head dimension do not match `cos`/`sin`; - `unsqueeze_dim` other than 1 or 2; - `cos`/`sin` that require grad. Without Triton, or on ROCm, it always runs eager. - **Direct call.** `fused_apply_rotary_pos_emb` applies the kernel directly and raises on unsupported inputs instead. - **Launch device.** Forward and backward select the inputs' CUDA device for the Triton launch, use that device's current stream, and restore the caller's current device. Inputs need not be on the device that was current when the function was called. - **Autograd.** Gradients are first order, for `q` and `k`; `cos` and `sin` are constants. Double backward raises. ## Numerics and layout Every product and sum is rounded to the input dtype where the eager expression rounds it. The kernel is compiled with `enable_fp_fusion=False`, because an FMA contraction would skip a product's rounding. Outputs and the gradients for `q` and `k` equal eager's element for element under `torch.equal`, which does not distinguish `+0.0` from `-0.0`. Layout: - For dense inputs, such as attention's transposed projection, outputs keep the input strides, as eager's do. - Other non-contiguous inputs can give outputs laid out differently from eager's, with equal values. - The gradients for `q` and `k` take the outputs' layout, whereas eager's follow the incoming gradient. Weight gradients computed from them further back can therefore differ in the last bits (see the attention block below). ## Validation Three levels, reported separately. **1. Operator.** Earlier validation passed the original 32 cases on one H100. The review follow-up adds two cross-device cases (BF16/FP16); current regression results are listed below. **2. Full attention block, one H100.** Qwen3-30B-A3B attention layer (32 query heads, 4 KV heads, head dim 128). The unit is forward, recompute and backward under reentrant activation checkpointing; each arm ran twice in mirrored order. | Sequence | Eager RoPE | Fused RoPE | Saved per layer | RoPE segment | |---|---|---|---|---| | 8192 | 9.27 ms | 7.80 ms | 1.46 ms | 1.57 → 0.19 ms | | 16384 | 26.62 ms | 23.66 ms | 2.96 ms | 3.13 → 0.39 ms | - The block output and the block's input gradient equal eager's. - The `q_proj` and input-norm weight gradients differ from eager's by a relative 4e-5. A `torch.compile`d RoPE moves them too (8e-6 and 1e-5). This comes from the layout of the gradient the weight GEMMs receive, not from RoPE's arithmetic. - The fused kernel is about 0.2–0.4 ms per layer faster than a `torch.compile`d RoPE configured to reproduce eager rounding. **3. End to end, together with the narrow-row RMSNorm change.** AutoEP training of Qwen3-30B-A3B: - 16× H100, expert parallel 16, 48 layers, one sequence per GPU, BF16, activation checkpointing. - Both arms use other opt-in AutoEP changes, including the fused row weighting (deepspeedai#8644), fused RMSNorm (deepspeedai#8645) and chunked loss (deepspeedai#8653). - "After" adds this PR and a narrow-row path for the fused RMSNorm (a follow-up to deepspeedai#8645), and nothing else. - Both arms ran on the same 16 GPUs, two runs each. | Sequence | Before | After | Change | |---|---|---|---| | 8192 | 1713.8 ms | 1654.2 ms | −3.5% | | 16384 | 3631.7 ms | 3510.5 ms | −3.3% | - At 8192 the result separates: both "after" runs are below both "before" runs. At 16384 the run ranges overlap, so that result is indicative. - These numbers cover both changes and cannot be split between them. In the attention-block measurement scaled to 48 layers, RoPE accounts for 70 of the 84 ms the two save at 8192, and 142 of 179 ms at 16384. End to end, about 70% of that combined estimate shows up. - Peak allocated memory is unchanged. - The step-0 loss differs by 8e-4. That comes from the narrow-row RMSNorm's reduction order, since RoPE's forward equals eager's. Final-step losses differ by at most 0.0023, within the 0.0016–0.0068 spread between runs of the same arm. This is a short-run check, not a convergence result. The attention-block and end-to-end numbers were measured with this PR's kernel and autograd function. Earlier follow-ups hardened the installer check, tests and documentation. The multi-GPU review follow-up adds an input-device guard to the shared forward/backward launcher; kernel arithmetic and launch configuration are unchanged. The existing performance measurements were not rerun for this correctness fix. ## Tests `tests/unit/v1/ops/triton_ops/test_fused_rotary_pos_emb.py`, 34 tests. They need CUDA and Triton and are skipped otherwise; the two cross-device cases additionally require two visible CUDA devices. Comparisons with eager use `torch.equal`. Coverage: - forward and backward in bf16/fp16 across shapes, for attention's transposed projection and for contiguous inputs, including output and gradient strides; - `unsqueeze_dim=2`, a table broadcast over the batch, non-contiguous incoming gradients, an unused output leaving no gradient, an empty sequence, and double backward raising; - every rejected input on the direct call, and the eager fallback of the installed function; - an installed two-layer Qwen3 (eager attention, small shapes) whose logits and every parameter gradient equal eager's; - installer idempotence and restore, and an unlisted model; - refusal of a changed expression, and of two `rotate_half` variants that differ from the split-half one only in constants; - acceptance of functions that differ only in their docstrings. - BF16/FP16 inputs and a non-default stream on one device while another device is current: compare outputs and both input gradients against eager, and check caller device and stream restoration. The rejected-input cases are parametrized by name and built inside the test, so collection creates no tensors on any device. Results: - 1× NVIDIA H100 80GB HBM3, Python 3.12, torch 2.10 (CUDA 13.0), Triton 3.6.0, transformers 5.12.0: 32 passed. - The same tests against the previous installer check, which compared bytecode, names and defaults but not constants: 30 passed. The two constant-variant tests failed because that check patched the module. - CPU review regression: 34 skipped under `pytest -n 4 --forked`. - Multi-GPU review regression on two NVIDIA H100 80GB HBM3 GPUs, torch 2.10 (CUDA 13.0), Triton 3.6.0, transformers 5.12.0: the full suite passes all 34 cases under `pytest --forked`, with no skips. The two BF16/FP16 cross-device cases also pass plain pytest and `pytest -n 4 --forked`. - With the same new tests and the previous runtime, both cross-device cases fail with the reported `Pointer argument ... cannot be accessed from Triton` error. This confirms the device guard fixes the reported issue. - Code check without a GPU, on transformers 5.12 and 5.17 under Python 3.13 and 3.14: all eight listed modules still match. The functions of Phi-3, OLMo-2, GPT-NeoX, Qwen3-Next, GLM-4-MoE, ERNIE-4.5-MoE and Cohere, none of them listed, are refused. - `pre-commit run --files` on the changed files: passed. ## CI - `cpu-torch-latest` collects the file and skips it. - `python ci/tests_fetcher.py --base upstream/master --explain` selects exactly this file. `modal-torch-latest` runs it on the GPU, without `--forked`, when the PR enters the merge queue. - `aws-torch-latest` runs `tests/unit/v1` with `pytest --forked`. The cases now use `DistributedTest(world_size=1, init_distributed=False)` to run in clean workers despite CUDA state created during collection. This file no longer probes CUDA availability in its collection-time skip condition; process-wide installer patches are restored in the worker that installed them. Documentation: a new "Fused rotary position embedding (experimental)" section in `docs/code-docs/source/autoep.rst`, before the AutoEP constraints. ## Not covered - Architectures outside `SUPPORTED_ROTARY_MODULES`. For example, Gemma's functions also match the split-half expression but are not listed or tested. - Transformers releases whose `apply_rotary_pos_emb` takes `position_ids`, which are left unpatched. - Partial, interleaved or other RoPE variants, fp32, ROCm, and `torch.compile`/`torch.func` transforms. - Matching eager's layout for non-dense inputs; the values are equal. - Splitting the end-to-end gain between this PR and the narrow-row RMSNorm change, and long-run convergence. --------- Signed-off-by: yh0903 <helloyu0903@gmail.com> Co-authored-by: Masahiro Tanaka <81312776+tohtana@users.noreply.github.com>
) ## Summary This PR adds an opt-in decode-front alignment path for continuous-batching rollouts. When `align_decode_fronts=False`, the existing equal-width padded layout remains the default. Requests may have different effective lengths in their attention masks, but their physical decode fronts are not right-aligned or compacted. When `align_decode_fronts=True`, the rollout: * derives effective prompt lengths from attention masks; * orders requests from longest to shortest; * right-aligns prefill spans; * tracks logical positions and physical write positions separately; * trims dead cache columns with attention metadata and write positions; * restores the original request order in the returned batch. The scheduler no longer exposes `admit_if`. Trimming preserves enough physical cache span for prompts admitted during the current refill. ## Validation ### Test Results - ✅ 14 tests passed - ✅ Changed-file pre-commit checks passed ### Device-Backed Validation - **GPU:** NVIDIA RTX 4000 Ada, 20 GB - **PyTorch:** 2.9.1+cu128 - **CUDA:** 12.8 - **Transformers:** 4.57.1 - **Model:** Qwen/Qwen2.5-3B-Instruct - **Precision:** FP32 > The aligned and equal-width outputs matched the single-request eager oracle token by token. ### Performance #### Workload 1: 32 mixed left-padded requests * **Prompt shape:** `[32, 20]` * **max_new_tokens:** 16 | Case | Time | Throughput | | :--- | :--- | :--- | | **no-CB** | 1183.46 ms | 432.63 tok/s | | **CB equal-width, batch 32** | 1418.99 ms | 360.82 tok/s | | **aligned CB, batch 32** | 2600.53 ms | 196.88 tok/s | | **dynamic CB, continuous_batch_size=8** | 4315.39 ms | 118.65 tok/s | > The optimization is workload-dependent. For uniform short prompts, aligned CB is slower because per-request prefill and cache-management overhead dominate. For long-tail prompt lengths, aligned CB can be much faster by avoiding padded prefill computation. #### Workload 2: Long-tail workload * **Composition:** 1 × 512-token prompt and 31 × 16-token prompts (padded to `[32, 512]`) | Case | Mean time | Mean throughput | | :--- | :--- | :--- | | **no-CB** | 9539.69 ms | 53.67 tok/s | | **CB equal-width, batch 32** | 9668.58 ms | 52.96 tok/s | | **aligned CB, batch 32** | 3711.05 ms | 137.97 tok/s | > The aligned path was **2.57× faster** than no-CB for this long-tail workload by avoiding repeated prefill computation on padded rows. These measurements are workload-dependent and are not presented as a general CB speedup claim. > The observed 2.57x improvement comes from avoiding padded prefill work in the long-tail prompt workload, not from cache trimming. The workload had trim_count=0, so it does not provide real-model trim overhead data. Trimming is covered by the synthetic regression test, while a real trim measurement would require a workload with staggered EOS or per-request token budgets. ### Notes The tested workloads did not trigger real-model trimming: ```text trim_count=0 trimmed_columns=0 trim_latency_ms=0.0 trim_bytes_moved=0 ``` ### Applicability and Limitations | Workload | Expected behavior | Main reason | | --- | --- | --- | | Short prompts with similar lengths | May be slower | Scheduler, cache-management, and per-request prefill overhead dominate | | Highly variable prompt lengths | Can improve throughput | Reduces padded prefill computation | | Dynamic request arrivals | Can improve GPU utilization | Released slots can be refilled with pending requests | | Staggered request completion or EOS retirement | Enables trimming benefits | Dead cache columns can be reclaimed | | Fixed batch with similar-length requests | Standard static batching may be faster | It avoids continuous-batching overhead | | No early request completion | No real trimming benefit | The trimming path is not exercised | *BF16 token-exactness is not claimed; separate BF16 runs showed numerical token divergence.* Related to deepspeedai#8462 and follow-up to deepspeedai#8368. --------- Signed-off-by: nathon-lee <leejianwoo@gmail.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Resolve the three overlaps with deepspeedai#8632 by preserving the existing offload readiness, reuse-event and storage-lifetime handling alongside the per-buffer completion state. Keep the offload reverse barrier unchanged.
Initialize the non-offload fixtures introduced by deepspeedai#8366 for the explicit safety flag from deepspeedai#8632. Cover releasing both per-buffer completion and offload reuse events so the conflict resolution cannot silently retain stale buffer state. Signed-off-by: guanghuiwang <209993960+ghwang-s@users.noreply.github.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This brings current upstream master into the branch for deepspeedai#8366 and resolves the three conflicts with deepspeedai#8632. Buffer teardown clears both event stores, writes keep both reuse dependencies, and reduction completion retains the offload-copy ordering. The existing offload reverse barrier stays as it is.
The merge resolution is in ghwang-s@9e0b38f and the test update is in ghwang-s@f18de91. The latter fixes two fixtures affected by the new offload flag and checks that releasing a physical buffer clears both completion and reuse events. Your five original commits are preserved.
44 CPU tests pass, including two-process Gloo training comparisons, and the changed-file pre-commit checks pass. The merged tree still needs the six delayed two-GPU reduction tests and two CUDA producer-handoff tests.