Repository navigation
Add Biren SUPA accelerator support - #8054
Conversation
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3eb1e1811a
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
Signed-off-by: frozenleaves <[email protected]>
Signed-off-by: frozenleaves <[email protected]>
|
@frozenleaves Thanks for submitting this PR, very exciting work. A couple of suggestions:
|
I think the testing level should be two tiers:
Also this table can be updated along with this PR. |
Thank you very much for your review comments. I will fix the CI issue as soon as possible, and add the Workload test result to the comment section of the PR later. Benchmarking results maye we can shared in the followup blog post. |
Signed-off-by: frozenleaves <[email protected]>
|
Hi @frozenleaves can you fix the DCO error in CI? |
Signed-off-by: frozenleaves <[email protected]>
UT case test results✅ Passed accelerator/
autotuning/
checkpoint/
compile/
compression/
launcher/
model_parallelism/
module_inject/
monitor/
ops/
pipe/
profiling/
runtime/
sequence_parallelism/
ulysses_alst/
utils/
⏭️ Skipped comm/
checkpoint/
compression/
elasticity/
hybrid_engine/
inference/
linear/
model_parallelism/
ops/
sequence_parallelism/
v1/
❌ Failed checkpoint/
launcher/
moe/
runtime/
v1/
|
# Add Biren SUPA Accelerator Support
## Summary
This PR adds accelerator backend support for the **Biren SUPA GPU** (the
Biren Technology GPU, software stack SUPA) to DeepSpeed, enabling
DeepSpeed to automatically detect the device, run training and inference
on Biren GPUs, and reuse DeepSpeed's existing operator invocation
framework (fused optimizer, transformer inference, quantizer, async-io,
etc.).
SUPA is onboarded as the 9th supported accelerator, following `cuda /
cpu / xpu / npu / mps / hpu / mlu / sdaa`. It adheres to DeepSpeed's
existing `DeepSpeedAccelerator` abstract interface and the `op_builder`
plugin mechanism, with **zero intrusion** into existing backends — the
only existing file modified is the accelerator auto-detection entry
point `accelerator/real_accelerator.py`.
## Changes
### 1. Accelerator auto-detection and registration —
`accelerator/real_accelerator.py` (the only existing file modified)
- Add `'supa'` to `SUPPORTED_ACCELERATOR_LIST`.
- **Explicit specification** (`DS_ACCELERATOR=supa`): attempt `import
torch_supa`, and emit a clear error message if it is missing.
- **Auto-detection**: add a SUPA probing branch that determines
availability via `import torch_supa` and checking
`torch.supa.is_available()`.
- Critical ordering: because `torch_supa` spoofs `torch.cuda`, the SUPA
detection branch **must come before** the CUDA detection, otherwise
Biren cards would be misidentified as CUDA devices. This constraint is
clearly noted with a comment in the code.
- In the third-step instantiation logic, add the `accelerator_name ==
'supa'` → `SUPA_Accelerator()` branch.
### 2. Accelerator implementation — `accelerator/supa_accelerator.py`
Implements all interfaces of the `DeepSpeedAccelerator` abstract base
class. The vast majority of APIs delegate directly to `torch.supa.*`
(mirroring the semantics of `torch.cuda.*`):
- **Device management**: `device / set_device / current_device /
device_count / synchronize`, etc.
- **RNG**: `manual_seed(_all) / get_rng_state / set_rng_state /
default_generator`.
- **Stream / Event**: `Stream / Event / current_stream /
default_stream`.
- **Memory management**: `empty_cache / memory_allocated /
max_memory_allocated / memory_reserved / memory_stats / total_memory /
available_memory`, etc. (some use `hasattr` for capability probing, for
compatibility across different versions of torch_supa).
- **Data types**: declares support for fp32 / fp16 / bf16.
- **Communication backend**: uses **BCCL** (the Biren collective
communication library) on Linux, falling back to `gloo` on Windows.
- **CUDA Graph**: mapped to `torch.supa.SUPAGraph()` /
`torch.supa.graph(...)`.
- **op_builder loading**: `op_builder_dir()` returns `op_builder.supa`
(local install) or `deepspeed.ops.op_builder.supa` (pip install), and
lazily loads via `pkgutil`, scanning all `*Builder` classes in that
directory to build the `class_dict`.
- **Environment variables**: `export_envs` exports `BCCL / BIREN / SUPA
/ LD_LIBRARY / PATH`; `visible_devices_envs` uses
`SUPA_VISIBLE_DEVICES`.
- **Compile backend**: defaults to `inductor`, with Triton support.
### 3. SUPA op_builder plugin package — `op_builder/supa/` (new)
A new SUPA builder package, parallel to `op_builder/{cpu,xpu,npu,...}`:
| File | Purpose |
|------|------|
| `builder.py` | `SUPAOpBuilder` base class, compiling host-side C++
sources based on `CppExtension` (`-O3 -std=c++17 -fopenmp` + CPU arch /
SIMD width). |
| `fused_adam.py` | `FusedAdamBuilder` + `SUPAFusedAdam`: prefers
calling the `torch.ops.deepspeed.multi_tensor_adam` compiled kernel,
falling back to a **numerically equivalent pure-PyTorch implementation**
when missing (supports Adam mode=0 / AdamW mode=1). |
| `fused_lamb.py` | `FusedLambBuilder` + `SUPAFusedLamb`:
`torch.ops.deepspeed.lamb`, with a pure-PyTorch fallback (trust-ratio
clamp). |
| `fused_lion.py` | `FusedLionBuilder` + `SUPAFusedLion`:
`torch.ops.deepspeed.multi_tensor_lion`, with a pure-PyTorch fallback. |
| `inference.py` | `InferenceBuilder` + `SUPAInference`: wraps the full
set of transformer inference kernels (layer_norm / rms_norm /
softmax(_context) / bias_* / qkv_gemm / mlp_gemm / vector_matmul /
linear_layer / rotary / einsum / MoE / gated_activation), in
fp16/bf16/fp32 precisions, each delegating to `torch.ops.deepspeed.*`. |
| `quantizer.py` | `QuantizerBuilder` + `SUPAQuantizer`:
symmetric/asymmetric quantization, stochastic rounding (SR), int4/int8
dequantization, swizzle_quant, quantized_reduction, LoCo, etc. |
| `async_io.py` | `AsyncIOBuilder`: reuses DeepSpeed's existing
`csrc/aio/*` C++ sources, depends on `libaio`, includes a
package-manager detection hint. |
| `cpu_adam.py` / `cpu_lion.py` / `cpu_adagrad.py` | CPU offload
optimizer builders, reusing the `csrc/{adam,lion,adagrad}/*` sources. |
| `no_impl.py` | `NotImplementedBuilder`: a placeholder stub for
unimplemented ops; `load()` raises a clear `NotImplementedError`. |
| `__init__.py` | Exports all builders. |
**Design highlights**:
- Compiled kernels are hooked in via `import torch_supa_ext.deepspeed`
(side effect: registers `torch.ops.deepspeed.*`); all imports are
wrapped in `try/except` so the module remains importable even without
the compiled extension.
- `is_compatible()` uses a two-stage decision: "fast path checks whether
the op is already registered → otherwise attempt to import the
extension".
- optimizer builders provide a pure-PyTorch fallback, making it
convenient to do functional verification in cmodel / hardware-free
environments.
## Dependencies
Runtime dependencies (all are Biren software-stack components, needed
only when using the SUPA backend):
- **`torch_supa`** — the Biren PyTorch device extension, providing the
`torch.supa.*` namespace. **Required** (the basis for accelerator
detection and all device APIs).
- **`torch_supa_ext`** — the Biren compiled operator extension, with
submodules:
- `torch_supa_ext.deepspeed` — registers `torch.ops.deepspeed.*` (fused
optimizer / inference / quantizer kernels).
*Optional*: when missing, the optimizer falls back to pure PyTorch,
while inference/quantizer raise a clear error on invocation and tests
are skipped automatically.
- **BCCL** — the Biren collective communication library (the
communication backend for distributed training).
- **libaio** — required by `AsyncIOBuilder` (ZeRO-Infinity NVMe offload)
via `libaio-dev`.
**No new dependencies** are introduced for DeepSpeed's existing code or
other backends.
## Usage
Prerequisite: the Biren driver + `torch_supa` (+ `torch_supa_ext` as
needed) is already installed.
```bash
# Option 1: explicitly specify the backend
export DS_ACCELERATOR=supa
# Option 2: auto-detection (just install torch_supa; no environment variable needed)
```
Usage in code is exactly the same as for other backends, through the
unified `get_accelerator()` abstraction:
```python
import torch
from deepspeed.accelerator import get_accelerator
accelerator = get_accelerator() # automatically returns SUPA_Accelerator
print(accelerator.device_name()) # 'supa'
device = accelerator.device(0) # torch.device('supa', 0)
tensor = torch.randn(3, device=device) # tensor([-0.8643, 1.3154, 1.5823, ], device='supa:0')
# DeepSpeed training/inference initialization requires no changes; op_builder is automatically routed to op_builder.supa
```
Multi-card visibility is controlled via the `SUPA_VISIBLE_DEVICES`
environment variable; the distributed communication backend defaults to
`bccl`.
## Compatibility and scope of impact
- The SUPA path is activated only when `DS_ACCELERATOR=supa` is
explicitly set or `torch_supa` is present in the environment; behavior
in all other environments is completely unchanged.
- The only existing file modified, `real_accelerator.py`, only adds
branches and does not modify existing logic.
- Tests are skipped automatically when no hardware is present, remaining
transparent to upstream CI.
---------
Signed-off-by: frozenleaves <[email protected]>
Co-authored-by: Ma, Guokai <[email protected]>
Signed-off-by: nathon-lee <[email protected]>
# Add Biren SUPA Accelerator Support
## Summary
This PR adds accelerator backend support for the **Biren SUPA GPU** (the
Biren Technology GPU, software stack SUPA) to DeepSpeed, enabling
DeepSpeed to automatically detect the device, run training and inference
on Biren GPUs, and reuse DeepSpeed's existing operator invocation
framework (fused optimizer, transformer inference, quantizer, async-io,
etc.).
SUPA is onboarded as the 9th supported accelerator, following `cuda /
cpu / xpu / npu / mps / hpu / mlu / sdaa`. It adheres to DeepSpeed's
existing `DeepSpeedAccelerator` abstract interface and the `op_builder`
plugin mechanism, with **zero intrusion** into existing backends — the
only existing file modified is the accelerator auto-detection entry
point `accelerator/real_accelerator.py`.
## Changes
### 1. Accelerator auto-detection and registration —
`accelerator/real_accelerator.py` (the only existing file modified)
- Add `'supa'` to `SUPPORTED_ACCELERATOR_LIST`.
- **Explicit specification** (`DS_ACCELERATOR=supa`): attempt `import
torch_supa`, and emit a clear error message if it is missing.
- **Auto-detection**: add a SUPA probing branch that determines
availability via `import torch_supa` and checking
`torch.supa.is_available()`.
- Critical ordering: because `torch_supa` spoofs `torch.cuda`, the SUPA
detection branch **must come before** the CUDA detection, otherwise
Biren cards would be misidentified as CUDA devices. This constraint is
clearly noted with a comment in the code.
- In the third-step instantiation logic, add the `accelerator_name ==
'supa'` → `SUPA_Accelerator()` branch.
### 2. Accelerator implementation — `accelerator/supa_accelerator.py`
Implements all interfaces of the `DeepSpeedAccelerator` abstract base
class. The vast majority of APIs delegate directly to `torch.supa.*`
(mirroring the semantics of `torch.cuda.*`):
- **Device management**: `device / set_device / current_device /
device_count / synchronize`, etc.
- **RNG**: `manual_seed(_all) / get_rng_state / set_rng_state /
default_generator`.
- **Stream / Event**: `Stream / Event / current_stream /
default_stream`.
- **Memory management**: `empty_cache / memory_allocated /
max_memory_allocated / memory_reserved / memory_stats / total_memory /
available_memory`, etc. (some use `hasattr` for capability probing, for
compatibility across different versions of torch_supa).
- **Data types**: declares support for fp32 / fp16 / bf16.
- **Communication backend**: uses **BCCL** (the Biren collective
communication library) on Linux, falling back to `gloo` on Windows.
- **CUDA Graph**: mapped to `torch.supa.SUPAGraph()` /
`torch.supa.graph(...)`.
- **op_builder loading**: `op_builder_dir()` returns `op_builder.supa`
(local install) or `deepspeed.ops.op_builder.supa` (pip install), and
lazily loads via `pkgutil`, scanning all `*Builder` classes in that
directory to build the `class_dict`.
- **Environment variables**: `export_envs` exports `BCCL / BIREN / SUPA
/ LD_LIBRARY / PATH`; `visible_devices_envs` uses
`SUPA_VISIBLE_DEVICES`.
- **Compile backend**: defaults to `inductor`, with Triton support.
### 3. SUPA op_builder plugin package — `op_builder/supa/` (new)
A new SUPA builder package, parallel to `op_builder/{cpu,xpu,npu,...}`:
| File | Purpose |
|------|------|
| `builder.py` | `SUPAOpBuilder` base class, compiling host-side C++
sources based on `CppExtension` (`-O3 -std=c++17 -fopenmp` + CPU arch /
SIMD width). |
| `fused_adam.py` | `FusedAdamBuilder` + `SUPAFusedAdam`: prefers
calling the `torch.ops.deepspeed.multi_tensor_adam` compiled kernel,
falling back to a **numerically equivalent pure-PyTorch implementation**
when missing (supports Adam mode=0 / AdamW mode=1). |
| `fused_lamb.py` | `FusedLambBuilder` + `SUPAFusedLamb`:
`torch.ops.deepspeed.lamb`, with a pure-PyTorch fallback (trust-ratio
clamp). |
| `fused_lion.py` | `FusedLionBuilder` + `SUPAFusedLion`:
`torch.ops.deepspeed.multi_tensor_lion`, with a pure-PyTorch fallback. |
| `inference.py` | `InferenceBuilder` + `SUPAInference`: wraps the full
set of transformer inference kernels (layer_norm / rms_norm /
softmax(_context) / bias_* / qkv_gemm / mlp_gemm / vector_matmul /
linear_layer / rotary / einsum / MoE / gated_activation), in
fp16/bf16/fp32 precisions, each delegating to `torch.ops.deepspeed.*`. |
| `quantizer.py` | `QuantizerBuilder` + `SUPAQuantizer`:
symmetric/asymmetric quantization, stochastic rounding (SR), int4/int8
dequantization, swizzle_quant, quantized_reduction, LoCo, etc. |
| `async_io.py` | `AsyncIOBuilder`: reuses DeepSpeed's existing
`csrc/aio/*` C++ sources, depends on `libaio`, includes a
package-manager detection hint. |
| `cpu_adam.py` / `cpu_lion.py` / `cpu_adagrad.py` | CPU offload
optimizer builders, reusing the `csrc/{adam,lion,adagrad}/*` sources. |
| `no_impl.py` | `NotImplementedBuilder`: a placeholder stub for
unimplemented ops; `load()` raises a clear `NotImplementedError`. |
| `__init__.py` | Exports all builders. |
**Design highlights**:
- Compiled kernels are hooked in via `import torch_supa_ext.deepspeed`
(side effect: registers `torch.ops.deepspeed.*`); all imports are
wrapped in `try/except` so the module remains importable even without
the compiled extension.
- `is_compatible()` uses a two-stage decision: "fast path checks whether
the op is already registered → otherwise attempt to import the
extension".
- optimizer builders provide a pure-PyTorch fallback, making it
convenient to do functional verification in cmodel / hardware-free
environments.
## Dependencies
Runtime dependencies (all are Biren software-stack components, needed
only when using the SUPA backend):
- **`torch_supa`** — the Biren PyTorch device extension, providing the
`torch.supa.*` namespace. **Required** (the basis for accelerator
detection and all device APIs).
- **`torch_supa_ext`** — the Biren compiled operator extension, with
submodules:
- `torch_supa_ext.deepspeed` — registers `torch.ops.deepspeed.*` (fused
optimizer / inference / quantizer kernels).
*Optional*: when missing, the optimizer falls back to pure PyTorch,
while inference/quantizer raise a clear error on invocation and tests
are skipped automatically.
- **BCCL** — the Biren collective communication library (the
communication backend for distributed training).
- **libaio** — required by `AsyncIOBuilder` (ZeRO-Infinity NVMe offload)
via `libaio-dev`.
**No new dependencies** are introduced for DeepSpeed's existing code or
other backends.
## Usage
Prerequisite: the Biren driver + `torch_supa` (+ `torch_supa_ext` as
needed) is already installed.
```bash
# Option 1: explicitly specify the backend
export DS_ACCELERATOR=supa
# Option 2: auto-detection (just install torch_supa; no environment variable needed)
```
Usage in code is exactly the same as for other backends, through the
unified `get_accelerator()` abstraction:
```python
import torch
from deepspeed.accelerator import get_accelerator
accelerator = get_accelerator() # automatically returns SUPA_Accelerator
print(accelerator.device_name()) # 'supa'
device = accelerator.device(0) # torch.device('supa', 0)
tensor = torch.randn(3, device=device) # tensor([-0.8643, 1.3154, 1.5823, ], device='supa:0')
# DeepSpeed training/inference initialization requires no changes; op_builder is automatically routed to op_builder.supa
```
Multi-card visibility is controlled via the `SUPA_VISIBLE_DEVICES`
environment variable; the distributed communication backend defaults to
`bccl`.
## Compatibility and scope of impact
- The SUPA path is activated only when `DS_ACCELERATOR=supa` is
explicitly set or `torch_supa` is present in the environment; behavior
in all other environments is completely unchanged.
- The only existing file modified, `real_accelerator.py`, only adds
branches and does not modify existing logic.
- Tests are skipped automatically when no hardware is present, remaining
transparent to upstream CI.
---------
Signed-off-by: frozenleaves <[email protected]>
Co-authored-by: Ma, Guokai <[email protected]>
|
@frozenleaves do you intend to do any Biren SUPA publications on model scaling and performance with DeepSpeed? |
Sure, we do intend to publish on Biren SUPA regarding model scaling and performance with DeepSpeed. I will update and release this data here in the near future. Due to some reasons, we are unable to disclose it immediately at this moment. We appreciate your patience and understanding. |
Fixes deepspeedai#8604 Follow-up to deepspeedai#4318 (graph operations for short kernel sequences). ## Summary - Implement create_graph / capture_to_graph / replay_graph on NPU_Accelerator via the graph API torch_npu ships: torch.npu.NPUGraph() creates the graph object, torch.npu.graph(graph, pool, stream) is the capture context manager, and graph.replay() replays. Previously NPU_Accelerator carried the stub that deepspeedai#4318 originally left (None / a no-op context / nothing), so graph_process cached an empty graph and every subsequent "replay" did nothing: with graph_harvesting enabled, gradient norms silently went stale, clipping silently stopped, and the hp→lp gradient write-back silently stopped — reproduced on hardware (see below). - Mirrors the HPU (deepspeedai#4912), MLU (deepspeedai#6472), and SUPA (deepspeedai#8054) implementations, which wrap their runtime graph APIs the same way. - Adds tests/unit/accelerator/test_npu_accelerator.py with three hardware-independent contract tests that stub torch.npu and run on CPU-only CI, following the pattern of tests/unit/accelerator/test_mps_accelerator.py. ## Implementation notes The torch_npu graph API. NPUGraph wraps the runtime's graph object with capture_begin / capture_end / replay / reset / pool. torch.npu.graph(graph, pool, stream) is the context manager that performs the synchronization, cache cleanup, side-stream switching, and capture begin/end around the with block. pool and stream pass through positionally and default to None; graph_process captures without pool/stream, so the defaults are part of the contract. The graph APIs are core torch_npu APIs available across the torch versions DeepSpeed supports, so the methods call them directly with no existence checks — matching the CUDA/HPU/MLU/SUPA implementations. What it unblocks. The whole graph_harvesting chain already existed and is accelerator-agnostic: ds_config["graph_harvesting"]: true → engine.graph_harvesting → BF16_Optimizer(graph_harvesting=True) → graph_process (gradient norm, clipping, update_hp_grads). Implementing the trio is the only missing piece on NPU. Performance on Ascend 910B4 Whole-block timing with torch.npu.synchronize() on both sides of the block, 3 rounds, best round (shared-box methodology), CANN 8.5.0, torch 2.9.0+cpu, torch_npu 2.9.0.post7, Ascend 910B4 (aarch64): | Workload | eager (us/iter) | graph replay (us/iter) | speedup | |---|---|---|---| | 200 independent tiny ops (norm-style) | 6456 | 910 | 7.1x | | 50-step chained small ops (clip-style) | 3067 | 135 | 22.7x | | 20 ops on a 1M-element tensor | 1271 | 307 | 4.1x | End-to-end: with graph_harvesting: true on Ascend 910B4, _norm_tensors, clip_tensors, and _update_hp_grads_func are all captured into graph_cache, and 5 training steps (BF16_Optimizer, bf16 + fp32 gradient accumulation) are bitwise-identical to eager execution (equal losses, torch.equal parameters). Before/after: the same graph_process scenario run against the stub vs. this implementation — with the stub the reported norm froze at its first-step value, clipping stopped being applied, and the hp accumulation stopped, with no error raised; with this change all three track eager exactly. ## Test plan - pre-commit run --files on touched paths — yapf, flake8, check-torchdist, check-torchcuda, check-license, codespell all pass - pytest tests/unit/accelerator/ — 5 passed (3 new NPU contract tests + 2 existing MPS tests) - pytest tests/unit/v1/pin_memory/ — 45 passed (no regression) - Real-device on Ascend 910B4: capture → replay parity across two consecutive replays and explicit pool/stream arguments; graph_harvesting end-to-end chain; stub-vs-fix corruption demonstration ## Known limitation - Pre-existing and unrelated to NPU: engine.step() calls zero_grad() with the torch default set_to_none=True, which trips the graph_harvesting assert in deepspeed/runtime/bf16_optimizer.py on every accelerator. The end-to-end validation above calls optimizer.step() with zero_grad(set_to_none=False); worth a separate issue. --------- Signed-off-by: Zizhao Tang <[email protected]>
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 <[email protected]>
Add Biren SUPA Accelerator Support
Summary
This PR adds accelerator backend support for the Biren SUPA GPU (the Biren Technology GPU, software stack SUPA) to DeepSpeed, enabling DeepSpeed to automatically detect the device, run training and inference on Biren GPUs, and reuse DeepSpeed's existing operator invocation framework (fused optimizer, transformer inference, quantizer, async-io, etc.).
SUPA is onboarded as the 9th supported accelerator, following
cuda / cpu / xpu / npu / mps / hpu / mlu / sdaa. It adheres to DeepSpeed's existingDeepSpeedAcceleratorabstract interface and theop_builderplugin mechanism, with zero intrusion into existing backends — the only existing file modified is the accelerator auto-detection entry pointaccelerator/real_accelerator.py.Changes
1. Accelerator auto-detection and registration —
accelerator/real_accelerator.py(the only existing file modified)'supa'toSUPPORTED_ACCELERATOR_LIST.DS_ACCELERATOR=supa): attemptimport torch_supa, and emit a clear error message if it is missing.import torch_supaand checkingtorch.supa.is_available().torch_supaspoofstorch.cuda, the SUPA detection branch must come before the CUDA detection, otherwise Biren cards would be misidentified as CUDA devices. This constraint is clearly noted with a comment in the code.accelerator_name == 'supa'→SUPA_Accelerator()branch.2. Accelerator implementation —
accelerator/supa_accelerator.pyImplements all interfaces of the
DeepSpeedAcceleratorabstract base class. The vast majority of APIs delegate directly totorch.supa.*(mirroring the semantics oftorch.cuda.*):device / set_device / current_device / device_count / synchronize, etc.manual_seed(_all) / get_rng_state / set_rng_state / default_generator.Stream / Event / current_stream / default_stream.empty_cache / memory_allocated / max_memory_allocated / memory_reserved / memory_stats / total_memory / available_memory, etc. (some usehasattrfor capability probing, for compatibility across different versions of torch_supa).glooon Windows.torch.supa.SUPAGraph()/torch.supa.graph(...).op_builder_dir()returnsop_builder.supa(local install) ordeepspeed.ops.op_builder.supa(pip install), and lazily loads viapkgutil, scanning all*Builderclasses in that directory to build theclass_dict.export_envsexportsBCCL / BIREN / SUPA / LD_LIBRARY / PATH;visible_devices_envsusesSUPA_VISIBLE_DEVICES.inductor, with Triton support.3. SUPA op_builder plugin package —
op_builder/supa/(new)A new SUPA builder package, parallel to
op_builder/{cpu,xpu,npu,...}:builder.pySUPAOpBuilderbase class, compiling host-side C++ sources based onCppExtension(-O3 -std=c++17 -fopenmp+ CPU arch / SIMD width).fused_adam.pyFusedAdamBuilder+SUPAFusedAdam: prefers calling thetorch.ops.deepspeed.multi_tensor_adamcompiled kernel, falling back to a numerically equivalent pure-PyTorch implementation when missing (supports Adam mode=0 / AdamW mode=1).fused_lamb.pyFusedLambBuilder+SUPAFusedLamb:torch.ops.deepspeed.lamb, with a pure-PyTorch fallback (trust-ratio clamp).fused_lion.pyFusedLionBuilder+SUPAFusedLion:torch.ops.deepspeed.multi_tensor_lion, with a pure-PyTorch fallback.inference.pyInferenceBuilder+SUPAInference: wraps the full set of transformer inference kernels (layer_norm / rms_norm / softmax(context) / bias* / qkv_gemm / mlp_gemm / vector_matmul / linear_layer / rotary / einsum / MoE / gated_activation), in fp16/bf16/fp32 precisions, each delegating totorch.ops.deepspeed.*.quantizer.pyQuantizerBuilder+SUPAQuantizer: symmetric/asymmetric quantization, stochastic rounding (SR), int4/int8 dequantization, swizzle_quant, quantized_reduction, LoCo, etc.async_io.pyAsyncIOBuilder: reuses DeepSpeed's existingcsrc/aio/*C++ sources, depends onlibaio, includes a package-manager detection hint.cpu_adam.py/cpu_lion.py/cpu_adagrad.pycsrc/{adam,lion,adagrad}/*sources.no_impl.pyNotImplementedBuilder: a placeholder stub for unimplemented ops;load()raises a clearNotImplementedError.__init__.pyDesign highlights:
import torch_supa_ext.deepspeed(side effect: registerstorch.ops.deepspeed.*); all imports are wrapped intry/exceptso the module remains importable even without the compiled extension.is_compatible()uses a two-stage decision: "fast path checks whether the op is already registered → otherwise attempt to import the extension".Dependencies
Runtime dependencies (all are Biren software-stack components, needed only when using the SUPA backend):
torch_supa— the Biren PyTorch device extension, providing thetorch.supa.*namespace. Required (the basis for accelerator detection and all device APIs).torch_supa_ext— the Biren compiled operator extension, with submodules:torch_supa_ext.deepspeed— registerstorch.ops.deepspeed.*(fused optimizer / inference / quantizer kernels).Optional: when missing, the optimizer falls back to pure PyTorch, while inference/quantizer raise a clear error on invocation and tests are skipped automatically.
BCCL — the Biren collective communication library (the communication backend for distributed training).
libaio — required by
AsyncIOBuilder(ZeRO-Infinity NVMe offload) vialibaio-dev.No new dependencies are introduced for DeepSpeed's existing code or other backends.
Usage
Prerequisite: the Biren driver +
torch_supa(+torch_supa_extas needed) is already installed.Usage in code is exactly the same as for other backends, through the unified
get_accelerator()abstraction:Multi-card visibility is controlled via the
SUPA_VISIBLE_DEVICESenvironment variable; the distributed communication backend defaults tobccl.Compatibility and scope of impact
DS_ACCELERATOR=supais explicitly set ortorch_supais present in the environment; behavior in all other environments is completely unchanged.real_accelerator.py, only adds branches and does not modify existing logic.