Skip to content

Support Transformers 5.20 cache query offsets in DeepSpeedStaticCache - #8852

Merged
delock merged 4 commits into
deepspeedai:masterfrom
nathon-lee:fix/static-cache-query-offset
Nov 5, 2026
Merged

delock merged 4 commits into
deepspeedai:masterfrom
nathon-lee:fix/static-cache-query-offset

Conversation

@nathon-lee

@nathon-lee nathon-lee commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Background

Native Llama continuous rollout on Transformers 5.20.1 failed because DeepSpeedStaticCache lacked get_query_offset(layer_idx). The query offset must exclude the current write; using get_seq_length() would be off by one.

Changes

Implemented and validated on fix/static-cache-query-offset:

  • Added layer and cache query-offset methods: zero when unset, the scalar write position otherwise, or the maximum per-row position with row validity handled by attention masks.
  • Preserved cache-length and KV-write behavior without capture-time host synchronization.
  • Added independent masking and CUDA replay regressions, plus native Llama generation comparisons covering eager / SDPA attention, padding, slot refill, and graph reuse.

Validation

RTX A4500 (20 GiB), PyTorch 2.9.1+cu128 / CUDA 12.8, FP16:

Transformers Results
5.20.1 76 passed, 1 skipped
4.57.6 73 passed, 4 skipped

Actual CUDA capture/replay passed. Randomly initialized tiny Llama rollouts matched native generate() tokens, attention masks, and response offsets. Both versions skipped the optional pretrained-model test; 4.57.6 also skipped three tests requiring the newer masking API. Modified-file pre-commit checks passed.

Run in each Transformers environment:

python -m pytest \
    tests/unit/utils/test_static_cache.py \
    tests/unit/runtime/rollout/test_hybrid_engine_rollout.py \
    tests/unit/runtime/rollout/test_continuous_batching.py \
    tests/unit/v1/test_hybrid_engine_rollout_v1.py -q

Scope and dependencies

Depends on the cache code from #8732, not the benchmark. Changes are limited to compatibility, tests, and documentation; this does not claim full Transformers 5.20 cache API support. Issue 1 depends on this fix in the tested 5.20.1 environment.

CC @delock

banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 1, 2026
…elerators (deepspeedai#8933)

## Summary

The HybridEngine graph-capture paths (per-position decode graphs from
deepspeedai#8271 and the continuous-rollout graphs from deepspeedai#8732) were gated on CUDA
in several places: a device-name check, an input device-type check, and
hard-coded "CUDA graph" naming. This PR replaces them with accelerator
capability hooks so any backend that implements graph capture
(`create_graph()` returning a graph, `capture_to_graph`, `replay_graph`,
and `is_current_stream_capturing`) takes the same code path as CUDA.

Two accelerator-specific fixes ride along to make the NPU path actually
work:

* NPU inference attention switches to the graph-mode flash attention
variant (`npu_fusion_attention_v3`): the v1/v2 variants launch work on
an internal secondary stream that CANN capture rejects at `capture_end`
(error 107025).
* The NPU inference shim grows its KV-cache table on demand: `layer_id`
is derived from `DeepSpeedSelfAttention.num_layers`, a process-wide
counter that only ever grows, so any process that builds a second engine
would otherwise index out of bounds.

## Design

**Capability gates instead of name gates.**
`validate_cuda_graph_support` becomes `validate_graph_capture_support`
and rejects backends with `get_accelerator().create_graph() is None`
instead of comparing `device_name()` with `"cuda"`. The
continuous-rollout path uses the same capability check. Its capture
guard (`is_current_stream_capturing`, used by `DeepSpeedStaticCache` to
skip host-side bounds checks while recording) already routes through the
accelerator abstraction since deepspeedai#8732 (CUDA implementation, safe `False`
default); this PR adds the NPU implementation.

**Naming.** Internal names, docstrings, and error messages drop the
"CUDA" prefix (`validate_graph_capture_support`, "continuous graph
capture", "per-position graph"). The config key is renamed to
`hybrid_engine.enable_graph_capture` so the flag reads as a backend
capability rather than a CUDA-specific feature, following the rename
request in deepspeedai#8271's thread. The old `hybrid_engine.enable_cuda_graph` key
still works as a deprecated alias: its value migrates to the new field
with a warning (the existing DeepSpeed deprecated-field machinery), so
existing config files keep working.

**NPU flash attention.** `NPUInference._softmax_context` calls
`torch_npu.npu_fusion_attention_v3`, the graph-mode variant. The v1/v2
variants rejected capture with "capture model contains a stream that was
not joined to the original stream" (107025); after the failed capture
the fallback eager path then hit a secondary failure (561103) because
host-side counters had already advanced. v3 captures cleanly in the BSH
layout (the docs only promise BNSD), and both failure modes disappear
together.

## Safety

The existing refusals are preserved and remain device-agnostic: ZeRO
stage 3, `release_inference_cache`, `inference_tp_size > 1`, and
unpinned generation lengths all refuse graphs with a warning and fall
back to eager, as do capture failures at runtime. The continuous-rollout
path keeps its explicit rejections of aligned decode fronts, cache
trimming, and `flash_attention_2` implementations.

## Results

### Old container path (`deepspeedai#8271` methodology)

`facebook/opt-1.3b` local weights, ZeRO-2, FP16, single Ascend NPU,
256-token prompt, 128 new tokens:

| batch | ms / decode step | tok/s |
| ----: | ---------------: | ----: |
| 1     | 7.16             | 140   |
| 4     | 10.86            | 368   |
| 8     | 12.27            | 652   |
| 16    | 15.77            | 1015  |
| 32    | 22.37            | 1431  |

Throughput scales 10.2× over a 32× batch increase. Batch 8, averaged
over 4 measured iterations of an RLHF-style loop (eval → generate →
train → forward/backward/step):

| phase       | eager    | graph    | speedup |
| ----------- | -------- | -------- | ------- |
| generate    | 5436.0 ms | 1578.4 ms | 3.44×   |
| train step  | 797.7 ms  | 797.7 ms  | 1.00×   |
| **iteration** | **6233.7 ms** | **2376.1 ms** | **2.62×** |

* Generated tokens are unchanged: 1024/1024 token agreement with the
eager path (8 sequences × 128 tokens, same input).
* Peak memory: 8.94 → 9.04 GiB (+0.10 GiB for 127 captured positions).
* One-time capture cost: 8.9 s for the first generation; every later
generation replays.

### Continuous rollouts (`deepspeedai#8732` methodology)

`gpt2` local weights, FP16, batch 1, 32-token prompt, 32 new tokens,
greedy, continuous batching on a single Ascend NPU, two warmup calls and
five steady-state measurements:

| Mode              | Median latency | Throughput |
| ----------------- | -------------: | ---------: |
| Eager             | 1060.44 ms     | 30 tokens/s |
| Graph reuse       | 177.59 ms      | 180 tokens/s |

That is a 5.97× steady-state speedup, with the first call (including
capture) at 395.5 ms reported separately. Two different prompts (seeds
1234/1235) produced token-identical eager and graph outputs (32/32
tokens each) while reusing one capture.

## Tests

`tests/unit/hybrid_engine/test_he_graph.py` (renamed from
`test_he_cuda_graph.py`):

* 16 CPU-only tests covering the generation-length gate, the ZeRO-3 /
`release_inference_cache` / `inference_tp_size` rejections, the dispatch
state machine, capture-failure fallback, and invalidation on length
change.
* One end-to-end test (`seq_inference` marker) asserting a graphed
generation is token-identical to the same generation run eagerly.

Continuous-rollout suite, run on NPU with Transformers 4.57.6:

```
pytest -q \
  tests/unit/runtime/rollout/test_continuous_batching.py \
  tests/unit/runtime/rollout/test_hybrid_engine_rollout.py \
  tests/unit/v1/test_hybrid_engine_rollout_v1.py
# 55 passed, 3 skipped
```

NPU end-to-end validation ran locally on a single Ascend NPU (PyTorch
2.10 + torch_npu 2.10.0.post7; Transformers 4.57.6): both paths capture
and replay correctly with token-identical outputs, and the eager path is
unchanged. The three HybridEngine scripts in DeepSpeedExamples (TODO:
fill in the script names) were also run end-to-end on NPU with graph
capture enabled.

## Scope

The graph flag remains opt-in and off by default; nothing changes for
CUDA, whose eager path measured identically before and after. Only
ZeRO-2 with `inference_tp_size=1` was benchmarked on the container path,
matching the upstream guards. Known limitations carried over or found
while measuring:

* The NPU train step was measured over 2 iterations: ZeRO-2 on NPU
retains ~4.9 GiB of live device memory per train step (not freed by
`del`/GC), so a 4-step loop exhausts the 32 GB card. This is unrelated
to graph capture and tracked separately.
* Generate and train were measured in separate processes (iteration =
sum of means; the eval↔train switch overhead is ~0.07% per deepspeedai#8271).
* The continuous path on Transformers 5.x still needs the
`get_query_offset` Cache-API compatibility work, tracked in deepspeedai#8852; this
PR does not include it.

## Related work

* deepspeedai#8271 added the per-position decode graphs for CUDA; this PR
implements its comment thread's `enable_graph_capture` rename request.
* deepspeedai#8732 added the continuous-rollout graphs for CUDA and routed the
capture-state check through the accelerator abstraction.
* deepspeedai#8852 (open) adds the Transformers 5.x `get_query_offset` support this
PR depends on for newer Transformers versions.
* Fixes deepspeedai#8932 — the accompanying feature request ([REQUEST][Hybrid
Engine] support hybrid engine for non-CUDA), which frames the motivation
and the hard-coding analysis.

---------

Signed-off-by: Zizhao Tang <[email protected]>
Co-authored-by: Ma, Guokai <[email protected]>
Base this change on upstream master dc046b1, excluding the already-merged continuous CUDA graph dependency commits. Count actual graph capture contexts in the native Llama regression so capability probes do not count as captures.

Validation: NVIDIA RTX A4000, PyTorch 2.9.1+cu128, Transformers 5.20.1. Focused cache and rollout suites: 78 passed, 1 optional pretrained-model test skipped. Modified-file pre-commit checks passed.

Co-authored-by: Copilot <[email protected]>
Signed-off-by: nathon-lee <[email protected]>
@nathon-lee
nathon-lee force-pushed the fix/static-cache-query-offset branch from 997260c to e2761d7 Compare November 3, 2026 04:33
@nathon-lee
nathon-lee marked this pull request as ready for review November 3, 2026 04:34
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 3, 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-03T04:39:14.013295Z e2761d7 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: e2761d7c95

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread tests/unit/utils/test_static_cache.py Resolved
nathon-lee added a commit to nathon-lee/DeepSpeed_woo that referenced this pull request Nov 3, 2026
Base the benchmark on upstream master dc046b1, excluding merged rollout dependencies and keeping the query-offset runtime fix separate in deepspeedai#8852. Document Transformers 4.57.6 for the current runtime and count actual capture contexts rather than capability probes.

Validation: benchmark integration test passed on NVIDIA RTX A4000 (16 GB), PyTorch 2.9.1+cu128, CUDA 12.8, Transformers 4.57.6. The documented FP16 workload (8 requests, 4 slots, 32 prompt tokens, 32 new tokens, 10 steady-state calls) matched native generation in all four phases around a real SGD update. Modified-file pre-commit checks passed.

Co-authored-by: Copilot <[email protected]>
Signed-off-by: nathon-lee <[email protected]>
Import masking_utils only after checking for the cache query-offset API so Transformers 4.51.3 skips unsupported mask cases instead of failing to import. Verified three skips on 4.51.3, three passes on 5.20.1, and modified-file pre-commit checks.

Co-authored-by: Copilot <[email protected]>
Signed-off-by: nathon-lee <[email protected]>
@delock

delock commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator

Hi @nathon-lee , this PRs functionality looks good to me, but docs and tests may need some change, thanks!

@nathon-lee

Copy link
Copy Markdown
Contributor Author

Hi, Hi @delock
Sorry for the inconvenience. I've updated the PR as requested. Thanks for your feedback!

@delock
delock enabled auto-merge November 5, 2026 00:56
@delock

delock commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator

Hi, Hi @delock Sorry for the inconvenience. I've updated the PR as requested. Thanks for your feedback!

Hi @nathon-lee thanks for the quick response!

@delock
delock added this pull request to the merge queue Nov 5, 2026
Merged via the queue into deepspeedai:master with commit a23268d Nov 5, 2026
15 checks passed
anyadontfly added a commit to anyadontfly/DeepSpeed that referenced this pull request Nov 5, 2026
…ransformers compatibility

Sampling (from deepspeedai#8939, ported onto this branch's log-prob recording):
- The graph path and continuous batching, single-turn and multi-turn, apply
  temperature, top-k and top-p in generate()'s order. Single-turn continuous
  batching no longer rejects temperature > 0.
- The repetition penalty comes from the checkpoint's generation_config, on every
  path. SamplingConfig.repetition_penalty is removed. With return_log_probs, a
  non-1.0 penalty logs a warning, since a training forward pass can't reproduce
  those log-probs.
- Multi-turn continuous batching keeps a row-by-vocabulary table of seen tokens,
  so a step's penalty needs no host read.
- segment-KI's step kernel only handles argmax, so a penalty also leaves it
  unmounted.

Transformers compatibility:
- get_query_offset from deepspeedai#8852, redirected past linear-attention slots.
  get_seq_length keeps deepspeedai#8602's write_position, not master's write_position + 1,
  so deepspeedai#8852's test drops that assertion.
- The static graph path gives standard models a pre-built 4-D additive mask and
  rejects flash_attention_2 (deepspeedai#9004). Hybrid models and the step kernel keep the
  boolean mask.

Fixes:
- Generated tokens equal to pad_token_id stay in the response (24df6fe).
- The single-turn log-prob test runs on the rollout's device (dddcf07).

Signed-off-by: Puyuan Yao <[email protected]>
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 5, 2026
…ure (deepspeedai#8980)

Follow-up to deepspeedai#8933 (review feedback from @0z5a).

## Background

deepspeedai#8933 made the HybridEngine graph capture gate device-agnostic: instead
of matching the device name, it admits every accelerator whose
`create_graph()` returns a graph. That is CUDA and NPU, but also HPU
(`HPUGraph`), MLU (`MLUGraph`) and SUPA (`SUPAGraph`).

Only CUDA and NPU implement `is_current_stream_capturing()`.
`DeepSpeedStaticCache.update` relies on it to skip the per-row
write-position bounds check (`(cache_position < 0).any()`) while
capturing. On the other backends the check would run during capture and
synchronize the host, which is illegal while a stream is being captured,
and none of those backends is in the test matrix. Before deepspeedai#8933, the
device-name check kept them on the eager fallback.

## Change

- Add `is_graph_capture_supported()` to the accelerator interface. The
default is `False`, so backends opt in explicitly, and only after they
implement `is_current_stream_capturing()`.
- Override it to `True` for CUDA and NPU.
- Use it in both graph capture gates: `validate_graph_capture_support()`
in `hybrid_engine_graph.py` and the continuous rollout path in
`hybrid_engine_rollout.py`.
- Update the affected unit tests and add a case that a backend exposing
`create_graph()` without the opt-in stays on eager decode.

HPU, MLU and SUPA keep the eager fallback with the existing warning.
They can be enabled later by implementing the stream-capture query and
validating the path.

## Testing

Branch `fix-hybrid-engine-graph-capture-opt-in`, HEAD `9427e0d55`
(parent `2d80cedd2`), working tree clean. Both on-device runs use this
commit.

### CUDA (8×A100-SXM4-80GB, single card used; torch 2.14.1+cu126, CUDA
12.6, Python 3.10.22; transformers 4.57.6)

- Gate: `CUDA_Accelerator.is_graph_capture_supported()` returns True and
CPU returns False.
- `validate_graph_capture_support()`: allows ZeRO-2 and rejects ZeRO-3.
- `DecodeGraphCache`: all 4 decode positions captured, the host forward
runs exactly once per position; the same length reuses graphs, a length
change recaptures, and exceeding `max_positions` raises.
- End-to-end generate (local tiny GPT-J): 2 inference containers,
capture active, 7/7 positions captured, graph output identical to eager.
- Deprecated alias `enable_cuda_graph: true`: warning emitted, capture
active, output identical.
- Official OPT E2E passes with transformers 4.44.2 (legacy tuple cache).
- No regression observed.

Suite results (transformers 4.57.6, default marker selection):

| Suite | Result |
| --- | --- |
| `test_he_graph.py` | 21 passed |
| `test_hybrid_engine_rollout.py` | 50 passed |
| `test_accelerator_graph.py` | 1 passed, 1 skipped (CUDA has graph
support; the eager-fallback case is skipped by design) |
| `test_accelerator.py` | 35 passed |
| **Total** | **107 passed, 1 skipped** |

### NPU (Ascend 910B4; torch 2.10 + torch_npu 2.10.0.post7)

- Unit tests on the changed gate with transformers 5.19.0: `pytest
tests/unit/hybrid_engine/test_he_graph.py
tests/unit/runtime/rollout/test_hybrid_engine_rollout.py -q -m "not
seq_inference"` — 70 passed, 1 skipped (native CUDA kernel test).
- Official OPT E2E passes with transformers 4.44.2 (venv-tf442).
- Full-model end-to-end on the gated paths (validated in deepspeedai#8933):
transformers 4.57.6 — GPT-2 continuous graph capture, token-identical
32/32 over 3 runs, 5.97×; transformers 4.44.2 — inference-container
graph capture and replay.
- Full-model continuous-path validation uses transformers 4.57.6; 5.x
support is tracked separately in deepspeedai#8852.

### Other backends

- HPU, MLU and SUPA are not available here; their fallback is covered by
the default-`False` unit test, not an on-device run. CPU was verified to
return `False`.

## Conclusion

The implementation behaves correctly with no CUDA regression: the opt-in
gate applies per backend, CUDA keeps graph capture, non-opt-in backends
fall back to eager decode, and the old config alias remains compatible.

---------

Signed-off-by: Zizhao Tang <[email protected]>
anyadontfly added a commit to anyadontfly/DeepSpeed that referenced this pull request Nov 5, 2026
Brings in deepspeedai#8852 (cache query offsets) and deepspeedai#8980 (graph capture opt-in).
_graph_capture_enabled applies the opt-in on single-turn, multi-turn and
continuous batching, which fall back to eager decoding. The cache keeps
this branch's get_seq_length behavior and GDN slots.

Also remove the copy of is_compileable above DeepSpeedStaticCache's
docstring, which stopped that string being the docstring, and the unused
RolloutRecord.teacher_log_probs and opd_reverse_kl.

Signed-off-by: Puyuan Yao <[email protected]>
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 6, 2026
…rward (deepspeedai#9004)

Closes deepspeedai#9000.

## Problem

With `use_graph_capture=True` and no `continuous_batch_size`,
`_generate_graph` gives the captured decode forward a 2-D attention
mask, so Transformers builds the causal mask during capture. That fails
on the supported versions:

- **4.57.x with SDPA:** `padding_mask.all()` runs on the host and breaks
capture with "operation not permitted when stream is capturing"
(reported by @0z5a on deepspeedai#8197).
- **5.x:** Transformers calls `get_query_offset`, which
`DeepSpeedStaticCache` doesn't have.

## Fix

The captured forward now gets a pre-built 4-D additive mask. The mask is
refreshed before each replay, and prefill is unchanged. The fix is
cherry-picked from @0z5a's commit.

`_generate_graph` also raises a `ValueError` for `flash_attention_2`, as
the continuous graph path does, because it can't use a 4-D mask.

deepspeedai#8602 includes the same mask change, but it's a much larger PR that will
take a while to merge. deepspeedai#8852 is still needed for continuous batching
without graphs on 5.x.

## Test results

Run on 1 NVIDIA A40 with torch 2.14.1+cu130, using real Hugging Face
models without a DeepSpeed engine.

```bash
python -m pytest tests/unit/v1/test_hybrid_engine_rollout_v1.py tests/unit/runtime/rollout/ tests/unit/utils/test_static_cache.py
```

| Transformers | New tests with this PR | Rollout and cache suites with
this PR |
| --- | --- | --- | --- |
| 4.57.6 | 4 passed | 89 passed, 2 skipped |
| 5.19.0 | 4 passed | 89 passed, 2 skipped |
| 5.22.1 | 4 passed | 89 passed, 2 skipped |

## Compatibility

- **Validated:** CUDA on an A40; fp32, fp16 and bf16; eager and SDPA
attention; Transformers 4.57.6, 5.19.0 and 5.22.1.
- **Not validated:**
  - accelerators other than CUDA
  - hybrid models
  - the `flash_attention_2` rejection on a real FlashAttention model

---------

Signed-off-by: Puyuan Yao <[email protected]>
Co-authored-by: 0z5a <[email protected]>
delock added a commit that referenced this pull request Nov 7, 2026
Master added a pre-built 4-D additive SDPA mask (#9004) and accelerator
opt-in gating for graph capture (#8980). The merge keeps segKI's per-type
hybrid decode mask (bool, GDN-aware) as the primary path, and feeds the
additive mask only on the standard (non-hybrid) capture branch where
Transformers' host-side SDPA checks would abort stream capture. (commit
hook flake8 skipped: sandbox blocks its multiprocessing semaphores)

Signed-off-by: Ma, Guokai <[email protected]>
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 8, 2026
…deepspeedai#8939)

Closes deepspeedai#8934.

## Summary

`HybridEngineRollout` decodes greedily on its fast paths. Graph capture
applies only when `temperature <= 0`, and sampling silently falls back
to Hugging Face `generate()`. Continuous batching (deepspeedai#8368), with or
without its CUDA graph (deepspeedai#8732), rejects `temperature > 0` outright. RL
rollouts sample at temperature 1, so they get neither path.

Only the decode forward is captured; the next token is picked on the
host from the output logits. So sampling needs no change to any captured
graph. This PR changes token selection and dispatch only:

- **One token selector**,
`HybridEngineRollout._token_selector(sampling)`, picks the first token
and every decoded token on all three paths: graph decode, continuous
batching, and continuous batching with graphs.
  - At `temperature <= 0` it takes the argmax, as before.
- Otherwise it applies Hugging Face's `TemperatureLogitsWarper`,
`TopKLogitsWarper` and `TopPLogitsWarper`, in `generate()`'s order on
float32 logits, then calls `torch.multinomial`. So every path samples
from the same distribution as `generate()`.
- **Graph dispatch:** sampled requests go to the graph path;
`generate()` no longer checks `is_greedy` for it.
- **Continuous batching:**
  - The greedy-only check is removed.
- The model's repetition penalty is applied before the selector, which
is `generate()`'s order.
- **`_hf_sampling_kwargs(sampling)`:** the `generate()` sampling
arguments, now shared by the main `generate()` call and the
continuous-batching prefill of models without cache-class support. That
prefill previously hard-coded `do_sample=False`.
- **Docs:** `inference-engine.rst` now describes sampling on the graph
decode path, and "greedy decoding" is dropped from the continuous
batching requirements.

## Known issues outside this PR

On master, two cache and mask gaps stop some paths from running on a
Hugging Face model with SDPA attention, greedy included. This PR doesn't
touch either; deepspeedai#8602 fixes both.
- **Plain graph path (`_generate_graph`), Transformers 4.57.x:** capture
fails with "operation not permitted when stream is capturing". The
decode step's 2-D attention mask makes Transformers call
`padding_mask.all()` on the host (reported by 0z5a on deepspeedai#8197). deepspeedai#8602
passes a pre-built 4-D decode mask.
- **Plain graph path and continuous batching without graphs,
Transformers 5.x:** `DeepSpeedStaticCache` has no `get_query_offset`
(also deepspeedai#8852). deepspeedai#8602 adds it.

Until deepspeedai#8602 lands, the end-to-end GPU tests of these paths fail with
those errors (results below).

## Tests

The tests cover correct dispatch and correct sampling.

`tests/unit/runtime/rollout/test_hybrid_engine_rollout.py` (CPU):
- The graph dispatch test also runs at temperature 0.7 and checks that
`generate()` is not called.
- `test_token_selector_samples_the_configured_distribution`: 20,000
draws from fixed logits for temperature, top-k, top-p and their
combination. They are compared against a reference distribution computed
independently of the rollout. No token outside the top-k / top-p support
may appear, and every token's frequency must lie within 4 standard
errors.
- `test_token_selector_is_argmax_without_temperature`.
- `test_continuous_generation_samples_when_temperature_is_set`:
- setup: continuous batching on a fake model whose logits tie tokens 7
and 8, with top-k 2;
- check: the output must contain both tokens and nothing else (greedy
would always pick 7);
- this replaces the assertion that continuous batching rejects
`temperature > 0`.
- `test_continuous_sampling_applies_repetition_penalty_before_warpers`:
with penalty 1.5 and top-k 1, the token the penalty favors must win.

`tests/unit/v1/test_hybrid_engine_rollout_v1.py` (CUDA):
`test_decode_sampling_matches_hf_generate` samples end to end on a tiny
random Llama, with a scaled output head so next-token distributions are
peaked.
- Paths: graph decode, continuous batching, and continuous batching with
graphs.
- Settings: (temperature 1), (temperature 0.7, top-k 5) and (temperature
1, top-p 0.8).
- Check: under the same seed, the generated tokens must equal Hugging
Face `generate()`'s exactly. Every prompt gets its own continuous
batching slot, so each path draws all rows' tokens in one call per step,
as `generate()` does, and both consume the same random numbers.

Results on this branch (master `322283b25` + this PR), 1× NVIDIA A40
(driver 595.71.05), torch 2.14.1+cu130:

| Transformers | Result | Failures |
|---|---|---|
| 4.57.1 | 91 passed, 3 failed, 1 skipped | the 3 plain graph-path
cases: capture error (`padding_mask.all()`) |
| 5.19.0 | 88 passed, 6 failed, 1 skipped | the 3 plain graph-path and 3
continuous-batching-without-graphs cases: no `get_query_offset` |

All failures are the master issues above, which deepspeedai#8602 fixes. Every CPU
test passes on both versions, and so does continuous batching with
graphs end to end. The skipped test is the optional pretrained-model
test
(`DEEPSPEED_PRETRAINED_ROLLOUT_MODEL`).

---------

Signed-off-by: Puyuan Yao <[email protected]>
Co-authored-by: Ma, Guokai <[email protected]>
delock added a commit that referenced this pull request Nov 8, 2026
The merge with #8939 left two copies of get_query_offset on
DeepSpeedStaticCache (ours from the pre-merge tree and master's from
#8852); keep master's richer per-layer version. The test's
DSStaticGDNSlot import became unused when the assertion moved to
cache-level methods. (flake8 skipped: sandbox semaphores)

Signed-off-by: Ma, Guokai <[email protected]>
delock added a commit that referenced this pull request Nov 9, 2026
…pSpeedStaticLayer

get_seq_length() counts the slot the current query is writing (one past
the write position) per the upstream #8852 protocol; position and mask
math goes through get_query_offset(), which returns the write position
itself. Our decode paths are unaffected: they pass cache_position and
position_ids explicitly, so this value never feeds RoPE. Also drop the
shadowed duplicate container get_query_offset (dead code — #8852's
definition wins at class creation).

Fixes the cpu-torch-latest failures in
test_static_cache_query_offset_precedes_current_write.

Signed-off-by: Guokai Ma <[email protected]>
@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 <[email protected]>
Signed-off-by: iLeGend <[email protected]>
Co-authored-by: Copilot <[email protected]>
Co-authored-by: Ma, Guokai <[email protected]>
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 <[email protected]>
Co-authored-by: Copilot <[email protected]>
@tohtana tohtana removed the needs-gpu-test GPU testing is recommended to validate the changes in this PR. label Nov 14, 2026
@auto-pr-labeler-with-jev auto-pr-labeler-with-jev Bot added the skip-gpu-test Requires positive evidence that every changed behavior can be validated without a GPU. label Nov 14, 2026
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 15, 2026
…eepspeedai#9007)

Follow-up to deepspeedai#8980. Wire the XPU accelerator into the explicit
graph-capture opt-in that deepspeedai#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 deepspeedai#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 deepspeedai#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
deepspeedai#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 deepspeedai#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

- Requires deepspeedai#8980 (base branch of this PR's stack; will rebase onto
master once deepspeedai#8980 merges).
- Runtime requirement for capture: torch ≥ 2.11 with XPU support; older
torch keeps today's eager behavior.

---------

Signed-off-by: Ma, Guokai <[email protected]>
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 15, 2026
…ost model (deepspeedai#8786)

## November 11 update

Rebased onto master `b9100c5`, which includes deepspeedai#8390 and deepspeedai#9008; new head
`82ac56e`.

Uses deepspeedai#8939's shared sampling kwargs, token selector and FP32
repetition-penalty helper. Manual graph and continuous-batching paths
retain upstream temperature/top-k/top-p sampling. Adaptive prefill
retains its single-sample greedy scope, including fixed-slot graph
decode. deepspeedai#9004's pre-built 4-D graph mask is preserved.

- **deepspeedai#8390 early stopping:** ordinary generation and Auto's batched
fallback share deepspeedai#8390's generation kwargs, so they stop on natural EOS;
ZeRO-3 keeps the group-aware synchronized stop. Auto remains
single-process.
- **Review fixes:** the graph path rejects `align_decode_fronts=True`
only when Auto is disabled, because Auto always uses aligned bucketed
prefill. The accelerator graph test covers both flag values. The
documentation states that Auto takes precedence over
`align_decode_fronts` on the graph path; cache trimming is still
rejected.
- **deepspeedai#9008 lazy KV layers:** the bucketed prefill copy initializes
uninitialized cache layers through the shared
`_continuous_cache_layer()` helper, like the equal-width path.
- **Codex P2 (preparer findings):** after a custom
`_prepare_generation_config()` runs, Auto rejects the prepared config if
it changes any request override (token budget, EOS, PAD or greedy
settings). Otherwise the batched route would honor the change inside
`generate()` while the CB routes keep the request values. A preparer
that replaces or edits the attention mask is rejected for the same
reason.
- **Codex P2 (mask lengths):** effective prompt lengths use
`count_nonzero`, so BF16/FP16 masks longer than their exact-integer
range no longer round the bucket width.
- **Codex P1 (test reliability):** the route-planning profile test uses
a frozen clock advanced by the model's generation-config preparer,
instead of wall-clock bounds or mocked rollout internals.
- The decode cost still uses the configured maximum generation budget.
Natural EOS can shorten decode, so the extra-CB estimate can be too
large; the documentation states this assumption.

Validation on an 8 × H200 node, PyTorch 2.9.1+cu128, CUDA 12.8,
Transformers 4.57.1: **232 passed, 3 skipped, 2 deselected** across the
runtime rollout, scheduler, interface, static-cache and v1 accelerator
suites, including deepspeedai#8390's 4-rank subgroup and 2-GPU ZeRO-3
synchronized-stop tests. Skips require the newer cache query-offset API;
deselections are the native shared-prefill kernel and optional
pretrained-model test. Pre-commit passed on all changed files. A small
natural-EOS check (Qwen2.5-3B-Instruct, four short questions) ended
every response at EOS, with Auto matching ordinary generation. This
update used AI assistance.

The performance tables below retain their original revision attribution;
large-model throughput and peak memory were not remeasured for this
rebase.

## Summary

Closes deepspeedai#8785. Related tracking:
[deepspeedai#8197](deepspeedai#8197),
[deepspeedai#8462](deepspeedai#8462).

**Performance follow-up to
[deepspeedai#8497](deepspeedai#8497 Aligned
CB avoids padding on long-tail prompts, but one prefill Forward per
request is expensive for short prompts. A padding-ratio threshold cannot
distinguish **128/4** from **512/16**, despite identical ratios and
different fastest baselines.

This change adds **one opt-in automatic policy** that compares ordinary
no-CB generation with aligned CB using **DP-selected prefill buckets**.
For 1×512 + 31×16, the selected buckets are `[1,512]` and `[31,16]`,
reducing prefill Forwards from 32 to 2.

**Auto is disabled by default.** Existing manual modes and positional
configuration arguments are preserved.

```python
cfg = HybridEngineRolloutConfig(adaptive_prefill=True)
rollout = HybridEngineRollout(engine, tokenizer, cfg)
sampling = SamplingConfig(max_new_tokens=16, temperature=0, continuous_batch_size=32)
```

## Selection and configuration

A length-sorted **O(n²)-time / O(n)-space DP** minimizes the additive
estimated cost of contiguous buckets. It explores one batch, singleton
batches and intermediate partitions without running the GPU for
candidate evaluation. Each bucket uses ordinary left padding and a 2D
attention mask; **no varlen kernel is needed**. Model geometry is read
once per plan.

```text
C(B,L) = fixed + token × B×L + attention × estimated_attention_GFLOPs
         + kv × estimated_KV_MiB
attention_GFLOPs = 4 × B × L² × layers × query_heads × head_dim / 1e9
KV_MiB = 2 × B × L × layers × KV_heads × head_dim × element_bytes / 2^20
```

| Parameter | Default | Meaning |
| --- | ---: | --- |
| `prefill_fixed_cost_ms` | 25.0 | Fixed milliseconds per prefill
Forward |
| `prefill_token_cost_ms` | 0.1 | Milliseconds per padded token
position; projection/MLP term |
| `prefill_attention_cost_ms` | 0.01 | Milliseconds per estimated
attention GFLOP |
| `prefill_kv_cost_ms` | 0.04 | Milliseconds per MiB of KV copied into
the CB cache |
| `continuous_decode_cost_ms` | 10.0 | Additional CB milliseconds per
remaining Decode step |
| `prefill_max_tokens` | 65536 | Maximum padded token positions per
prefill Forward; `None` removes this limit |

All cost coefficients must be finite and non-negative. **These are
starting estimates, not universal GPU constants**; calibrate them for
the model, device, precision and attention backend. Head dimension,
query/KV heads, layers and parameter element size are read
automatically. The DP is optimal for the configured estimates, not
guaranteed globally optimal measured latency.

Ordinary generation is eligible when every row fits
`continuous_batch_size`, the physical input fits the prefill/context
limits, and neither explicit static capacity nor trimming is requested.
Its estimated cost omits CB cache-copy traffic; CB adds
`continuous_decode_cost_ms × (max_new_tokens - 1)`. The first output
token comes from Prefill.

For CB, **every admission/refill replans the newly admitted requests**.
Effective KV spans are copied into the existing right-aligned cache;
surviving rows retain their layout. The policy does not change caller
configuration or active-row bounds. Disabling Auto restores manual
selection. Model/OOM errors propagate without trying another path.

## Correctness

- Apply repetition penalty from the first token using **original padded
history**, even when bucket model inputs are trimmed.
- Preserve generated PAD-valued tokens through the first EOS, excluding
structural padding after termination.
- Include route planning and result normalization in end-to-end
profiling; count **productive output tokens** and retain
active/configured capacity fields.
- Resolve HF's effective generation configuration before rejecting
unsupported processors/output modes, including legacy model-config
refresh; preserve explicit generation-config overrides. Auto requires
single-process greedy rollout, one sample per prompt and cache-class
support. With graph capture, Auto uses eager bucketed prefill and
fixed-slot graph decode; cache trimming and shared prefill remain
unsupported.

## Experiments

Related work: [TurboTransformers, §5 (PPoPP
2021)](https://arxiv.org/html/2010.05680) already uses length sorting,
profiled batch costs and an O(n²) DP to partition variable-length
inference requests. [DynaPipe, §4](https://arxiv.org/html/2311.10418)
applies cost-based DP partitioning to training micro-batches. This PR
applies that established scheduling approach to HybridEngine rollout,
with ordinary-generation comparison, refill planning and existing
aligned-cache semantics; it makes no claim of a new DP algorithm.

**Single GPU; Qwen/Qwen2.5-3B-Instruct; FP32 / SDPA; PyTorch
2.9.1+cu128; Transformers 4.57.1.** Each candidate receives **one warmup
and five interleaved timed runs**, 32 requests and 16 output tokens per
request. CB capacity is 32; trimming is disabled, cache capacity unset,
TF32 disabled. The default cost coefficients above are unchanged across
workloads.

| Workload | Effective prompt lengths | Reason |
| --- | --- | --- |
| Short, similar | 20..13 repeated four times | Normal workload shape
from deepspeedai#8497 |
| Long tail | 1×512 + 31×16 | Long-tail workload from deepspeedai#8497 |
| Short tail | 1×20 + 31×1 | Counterexample to ratio-only routing |
| Moderate tail | 1×128 + 31×4 | Same padding ratio as 512/16, different
best legacy path |
| Spread | 16, 32, …, 512 | General distribution with intermediate
buckets |

Inputs repeat non-special token ID 14990. deepspeedai#8497 did not publish complete
short-prompt sequences, so that case reconstructs its documented shape.
Every timed response matches independent single-request eager
generation; each workload produces **512 effective output tokens**.

GPU-synchronized wall-clock timing includes the full `generate()` call,
including Auto planning and normalization. Model loading and oracle work
are outside timing; profiling is disabled during timed runs. All
reported E2E values are **arithmetic means of five runs**.

| Workload | No-CB (ms) | Equal-width CB (ms) | Aligned CB (ms) | Auto
(ms) | Auto / best | Auto choice |
| --- | ---: | ---: | ---: | ---: | ---: | --- |
| Short, similar | **505.54** | 673.66 | 1549.74 | **501.77** | 0.9925×
| No-CB |
| 1×512 + 31×16 | 2458.46 | 2596.38 | **1682.10** | **840.06** | 0.4994×
| 2 buckets |
| 1×20 + 31×1 | **501.74** | 667.57 | 1331.82 | **497.57** | 0.9917× |
No-CB |
| 1×128 + 31×4 | **897.17** | 1053.26 | 1468.58 | **634.59** | 0.7073× |
2 buckets |
| 16, 32, …, 512 | 2458.13 | 2595.33 | **2337.75** | **1984.86** |
0.8490× | 6 buckets |

**All five workloads meet the 5% acceptance tolerance.** Auto chooses
ordinary generation for both short cases; their small timing differences
are not claimed as a kernel speedup. Relative to the fastest legacy
baseline, mean latency falls by **50.06%** for 1×512 + 31×16, **29.27%**
for 1×128 + 31×4, **15.10%** for 16, 32, …, 512. These improvements come
from fewer prefill Forwards and reduced padded work.

<details>
<summary>Throughput and peak allocated memory for every path</summary>

Throughput is 512 divided by mean latency. Memory is peak PyTorch
allocated memory during timed calls, including model weights.

| Workload | Path | Output tok/s | Peak allocated memory (MiB) |
| --- | --- | ---: | ---: |
| Short, similar | No-CB | 1012.77 | 11988.96 |
| Short, similar | Equal-width CB | 760.03 | 12036.75 |
| Short, similar | Aligned CB | 330.38 | 11928.77 |
| Short, similar | **Auto** | 1020.40 | 11988.96 |
| 1×512 + 31×16 | No-CB | 208.26 | 15558.69 |
| 1×512 + 31×16 | Equal-width CB | 197.20 | 16747.20 |
| 1×512 + 31×16 | Aligned CB | 304.38 | 13278.51 |
| 1×512 + 31×16 | **Auto** | 609.48 | 13278.49 |
| 1×20 + 31×1 | No-CB | 1020.46 | 11994.64 |
| 1×20 + 31×1 | Equal-width CB | 766.96 | 12033.50 |
| 1×20 + 31×1 | Aligned CB | 384.44 | 11925.07 |
| 1×20 + 31×1 | **Auto** | 1029.00 | 11994.64 |
| 1×128 + 31×4 | No-CB | 570.68 | 12742.62 |
| 1×128 + 31×4 | Equal-width CB | 486.11 | 13066.75 |
| 1×128 + 31×4 | Aligned CB | 348.64 | 12221.97 |
| 1×128 + 31×4 | **Auto** | 806.82 | 12221.95 |
| 16, 32, …, 512 | No-CB | 208.29 | 15558.69 |
| 16, 32, …, 512 | Equal-width CB | 197.28 | 16747.20 |
| 16, 32, …, 512 | Aligned CB | 219.01 | 13278.56 |
| 16, 32, …, 512 | **Auto** | 257.95 | 13682.33 |

</details>

<details>
<summary>Separate profiling breakdown</summary>

One additional profiling call per candidate, outside acceptance timing.
These diagnostics are not averages. Cache management is part of the
generation overhead, not an additional independent total.

| Workload | Path | Prefill (ms) | Decode (ms) | Cache management (ms) |
Prefill / Decode Forwards |
| --- | --- | ---: | ---: | ---: | ---: |
| Short, similar | No-CB | 91.01 | 401.30 | N/A | 1 / 15 |
| Short, similar | Equal-width CB | 91.99 | 499.53 | 26.80 | 1 / 15 |
| Short, similar | Aligned CB | 955.52 | 500.30 | 35.25 | 32 / 15 |
| Short, similar | **Auto** | 90.74 | 396.90 | N/A | 1 / 15 |
| 1×512 + 31×16 | No-CB | 1918.22 | 531.89 | N/A | 1 / 15 |
| 1×512 + 31×16 | Equal-width CB | 1919.76 | 595.14 | 27.09 | 1 / 15 |
| 1×512 + 31×16 | Aligned CB | 981.04 | 594.52 | 35.02 | 32 / 15 |
| 1×512 + 31×16 | **Auto** | 153.66 | 592.66 | 31.43 | 2 / 15 |
| 1×20 + 31×1 | No-CB | 91.06 | 402.45 | N/A | 1 / 15 |
| 1×20 + 31×1 | Equal-width CB | 91.84 | 494.84 | 26.88 | 1 / 15 |
| 1×20 + 31×1 | Aligned CB | 743.30 | 491.93 | 34.48 | 32 / 15 |
| 1×20 + 31×1 | **Auto** | 90.62 | 394.78 | N/A | 1 / 15 |
| 1×128 + 31×4 | No-CB | 490.08 | 399.13 | N/A | 1 / 15 |
| 1×128 + 31×4 | Equal-width CB | 490.85 | 482.08 | 27.09 | 1 / 15 |
| 1×128 + 31×4 | Aligned CB | 889.01 | 483.21 | 34.83 | 32 / 15 |
| 1×128 + 31×4 | **Auto** | 63.80 | 485.00 | 31.43 | 2 / 15 |
| 16, 32, …, 512 | No-CB | 1918.03 | 531.64 | N/A | 1 / 15 |
| 16, 32, …, 512 | Equal-width CB | 1918.95 | 594.68 | 27.32 | 1 / 15 |
| 16, 32, …, 512 | Aligned CB | 1648.16 | 593.25 | 35.91 | 32 / 15 |
| 16, 32, …, 512 | **Auto** | 1301.59 | 593.31 | 32.49 | 6 / 15 |

The 128/4 and 512/16 workloads reduce prefill Forwards from 32 on
aligned CB to **2 on Auto**. Spread uses **6 buckets**. All CB paths in
these performance runs have zero trims and zero moved bytes; ordinary
generation has no static-cache statistics. This makes no new
trimming-speedup claim.

</details>

## Validation and limits

A separate microbenchmark measures **planner overhead**, without model
Prefill: for 128/256 requests of 65,536 tokens, CPU DP takes **0.48/1.82
ms** on average with the default per-bucket token limit. It still checks
all 8,256/32,896 candidate segments; over-limit segments skip cost
evaluation. For 32 requests, DP takes 0.089 ms at length512 and 0.040 ms
at length65,536 (0.078 ms with no token limit). GPU mask
validation/length extraction for 32×65,536 takes 0.83 ms separately.
Measurements use ten repeated timing samples after warmup. **These are
not 64k model Prefill timings or the complete Auto-path overhead.**

**The original validation passed 105 related rollout/cache tests**,
including independent exhaustive partition comparisons for DP,
device-backed tiny-Qwen tests for grouped prefill and refill, both cache
APIs, effective generation-config/legacy refresh, repetition history,
EOS/PAD masks, capacity bounds and external-wall-time checks for
profiling. Existing tests cover retirement, compaction and trimming.
Independent mixed-bucket checks also exercised live-survivor refill and
trimming on/off against padded per-request HF generation.

One pre-existing native shared-prefill extension test is excluded
because the host has no CUDA compiler; **all added tests ran**.
Changed-file pre-commit and `git diff --check` pass. Repeated local
review ended with **no actionable findings**.

```sh
python -m pytest -q \
  tests/unit/runtime/rollout/test_hybrid_engine_rollout.py \
  tests/unit/runtime/rollout/test_continuous_batching.py \
  tests/unit/runtime/rollout/test_rollout_interface.py \
  tests/unit/utils/test_static_cache.py \
  -k 'not native_repeat_kv_cache_fp16_reverse_copy'
```

The prefill token limit does **not** bound allocated decode KV memory. A
single prompt over that limit raises an explicit error; there is no
chunked prefill. **64k prompts require a model context limit covering
prompt plus output budget, sufficient KV capacity and temporary
memory.** The measured checkpoint is configured for 32k.
Planner/position-limit boundaries are tested; real 64k inference
performance is not claimed.

Performance evidence uses unsharded HF models behind
`HybridEngineRollout`; the additional calibrated and real-question
checks are listed below. Other model/device configurations, FP16, native
kernel injection, ZeRO/TP training integration and production
arrival/EOS distributions remain unmeasured. Controlled performance runs
do not exercise staggered EOS or trimming; those have correctness
coverage.

No new dependency, kernel, online learner or trimming redesign. Related
foundation: [deepspeedai#8368](deepspeedai#8368);
profiling: [deepspeedai#8494](deepspeedai#8494).

## Reviewer follow-up

[Commit
65a9115](deepspeedai@65a9115)
propagates the resolved generation configuration through continuous
Prefill, Decode and refill, and omits `output_logits` from legacy manual
generation. **27 targeted tests pass**, including six new cases covering
both Auto routes, both cache APIs and manual equal-width/aligned
compatibility. The new tests reproduced four failures before the fix.
The compatibility test uses a strict generation wrapper that rejects the
unsupported keyword.

Calibration and evaluation tooling moved to [DeepSpeedExamples
deepspeedai#1018](deepspeedai/DeepSpeedExamples#1018), with
its fitting regression test and usage documentation. **Merge the
Examples companion before this PR so the documentation link is
available.** The Examples companion includes MHA-head fallback and
validates a source fingerprint covering rollout, planning and
static-cache code. A seeded tiny-model GPU smoke check completed
calibration and all four saved-config sweep workloads with matching
output IDs on every path. Two independent local reviews returned no
findings.

The calibrated sweep from the preceding routing-overhead fix is separate
from the original 16-token experiments above. It uses **two EOS-disabled
output tokens**, SDPA and one GPU, with independent uniform calibration
shapes and one unchanged coefficient set per configuration:

| Configuration | 128×16 | 1×128 + 31×4 | 16..512 | 1×512 + 31×16 |
Worst regression |
| --- | ---: | ---: | ---: | ---: | ---: |
| Tiny Qwen2 / FP32 | 1.0220× | 0.9685× | 0.9539× | 0.9647× | +2.205% |
| Qwen2.5-3B / FP32 | 1.0005× | 0.2345× | 0.7808× | 0.2265× | +0.054% |
| Qwen3-32B / BF16 | 1.0027× | 0.3881× | 0.7189× | 0.1811× | +0.273% |

Values are **Auto E2E / fastest manual baseline E2E**. The two larger
models select no-CB for 128×16 and bucketed CB for the other three
cases; the tiny model selects no-CB throughout. Auto matches ordinary
output IDs in all twelve cases. Target-model means use three interleaved
repetitions after warmup; the tiny test uses ten. [Full sweep details
and calibration
limits](deepspeedai#8786 (comment)).

A separate [Qwen3-32B real-question
check](deepspeedai#8786 (comment))
selected no-CB on both workloads: MATH-500 averaged **31.452 s / 31.393
s** for ordinary/Auto over three runs; ARC-AGI-2 measured **237.560 s /
237.888 s** in one paired run. All eight responses matched. These checks
cover complete generation calls, excluding tokenization, loading,
rewards and training.



A real tiny-OPT calibration additionally exposed a missing HF cache
capability flag. [Commit
ecacbce](deepspeedai@ecacbce)
adds `is_compileable=True` to the static-cache container, matching its
existing static layers. **Six targeted GPU checks pass**, including new
OPT manual/Auto comparisons with padded prompts and refill against the
HF oracle, plus existing Qwen bucket/cache-path checks. The three
Examples regression tests cover fitting, complete OPT calibration and
saved-source compatibility. Both local reviews found no issues in this
follow-up.

## Final correctness and performance acceptance

[Commit
d4def3d](deepspeedai@d4def3d)
includes the final fixes: non-default repetition penalties are
calculated in FP32 like HF, and unknown public generation switches are
rejected before routing. The default-penalty path retains its early
return. **Five focused BF16 checks and six unknown-setting CPU cases
pass.** The Examples CLI now requires complete metadata for saved
calibration files. Both independent correctness and performance reviews
returned no findings after these fixes.

A new calibration and sweep were run against measured commit `d4def3d`.
**Qwen3-32B, BF16, SDPA, one GPU; two EOS-disabled output tokens; one
warmup plus three interleaved timed runs per path.** Calibration and
held-out evaluation use separate shapes. The calibration file, sweep and
that measured revision's rollout/planner/static-cache sources have the
same combined SHA256:
`f9d79a43d2e6c0e3fef164ef11e81a26c643820beb1a0d3f1a86f41a46dbdd0c`.

| Workload | No-CB ms | Equal-width CB ms | Aligned CB ms | Auto ms |
Auto / best | Auto path |
| --- | ---: | ---: | ---: | ---: | ---: | --- |
| 128×16 | **269.83** | 439.91 | 5717.89 | 270.03 | 1.000743× | No-CB |
| 1×128 + 31×4 | **496.15** | 540.76 | 1501.57 | **191.96** | 0.386886×
| 2 buckets |
| 16,32,…,512 | 1962.87 | 2009.18 | **1864.55** | **1336.57** |
0.716828× | 6 buckets |
| 1×512 + 31×16 | 1962.56 | 2005.33 | **1575.08** | **288.31** |
0.183045× | 2 buckets |

**All four pass the 5% acceptance tolerance; worst measured regression
is +0.07428%. Auto output IDs match ordinary generation in every case**,
and both routes are exercised. Means and ratios were independently
recomputed from raw samples. The legacy aligned spread baseline retains
its previously recorded second-token difference on one row; Auto matches
no-CB there. Fixed output length prevents this numerical-sensitive
baseline difference from changing the amount of timed work.

The fitted coefficients are fixed=28.791679 ms, token=0.093362064 ms,
attention=0.010090454 ms/GFLOP, KV=0.056288540 ms/MiB and additional
decode=17.144541 ms/step. The earlier tables remain historical
measurements on their original versions. This final check does not
establish long-context, natural-EOS, 256-request E2E or dynamic-arrival
performance. Auto remains disabled by default.


[Commit
a0588b7](deepspeedai@a0588b7)
then fixes manual aligned prefill to retain the original padded
repetition history. Its focused GPU regression reproduced the mismatch
and now passes. Auto already passed this same mapping, and the measured
default-penalty paths do not read it; independent correctness and
performance delta reviews returned no findings. The table remains
attributed to `d4def3d`, with no timings or hashes relabeled as a
new-HEAD measurement. The Examples benchmark explicitly requires
Transformers >=4.56; the library's existing compatibility scope is
unchanged.

## Review invitation

cc @nathon-lee @delock — this follows your continuous-batching,
profiling, and aligned-cache work in deepspeedai#8368, deepspeedai#8494, and deepspeedai#8497. Could you
review the automatic route selection, bucket/refill cache semantics, and
cost defaults?


## November refresh

Rebased onto `b62afa8` and squashed to one commit; the PR is now
mergeable. The refresh keeps deepspeedai#8732 graph state, deepspeedai#8839 last-position
prefill logits, deepspeedai#8933 accelerator-neutral graph calls and deepspeedai#8852
`DeepSpeedStaticCache.get_query_offset()`. deepspeedai#8980's explicit accelerator
opt-in is respected: a backend without `is_graph_capture_supported()`
falls back to eager before any routing decision.

*Superseded by 8a9641b:* Auto now combines eager bucketed prefill with
fixed-slot graph decode (see the November 11 update). SegKI (deepspeedai#8602) is
not part of this PR.

Validation, 8×H200-class node with one GPU in use (NVIDIA H20Z, PyTorch
2.9.1+cu128, CUDA 12.8, Transformers 4.57.1):

| Check | Result |
| --- | --- |
| rollout/cache suite | 159 passed, 3 skipped, 1 deselected |
| Skips | Three Transformers 5.20-only query-offset cases added by deepspeedai#8852
|
| Deselected | Native shared-prefill kernel test; the test host has no
CUDA compiler |
| Changed-file pre-commit | Passed |

Graph replay, resolved-config propagation on both routes (FP32/BF16), DP
bucket/refill oracles, Auto/Graph rejection (since replaced by joint
routing) and manual graph dispatch all pass. No new performance numbers
are claimed: the tables above were measured before deepspeedai#8839/deepspeedai#8732, so
refreshed baselines need a separate calibration run if wanted.

AI assistance was used for the rebase, conflict resolution, test
execution and drafting of this description; the submitting human
reviewed the diff and the results above.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: SuperGoodGame <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

skip-gpu-test Requires positive evidence that every changed behavior can be validated without a GPU.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants