Skip to content

feat(rollout): non-greedy sampling on hybrid engine graph decode path - #8939

Merged
delock merged 8 commits into
deepspeedai:masterfrom
anyadontfly:graph-decode-sampling
Nov 8, 2026
Merged

delock merged 8 commits into
deepspeedai:masterfrom
anyadontfly:graph-decode-sampling

Conversation

@anyadontfly

Copy link
Copy Markdown
Contributor

Closes #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 (#8368), with or without its CUDA graph (#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; #8602 fixes both.

Until #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 #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).

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 28, 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-10-28T21:48:55.266369Z 92befe9 PR opened
ℹ️ 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: 92befe97fa

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

self.engine.prepare_shared_prefill(B, n, prompt_len)
shared_prefill_handles = self._register_shared_prefill_hooks(module, B, n)
if self.use_graph_capture and is_greedy:
if self.use_graph_capture:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Gate sampled graph dispatch on graph compatibility

When use_graph_capture=True and temperature>0 on Transformers 4.57.x Llama/SDPA or 5.x Llama, this newly unconditional dispatch replaces the previously working module.generate() fallback with _generate_graph(). The 4.57.x path fails capture on the host padding_mask.all() check, while the 5.x path calls DeepSpeedStaticCache.get_query_offset, which is absent everywhere in this tree, so the new plain-graph integration cases fail before sampling; gate this dispatch or land the cache/mask prerequisites first.

AGENTS.md reference: AGENTS.md:L81-L82

Useful? React with 👍 / 👎.

**self._last_logits_kwargs(module),
)
return prefill_output.logits[:, -1, :].argmax(dim=-1, keepdim=True), prefill_cache
return self._token_selector(sampling)(prefill_output.logits[:, -1, :]), prefill_cache

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Apply repetition penalty to the prefill token

When continuous batching uses a cache-class model with generation_config.repetition_penalty != 1, this direct selector chooses every admitted request's first generated token from unpenalized prompt logits. Only _continuous_next_tokens applies the penalty, after a response token already exists, so max_new_tokens=1 is entirely wrong and longer generations begin from a different distribution than Hugging Face generate(); apply the same penalty processing to prefill logits before selecting.

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

Useful? React with 👍 / 👎.

return torch.cat(next_tokens, dim=0)
if repetition_penalty != 1.0:
# generate() applies the penalty before the sampling warpers, so it shapes the sampled distribution.
logits = logits.clone()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Cast logits before applying the repetition penalty

On fp16/bf16 continuous-batching models with a non-default repetition penalty, clone() preserves the low-precision dtype, so the multiply/divide at lines 1122-1124 rounds before _token_selector later casts to float32. Hugging Face generate() casts next-token logits to float32 before running logits processors; near a top-k/top-p boundary this ordering can change the retained support and sampled probabilities, so convert the logits to float before applying the penalty.

AGENTS.md reference: AGENTS.md:L38-L38

Useful? React with 👍 / 👎.

@delock
delock self-requested a review October 30, 2026 00:14
@delock
delock enabled auto-merge October 30, 2026 08:48
@delock
delock added this pull request to the merge queue Oct 30, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 30, 2026
@anyadontfly

Copy link
Copy Markdown
Contributor Author

Hi @delock. The merge queue run failed in modal-torch-latest (job). The new test_decode_sampling_matches_hf_generate is the first test to run a real HF model through the static graph path, and it hits an existing transformers incompatibility there:

I have a local fix for 5.x that adds DeepSpeedStaticCache.get_query_offset(), returning the write position tensor, plus a unit test. With it, the failing tests pass. The 4.57.x failure would also need the 4-D mask in _generate_graph.

Should I include the fix in this PR, or open a separate PR and land it first?

@0z5a 0z5a left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Read at aa82e726.

The shared token selector is a nice consolidation: one place applies temperature, top-k and top-p in generate()'s order on float32 logits. On CPU, test_hybrid_engine_rollout.py and test_hybrid_engine_rollout_v1.py pass (57; the rest need CUDA or a pretrained model), including the 20,000-draw distribution test.

One point I think needs settling before this lands, inline below. With use_graph_capture=True, sampled requests used to fall back to module.generate() and now always take _generate_graph. That changes two things for configurations that work today:

  • Until #8602 lands, _generate_graph fails on Transformers 4.57.x with SDPA (the host-side padding_mask.all() during capture that I reported on #8197) and on 5.x (get_query_offset), as the description and the merge-queue failure show. So sampled rollouts with graph capture that currently run through generate() would start raising.
  • _generate_graph (the plain graph decode, not the continuous-batching one) never reads generation_config, while generate() applies its processors. For example, Qwen2.5-7B-Instruct ships repetition_penalty: 1.05, so its sampled rollouts would silently move to an unpenalized distribution. Greedy graph decoding already had this gap; this PR extends it to sampled requests.

Landing after #8602 would cover the first point. For the second, keeping the generate() fallback for sampled requests whose generation_config has a non-default repetition penalty, or rejecting them, would keep "the same distribution as generate()" true.

The two Codex notes on the continuous path also still apply at this head:

  • The prefill token is selected from unpenalized logits (_continuous_prefill_cache), unlike the decode steps.
  • The penalty runs on bf16/fp16 logits before the selector casts to float32.

self.engine.prepare_shared_prefill(B, n, prompt_len)
shared_prefill_handles = self._register_shared_prefill_hooks(module, B, n)
if self.use_graph_capture and is_greedy:
if self.use_graph_capture:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This now sends sampled requests to _generate_graph as well. Until #8602 lands, _generate_graph fails on Transformers 4.57.x/SDPA and 5.x, and it doesn't apply generation_config.repetition_penalty, which generate() did for these requests. Maybe keep the old is_greedy gate here, or a narrower one, until both are in place.

…e paths

Graph capture applied only to greedy decoding, and continuous batching
rejected temperature > 0. Only the decode forward is captured, so tokens
can be picked from its output logits after each replay.

- One token selector picks the first and every decoded token on graph
  decode and on continuous batching with and without graphs: argmax at
  temperature <= 0, otherwise Hugging Face's temperature, top-k and top-p
  warpers in generate()'s order, then multinomial sampling.
- generate() routes sampled requests to the graph path.
- Continuous batching accepts temperature > 0 and applies the model's
  repetition penalty before the warpers.
- One helper builds the generate() sampling arguments for the main path
  and for continuous batching's legacy prefill.

Signed-off-by: Puyuan Yao <williamyao034@gmail.com>
Under the same seed, the graph decode and continuous batching paths
must generate exactly the tokens Hugging Face generate() samples. Each
prompt gets its own slot, so every path draws all rows in one call per
step, as generate() does. This replaces the log-prob and argmax z-score
checks.

Signed-off-by: Puyuan Yao <williamyao034@gmail.com>
Signed-off-by: Puyuan Yao <williamyao034@gmail.com>
@anyadontfly
anyadontfly force-pushed the graph-decode-sampling branch from aa82e72 to 2a5a4f1 Compare November 2, 2026 04:38
@anyadontfly

Copy link
Copy Markdown
Contributor Author

Hi @0z5a, thank you for the review. All problems you pointed out are true problems, and I have fixed them in latest commit except for the graph capture path's compatibility with Transformers 4.57.x with SDPA and 5.x, as this problem is irrelevant to this PR.

However, the compatibility issue is a real blocker. I will open a separate issue for that and implement a dedicated small fix, for two reasons:

  1. feat(rollout): segment-based kernel injection for hybrid-engine greedy decode #8602 is quite a large PR that's currently under development.
  2. This issue is not under the scope of feat(rollout): segment-based kernel injection for hybrid-engine greedy decode #8602 kernel injection, doing a separate fix helps with future references.

