Fix HybridEngineRollout KV caches under autocast when keys and values differ in dtype #9124
All Vouch review confidence checks passed
Residual risk 0.22 = Change Risk (0.52) × (1 − Review Confidence (0.57)).
Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.52 · 650 lines diff across 8 files
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size
diff_size
0.388
Shallow Review Depth
shallow_review_depth
0.289
Real PR Conversation Timeline
1 comments
"Review active on #9124"
general
weight: 0.35
delock
Fixes #9102.
Root cause
The issue attributes the failure to caches being created with the parameter dtype. Tracing it on master, the cause is slightly different: under
torch.autocast(dtype=bf16)an fp32 Llama model produces keys and values in different dtypes:k_proj/v_projrun under autocast and return bf16.apply_rotary_pos_embmultiplies the bf16 keys by the fp32cos/sin(the rotary module runs with autocast disabled), so the keys are promoted back to fp32. The values stay bf16.Caches that take their dtype from the first keys (fp32) then reject the bf16 values:
DeepSpeedStaticLayer.update(continuous-batching decode, with or without graph capture):Index put requires the source and destination dtypes match, got Float ... BFloat16.StaticCache.update, used for the prefill of the static graph path (_generate_graph) and of the continuous paths (_continuous_prefill_cache, for models that set_supports_cache_class):index_copy_(): self and source expected to have the same dtype ... Float ... BFloat16. HFStaticCachecannot hold fp32 keys and bf16 values at once, whatever dtype it is allocated in.Allocating the caches in the autocast dtype would not fix this, because the keys really are fp32.
Change (+27 / -3 in
deepspeed/)DeepSpeedStaticLayer.update: cast the incoming key/value states to the cache dtype before writing..to()returns the same tensor when the dtypes already match, so graph capture and the non-autocast paths are unchanged.HybridEngineRollout._create_prefill_cache, used by both prefill sites (_generate_graph,_continuous_prefill_cache):- Models whose layers are all full attention (no
sliding_window, everylayer_typesentryfull_attention) prefill into a lazily sizedDeepSpeedStaticCache, which is sized from the prefill keys so AutoTP-local KV heads still work. With no write position set, it writes the prompt at[0, prompt_len)and gives a single prefill forward the same mask sizes and offsets as a fresh HFStaticCache.- All other models keep HF
StaticCache, exactly as on master.DeepSpeedStaticCachemodels every layer as full attention, so a sliding-window model prefilled into it would silently attend outside the window. Hybrid models also need the HF cache because their GDN slots are bound to its layers (#8602).Model families by path (default configs, transformers 5.12 and 5.23):
Behaviour without autocast
To check this doesn't change behaviour anywhere else, I ran the same 30 rollout scenarios on master and on this branch and compared the generated tokens (or the raised error):
_supports_cache_class.All 30 are identical. The sliding-window runs use prompts longer than the window, and they still raise the same error they raise on master.
Tradeoff
The cast can also narrow. When the decode cache is allocated eagerly in the parameter dtype and that dtype is narrower than the incoming states (e.g. fp16 parameters under bf16 autocast), keys and values are now rounded to that dtype where master raised an error. That only happens under autocast and matches the model's own parameter precision; I can restrict the cast to widening and raise otherwise if you prefer.
Relation to other PRs
_create_static_cachecall lines in_generate_graph/_continuous_prefill_cachethere, so any rebase against #9077 should be trivial.generate()uses HFDynamicCache(concatenation handles mixed dtypes) and already worked.Tests
Every new test fails on master. Reverting either half of the fix makes some of them fail:
| Test | master | cast reverted | prefill routing reverted | this PR |
|---|---|---|---|---|
|
test_rollout_under_autocast_matches_hf_generate: 6 cases = {static graph, continuous graph, continuous eager} × {default,_supports_cache_class=True}. Greedy rollout of an fp32 tiny Llama under bf16 autocast, token-for-token vs HFgenerate()under the same autocast | 6 fail | 6 fail | 4 fail | 6 pass ||
test_static_layer_accepts_values_in_a_different_dtype_than_keys: fp32 keys + bf16 values through both write paths (prefill and per-row decode positions) | 2 fail | 2 fail | pass | 2 pass ||
test_prefill_cache_keeps_hf_static_cache_unless_full_attention_only: routing for full-attention, sliding-window and linear-attention configs | 5 fail | pass | 5 fail | 5 pass |Suites:
| Setup | Command | Result |
|---|---|---|
| 1x NVIDIA T1000 8GB (sm_75), driver 596.51, torch 2.6.0+cu124, transformers 5.12.1, Windows 11, Python 3.11 |
pytest unit/v1/test_hybrid_engine_rollout_v1.py unit/utils/test_static_cache.py unit/runtime/rollout| 240 passed, 6 failed, 10 skipped || CPU (WSL2 Ubuntu), torch 2.15.0+cpu, transformers 5.23.0, Python 3.12, pytest 8.3.5,
DS_ACCELERATOR=cpu|pytest --forked -n 4 unit/runtime/rollout unit/utils/test_static_cache.py unit/v1/test_hybrid_engine_rollout_v1.py| 209 passed, 47 skipped |The 6 GPU failures fail on master on the same machine with byte-identical assertion output:
test_static_graph_uses_prefill_kv_shape[1,2,4]test_static_graph_matches_native_llama_generation[eager]test_decode_repetition_penalty_matches_hf_generate[0.0-True-None]and[0.7-True-None]They look specific to this setup (sm_75 with bf16 emulation, torch 2.6, transformers 5.12).
pre-commit run --files <changed files>passes.Not validated: bf16-native GPUs (sm_80+), fp16 autocast, hybrid (GDN) models, ZeRO-3 / AutoTP rollout under autocast, and multi-GPU. Without a GPU, upstream CI only runs the continuous-eager cases, the static-cache tests and the routing test; the graph-capture cases need a CUDA run.
AI assistance
AI assistance (Claude Code) was used to reproduce the bug, trace the root cause, draft the change and tests, and run the commands above. I reviewed every changed line and ran the tests myself.
🤖 Generated with Claude Code