Skip to content

Reuse the static rollout decode graph across calls - #9077

Open
jinyouzhi wants to merge 5 commits into
deepspeedai:masterfrom
jinyouzhi:static-graph-reuse
Open

jinyouzhi wants to merge 5 commits into
deepspeedai:masterfrom
jinyouzhi:static-graph-reuse

Conversation

@jinyouzhi

@jinyouzhi jinyouzhi commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The default graph path (use_graph_capture=True without continuous_batch_size) builds a new DeepSpeedStaticCache, runs three warmup forwards and captures a new graph on every generate() call. In an RL loop that is a fixed cost per rollout round, although the decode graph depends only on the decode shape.

This PR keeps the static path's graph and cache across calls, as #8732 / #9009 do for the continuous path. Rebased onto master after #9127 merged, so the #9126 correctness fixes are inherited rather than duplicated. The remaining patch is focused on static graph reuse and segment-KI lifecycle.

Before After
Per generate() call Allocate cache, 3 warmups, capture Eager prefill; replay the retained graph
Recapture trigger Every call Graph signature changes: batch size, prompt width + max_new_tokens, device, dtype, parameter layout, training mode, autocast, b=1 step-kernel use, or a segki_refresh()
In-place weight updates n/a Without segKI: replayed without recapture. With segKI: sync_weights() / refresh_weights() / segki_refresh() force a recapture, because the injected kernels cache tensors derived from the weights
AutoTP n/a Ranks agree on recapture with an all-reduce, so no rank captures while its peers replay
shutdown() Releases the continuous state Releases both states

