Skip to content

[Hybrid Engine] Enable XPU graph capture behind the explicit opt-in - #9007

Merged
delock merged 3 commits into
deepspeedai:masterfrom
delock:xpu-graph-capture
Nov 15, 2026
Merged

delock merged 3 commits into
deepspeedai:masterfrom
delock:xpu-graph-capture

Conversation

@delock

@delock delock commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator

Follow-up to #8980. Wire the XPU accelerator into the explicit graph-capture opt-in that #8980 introduces.

Background

XPU_Accelerator currently stubs the graph interfaces: create_graph() returns None, capture is a no-op context, and replay does nothing, so HybridEngine always runs eager on XPU. Upstream PyTorch ships XPU stream capture since 2.11 (torch.xpu.XPUGraph, the torch.xpu.graph capture context, and torch.xpu.is_current_stream_capturing()), so the capability exists but was never connected. Note #8980 does not regress XPU — it opts XPU out of a path that was never functional — this PR turns the real support on.

Change

  • create_graph() returns torch.xpu.XPUGraph() when available (None otherwise, preserving eager on older torch).
  • capture_to_graph() delegates to torch.xpu.graph(graph, pool, stream); replay_graph() to graph.replay().
  • is_current_stream_capturing() delegates to torch.xpu.is_current_stream_capturing().
  • is_graph_capture_supported() returns torch.xpu.is_available() and hasattr(torch.xpu, 'is_current_stream_capturing'). Both checks are required: torch builds without an XPU backend stub torch.xpu with dummy types where the query exists but raises when called, and pre-2.11 builds expose no query at all — either way XPU stays opted out and keeps the eager fallback.
  • Contract test in tests/unit/accelerator/test_accelerator_graph.py: the opt-in matches torch.xpu's actual capture capability (runs green on any accelerator; pins both a hardcoded-True regression and a forgotten opt-in).

Testing

Hardware: Intel Arc Pro B60 ×2 (single card used), torch 2.15.0+xpu, Python 3.12.16, transformers 5.22.1, Ubuntu 26.10. Branch under test: this PR stacked on #8980 (ec6fc5d).

  • DS_ACCELERATOR=xpu pytest tests/unit/accelerator/test_accelerator_graph.py -v — 3 passed, 1 skipped (the eager-fallback test skips by design once XPU returns a real graph). test_graph_capture_replay_roundtrip exercises real XPUGraph capture → replay on device, including the in-capture is_current_stream_capturing() query.
  • DS_ACCELERATOR=xpu pytest tests/unit/runtime/rollout/test_hybrid_engine_rollout.py -q — 50 passed.
  • tests/unit/hybrid_engine/test_he_graph.py skips module-level on XPU: InferenceBuilder (transformer inference kernels) is not implemented for XPU — pre-existing on master, unrelated to this change.
  • CPU-only machine (torch 2.12.1+cpu): same accelerator suite 3 passed, 1 skipped; dummy-type torch.xpu correctly stays opted out.
  • Rollout micro-benchmark (card 0, GPT-2 small 124M bf16, 8 prompts × 64 new tokens, continuous_batch_size=4, greedy): eager 466 tok/s vs graph capture 2109 tok/s — 4.53×. Outputs: prompts identical; 22/512 response tokens differ in 2/8 rows with first divergence at new-token 31/35, consistent with bf16 numerics cascade rather than a logic error. Note: running against transformers 5.22 additionally required stacking Support Transformers 5.20 cache query offsets in DeepSpeedStaticCache #8852 (DeepSpeedStaticCache.get_query_offset) in the validation tree; that fix is independent of and not included in this PR.

No-duplicate / AI statement

No open PR or issue wires XPU into graph capture (checked gh pr list --search "xpu graph", issue search). This change is small and follows the opt-in mechanism #8980 defines. AI assistance was used for implementation, testing, and benchmarking; the change was reviewed line-by-line by the submitter, and all listed tests were executed on real hardware as reported above.

Dependencies

XPU previously stubbed the graph interfaces (create_graph returned None,
capture was a no-op), so HybridEngine always ran eager on XPU. torch.xpu
now ships stream capture (XPUGraph, torch.xpu.graph, and
is_current_stream_capturing), so wire the interfaces up and opt in when a
real XPU runtime is present. Builds that stub torch.xpu with dummy types
or lack the stream-capture query stay opted out and keep the eager path.

