Skip to content

Add Biren SUPA accelerator support - #8054

Merged
delock merged 5 commits into
deepspeedai:masterfrom
frozenleaves:main-supa
Jun 16, 2026
Merged

delock merged 5 commits into
deepspeedai:masterfrom
frozenleaves:main-supa

Conversation

@frozenleaves

@frozenleaves frozenleaves commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

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.

# 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:

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread op_builder/supa/fused_adam.py Resolved
Comment thread op_builder/supa/builder.py Resolved
Signed-off-by: frozenleaves <[email protected]>
@frozenleaves

Copy link
Copy Markdown
Contributor Author

CC @PKUWZP @delock

@PKUWZP

PKUWZP commented Jun 8, 2026

Copy link
Copy Markdown
Collaborator

@frozenleaves Thanks for submitting this PR, very exciting work. A couple of suggestions:

  • Can you make sure to run pre-commit command to fix any formatting errors?
  • Can you add some testing results and ideally some benchmarking results? No need to be very large-scale, but a few Biren GPUs are fine.

@delock

delock commented Jun 9, 2026

Copy link
Copy Markdown
Collaborator

@frozenleaves Thanks for submitting this PR, very exciting work. A couple of suggestions:

  • Can you make sure to run pre-commit command to fix any formatting errors?
  • Can you add some testing results and ideally some benchmarking results? No need to be very large-scale, but a few Biren GPUs are fine.

I think the testing level should be two tiers:

  1. UT test result -- whether a core subset of UT had passed on SUPA
  2. Workload test result -- which ZeRO stages are currently supported, whether SP/TP is supported etc.
  3. Benchmarking results -- could be shared in the comments or a followup blog post.

Also this table can be updated along with this PR.
https://github.com/deepspeedai/DeepSpeed#contributed-hw-support

@frozenleaves

Copy link
Copy Markdown
Contributor Author

@frozenleaves Thanks for submitting this PR, very exciting work. A couple of suggestions:

  • Can you make sure to run pre-commit command to fix any formatting errors?
  • Can you add some testing results and ideally some benchmarking results? No need to be very large-scale, but a few Biren GPUs are fine.

@frozenleaves Thanks for submitting this PR, very exciting work. A couple of suggestions:

  • Can you make sure to run pre-commit command to fix any formatting errors?
  • Can you add some testing results and ideally some benchmarking results? No need to be very large-scale, but a few Biren GPUs are fine.

I think the testing level should be two tiers:

  1. UT test result -- whether a core subset of UT had passed on SUPA
  2. Workload test result -- which ZeRO stages are currently supported, whether SP/TP is supported etc.
  3. Benchmarking results -- could be shared in the comments or a followup blog post.

Also this table can be updated along with this PR. https://github.com/deepspeedai/DeepSpeed#contributed-hw-support

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]>
@delock

delock commented Jun 12, 2026

Copy link
Copy Markdown
Collaborator

Hi @frozenleaves can you fix the DCO error in CI?
When you have workload test result you can post in comments and ping me. Thanks!

Signed-off-by: frozenleaves <[email protected]>
@frozenleaves

frozenleaves commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor Author

UT case test results

✅ Passed

accelerator/

  • accelerator/test_accelerator.py

autotuning/

  • autotuning/test_autotuning.py

checkpoint/

  • checkpoint/test_autotp_uc_checkpoint.py
  • checkpoint/test_convert_checkpoint.py
  • checkpoint/test_reshape_checkpoint.py
  • checkpoint/test_sparse.py
  • checkpoint/test_shared_weights.py
  • checkpoint/test_tag_validation.py

compile/

  • compile/test_inductor_aot_kwargs.py
  • compile/test_list_schedule.py

compression/

  • compression/test_compression.py [2 passed, 1 skipped]

launcher/

  • launcher/test_ds_arguments.py
  • launcher/test_multinode_runner.py
  • launcher/test_run.py

model_parallelism/

  • model_parallelism/test_tp_plan_e2e.py
  • model_parallelism/test_autotp_custom_patterns.py

module_inject/

  • module_inject/test_tp_plan_converter.py

monitor/

  • monitor/test_monitor.py

ops/

  • ops/adam/
  • ops/adagrad/
  • ops/aio/ [44 passed, 46 skipped]
  • ops/deepspeed4science/ [9 passed, 1 skipped]
  • ops/lion/
  • ops/test_op_builder.py

pipe/

  • pipe/test_pipe_module.py

profiling/

  • profiling/flops_profiler/test_flops_profiler.py

runtime/

  • runtime/activation_checkpointing/
  • runtime/comm/
  • runtime/tensor_parallel
  • runtime/zero/
  • runtime/utils/
  • runtime/zenflow/
  • runtime/test_autocast.py
  • runtime/test_data_efficiency.py
  • runtime/test_data.py
  • runtime/test_ds_config_dict.py
  • runtime/test_ds_initialize.py
  • runtime/test_ds_config_model.py
  • runtime/test_lr_schedulers.py
  • runtime/test_multi_output_model.py
  • runtime/test_multiple_models.py
  • runtime/test_mup_optimizers.py
  • runtime/test_no_sync_ctxt.py
  • runtime/test_pld.py
  • runtime/test_precision_config_loss_scale.py
  • runtime/test_runtime_utils.py
  • runtime/test_tp_plan_extraction.py

sequence_parallelism/

  • sequence_parallelism/test_autosp_equivalence.py
  • sequence_parallelism/test_autosp_integration.py

ulysses_alst/

  • ulysses_alst/test_tiled_compute.py
  • ulysses_alst/test_ulysses_sp_hf.py

utils/

  • utils/test_get_optim_files.py
  • utils/test_groups.py
  • utils/test_init_on_device.py
  • utils/test_nvtx.py

⏭️ Skipped

comm/

  • comm/test_dist.py

checkpoint/

  • checkpoint/test_latest_checkpoint.py
  • checkpoint/test_mics_optimizer.py
  • checkpoint/test_moe_checkpoint.py
  • checkpoint/test_pipeline.py
  • checkpoint/test_universal_checkpoint.py

compression/

  • compression/test_dequantization.py

elasticity/

  • elasticity/test_elastic.py

hybrid_engine/

  • hybrid_engine/test_he_all.py
  • hybrid_engine/test_he_llama.py
  • hybrid_engine/test_he_lora.py

inference/

  • inference/ [skipped]

linear/

  • linear/test_ctx.py
  • linear/test_linear.py
  • linear/test_quant_param.py

model_parallelism/

  • model_parallelism/test_autotp_training.py
  • model_parallelism/test_configurable_parallel_mp.py
  • model_parallelism/test_configurable_parallel_pp.py

ops/

  • ops/accelerators/
  • ops/fp_quantizer/
  • ops/muon/
  • ops/quantizer/
  • ops/sparse_attention/
  • ops/spatial/
  • ops/transformer/

sequence_parallelism/

  • sequence_parallelism/test_ulysses.py

v1/

  • v1/compile/test_compile_autosp.py
  • v1/compile/test_compile_fx.py
  • v1/half_precision/test_bf16.py

❌ Failed

checkpoint/

  • checkpoint/test_other_optimizer.py

launcher/

  • launcher/test_user_args.py [4 failed, 7 passed] [RuntimeError: launcher 'pdsh' not installed]

moe/

  • moe/test_moe.py
  • moe/test_moe_tp.py

runtime/

  • runtime/sparse_tensor/

v1/

  • v1/compile/test_compile_zero.py

@delock
delock merged commit 7ad4108 into deepspeedai:master Jun 16, 2026
13 checks passed
nathon-lee pushed a commit to nathon-lee/DeepSpeed_woo that referenced this pull request Jul 1, 2026
# 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]>
nathon-lee pushed a commit to nathon-lee/DeepSpeed_woo that referenced this pull request Jul 1, 2026
# 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]>
@sfc-gh-truwase

Copy link
Copy Markdown
Collaborator

@frozenleaves do you intend to do any Biren SUPA publications on model scaling and performance with DeepSpeed?

@frozenleaves

Copy link
Copy Markdown
Contributor Author

@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.

pull Bot pushed a commit to fish003/DeepSpeed that referenced this pull request Sep 22, 2026
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]>
pull Bot pushed a commit to FANGOD/DeepSpeed that referenced this pull request Sep 28, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants