Skip to content

Implement graph operations for NPU accelerator - #8605

Merged
delock merged 9 commits into
deepspeedai:masterfrom
VenusTZZ:npu-graph-operations
Sep 22, 2026
Merged

delock merged 9 commits into
deepspeedai:masterfrom
VenusTZZ:npu-graph-operations

Conversation

@VenusTZZ

@VenusTZZ VenusTZZ commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #8604

Follow-up to #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 Capture short kernel sequences to graph #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 (Add Habana Labs HPU accelerator support #4912), MLU ([Accelerator] Cambricon MLU support #6472), and SUPA (Add Biren SUPA accelerator support #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.

Replace the deepspeedai#4318-era stub (create_graph returning None, no-op capture,
empty replay) with torch_npu's graph API: torch.npu.NPUGraph(),
torch.npu.graph(graph, pool, stream), and graph.replay(), mirroring the
HPU/MLU/SUPA implementations. The stub made graph_process a silent no-op
on every replay after the first call, so enabling graph_harvesting on NPU
silently froze gradient norms, clipping, and the hp->lp write-back.

Add hardware-independent contract tests (tests/unit/accelerator/
test_npu_accelerator.py) that stub torch.npu so they run on CPU-only CI.

Signed-off-by: Zizhao Tang <[email protected]>
@VenusTZZ VenusTZZ changed the title Npu graph operations Implement graph operations for NPU accelerator Sep 20, 2026
@VenusTZZ
VenusTZZ marked this pull request as ready for review September 20, 2026 07:06
@delock
delock self-requested a review September 20, 2026 07:21
@delock
delock enabled auto-merge September 22, 2026 01:35
npu_accelerator.py imports torch only via 'import torch.npu' inside a
try/except, which binds the 'torch' name only when the import succeeds.
With torch_npu installed it always succeeds, but on CPU-only CI the
ImportError is swallowed and 'torch' stays unbound, so
create_graph/capture_to_graph/replay_graph raise NameError. Add a plain
'import torch' in the same try block, preserving the setup-stage
behavior (the module still imports without torch).

Signed-off-by: Zizhao Tang <[email protected]>
auto-merge was automatically disabled September 22, 2026 02:41

Head branch was pushed to by a user without write access

@VenusTZZ

VenusTZZ commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the review, @delock!

I noticed the cpu-torch-latest CI run was failing on the new NPU graph tests and found the cause: npu_accelerator.py only had import torch.npu inside a try/except, which binds the torch name only when it succeeds. On machines with torch_npu it always succeeds (which is why local runs passed), but on CPU-only CI the ImportError is swallowed and torch stays unbound — so the three graph methods raise NameError.

Fixed by adding a plain import torch in the same try block (one line, setup-stage behavior unchanged). Reproduced the failure in a CI-like environment (torch 2.10.0+cpu without torch_npu) and confirmed the tests pass there, with no regression on NPU.

Pushed as 9d9d00f.

The workflow runs for the new commit are waiting for approval — would appreciate it if you could approve them.

@VenusTZZ
VenusTZZ requested a review from delock September 22, 2026 02:47
@delock

delock commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the review, @delock!

I noticed the cpu-torch-latest CI run was failing on the new NPU graph tests and found the cause: npu_accelerator.py only had import torch.npu inside a try/except, which binds the torch name only when it succeeds. On machines with torch_npu it always succeeds (which is why local runs passed), but on CPU-only CI the ImportError is swallowed and torch stays unbound — so the three graph methods raise NameError.

Fixed by adding a plain import torch in the same try block (one line, setup-stage behavior unchanged). Reproduced the failure in a CI-like environment (torch 2.10.0+cpu without torch_npu) and confirmed the tests pass there, with no regression on NPU.

Pushed as 9d9d00f.

The workflow runs for the new commit are waiting for approval — would appreciate it if you could approve them.

Thanks for the update. I have a question for the test. From the content of test it looks like it should be device agnostic. Why the test didn't use get_accelerator() to get the NPU_accelerator on a NPU system? We encourage writing device agnostic test instead of test designed for specific device. Is there a reason for this test to be NPU specific?

The NPU graph tests stubbed torch.npu to run on CPU-only CI, which made
them backend-specific. Per review feedback, replace them with tests that
drive get_accelerator(): a capture/replay roundtrip that runs on real
hardware for any graph-capable backend, and the eager/no-op contract for
backends without graph support (the path CPU-only CI executes).

Signed-off-by: Zizhao Tang <[email protected]>
@VenusTZZ
VenusTZZ force-pushed the npu-graph-operations branch from da47710 to bb038ba Compare September 22, 2026 04:59
@VenusTZZ

Copy link
Copy Markdown
Contributor Author

Thanks for the update. I have a question for the test. From the content of test it looks like it should be device agnostic. Why the test didn't use get_accelerator() to get the NPU_accelerator on a NPU system? We encourage writing device agnostic test instead of test designed for specific device. Is there a reason for this test to be NPU specific?

Thanks for the review, @delock. You're right — I should have driven this through the accelerator interface from the start; stubbing torch.npu to run on CPU-only CI is what made the test NPU-specific. Apologies for the miss.

Reworked in bb038ba to be device-agnostic via get_accelerator():

  • test_graph_capture_replay_roundtrip — real create/capture/replay roundtrip on whatever device the machine has; asserts replay re-executes the captured work (skips on backends without graph support).
  • test_graph_ops_run_eagerly_without_graph_support — the no-graph contract (create_graph → None, capture runs eagerly, replay is a no-op), which is what CPU-only CI executes.

Verified on Ascend 910B4 (real NPUGraph capture/replay) and in a CPU-only CI-replica; pre-commit clean.

@delock
delock enabled auto-merge September 22, 2026 05:24
@delock
delock added this pull request to the merge queue Sep 22, 2026
Merged via the queue into deepspeedai:master with commit 478228b Sep 22, 2026
15 checks passed
@VenusTZZ

Copy link
Copy Markdown
Contributor Author

Thanks a lot for reviewing and merging this pull request!

@VenusTZZ
VenusTZZ deleted the npu-graph-operations branch September 28, 2026 06:27
@tohtana tohtana added the needs-gpu-test GPU testing is recommended to validate the changes in this PR. label Nov 10, 2026
@tohtana tohtana removed the needs-gpu-test GPU testing is recommended to validate the changes in this PR. label Nov 14, 2026
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.

[REQUEST] NPU: implement graph operations for short kernel sequences (follow-up to #4318)

3 participants