Signed-off-by: Ma, Guokai <guokai.ma@intel.com>
@delock
delock force-pushed the xpu-graph-capture branch from 1a60772 to 81a2b8f Compare November 5, 2026 05:38
@delock
delock marked this pull request as ready for review November 5, 2026 05:39
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-05T05:43:57.223826Z 81a2b8f Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@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: 81a2b8f603

ℹ️ 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".

return torch.xpu.is_available() and hasattr(torch.xpu, 'is_current_stream_capturing')

def is_current_stream_capturing(self) -> bool:
return torch.xpu.is_current_stream_capturing()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Return false when the XPU capture query is unavailable

On the supported torch 2.10 XPU environment (the checked .github/workflows/xpu-max1100.yml:54 installs 2.10), torch.xpu.is_available() is true but this pre-2.11 capture-state query does not exist. Calls to this hook therefore raise instead of reporting eager execution; DeepSpeedStaticCache.update invokes it unconditionally for per-row cache positions at deepspeed/utils/static_cache.py:101, and the accelerator fallback test invokes it as well. Guard the attribute and return False on runtimes without the query.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

is_current_stream_capturing attribute now checked before used.

Comment thread accelerator/xpu_accelerator.py Outdated
Comment on lines +350 to +354
def capture_to_graph(self, graph, pool=None, stream=None):
from deepspeed.runtime.utils import noop_context
return noop_context()
return torch.xpu.graph(graph, pool, stream)

def replay_graph(self, graph):
graph.replay()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve no-op graph methods when create_graph returns None

On XPU torch <2.11, create_graph() deliberately returns None, but test_graph_ops_run_eagerly_without_graph_support then enters capture_to_graph(None) and calls replay_graph(None). The former accesses the unavailable torch.xpu.graph, and the latter dereferences None, so the eager compatibility path—including the torch 2.10 accelerator suite run by .github/workflows/xpu-max1100.yml:73—crashes. Keep the old no-op context and replay behavior whenever no graph was created.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

A guard had been added when the graph is None. Thanks!

Comment on lines +339 to +340
def is_graph_capture_supported(self) -> bool:
return torch.xpu.is_available() and hasattr(torch.xpu, 'is_current_stream_capturing')

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Document XPU graph capture and its torch requirement

This enables a new user-facing backend path, but the diff leaves docs/_tutorials/accelerator-abstraction-interface.md:46-57 unchanged, so users cannot discover that XPU capture is now supported only with the new torch APIs or that older runtimes remain eager. Add the XPU support and minimum-runtime behavior to the accelerator documentation before shipping the feature.

AGENTS.md reference: AGENTS.md:L71-L71

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Docs updated, thanks!

Comment on lines 345 to +348
def create_graph(self):
return None
if not hasattr(torch.xpu, 'XPUGraph'):
return None
return torch.xpu.XPUGraph()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Link an accepted proposal before enabling XPU capture

This changes XPU from eager-only execution to a new graph-capture feature, while the supplied description identifies only implementation PR #8980 as a dependency and no accepted proposal issue. Link or obtain acceptance for a proposal covering the motivation, design, and planned experiments before proceeding with the implementation.

AGENTS.md reference: AGENTS.md:L21-L23

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

This PR implements an accepted interface change on XPU, where graph capture on XPU is already supported in pytorch. We have also validated this feature on Intel Arc Pro B60.

@delock

delock commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

The failed test FAILED unit/checkpoint/test_fp32_master_only.py::test_elastic_dp_change_repartitions_masters_and_drops_moments seems not related to this PR since this PR change XPU behavior only.

@tohtana tohtana added the needs-gpu-test GPU testing is recommended to validate the changes in this PR. label Nov 10, 2026
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 11, 2026
…utoTP (deepspeedai#9008)

## Summary

Size HybridEngine rollout KV caches from each rank's own prefill KV
tensors, not from the global model config. Under AutoTP, each rank holds
only its share of the KV heads. Today the cache is allocated for the
full model's KV-head count, so TP>1 rollout fails on all three decode
paths:

| Path | TP>1 failure today | Change |
| --- | --- | --- |
| Plain graph (`_generate_graph`) | Passing batch size, device and dtype
makes `DeepSpeedStaticCache` initialize from `module.config` up front,
so the lazy per-layer setup never runs. The prefill copy then fails with
`4 vs 2` heads, or broadcasts silently when the rank has 1 local head. |
Drop those up-front arguments, so the existing lazy setup sizes each
layer from the prefill tensors before capture. |
| Continuous eager (`_generate_continuous`) | The same up-front setup
from config fails on the first prefill copy (`4 vs 2`, `2 vs 8`). |
Create the cache lazily. `_continuous_cache_layer` initializes each
layer from the prefill tensors, sized to the slot count. The slot count
is the decode batch capacity, not the prefill batch. |
| Continuous graph | The graph state cache is initialized from config,
and capture happens before any prefill. | Create the cache lazily and
run one decode forward on the current stream before warmup, so every
layer is initialized with local shapes. Without this, those tensors
would be allocated on the warmup side stream. |

`lazy_initialization` gains an optional `max_batch_size`, which the
continuous path uses because its capacity is the slot count.
`cache_memory_bytes` is now computed after decode, once the layers
exist. No model config is changed and no TP/world group is consulted, so
TP×DP layouts work with no extra logic.

## Related work / scope

- deepspeedai#9000 / deepspeedai#9004 fix attention-mask construction during capture, not KV
shape allocation. This PR is independent of them. For real Hugging Face
model validation, deepspeedai#9004's runtime hunk was applied to **both** the
baseline and the fixed tree.
- deepspeedai#8602 divides cache heads by the global world size, which breaks TP×DP
(for example TP2×DP4). This fix reads the tensors directly instead of
inferring the TP group.
- On Transformers 5.17, continuous eager also needs deepspeedai#8852
(`get_query_offset`), which is still open, so the continuous eager HF
runs below apply deepspeedai#8852 to both baseline and fixed trees. The new unit
tests use a local model and do not depend on deepspeedai#8852.
- **Known limitation, not changed here:** a persistent continuous graph
(deepspeedai#8732) that contains NCCL ops makes
`torch.distributed.destroy_process_group()` hang in
`ProcessGroupNCCL.shutdown()` at exit. Releasing the rollout (`del` +
`gc.collect()` + `synchronize()`) before destroying avoids it. Before
this PR, TP>1 continuous graph could not run, so the hang was not
reachable. A release/close API is left for a follow-up.

## Validation

**Hardware/software:** 8× NVIDIA L20, driver 580.173.02, CUDA runtime
13.0, torch 2.14.1+cu130, Transformers 5.17.0, Python 3.10.22. Baseline:
`d8241a9ba266405e1a58fadf19e24b2370f6d7fa`.

```bash
CUDA_VISIBLE_DEVICES=0 python -m pytest --forked tests/unit/v1/test_hybrid_engine_rollout_v1.py \
  -k "static_graph_uses_prefill_kv_shape or continuous_generation_uses_local_kv_shape"
# baseline: 6 failed, 3 passed; this PR: 9 passed

CUDA_VISIBLE_DEVICES=0 python -m pytest --forked tests/unit/v1/test_hybrid_engine_rollout_v1.py \
  tests/unit/runtime/rollout/test_hybrid_engine_rollout.py tests/unit/utils/test_static_cache.py
# baseline: 6 failed, 64 passed, 1 skipped; this PR: 70 passed, 1 skipped
```

The new tests write head-dependent cache contents, compare tokens with
an independent oracle, and count real graph replays:

| Local / config KV heads | Plain graph | Continuous eager | Continuous
graph |
| --- | --- | --- | --- |
| 4 / 4 | pass → pass | pass → pass | pass → pass |
| 2 / 4 | fail → pass | fail → pass | fail → pass |
| 1 / 4 | fail → pass | fail → pass | fail → pass |

**Multi-GPU tiny Llama, continuous path.** 2 layers, 4 KV heads, fp32, 4
requests per rank, 2 slots. Tokens were compared with plain eager
generation on every rank.

| Layout | Continuous graph (before → after) | Continuous eager + deepspeedai#8852
(before → after) |
| --- | --- | --- |
| TP1, world 1 | pass → pass | pass → pass |
| TP2, world 2 | shape error → pass | `4 vs 2` error → pass |
| TP4, world 4 | shape error → pass | `2 vs 8` error → pass |
| TP2×DP4, world 8 | shape error → pass | `4 vs 2` error → pass |
| TP4×DP2, world 8 | not run → pass | `2 vs 8` error → pass |

**Plain graph with real models**, with deepspeedai#9004 applied to both trees:

| Model / precision | Layouts | Result |
| --- | --- | --- |
| Tiny Llama / fp32 | TP1×DP1, TP1×DP4, TP2×DP2, TP2×DP4 | All pass;
graph tokens and masks equal native eager generation |
| Qwen3-8B / bf16 | TP2×DP4 | 4 prompts × 16 new tokens; graph tokens
and masks equal native eager generation |

On the plain-graph runs, each rank made three generation calls: 3
captures and 45 replays, and repeated graph outputs matched. The
baseline TP2×DP4 Llama run failed at the KV copy (`4 vs 2`). The Qwen3
graph calls took 0.464 / 0.439 s, including prefill and capture, with
8.25 GiB max allocated per GPU. These numbers come from correctness
runs; **no speedup is claimed**.

**Distributed AutoTP integration test** (`TestAutoTPContinuousRollout`,
world size 2): real AutoTP via `deepspeed.initialize` (`autotp_size=2`)
on a tiny Llama, 3 requests on 2 continuous slots, tokens compared with
`generate()` on the same sharded model. On 2× NVIDIA H20, torch
2.9.0a0+50eac811a6.nv25.09, Transformers 4.57.6, Python 3.12.3:

```bash
CUDA_VISIBLE_DEVICES=0,1 python -m pytest tests/unit/v1/test_hybrid_engine_rollout_v1.py -k TestAutoTPContinuousRollout
# baseline (rollout + static cache from d8241a9): 2 failed (eager `4 vs 2`, graph `[2, 2, 16]` vs `[2, 4, 16]`); this PR: 2 passed
```

```bash
DS_ACCELERATOR=cpu python -m pytest tests/unit/runtime/rollout/test_hybrid_engine_rollout.py \
  tests/unit/utils/test_static_cache.py tests/unit/v1/test_hybrid_engine_rollout_v1.py
# 60 passed, 11 skipped; Python 3.12.3 / torch 2.14.0.dev20260804+xpu

pre-commit run --files deepspeed/runtime/rollout/hybrid_engine_rollout.py \
  deepspeed/utils/static_cache.py tests/unit/v1/test_hybrid_engine_rollout_v1.py
# passed
```

**Intel XPU** (1× Arc Pro B70, torch 2.14.1+xpu, Transformers 5.22.1,
Intel compute runtime 26.27.39122.11, Level Zero loader 1.28.2). Master
has no XPU graph backend, so the new graph tests skip there. On top of
deepspeedai#9007 (XPU graph capture):

```bash
DS_ACCELERATOR=xpu python -m pytest tests/unit/v1/test_hybrid_engine_rollout_v1.py \
  -k "static_graph_uses_prefill_kv_shape or continuous_generation_uses_local_kv_shape"
# deepspeedai#9007 alone: 6 failed, 3 passed; deepspeedai#9007 + this PR: 9 passed

DS_ACCELERATOR=xpu python -m pytest tests/unit/v1/test_hybrid_engine_rollout_v1.py \
  tests/unit/runtime/rollout/test_hybrid_engine_rollout.py
# deepspeedai#9007 + this PR: 60 passed, 3 skipped; process exit 0
```

This clean-exit torch 2.14.1 rerun confirms all nine new tests pass; the
same tests against deepspeedai#9007 without this PR give 6 failed / 3 passed (exit
1). The earlier torch 2.15.0+xpu run printed passing tests but aborts
during interpreter teardown on this host (exit 134). A minimal XPU
tensor program reproduces that abort without DeepSpeed, so that earlier
run is not counted as a clean test pass. The earlier master-based tree
reported 52 passed / 10 skipped, with graph coverage skipped as
expected.

The opt-in `test_continuous_graph_matches_pretrained_model_when_enabled`
(only runs when `DEEPSPEED_PRETRAINED_ROLLOUT_MODEL` is set) fails the
same way on master and on this PR with Transformers 5.17:
`'DeepSpeedStaticCache' object has no attribute 'get_query_offset'`,
which deepspeedai#8852 addresses.

**Validated:** ZeRO-0, no offload, fp32/bf16, AutoTP with data-parallel
replicas on CUDA, plain and continuous decode, eager and graph;
single-device graph tests on XPU with deepspeedai#9007. **Not validated:** a full
training-to-rollout cycle, ZeRO-1/2/3, offload, pipeline/expert/sequence
parallelism, older HF preallocated cache APIs, and multi-device XPU
graph. No claim is made about training convergence or performance.

AI assistance: GitHub Copilot helped with the implementation, the tests
and the validation. I reviewed every changed line before signing off.

---------

Signed-off-by: Jin, Youzhi <youzhi.jin@intel.com>
Signed-off-by: iLeGend <824040212@qq.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Ma, Guokai <guokai.ma@gmail.com>
GuCarpenter added a commit to GuCarpenter/DeepSpeed that referenced this pull request Nov 12, 2026
deepspeedai#8980 made HybridEngine graph capture an explicit per-accelerator opt-in and,
for klxpu, added an is_graph_capture_supported() override returning False with
the note that capture "is not validated on this backend." It is validated now,
so remove the override and let klxpu inherit CUDA_Accelerator's opt-in.

Drop test_klxpu_keeps_explicit_graph_capture_opt_out from
tests/unit/accelerator/test_accelerator_graph.py along with it: the test pinned
the exact opt-out this change removes (asserting that a bare KLXPU_Accelerator
reports is_graph_capture_supported() is False), so it contradicts the inherited
opt-in and failed cpu-torch-latest CI on the first push of this PR. The file's
remaining two graph tests are backend-agnostic and untouched.

KLXPU_Accelerator subclasses CUDA_Accelerator and presents its device through
the CUDA runtime (cuda-compat), so it already inherits create_graph() ->
torch.cuda.CUDAGraph(), capture_to_graph() -> torch.cuda.graph(...), and
replay_graph(). The only thing holding the path off was the capability flag.
This is the klxpu counterpart of deepspeedai#9007, which wires Intel XPU into the same
opt-in; unlike that backend klxpu needs no new graph methods, only the flag.

Deleting the override is deliberate rather than returning True: klxpu overrides
a CUDA default only where the backend genuinely differs (is_triton_supported,
prefer_triton_grouped_mm both stay False because Triton kernels fault at launch
with CUDA_ERROR_NOT_SUPPORTED). Graph capture does not differ, so inheriting is
the honest statement.

Validated on KUNLUNXIN P800 OAM XPU (torch 2.9.0+cu129, torch_xmlir,
transformers 5.22.2):

  - bare torch.cuda.CUDAGraph() capture + replay returns correct results.
  - tests/unit/v1/test_hybrid_engine_rollout_v1.py: 5 failed -> 23 passed,
    1 skipped. The 5 that failed under the default-deny all assert the graph
    path engaged: four check capture_count == 1 (was 0, eager fallback never
    captured) and test_continuous_graph_generation_refills_a_fixed_slot_on_cuda
    checks the fixed-slot cache stats (peak_cache_length was 5 under eager vs
    the graph path's 4). That last test also only reached klxpu because its
    device_name() == "cuda" guard does not exclude a CUDA-compat backend; with
    capture enabled it passes rather than needing the guard tightened.

Signed-off-by: guhangsong <guhangsong@outlook.com>
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 13, 2026
…tdown (deepspeedai#9009)

## Summary

Keep the continuous-decode graph alive across RL rollout rounds, and add
an explicit way to release it.

| Change | Before | After |
| --- | --- | --- |
| Graph signature | Includes `prompt_len` and every parameter's
`(data_ptr, _version)`. | Keeps the decode batch size, cache length,
device and dtype, plus each parameter's and buffer's address, device,
dtype, shape and strides. Captured kernels read these tensors through
the address and layout fixed at capture, so in-place value updates are
replayed correctly. Replacing a parameter or buffer (for example a
re-registered rotary `inv_freq` or quant scale), or changing its layout
at the same address (for example `transpose_()`), triggers a recapture.
An unindexed device is normalized to the current device index. |
| Width changes | Every new prompt width recaptures, even when
`continuous_cache_capacity` pins the cache length. | With a pinned
capacity, one graph serves all widths that fit. The capacity check still
runs on every call. |
| Rebuild order | The new static cache and graph pool are allocated
while the old state is still alive. | Drop the old state before
allocating its replacement, avoiding overlapping ownership of both
states. |
| `HybridEngineRollout.shutdown()` | No API; the state lives until the
rollout object is collected. | Synchronizes and releases the graph and
static cache. The rollout stays usable and recaptures on the next graph
call. |

`shutdown()` implements the existing `RolloutEngine.shutdown()`
lifecycle hook. It matters for TP>1: in the NCCL reproducer below, a
persistent graph holding captured collectives makes
`destroy_process_group()` hang in `ProcessGroupNCCL.shutdown()`. Call
`shutdown()` on each rank before destroying the process group. The docs
describe reuse and release.

## Why dropping `_version` is safe

- With bf16, DeepSpeed's optimizer writes updated weights through flat
buffers that the parameters view via `.data`, which does not bump
`param._version`. On master, single-width bf16 rollouts already reused
the graph after `engine.step()`, and the replayed outputs changed with
the weights. The version check gave no protection there.
- On paths where a plain torch optimizer updates parameters in place
(for example fp32 ZeRO-0), `_version` changes on every step, so master
recaptured on every rollout round.
- The cases where storage really moves (AutoTP gather/partition or a
`.data =` swap) change `data_ptr`, which stays in the signature.
- A same-address layout change also invalidates the captured kernels.
Shape and strides are in the signature, so this recaptures too. This
also covers `param.data = param.data.t()`, which keeps both `data_ptr`
and `_version` and was therefore missed by the old signature.

## Related work / scope

- Depends on deepspeedai#9008 for TP>1 continuous graph. Without it, TP>1
continuous graph fails at the KV copy before this code matters. The two
PRs touch neighbouring lines in `_get_continuous_graph_state`; whichever
merges second needs a trivial rebase. TP2 results below use deepspeedai#9008 + this
PR.
- Builds on deepspeedai#8732 (persistent continuous graph), reusing its existing
fixed-capacity setting rather than adding another configuration option.
- deepspeedai#8853 only measures graph capture and keeps the version check. Its
`test_continuous_graph_first_call_benchmark_on_cuda` asserts
`capture.call_count == 2` because an in-place SGD step currently forces
a recapture. With this PR that step reuses the graph, so whichever of
the two merges second needs that expectation changed to 1 (and the
benchmark's post-update number no longer includes a recapture). deepspeedai#8786
buckets prefill and does not change graph reuse or release.
- Not covered: ZeRO-3, offload, HybridEngine kernel injection, LoRA
fuse/unfuse inside rollout.

## Validation

### After merging master

Merge `dedd6c840` includes master `a4c989b76`. On 1× NVIDIA L20 (driver
580.173.02, CUDA 13.0, torch 2.14.1+cu130, Transformers 5.17.0), the
tested files matched the merged worktree by SHA-256:

```bash
unset DEEPSPEED_PRETRAINED_ROLLOUT_MODEL
CUDA_VISIBLE_DEVICES=0 DS_ACCELERATOR=cuda OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 \
  HF_HUB_OFFLINE=1 timeout 600 python -m pytest -q -p no:cacheprovider -o addopts= \
  tests/unit/v1/test_hybrid_engine_rollout_v1.py \
  tests/unit/runtime/rollout/test_hybrid_engine_rollout.py tests/unit/utils/test_static_cache.py
# 104 passed, 2 skipped: optional pretrained model and native inference extension

CUDA_VISIBLE_DEVICES=0 DS_ACCELERATOR=cuda OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 \
  HF_HUB_OFFLINE=1 DEEPSPEED_PRETRAINED_ROLLOUT_MODEL=Qwen/Qwen3-0.6B \
  timeout 300 python -m pytest -q -p no:cacheprovider -o addopts= \
  tests/unit/v1/test_hybrid_engine_rollout_v1.py::test_continuous_graph_matches_pretrained_model_when_enabled
# 1 passed, using cached Qwen3-0.6B weights
```

On CPU (AMD EPYC 9575F, 256 logical CPUs visible; Python 3.12.3, torch
2.14.0.dev20260804+xpu):

```bash
DS_ACCELERATOR=cpu OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 python -m pytest -q -p no:cacheprovider -o addopts= \
  tests/unit/runtime/rollout/test_hybrid_engine_rollout.py tests/unit/utils/test_static_cache.py \
  tests/unit/v1/test_hybrid_engine_rollout_v1.py
# 78 passed, 28 skipped (accelerator-only cases and the optional pretrained test)
```

Pre-commit passed on the four PR files after resolving the conflict.

### Earlier validation

**CUDA:** 8× NVIDIA L20 available (1/2/4 devices used below), driver
580.173.02, CUDA 13.0, torch 2.14.1+cu130, Transformers 5.17.0. Base:
`d8241a9ba`. The three tested Python files on L20 have identical SHA-256
hashes to the then-current PR head `55384d86d`.

With `DEEPSPEED_PRETRAINED_ROLLOUT_MODEL` unset:

```bash
CUDA_VISIBLE_DEVICES=0 python -m pytest -q -p no:cacheprovider \
  tests/unit/v1/test_hybrid_engine_rollout_v1.py \
  tests/unit/runtime/rollout/test_hybrid_engine_rollout.py tests/unit/utils/test_static_cache.py
# 61 passed, 2 skipped; exit 0
# Skips: optional pretrained model and native inference kernel unavailable in this invocation.
# Without the layout fix in 55384d8: the two lifecycle tests fail (unit: state reused after
# transpose_(); v1: graph tokens differ from eager after transpose_()).
```

The earlier run (before the layout fix) with the optional pretrained
model enabled and the native inference kernel available:

```bash
CUDA_VISIBLE_DEVICES=0 DEEPSPEED_PRETRAINED_ROLLOUT_MODEL=<Qwen3-0.6B> python -m pytest --forked \
  tests/unit/v1/test_hybrid_engine_rollout_v1.py tests/unit/runtime/rollout/test_hybrid_engine_rollout.py \
  tests/unit/utils/test_static_cache.py
# master + this PR's test files: 4 failed, 59 passed (3 incompatible/new regression tests + 1 pre-existing)
# this PR:            1 failed, 62 passed  (pre-existing only)
# this PR + deepspeedai#9008:    1 failed, 71 passed  (pre-existing only)
```

The pre-existing failure on baseline `d8241a9ba` was the opt-in
`test_continuous_graph_matches_pretrained_model_when_enabled` with
Transformers 5.17 (`'DeepSpeedStaticCache' object has no attribute
'get_query_offset'`, see deepspeedai#8852). The fix is now in master and the opt-in
test passes after the merge, as shown above; the test remains skipped in
CI without the model.

The unit test covers in-place updates, a same-address `transpose_()`,
parameter replacement, capacity changes and `shutdown()` with graph
capture mocked. On a real device the new test runs a tiny Llama with a
fixed capacity and widths 8 → 8 → 12 → 8. It applies an in-place weight
change before round 2 and a same-address `lm_head.weight.transpose_()`
before round 4. Each round matches plain eager token for token, the
output changes after the weight update, and there are exactly 2 captures
(initial + after the layout change). `shutdown()` frees at least the
cache size.

**Review follow-up (`2313079fa`, rebased on master `84481c333`).**
Buffers are now in the signature. The unit test also re-registers a
buffer, and the device test adds a fifth round that re-registers
`model.model.rotary_emb.inv_freq` at half its values: the output still
matches eager, the tokens change, and there are 3 captures. On 1× NVIDIA
L20 (torch 2.14.1+cu130):
`tests/unit/v1/test_hybrid_engine_rollout_v1.py` +
`tests/unit/runtime/rollout/test_hybrid_engine_rollout.py` give 102
passed, 6 skipped. With buffers removed from the signature, the device
test fails on the token comparison after the buffer swap. On 1× Arc Pro
B70 the same files give 71 passed, 37 skipped (graph-capture cases skip
on this XPU stack). Multi-GPU TP and the RL loop below were not rerun
for this change, which only adds buffers to the signature.

**RL loop on L20.** Qwen3-0.6B, TP1, 8 prompts, 4 slots, 32 new tokens,
greedy, 6 rounds. Each round does a graph rollout, then a real
`engine.backward()` + `engine.step()` with AdamW (lr 1e-4). Times are
wall-clock per rollout, including prefill.

| Setup | Captures (6 rounds) | Rollout ms (rounds 2–6) | Peak MiB
(rounds 2–6) |
| --- | --- | --- | --- |
| fp32 ZeRO-0, width 64 — master | 6 | 677–703 | 7069 → 7107 |
| fp32 ZeRO-0, widths 64/96, capacity 160 — this PR | 1 | 546–553 | 7107
/ 7070 alternating |
| bf16, widths 64/96, capacity 160 — master | 6 | 625–1331 | 8188 → 8220
|
| bf16, widths 64/96, capacity 160 — this PR | 1 | 401–542 | 8155 / 8137
alternating |
| bf16, width 64, no capacity — master / this PR | 1 / 1 | 386–388 /
390–396 | unchanged |

After the layout fix, the patched fp32 TP1, bf16 TP1 and fp32 TP2×DP2
runs were repeated: still 1 capture, the same per-round token-match
rates and the same `shutdown()` release. Optimizer steps do not change
parameter shape or strides.

These are exploratory short runs, not a controlled end-to-end speedup
claim. In particular the two fp32 rows use different prompt schedules
and cache capacities. No long-run convergence or training-throughput
claim is made.

**Correctness against plain eager generation.**

- **fp32:** every round is token-identical in the TP1 master and patched
runs, and in the patched TP2×DP2 run (with deepspeedai#9008).
- **bf16, TP1:** rounds 4–6 differ from plain eager after training
steps. The per-round token-match rates are the same on master and this
PR (0.9961 / 0.8984 / 0.9336). This is consistent with
precision-sensitive generation, but does not prove the root cause or
bitwise equivalence of the two graph runs.
- **bf16, TP2×DP2:** the patched run also differs from eager (minimum
match 0.5742 / 0.9805 / 0.9883 / 0.8047). There is no matched unpatched
TP2×DP2 run in this experiment, so this cell is **not validated for
token-exact correctness**.

**Tiny Llama fp32 runs:**

- ZeRO-2, widths 16/24: 1 capture, token-identical on every round.

**Release with TP2** (tiny Llama, deepspeedai#9008 + this PR):

| Exit path | Ranks that returned from `destroy_process_group()` |
| --- | --- |
| No `shutdown()` | 0/2 (killed by the 600 s timeout) |
| `shutdown()` first | 2/2 |

`shutdown()` released 116.5 MiB (Qwen3-0.6B bf16, TP1, capacity 160) and
43.7 MiB on rank 0 (TP2×DP2).

**Intel XPU** (1× Arc Pro B70, Intel compute runtime package
26.27.39122.11, Level Zero loader 1.28.2, torch 2.14.1+xpu, Transformers
5.22.1, on top of deepspeedai#9007, which adds XPU graph capture):

```bash
DS_ACCELERATOR=xpu python -m pytest tests/unit/v1/test_hybrid_engine_rollout_v1.py \
  tests/unit/runtime/rollout/test_hybrid_engine_rollout.py
# deepspeedai#9007 + this PR: 52 passed, 3 skipped; exit 0
# Without the layout fix, the v1 lifecycle test fails: graph tokens differ from eager after transpose_().
```

The earlier torch 2.15.0+xpu run also reported 52 passed / 3 skipped,
but **aborted during interpreter teardown (exit 134)**. A minimal
`torch.ones(16, device="xpu"); torch.xpu.synchronize()` program
reproduces that abort without importing DeepSpeed. It exits normally on
torch 2.14.1+xpu; the clean-exit test run above uses that version. The
earlier deepspeedai#9007-only comparison reached the expected assertion failure (3
captures rather than 1), but its process also used the affected 2.15
runtime.

**CPU:** Python 3.12.3, torch 2.14.0.dev20260804+xpu selected with
`DS_ACCELERATOR=cpu`.

```bash
DS_ACCELERATOR=cpu python -m pytest tests/unit/runtime/rollout/test_hybrid_engine_rollout.py \
  tests/unit/utils/test_static_cache.py tests/unit/v1/test_hybrid_engine_rollout_v1.py
# 57 passed, 6 skipped
pre-commit run --files <changed files>   # passed
```

**Compatibility:** fp32 ZeRO-0 at TP1/TP2/TP2×DP2 and fp32 ZeRO-2 at TP1
are token-exact on CUDA. Single-device fp16 graph inference matches
eager for the tested Qwen3 and tiny Llama cases after the merge.
Single-device fp32 graph tests pass on XPU with deepspeedai#9007. bf16 runs
establish capture/release behavior only; their eager-output
discrepancies are reported above. **Not validated:** ZeRO-1, ZeRO-3,
offload, fp16 training, autocast, quantization, HybridEngine kernel
injection, multi-device XPU graph, pipeline/expert/sequence parallelism,
or training convergence.

AI assistance: GitHub Copilot helped with implementation, documentation,
tests, review and validation. The original signed code commit is
preserved; this PR also includes signed documentation and
layout-signature follow-ups.

---------

Signed-off-by: Jin, Youzhi <youzhi.jin@intel.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@hwchen2017

Copy link
Copy Markdown
Contributor

@delock Can you fix the codex review comments?

@tohtana tohtana removed the needs-gpu-test GPU testing is recommended to validate the changes in this PR. label Nov 14, 2026
@delock

delock commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator Author

@delock Can you fix the codex review comments?

@hwchen2017 thanks for reminding, the codex review comments are verified on xpu device and had been addressed.

Signed-off-by: Ma, Guokai <guokai.ma@intel.com>

# Conflicts:
#	tests/unit/accelerator/test_accelerator_graph.py
Old torch XPU builds (<2.11) do not ship torch.xpu.is_current_stream_capturing
or XPUGraph. The capture hook then raised AttributeError instead of reporting
eager execution, and the graph ops dereferenced a None graph. Return False and
keep the no-op capture/replay behavior for those runtimes, matching the CPU/MPS
eager contract, and document the XPU opt-in condition.

Signed-off-by: Ma, Guokai <guokai.ma@intel.com>
@delock
delock added this pull request to the merge queue Nov 15, 2026
Merged via the queue into deepspeedai:master with commit 92661b2 Nov 15, 2026
21 checks passed
@delock
delock deleted the xpu-graph-capture branch November 15, 2026 06:26
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.

3 participants