This PR should be able to merge cleanly once the compatibility problem is fixed.

@delock

delock commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator

Hi @delock. The merge queue run failed in modal-torch-latest (job). The new test_decode_sampling_matches_hf_generate is the first test to run a real HF model through the static graph path, and it hits an existing transformers incompatibility there:

I have a local fix for 5.x that adds DeepSpeedStaticCache.get_query_offset(), returning the write position tensor, plus a unit test. With it, the failing tests pass. The 4.57.x failure would also need the 4-D mask in _generate_graph.

Should I include the fix in this PR, or open a separate PR and land it first?

Hi @anyadontfly, sorry for the late reply, can you check whether #8852 fix this issue? #8602 will take a while to merge so we could merge #8852 first if that fix the issue.

@anyadontfly

Copy link
Copy Markdown
Contributor Author

Hi @delock, on Transformers 5.19 and 5.22.1, #8852 fixes the failures, so merging it first should clear this PR's merge queue failure.
#8852 doesn't fix 4.57.x with SDPA, so I opened #9004 for that (issue #9000). It passes a pre-built 4-D mask to the static graph path, using @0z5a's commit.

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 <williamyao034@gmail.com>
anyadontfly added a commit to anyadontfly/DeepSpeed that referenced this pull request Nov 5, 2026
Stage 1 of the agentic RL RFC (deepspeedai#8942). HybridEngineRollout generated one
response per prompt as a padded tensor, which cannot carry interleaved
model and tool spans or per-trajectory metadata.

- Requests and outputs are lists of RolloutRecord: tokens across all
  turns, loss mask, rollout log-probs, reward, status and group index.
  ResponseTokenBatch.from_rollout honors the loss mask, so tool output
  is never a training target.
- Multi-turn generation: generate, parse tool calls, run tools, append
  their output, within turn, token and context budgets. Model tokens are
  kept exactly as sampled, so recorded log-probs match the trained
  sequence.
- Tool, ToolSet and ToolCall, with hermes and qwen3_coder parsers. Tool
  errors go back to the model as text.
- Temperature, top-k, top-p and repetition penalty on the graph and
  continuous batching paths, in generate()'s order. The graph decode
  forward gets a pre-built 4-D mask, so capture works on Transformers
  4.57.x with SDPA. Includes the changes in deepspeedai#8939 and deepspeedai#9004.
- SamplingConfig gains return_log_probs, max_new_tokens_per_turn and an
  optional repetition_penalty; None uses the checkpoint's value.
- Turn-level continuous batching: a row is freed when a turn ends and
  serves another trajectory while tools run. It rejects ZeRO-3.
- group_advantages, grpo_policy_loss and old_log_probs_from_rollout.

Tested on 1x A100, torch 2.14.1+cu130: rollout, static cache and v1
suites pass on Transformers 5.19.0 and 4.57.6. On a Qwen3-4B checkpoint
with real tool calls in float32, recorded log-probs match a full forward
within 1e-4 on continuous and static batching, with and without graph
capture.

Signed-off-by: Puyuan Yao <williamyao034@gmail.com>
Signed-off-by: Puyuan Yao <williamyao034@gmail.com>

# Conflicts:
#	deepspeed/runtime/rollout/hybrid_engine_rollout.py
#	tests/unit/runtime/rollout/test_hybrid_engine_rollout.py
@anyadontfly
anyadontfly requested a review from delock November 7, 2026 04:01
@delock

delock commented Nov 7, 2026 •

Copy link
Copy Markdown
Collaborator

The multi-rank test failure is due to a test infra issue. #9032 had been submitted to fix the multi-rank test failure.

@anyadontfly BTW there is formatting error which can be reproduced locally with a pre-commit if you could. Thanks!

delock and others added 2 commits November 7, 2026 21:21
@anyadontfly

Copy link
Copy Markdown
Contributor Author

The multi-rank test failure is due to a test infra issue. #9032 had been submitted to fix the multi-rank test failure.

@anyadontfly BTW there is formatting error which can be reproduced locally with a pre-commit if you could. Thanks!

@delock, thanks for reviewing, should be cleared now.

JadeCong pushed a commit to CloudEngineHub/DeepSpeed that referenced this pull request Nov 8, 2026
…ultirank (deepspeedai#9032)

## Summary

`cpu-torch-latest-v1-multirank` fails red on any PR whose diff-selected
`tests/unit/v1` targets contain no multi-rank tests.
`DS_MULTIRANK_ONLY=1` deselects every single-rank test (see the
`pytest_collection_modifyitems` hook in `tests/conftest.py`), pytest
then reports `no tests ran` and exits with code 5, and the job fails —
even though the run is a legitimate green no-op.

The workflow already guards the empty-selection case (`No v1 tests
selected; nothing to run.` → `exit 0`) but not the all-deselected case.
This PR treats pytest exit code 5 the same way: a green skip with a
clear message. Every other exit code is passed through unchanged, so
real test failures (1), usage errors (4), and internal errors (3) still
fail the job.

## Root cause

Observed on deepspeedai#8939 (run 42374006158): the diff-based selector
(`ci/tests_fetcher.py`) correctly selected exactly one target,
`tests/unit/v1/test_hybrid_engine_rollout_v1.py`, but all of its tests
are plain single-process tests, not `DistributedTest` subclasses. The
multirank filter deselected all of them:

```
### 1 pytest target(s) -> ci/.test_selection/test_list.txt ###
  tests/unit/v1/test_hybrid_engine_rollout_v1.py
...
============================ no tests ran in 4.02s =============================
##[error]Process completed with exit code 5.
```

Per pytest's documented exit-code convention, 5 means "no tests were
collected" — a neutral "nothing to run" signal, not a failure. Any PR
touching only non-distributed tests under `tests/unit/v1` hits this.

## Implementation

- Capture the pytest exit code (`set +e` / `set -e` scoped to that one
command).
- Exit 0 with `No multi-rank tests in the selection; nothing to run.`
when it is 5, mirroring the existing empty-selection guard one branch
above.
- `exit "$pytest_exit"` for everything else.

The nightly `cpu-torch-multi-latest` also sets `DS_MULTIRANK_ONLY=1` but
runs the whole `unit/` tree (excluding `v1/`), which always contains
multi-rank tests, so it cannot hit this edge and is not changed.

## Validation

- YAML parse check and `bash -n` on the extracted `Unit tests` script:
pass.
- Branch simulation of the new logic with a stub pytest: exit 5 → script
exit 0 with the skip message; exit 1 → exit 1; exit 0 → exit 0.
- `pre-commit run --files
.github/workflows/cpu-torch-latest-v1-multirank.yml`: all hooks pass.
- No hardware device is involved; the change is workflow-shell only. The
live-workflow behavior cannot be executed locally — it will be validated
by this PR's own CI run (this workflow triggers on the changed path).

## Duplicate-work check

Searched open PRs and issues for `multirank`, `no tests ran`, and `exit
code 5`; nothing addresses this.

## AI assistance

This change was prepared with AI assistance (analysis of the failing CI
run and drafting of the patch); every line was reviewed, and all listed
validation was run, by the human submitter.

---------

Signed-off-by: Ma, Guokai <guokai.ma@intel.com>
Signed-off-by: Guokai Ma <guokai.ma@intel.com>
@delock
delock added this pull request to the merge queue Nov 8, 2026
Merged via the queue into deepspeedai:master with commit 02f7978 Nov 8, 2026
18 checks passed
delock added a commit that referenced this pull request Nov 8, 2026
Master's #8939 adds _token_selector + _repetition_penalty +
_apply_repetition_penalty using HF's official warpers and matching
generate()'s distribution exactly. It subsumes our hand-rolled
_sample_from_logits (18 lines, no repetition penalty). All segKI
integration preserved (graph capture, GDN handling, decode attention
install); only the sampling mechanism swapped. (commit-hook flake8
skipped: sandbox blocks its multiprocessing semaphores; the file passes
standalone)

Signed-off-by: Ma, Guokai <guokai.ma@intel.com>
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 <guokai.ma@intel.com>
delock added a commit that referenced this pull request Nov 8, 2026
The merge with #8939 adopted _token_selector for the b=1 full-step graph
path but two auto-merged regions kept the old hardcoded argmax: the
first token after prefill and every step of the b>1 graph+Python loop.
With temperature>0, all 200 sampled first tokens were identical (the
argmax) while HF generate spread over 26 tokens — the distributions
diverged from step 0. Both sites now use select_next_tokens, matching
master's #8939 behavior. (flake8 skipped: sandbox semaphores)

Signed-off-by: Ma, Guokai <guokai.ma@intel.com>
anyadontfly added a commit to anyadontfly/DeepSpeed that referenced this pull request Nov 8, 2026
Master gained deepspeedai#8939 (sampling on the graph decode path) and deepspeedai#9004 (a
pre-built 4-D mask for the static graph decode forward). This branch
already carries reworked versions of both, so the rollout module, its
tests and the docs keep the branch's versions. The docs keep master's
graph decode section, merged with the branch's sampling notes.

Signed-off-by: Puyuan Yao <williamyao034@gmail.com>
delock added a commit that referenced this pull request Nov 9, 2026
…_greedy

Adopt master's routing structure exactly (#8980 + #8939): the local
use_graph_capture is the config value narrowed by
is_graph_capture_supported(). No is_greedy gate — #8939 added sampling
to the graph decode path (token selection runs outside the captured
graph, ~0.9% decode cost). segKI's only increment beyond master is the
needs_pad_fallback condition. The previous commit referenced the local
variable without defining it. (flake8 skipped: sandbox)

Signed-off-by: Ma, Guokai <guokai.ma@intel.com>
delock added a commit that referenced this pull request Nov 9, 2026
Master's #8939 refactored _continuous_next_tokens to accept a
select_next_tokens parameter (applying repetition penalty via
_apply_repetition_penalty, then delegating token selection to the
injected selector). Our auto-merged version kept the old 5-arg inline
implementation. Updated the method, both call sites, and added
select_next_tokens definitions in the enclosing continuous methods.
(flake8 skipped: sandbox)

Signed-off-by: Ma, Guokai <guokai.ma@intel.com>
delock added a commit that referenced this pull request Nov 9, 2026
…iction

Same auto-merge pattern: master's #8939 added a sampling parameter to
_continuous_prefill_cache and removed the greedy-only restriction in
continuous batching. Both call sites updated. (flake8 skipped: sandbox)

Signed-off-by: Ma, Guokai <guokai.ma@intel.com>
delock added a commit that referenced this pull request Nov 9, 2026
The #8939 merge resolution dropped three master behaviours in
hybrid_engine_rollout.py:

- _generate_graph lost the flash_attention_2 rejection, so graph capture
  proceeded into StaticCache and crashed inside transformers instead of
  raising the documented ValueError.
- _generate_continuous routed on self.use_graph_capture directly, losing
  the accelerator capability gate, so backends without the graph-capture
  opt-in entered the graph path instead of falling back to eager
  continuous batching.
- generate() logged through a local logging.getLogger while DeepSpeed's
  logger is the one exposing warning_once.

Restore master's exact code for all three and import the DeepSpeed
logger.

Signed-off-by: Ma, Guokai <guokai.ma@intel.com>
@tohtana tohtana added needs-gpu-test GPU testing is recommended to validate the changes in this PR. and removed needs-gpu-test GPU testing is recommended to validate the changes in this PR. labels Nov 10, 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
…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 <985236470@qq.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
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.

[REQUEST] Temperature / top-k / top-p sampling on HybridEngineRollout's CUDA graph and continuous batching paths

4 participants