segKI (#8602)

  • The segKI kernels are installed once per capture. Hybrid (GDN) models keep the HF prefill cache that the decode cache's GDN slots are bound to, so the graph's state addresses stay fixed across calls.
  • segki_refresh() bumps a counter in the graph signature, so a graph that captured the freed derived tensors is never replayed. refresh_weights() additionally releases it right away.
  • Making segKI graphs survive a weight sync needs the derived tensors refilled in place (including the backend GLU concat cache). Left for a follow-up.

Relationship to #9127

#9127 independently fixed the post-#8602 local-KV, additive-mask, and repetition-penalty regressions. This PR is rebased on top of that merged fix and drops duplicate correctness hunks. The following checks remain part of the graph-reuse validation:

  • test_static_graph_uses_prefill_kv_shape: the decode cache is sized from the prefill's local KV tensors again (Size HybridEngine rollout KV caches from local prefill shapes under AutoTP #9008), not from the config divided by world size.
  • test_static_graph_matches_native_llama_generation[eager]: eager attention adds the mask to the scores, so it gets an additive mask built inside the graph from the boolean one.
  • test_decode_repetition_penalty_matches_hf_generate: the repetition penalty is applied on the graph prefill and Python decode paths again; the b=1 step kernel is used only without a penalty.

Tests

  • test_static_graph_is_reused_across_rollouts_with_the_same_decode_shape (Llama): capture once per decode shape, in-place update changes the tokens without recapture, train mode and autocast force recapture, shutdown() frees the cache.
  • TestAutoTPGraphRecapture (2 GPUs): ranks recapture together.
  • test_graph_reused_until_refresh[1, 2] (Qwen3.5-0.8B, segKI): one capture across two rollouts with the same tokens; segki_refresh() and refresh_weights() each force one recapture with the same tokens.

4× NVIDIA L20, torch 2.14.1+cu130, Transformers 5.17.0, test_segment_ki_kernels.py, test_graph_position_regression.py, runtime/rollout/test_hybrid_engine_rollout.py, v1/test_hybrid_engine_rollout_v1.py: 220 passed, 3 skipped, 3 failed. The 3 failures fail the same way on master on this machine (Qwen3RMSNorm has no eps in Transformers 5.17; torch.get_accelerator missing in this torch). Master on the same files: 6 more failures (listed above).

Qwen3.5-0.8B, segKI + graph, prompt 128, 128 new tokens, greedy: tokens identical to master at b=1 and b=4; per-call time 0.63 → 0.53 s (b=1) and 0.76 → 0.65 s (b=4) from skipping the recapture.

Not covered

  • Keeping segKI graphs across a weight sync (see above).
  • A pinned cache capacity so different total lengths share one graph.
  • ZeRO-3, offload, HybridEngine kernel injection.

This PR was prepared with AI assistance (GitHub Copilot); I reviewed and tested the changes.

@tohtana tohtana added the needs-gpu-test GPU testing is recommended to validate the changes in this PR. label Nov 13, 2026
@tohtana tohtana removed the needs-gpu-test GPU testing is recommended to validate the changes in this PR. label Nov 14, 2026
@jinyouzhi
jinyouzhi marked this pull request as ready for review November 15, 2026 07:00
@chatgpt-codex-connector

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

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-21T20:09:58.937022Z b609ef9 Manual request
ℹ️ 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: 968022173a

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

@jinyouzhi
jinyouzhi marked this pull request as draft November 17, 2026 08:53
@jinyouzhi
jinyouzhi marked this pull request as ready for review November 17, 2026 12:41

@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: 56ffdb3198

ℹ️ 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 on lines +1021 to +1022
return (id(module), module.training, device.type, device_index, model_dtype, max_batch_size, max_cache_len,
tensor_signature)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Recapture graphs when autocast changes

When the newly retained static graph is reused across different autocast contexts (for example, first under torch.autocast('cuda', dtype=torch.bfloat16) and later with autocast disabled), every field in this signature remains unchanged because model_dtype is only the parameter dtype. Graph replay bypasses autocast dispatch and continues running the kernels captured under the first context, while the eager prefill follows the current context, so decode can silently use the wrong precision; include the accelerator autocast enabled state and dtype in the shared signature so both graph paths recapture.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 0f5e412: the autocast enabled state and dtype are now part of the shared graph signature, so both graph paths capture again when they change. The reuse test runs a bf16 copy of the model with and without bf16 autocast and expects a new capture; it fails without the change (autocast still switches kernels at the model's own dtype, e.g. softmax in fp32).

@jinyouzhi

Copy link
Copy Markdown
Contributor Author

4×L20 validation (26190f126)

Hardware/software: 4× NVIDIA L20, driver 580.173.02; PyTorch 2.15.0+cu132; CUDA toolkit 13.0; Transformers 5.22.1. Used a clean checkout and:

CUDA_VISIBLE_DEVICES=0,1,2,3 DS_ACCELERATOR=cuda OMP_NUM_THREADS=1 HF_HUB_OFFLINE=1 \
python -m pytest -q -p no:cacheprovider -o addopts= \
  tests/unit/module_inject/test_segment_ki_kernels.py \
  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 \
  -k 'not TestAutoTPContinuousRollout and not TestGlobalWorkRemainingSubgroups and not TestZero3SubgroupGeneration and not TestZero3SynchronizedEarlyStop and not TestAutoTPGraphRecapture'
# 228 passed, 8 skipped, 1 failed, 7 deselected

The one failure is unrelated to #9077: with Transformers 5.22.1, Qwen3RMSNorm no longer exposes .eps, causing test_glu_only_model_refresh_clears_backend_cat_cache to fail before its refresh assertion. Native kernel reference tests and the new static graph reuse/correctness tests passed.

The seven distributed cases were deselected after the same host hit the 600-second DistributedTest watchdog and CUDA_ERROR_DEVICE_UNAVAILABLE during teardown on both GPU pairs. No #9077 assertion failed before that infrastructure teardown.

@jinyouzhi

Copy link
Copy Markdown
Contributor Author

CI-matched L20 rerun update

Reran with PyTorch 2.10.0+cu128 and current Transformers main at 4bb61661e15e65c135839acfb8ed0781605aabe2 (5.24.0.dev0), on 4× L20 / driver 580.173.02.

rollout + cache matrix: 206 passed, 3 skipped, 7 deselected

This replaces the earlier 5.22.1-specific interpretation. The #9077 graph-reuse and local-KV/mask/repetition-penalty coverage passes. Current transformers/main now exposes a newer segKI integration incompatibility (past_key_values / cache duplicated at Qwen3Attention.forward), which is separate from #9077. Full native-kernel coverage was limited because the host has no CUDA 12.8 nvcc; distributed cases were excluded because this shared host's DistributedTest jobs hit the 600-second watchdog during teardown.

banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 21, 2026
## Summary

Fixes deepspeedai#9126.

- Size the static rollout KV cache from the actual local prefill tensors
instead of guessed global/TP head counts.
- Pass an additive 4-D mask to eager/SDPA attention while retaining a
separate boolean mask for the captured step kernel.
- Apply repetition penalties on the static graph path, reset
capture-time mask mutations before replay, and restrict the full-step
kernel to the single-row, unpenalized greedy fast path.

## Root cause

The segment-KI rollout change eagerly initialized `DeepSpeedStaticCache`
from global configuration head counts. That allocation can disagree with
AutoTP's local KV heads, causing either a copy shape failure or silent
wrong-token generation. The same change also passed a boolean 4-D mask
directly to attention implementations that expect additive masks, while
graph/Python token selection bypassed the repetition penalty. Together
these account for the nightly static-graph failures in
`tests/unit/v1/test_hybrid_engine_rollout_v1.py`.

The batched graph step did not need the full-step argmax kernel because
Python already selects each row's token. The kernel is now explicitly
limited to batch size one; the b=1 EOS check remains amortized over 16
replays because at most 15 trailing steps are padded away, avoiding a
synchronization on every replay. Batched decoding continues checking
after every step because its dead work is multiplied by the number of
active rows.

## Duplicate-work check

deepspeedai#9077 is primarily a static graph-reuse performance PR, not the
dedicated deepspeedai#9126 fix, but its rebase onto deepspeedai#8602 independently absorbed
the same local-KV, additive-mask, and repetition-penalty corrections
while preserving that performance work. deepspeedai#9127 remains the isolated
hotfix for the nightly regression. If deepspeedai#9127 is merged first, deepspeedai#9077
should rebase onto it and drop the duplicated correctness hunks; its
remaining scope is graph reuse and lifecycle. deepspeedai#9079 is stacked on deepspeedai#9077
and separately handles whole-step graph capture, including replacement
of the Python token-history loop.

## Validation

Hardware: 1x Intel Arc Pro B70 (16 devices visible), Level Zero XPU;
driver version is not exposed by the environment. Software: torch
`2.14.0.dev20260804+xpu`, Transformers `5.17.0`.

```bash
python -m pytest -q -p no:cacheprovider -o addopts= \
  tests/unit/utils/test_static_cache.py \
  'tests/unit/v1/test_hybrid_engine_rollout_v1.py::test_static_graph_attention_mask_uses_additive_values' \
  'tests/unit/v1/test_hybrid_engine_rollout_v1.py::test_static_graph_uses_prefill_kv_shape' \
  'tests/unit/v1/test_hybrid_engine_rollout_v1.py::test_static_graph_full_step_kernel_preconditions' \
  'tests/unit/v1/test_hybrid_engine_rollout_v1.py::test_static_graph_matches_native_llama_generation[eager]'
# 26 passed in the combined focused set

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

The broad two-file run produced 34 passes and 17 skips before the added
direct regressions; its remaining failures were unsupported Level Zero
SDPA/distributed operations (`UR_RESULT_ERROR_UNSUPPORTED_FEATURE`), not
assertion regressions in the changed path.

The new direct regressions assert that visible positions are additive
zero and masked positions are `finfo.min`, and that the full-step kernel
is not mounted for repetition penalties or batched decode. Existing
end-to-end tests compare generated tokens against Hugging Face and cover
the penalty result on CUDA CI.

## Compatibility coverage

- Validated: static graph replay on Intel XPU; AutoTP-like local KV head
counts 4/2/1; eager Llama attention; greedy decoding; additive mask
values; full-step-kernel preconditions; cache replay/position/compaction
contracts.
- Not validated locally: NVIDIA CUDA, SDPA on CUDA, ROCm,
sampled/repetition-penalty end-to-end rollout on a CUDA device,
Hybrid/linear-attention models, and multi-rank AutoTP. These require
hardware/backend coverage outside this environment.
- ZeRO stage/offload are not affected. No public API, config,
checkpoint, convergence, throughput, or peak-memory behavior is changed.

The per-step `torch.cat` used by repetition penalty remains O(n²),
matching the existing continuous rollout implementation. Optimizing only
this static path is small (roughly 30–60 minutes plus a focused test),
but unifying it with variable-length continuous rollout would take
roughly 2–4 hours and require broader compaction/padding/CUDA
validation. It is intentionally deferred from this correctness fix and
can be handled as a small follow-up performance PR, primarily benefiting
`repetition_penalty != 1`; the default penalty path is unaffected.

AI assistance was used for investigation, implementation, and test
preparation; the submitting human reviewed the final diff and is
responsible for the DCO sign-off.

---------

Signed-off-by: Jin, Youzhi <youzhi.jin@intel.com>
Co-authored-by: Ma, Guokai <guokai.ma@gmail.com>
@jinyouzhi
jinyouzhi marked this pull request as ready for review November 21, 2026 17:38
@jinyouzhi

Copy link
Copy Markdown
Contributor Author

Rebased validation (819ff3b8)

Rebased onto master after #9127 merged; the duplicate #9126 hunks were removed from the patch. With PyTorch 2.10.0+cu128 and Transformers main at 4bb61661e15e65c135839acfb8ed0781605aabe2 (5.24.0.dev0) on 4× NVIDIA L20 / driver 580.173.02:

rollout + cache matrix: 209 passed, 3 skipped, 7 deselected

The graph-reuse, local-KV, additive-mask, repetition-penalty, and prebuilt-mask replay checks pass on the rebased head. Distributed classes remain deselected because this shared host's DistributedTest processes hit the 600-second teardown watchdog in earlier runs.

@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: 819ff3b8e0

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

# Replay keeps the kernels of the mode it was captured in, e.g. dropout,
# and of the autocast precision active at capture.
autocast_enabled = _is_autocast_enabled(device.type)
autocast_dtype = _get_autocast_dtype(device.type) if autocast_enabled else None

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 Fall back to legacy autocast getters on PyTorch 2.0–2.3

When either graph path runs inside autocast on supported PyTorch 2.0–2.3 (requirements/requirements.txt:10 allows torch>=2.0.0), the newly added _get_autocast_dtype call reaches an absent torch.get_autocast_dtype attribute and that helper only catches TypeError, so signature construction raises AttributeError before generation. The existing compatibility helper in deepspeed/sequence/linear_cross_entropy.py:97-111 explicitly treats the unified getter as PyTorch 2.4+ and falls back to per-device getters; use an equivalent fallback for both graph paths here.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 6bfe9e9. _get_autocast_dtype now catches both AttributeError and TypeError and falls back to the PyTorch 2.0–2.3 CUDA getter names (get_autocast_gpu_dtype / get_autocast_cuda_dtype); _is_autocast_enabled uses the corresponding legacy CUDA fallback as well. Added a focused test that simulates the legacy API. CPU test: 3 passed; pre-commit passed.

autocast_dtype = _get_autocast_dtype(device.type) if autocast_enabled else None
# segki_refresh frees the injected kernels' derived-weight tensors, which
# a graph captured before it would still read.
segki_generation = getattr(module, "_ki_refresh_generation", 0)

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 graph reuse after non-segKI weight syncs

When the standard rollout loop calls sync_weights() after an in-place update with the default use_segki=False, refresh_weights() still invokes segki_refresh(), which increments _ki_refresh_generation; including that counter unconditionally here makes the same-shape signature differ on the next call. In particular, the newly retained static graph is discarded and pays the warmups and capture again after every training step, contrary to the non-segKI live-weight contract, so gate this generation on segment injection while applying the same decision consistently to the continuous sibling.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 6bfe9e9. refresh_weights() now returns immediately when segKI is disabled, and the shared graph signature includes _ki_refresh_generation only for segKI rollouts. SegKI-enabled sync still follows the existing #9130 refresh/lifecycle contract: release retained graphs, then call segki_refresh(). Added unit coverage for preserved graph states and extended the static reuse test to call sync_weights() after an in-place parameter update; 4×L20 validation: 2 graph-reuse tests passed.

@jinyouzhi

Copy link
Copy Markdown
Contributor Author

@codex review

@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: 6bfe9e92bc

ℹ️ 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 on lines +1869 to +1870
state = self._get_static_graph_state(module, batch_size, max_len, device, model_dtype, is_hybrid,
use_step_kernel)

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 Revalidate tensor addresses after eager prefill

When two requests have the same prompt_len + max_new_tokens, _get_static_graph_state can accept the retained graph here before the prompt forward runs. If that eager prefill lazily replaces a registered tensor—for example, a rotary cos/sin or dynamic inv_freq buffer when a wider prompt grows its cache—the replay still dereferences the old address (which may already have been freed), so decode can return corrupted tokens even though prefill used the new buffer. Recompute and compare the signature after prefill and recapture if it changed; the continuous sibling also chooses and captures its graph before its prefills and needs the same safeguard.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in c5abe9f. Static generation now compares the graph signature again after eager prefill and recreates/re-prefills the retained state when a module tensor address changed. Continuous graph state defers its initial capture until the first admission prefill, then revalidates after each admitted prefill and recaptures in-place at an unused cache position if the signature changed. Added public static/continuous tests that replace the rotary buffer during prefill and assert one recapture with token parity; 4×L20: 4 graph/reuse cases passed.

Comment on lines +1652 to +1653
rollout._continuous_graph_state = continuous_state
rollout._static_graph_state = static_state

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 Exercise sync through public rollout behavior

This test writes sentinel objects directly into _continuous_graph_state and _static_graph_state and then requires those private objects to survive by identity, so a correct refactor that changes the state representation would fail even when sync_weights() still avoids recapture and returns correct generations. Exercise generate/sync/generate through the public rollout behavior (or consolidate with the accelerator-backed reuse test) instead, as repository tests must verify contracts through stable interfaces rather than internal slots.

AGENTS.md reference: AGENTS.md:L76-L80

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in c5abe9f. Removed the private-state identity assertion. The existing accelerator-backed continuous graph test now calls sync_weights() through the public rollout API between generate calls and still requires identical output plus one retained capture. CPU contract tests and 4×L20 graph reuse tests pass.

@jinyouzhi

Copy link
Copy Markdown
Contributor Author

@codex review

@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: c5abe9fc7c

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

prefill_out = run_prefill(prefill_cache)
post_prefill_signature = self._graph_signature(module, batch_size, max_len, device,
model_dtype) + (use_step_kernel, )
if state.signature != post_prefill_signature:

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 Synchronize post-prefill recapture across AutoTP ranks

When AutoTP is active and only one rank's eager prefill replaces a registered tensor, only that rank enters this conditional and then _get_static_graph_state() executes the recapture all-reduce, while its peers skip the collective and continue toward replay. The mismatched collective sequence can hang generation; all-reduce the post-prefill mismatch before branching, as the continuous path does. This newly added post-prefill branch is fresh evidence beyond the earlier fixed pre-prefill decision.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in b609ef9. The post-prefill signature mismatch is now reduced across the AutoTP group before either recreating static state or replaying, so no rank can enter the recapture collective alone. Static and continuous paths use the same coordination rule; 4×L20 post-prefill recapture tests passed.

Comment on lines +1150 to +1151
autocast_enabled = _is_autocast_enabled(device.type)
autocast_dtype = _get_autocast_dtype(device.type) if autocast_enabled else None

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 Disable cached AMP weight casts for retained graphs

With FP32 parameters under an outer CUDA autocast context using the default weight cache, eager prefill populates temporary low-precision parameter casts and capture records kernels against those tensors. The cache is discarded when that autocast context exits, but a later context with the same enabled state and dtype passes this signature and both retained graph paths can replay freed/stale cast addresses; in-place parameter updates also never reach those copies. Capture with the autocast weight cache disabled, or avoid retaining such graphs across autocast contexts.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in b609ef9. Warmup and graph capture now run under _disable_autocast_weight_cache(), so retained static/continuous graphs no longer capture autocast-owned low-precision parameter casts. The previous cache setting is restored in finally; added a unit test for restoration.

post_prefill_signature = self._graph_signature(module, batch_size, max_len, device,
model_dtype) + (use_step_kernel, )
if state.signature != post_prefill_signature:
self._static_graph_state = None

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 Drop post-prefill locals before allocating replacement state

When a hybrid model's eager prefill changes a registered tensor and triggers this retry, the local state, prefill_cache, and prefill_out still retain the old graph, decode cache, and HF prefill cache while _get_static_graph_state() eagerly creates the replacement hybrid prefill cache. That transient extra full cache can OOM near-capacity rollouts even though either state fits alone; clear the stale locals before constructing the replacement. This new post-prefill retry is fresh evidence beyond the earlier fixed shape-change path.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in b609ef9. Before allocating replacement static state after a post-prefill mismatch, the old prefill_out, prefill_cache, and local state references are cleared. Allocation therefore no longer retains the old graph/HF caches concurrently; the public static/continuous recapture tests pass.

# segki_refresh frees the injected kernels' derived-weight tensors, which
# a graph captured before it would still read.
segki_generation = getattr(module, "_ki_refresh_generation", 0) if self.use_segki else 0
return (id(module), module.training, autocast_enabled, autocast_dtype, device.type, device_index, model_dtype,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Include child-module modes in the graph signature

When a caller changes only a child module's mode, such as putting a Dropout or BatchNorm block in eval mode while leaving the root model in training mode, module.training and every tensor field here remain unchanged. The eager prefill follows the child's new branch, but decode replays the graph captured under its old mode and silently produces inconsistent results; include the training flags of module.modules() in the signature.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in b609ef9. The shared graph signature now includes the training state of every child module, not only the root module. The reuse test changes one decoder-layer mode and verifies a recapture; 4×L20 validation passed.

@jinyouzhi

Copy link
Copy Markdown
Contributor Author

@codex review

@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: b609ef9978

ℹ️ 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 on lines +1180 to +1182
autotp_size = getattr(self.engine, "autotp_size", None)
if not callable(autotp_size) or autotp_size() <= 1:
return local_needs_capture

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 Coordinate recapture over HybridEngine inference TP

When graph capture wraps a DeepSpeedHybridEngine configured with hybrid_engine.inference_tp_size > 1 but the default autotp_size == 1, this early return leaves recapture rank-local. Fresh evidence beyond the earlier AutoTP fix is that create_inference_module() creates a separate engine.mp_group for this mode (deepspeed/runtime/hybrid_engine.py:387-420), not the AutoTP group checked here. If only one shard's signature moves, that rank executes warmup/capture forwards containing inference-TP collectives while its peers replay, so the group can hang; reduce over engine.mp_group (or reject this combination) too.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in b10865f. The recapture decision is now reduced over every tensor-parallel group the decode forward runs collectives on: the AutoTP group when autotp_size() > 1, and the DeepSpeedHybridEngine's own mp_group when inference_tp_size > 1. Added a CPU test that a peer's change on the hybrid engine's inference-TP group makes this rank capture too.

Comment on lines +992 to +993
state.graph = None
state.static_logits = None

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 Drop old continuous graph locals before recapture

When an admitted prefill replaces a registered tensor after a continuous graph already exists, clearing only these state fields does not release the old graph or output because the local graph and static_logits variables assigned at lines 925-926 still reference them until the right-hand-side capture returns. On a near-capacity model, the replacement graph pool and logits are therefore allocated alongside the old ones and can OOM; clear those locals before _capture_continuous_graph(), as the static retry does.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in b10865f. The continuous recapture now clears the local graph/static_logits together with the state fields before _capture_continuous_graph(), so the old graph pool and logits are released before their replacement is allocated.

Comment on lines +1171 to +1172
return (id(module), module.training, autocast_enabled, autocast_dtype, device.type, device_index, model_dtype,
max_batch_size, max_cache_len, segki_generation, module_modes, tensor_signature)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Include inference mode in the graph signature

When a same-shape static rollout is first called under torch.inference_mode() and later called without it, every field in this signature still matches even though the persistent cache and static buffers were allocated as inference tensors. The second call reaches state.cache.reset() and subsequent zero_/copy_ operations outside inference mode, which PyTorch rejects with an "Inplace update to inference tensor outside InferenceMode" runtime error; key retained state on torch.is_inference_mode_enabled() or allocate the persistent buffers outside inference mode.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in b10865f. The shared graph signature now includes torch.is_inference_mode_enabled(), so state allocated under inference_mode() is recreated instead of being updated in place outside it. Covered by a CPU signature test.

Comment on lines +1171 to +1172
return (id(module), module.training, autocast_enabled, autocast_dtype, device.type, device_index, model_dtype,
max_batch_size, max_cache_len, segki_generation, module_modes, tensor_signature)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Include the attention implementation in the signature

When an existing model's _attn_implementation is switched between eager and sdpa between same-shape calls, this signature remains unchanged, so eager prefill uses the new implementation while decode replays the old implementation and the boolean-versus-additive mask construction selected in _capture_static_graph(). This silently ignores the requested backend and can change decode results; include the attention implementation in the shared graph signature.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in b10865f. The shared graph signature now includes config._attn_implementation, so switching between eager and sdpa recaptures with the matching backend and mask format. Covered by a CPU signature test.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Cache eviction and decode-attention reinstallation can leave retained graphs valid after their backing storage is freed, creating critical replay hazards across models and shared-model rollout instances.

3 open issues
What changed in this PR

Extends persistent decode-graph reuse from continuous batching to static HybridEngine rollouts, reducing repeated warmup and capture work between rollout rounds while keeping prompt prefill eager.

Changes:

  • Retains static graphs and caches, with signature-based recapture and explicit shutdown cleanup.
  • Coordinates AutoTP recapture and connects segment-kernel weight refreshes to graph invalidation.
  • Adds reuse and lifecycle regression tests, updates documentation, and improves legacy autocast compatibility.
File Description
tests/​unit/​v1/​test_hybrid_engine_rollout_v1.py Tests graph reuse, coordinated AutoTP recapture, prefill tensor replacement, and cleanup.
tests/​unit/​runtime/​rollout/​test_hybrid_engine_rollout.py Tests autocast compatibility and cache-setting restoration; updates weight-sync coverage.
tests/​unit/​module_inject/​test_segment_ki_kernels.py Tests segment-kernel graph reuse and recapture after weight refresh.
docs/​code-docs/​source/​inference-engine.rst Documents graph reuse, resource lifetime, and segment-kernel refresh requirements.
deepspeed/​runtime/​zero/​linear.py Expands compatibility with legacy autocast getters.
deepspeed/​runtime/​rollout/​hybrid_engine_rollout.py Implements persistent static graph state, recapture coordination, and lifecycle cleanup.
deepspeed/​module_inject/​segment_ki.py Adds a refresh generation counter for graph invalidation.

Review effort: Balanced

Comment on lines +762 to +763
# Decode graphs that captured the dropped tensors key on this to recapture.
model._ki_refresh_generation = getattr(model, "_ki_refresh_generation", 0) + 1

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in b10865f. segki_refresh() now advances a process-wide backend generation whenever it empties the backend's GLU concat cache, and every segKI graph signature includes it alongside the model's own generation. Refreshing model B therefore invalidates model A's retained graphs too. Added a CPU test.

Comment on lines +2195 to +2196
if hasattr(attn_op, "decode_attn"):
install_decode_attention(module, write_pos, attn_op, cos_table=cos_t, sin_table=sin_t)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in b10865f. Before reinstalling the decode kernels, static capture advances the model's _ki_refresh_generation, and after the install (including a failed or partial one) it records the updated signature on the capturing state. Another rollout over the same model then sees a changed signature and recaptures, while the capturing rollout keeps replaying.

f"{(out_refreshed != out_fresh).sum().item()} of {out_fresh.numel()} tokens differ")

@pytest.mark.parametrize("batch_size", [1, 2])
def test_graph_reused_until_refresh(self, batch_size, monkeypatch):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added in b10865f: tests/unit/v1/test_hybrid_engine_rollout_v1.py::test_segki_graphs_recapture_after_refresh_or_a_shared_model_reinstall. Two segKI rollouts share a tiny Llama; the test checks token parity with HF generate and the capture count across replay, a second rollout's reinstall, and refresh_weights(). It needs no downloaded model, so it runs in the v1 suite.

jinyouzhi and others added 5 commits November 22, 2026 01:38
Rebase the static-graph reuse onto the segment-KI decode path from deepspeedai#8602.

- Keep the DeepSpeedStaticCache, decode inputs and captured graph across
  generate() calls with the same decode signature (batch, cache length,
  device, dtype, parameter layout, training mode, autocast, step-kernel
  use). AutoTP ranks agree on recapture through an all-reduce.
- Without segKI, in-place weight updates are replayed without recapture.
  With segKI, segki_refresh() bumps a generation in the signature and
  refresh_weights()/sync_weights() release the graphs, because the
  injected kernels cache tensors derived from the weights.
- Size the decode KV cache from the prefill's local KV tensors again, so
  AutoTP-sharded and narrowed-head models get the right shape.
- Apply the repetition penalty on the graph prefill and Python decode
  paths again; the b=1 step kernel is used only without a penalty.
- Give eager attention an additive mask built inside the graph from the
  boolean decode mask.

Signed-off-by: Jin, Youzhi <youzhi.jin@intel.com>
Signed-off-by: Jin, Youzhi <youzhi.jin@intel.com>
Signed-off-by: Jin, Youzhi <youzhi.jin@intel.com>
Signed-off-by: Jin, Youzhi <youzhi.jin@intel.com>
…n backend and shared segKI state

Co-authored-by: iLeGend <824040212@qq.com>
Signed-off-by: Jin, Youzhi <youzhi.jin@intel.com>

This branch has not been deployed

No deployments
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