Repository navigation
Conversation
29e7658 to
1ffa78a
Compare
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
There was a problem hiding this comment.
💡 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".
0f5e412 to
26190f1
Compare
4×L20 validation (
|
CI-matched L20 rerun updateReran with PyTorch 2.10.0+cu128 and current Transformers This replaces the earlier 5.22.1-specific interpretation. The #9077 graph-reuse and local-KV/mask/repetition-penalty coverage passes. Current |
## 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 <[email protected]> Co-authored-by: Ma, Guokai <[email protected]>
26190f1 to
819ff3b
Compare
Rebased validation (
|
There was a problem hiding this comment.
💡 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".
| 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
There was a problem hiding this comment.
💡 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".
| rollout._continuous_graph_state = continuous_state | ||
| rollout._static_graph_state = static_state |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
There was a problem hiding this comment.
💡 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".
| autocast_enabled = _is_autocast_enabled(device.type) | ||
| autocast_dtype = _get_autocast_dtype(device.type) if autocast_enabled else None |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
There was a problem hiding this comment.
💡 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".
| autotp_size = getattr(self.engine, "autotp_size", None) | ||
| if not callable(autotp_size) or autotp_size() <= 1: | ||
| return local_needs_capture |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| state.graph = None | ||
| state.static_logits = None |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
🟡 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
| # Decode graphs that captured the dropped tensors key on this to recapture. | ||
| model._ki_refresh_generation = getattr(model, "_ki_refresh_generation", 0) + 1 |
There was a problem hiding this comment.
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.
| if hasattr(attn_op, "decode_attn"): | ||
| install_decode_attention(module, write_pos, attn_op, cos_table=cos_t, sin_table=sin_t) |
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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.
… differ in dtype (deepspeedai#9124) Fixes deepspeedai#9102. ## Root cause The issue attributes the failure to caches being created with the parameter dtype. Tracing it on master, the cause is slightly different: under `torch.autocast(dtype=bf16)` an fp32 Llama model produces **keys and values in different dtypes**: - `k_proj`/`v_proj` run under autocast and return bf16. - `apply_rotary_pos_emb` multiplies the bf16 keys by the fp32 `cos`/`sin` (the rotary module runs with autocast disabled), so the keys are promoted back to **fp32**. The values stay **bf16**. Caches that take their dtype from the first keys (fp32) then reject the bf16 values: - `DeepSpeedStaticLayer.update` (continuous-batching decode, with or without graph capture): `Index put requires the source and destination dtypes match, got Float ... BFloat16`. - HF `StaticCache.update`, used for the prefill of the static graph path (`_generate_graph`) and of the continuous paths (`_continuous_prefill_cache`, for models that set `_supports_cache_class`): `index_copy_(): self and source expected to have the same dtype ... Float ... BFloat16`. HF `StaticCache` cannot hold fp32 keys and bf16 values at once, whatever dtype it is allocated in. Allocating the caches in the autocast dtype would not fix this, because the keys really are fp32. ## Change (+27 / -3 in `deepspeed/`) - `DeepSpeedStaticLayer.update`: cast the incoming key/value states to the cache dtype before writing. `.to()` returns the same tensor when the dtypes already match, so graph capture and the non-autocast paths are unchanged. - New `HybridEngineRollout._create_prefill_cache`, used by both prefill sites (`_generate_graph`, `_continuous_prefill_cache`): - Models whose layers are all full attention (no `sliding_window`, every `layer_types` entry `full_attention`) prefill into a lazily sized `DeepSpeedStaticCache`, which is sized from the prefill keys so AutoTP-local KV heads still work. With no write position set, it writes the prompt at `[0, prompt_len)` and gives a single prefill forward the same mask sizes and offsets as a fresh HF `StaticCache`. - All other models keep HF `StaticCache`, exactly as on master. `DeepSpeedStaticCache` models every layer as full attention, so a sliding-window model prefilled into it would silently attend outside the window. Hybrid models also need the HF cache because their GDN slots are bound to its layers (deepspeedai#8602). Model families by path (default configs, transformers 5.12 and 5.23): - Fixed by this PR: Llama, Qwen2/Qwen3, Mixtral, Phi-3, GPT-NeoX. - Unchanged (still fail under fp32-param + bf16 autocast on the cache-prefill paths): Mistral and Gemma 2/3, which default to a sliding window, and Qwen3-Next/Qwen3.5, which have linear-attention layers. ## Behaviour without autocast To check this doesn't change behaviour anywhere else, I ran the same 30 rollout scenarios on master and on this branch and compared the generated tokens (or the raised error): - Models: Llama, sliding-window Mistral, sliding-window Qwen2. - Attention: eager and sdpa. - Paths: static graph, continuous graph, continuous eager, and the continuous paths with `_supports_cache_class`. All 30 are identical. The sliding-window runs use prompts longer than the window, and they still raise the same error they raise on master. ## Tradeoff The cast can also narrow. When the decode cache is allocated eagerly in the parameter dtype and that dtype is narrower than the incoming states (e.g. fp16 parameters under bf16 autocast), keys and values are now rounded to that dtype where master raised an error. That only happens under autocast and matches the model's own parameter precision; I can restrict the cast to widening and raise otherwise if you prefer. ## Relation to other PRs - No other PR references deepspeedai#9102. - deepspeedai#9077 adds the autocast state to the continuous graph signature, which doesn't address this mismatch (as the issue notes). This PR now changes only the two `_create_static_cache` call lines in `_generate_graph` / `_continuous_prefill_cache` there, so any rebase against deepspeedai#9077 should be trivial. - Plain batched `generate()` uses HF `DynamicCache` (concatenation handles mixed dtypes) and already worked. ## Tests Every new test fails on master. Reverting either half of the fix makes some of them fail: | Test | master | cast reverted | prefill routing reverted | this PR | |---|---|---|---|---| | `test_rollout_under_autocast_matches_hf_generate`: 6 cases = {static graph, continuous graph, continuous eager} × {default, `_supports_cache_class=True`}. Greedy rollout of an fp32 tiny Llama under bf16 autocast, token-for-token vs HF `generate()` under the same autocast | 6 fail | 6 fail | 4 fail | 6 pass | | `test_static_layer_accepts_values_in_a_different_dtype_than_keys`: fp32 keys + bf16 values through both write paths (prefill and per-row decode positions) | 2 fail | 2 fail | pass | 2 pass | | `test_prefill_cache_keeps_hf_static_cache_unless_full_attention_only`: routing for full-attention, sliding-window and linear-attention configs | 5 fail | pass | 5 fail | 5 pass | Suites: | Setup | Command | Result | |---|---|---| | 1x NVIDIA T1000 8GB (sm_75), driver 596.51, torch 2.6.0+cu124, transformers 5.12.1, Windows 11, Python 3.11 | `pytest unit/v1/test_hybrid_engine_rollout_v1.py unit/utils/test_static_cache.py unit/runtime/rollout` | 240 passed, 6 failed, 10 skipped | | CPU (WSL2 Ubuntu), torch 2.15.0+cpu, transformers 5.23.0, Python 3.12, pytest 8.3.5, `DS_ACCELERATOR=cpu` | `pytest --forked -n 4 unit/runtime/rollout unit/utils/test_static_cache.py unit/v1/test_hybrid_engine_rollout_v1.py` | 209 passed, 47 skipped | The 6 GPU failures fail on master on the same machine with byte-identical assertion output: - `test_static_graph_uses_prefill_kv_shape[1,2,4]` - `test_static_graph_matches_native_llama_generation[eager]` - `test_decode_repetition_penalty_matches_hf_generate[0.0-True-None]` and `[0.7-True-None]` They look specific to this setup (sm_75 with bf16 emulation, torch 2.6, transformers 5.12). `pre-commit run --files <changed files>` passes. **Not validated:** bf16-native GPUs (sm_80+), fp16 autocast, hybrid (GDN) models, ZeRO-3 / AutoTP rollout under autocast, and multi-GPU. Without a GPU, upstream CI only runs the continuous-eager cases, the static-cache tests and the routing test; the graph-capture cases need a CUDA run. ## AI assistance AI assistance (Claude Code) was used to reproduce the bug, trace the root cause, draft the change and tests, and run the commands above. I reviewed every changed line and ran the tests myself. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: ArchanaChetan07 <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Ma, Guokai <[email protected]>
|
Hi @jinyouzhi thanks for your PR. Here is the review comments with aid of agent. Can you take a look? Thanks! Review — DeepSpeed PR #9077
BlockingB1 — restore the unconditional B2 — on rebase, route all 3 prefill caches through Non-blocking
|
b10865f to
ad73f30
Compare
|
Thanks @delock for the careful review. Pushed 818f327 on top of the rebased head (ad73f30, already on Blocking
Also fixed: the continuous graph path computed Non-blocking
Validation
|
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 <[email protected]>
Signed-off-by: Jin, Youzhi <[email protected]>
Signed-off-by: Jin, Youzhi <[email protected]>
Signed-off-by: Jin, Youzhi <[email protected]>
…n backend and shared segKI state Co-authored-by: iLeGend <[email protected]> Signed-off-by: Jin, Youzhi <[email protected]>
…ph cache after prefill A rollout without segKI skipped refresh_weights() and left segKI out of its graph signature even when another rollout over the same model had installed segment kernels, so an in-place weight sync kept stale derived-weight caches and replayed graphs that read them. Key both on whether the model carries injected kernels. The continuous graph path now captures after the first prefill, so the KV layers are not sized yet when its stats are created; measure cache_memory_bytes after decoding, as the eager path does. Signed-off-by: Jin, Youzhi <[email protected]>
818f327 to
1f5330d
Compare
|
Hi @jinyouzhi , thanks for the followup. The segki_injected fix may bring an unexpected performance overhead described below, with a proposed solution, can you take a look?
|
| Case | Cost per call |
|---|---|
| miss (attribute absent) | 1.29 µs |
hit (plain attribute in __dict__) |
0.075 µs |
A hit is ~17× cheaper than a miss.
3. Because of short-circuiting, cost depends on where the first marker sits
any(hasattr(...) for module in model.modules() for marker in _INJECTION_MARKERS) stops at the first hit. Measured on 1000 modules:
| First marker at | hasattr version |
__dict__ version |
|---|---|---|
| module #5 | 0.04 ms | 0.01 ms |
| module #500 | 4.28 ms | 0.43 ms |
| module #999 | 7.60 ms | 0.98 ms |
| no marker | 8.96 ms | 1.36 ms |
4. Who pays
| Scenario | Calls segki_injected? |
Cost per generate() |
|---|---|---|
use_segki=True rollout |
No (both call sites short-circuit on use_segki) |
0 |
| non-segKI, but the model was injected by another rollout | Yes; the first marker is found early | ~0.04 ms × 2 (negligible) |
| non-segKI, model never injected (default static path) | Yes; full miss scan | ~9 ms × 2 ≈ 18 ms |
The third row is the default path this PR is optimizing. It still wins by an order of magnitude over the recapture it removes, but 18 ms is ~3% of the 0.53 s per-call figure, and it is avoidable.
5. Two fixes
A. Use __dict__ lookups (3 lines, 6.6×)
def segki_injected(model: torch.nn.Module) -> bool:
"""Whether segment kernels run in ``model``'s forwards, whichever rollout installed them."""
return any(any(marker in module.__dict__ for marker in _INJECTION_MARKERS) for module in model.modules())Equivalence requires these markers to be plain attributes that setattr puts in __dict__ (op handles, tensors, ints). Parameter / Module values go to _parameters / _modules instead, and segKI does not store any of those under these names.
B. Set one model-level flag at install time (O(1))
After apply_segment_ki / each install_* succeeds, set model._ki_injected = True; segki_injected becomes getattr(model, "_ki_injected", False). Semantically cleaner, but every injection path must remember to set it — the same direction as the registered-callback work in #9109.
6. Reproduction
import timeit, torch
MARKERS = ("_ki_dual_op", "_ki_gdn_op", "_ki_attn_op", "_ki_qkv_op", "_ki_norm_op", "_ki_gemm_op")
scan = lambda m: any(hasattr(mod, mk) for mod in m.modules() for mk in MARKERS)
scan_dict = lambda m: any(any(mk in mod.__dict__ for mk in MARKERS) for mod in m.modules())
model = torch.nn.Sequential(*[torch.nn.Linear(8, 8) for _ in range(1000)])
print(timeit.timeit(lambda: scan(model), number=50) / 50) # ~8.96 ms
print(timeit.timeit(lambda: scan_dict(model), number=50) / 50) # ~1.36 ms
lin = torch.nn.Linear(4, 4); lin._ki_attn_op = object()
print(timeit.timeit(lambda: hasattr(lin, "_ki_attn_opX"), number=200000) / 200000) # ~1.29 us (miss)
print(timeit.timeit(lambda: hasattr(lin, "_ki_attn_op"), number=200000) / 200000) # ~0.075 us (hit)Environment: local CPU, torch 2.12.1+cpu. The absolute numbers are host-side Python overhead, which is where this code runs, so they carry over to a GPU host; only the module count changes (~500–800 for a 7B model, ~200–300 for a 0.8B one).


Summary
The default graph path (
use_graph_capture=Truewithoutcontinuous_batch_size) builds a newDeepSpeedStaticCache, runs three warmup forwards and captures a new graph on everygenerate()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.
generate()callmax_new_tokens, device, dtype, parameter layout, training mode, autocast, b=1 step-kernel use, or asegki_refresh()sync_weights()/refresh_weights()/segki_refresh()force a recapture, because the injected kernels cache tensors derived from the weightsshutdown()segKI (#8602)
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.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()andrefresh_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 (Qwen3RMSNormhas noepsin Transformers 5.17;torch.get_acceleratormissing 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
This PR was prepared with AI assistance (GitHub Copilot); I reviewed and tested the changes.