Fix HybridEngineRollout KV caches under autocast when keys and values differ in dtype (#9124)
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_proj` run under autocast and return bf16.
- `apply_rotary_pos_emb` multiplies the bf16 keys by the fp32
`cos`/`sin` (the rotary module runs with autocast disabled), so the keys
are promoted back to **fp32**. The values stay **bf16**.
Caches that take their dtype from the first keys (fp32) then reject the
bf16 values:
- `DeepSpeedStaticLayer.update` (continuous-batching decode, with or
without graph capture): `Index put requires the source and destination
dtypes match, got Float ... BFloat16`.
- HF `StaticCache.update`, used for the prefill of the static graph path
(`_generate_graph`) and of the continuous paths
(`_continuous_prefill_cache`, for models that set
`_supports_cache_class`): `index_copy_(): self and source expected to
have the same dtype ... Float ... BFloat16`. HF `StaticCache` cannot
hold fp32 keys and bf16 values at once, whatever dtype it is allocated
in.
Allocating the caches in the autocast dtype would not fix this, because
the keys really are fp32.
## Change (+27 / -3 in `deepspeed/`)
- `DeepSpeedStaticLayer.update`: cast the incoming key/value states to
the cache dtype before writing. `.to()` returns the same tensor when the
dtypes already match, so graph capture and the non-autocast paths are
unchanged.
- New `HybridEngineRollout._create_prefill_cache`, used by both prefill
sites (`_generate_graph`, `_continuous_prefill_cache`):
- Models whose layers are all full attention (no `sliding_window`, every
`layer_types` entry `full_attention`) prefill into a lazily sized
`DeepSpeedStaticCache`, which is sized from the prefill keys so
AutoTP-local KV heads still work. With no write position set, it writes
the prompt at `[0, prompt_len)` and gives a single prefill forward the
same mask sizes and offsets as a fresh HF `StaticCache`.
- All other models keep HF `StaticCache`, exactly as on master.
`DeepSpeedStaticCache` models every layer as full attention, so a
sliding-window model prefilled into it would silently attend outside the
window. Hybrid models also need the HF cache because their GDN slots are
bound to its layers (#8602).
Model families by path (default configs, transformers 5.12 and 5.23):
- Fixed by this PR: Llama, Qwen2/Qwen3, Mixtral, Phi-3, GPT-NeoX.
- Unchanged (still fail under fp32-param + bf16 autocast on the
cache-prefill paths): Mistral and Gemma 2/3, which default to a sliding
window, and Qwen3-Next/Qwen3.5, which have linear-attention layers.
## Behaviour without autocast
To check this doesn't change behaviour anywhere else, I ran the same 30
rollout scenarios on master and on this branch and compared the
generated tokens (or the raised error):
- Models: Llama, sliding-window Mistral, sliding-window Qwen2.
- Attention: eager and sdpa.
- Paths: static graph, continuous graph, continuous eager, and the
continuous paths with `_supports_cache_class`.
All 30 are identical. The sliding-window runs use prompts longer than
the window, and they still raise the same error they raise on master.
## Tradeoff
The cast can also narrow. When the decode cache is allocated eagerly in
the parameter dtype and that dtype is narrower than the incoming states
(e.g. fp16 parameters under bf16 autocast), keys and values are now
rounded to that dtype where master raised an error. That only happens
under autocast and matches the model's own parameter precision; I can
restrict the cast to widening and raise otherwise if you prefer.
## Relation to other PRs
- No other PR references #9102.
- #9077 adds the autocast state to the continuous graph signature, which
doesn't address this mismatch (as the issue notes). This PR now changes
only the two `_create_static_cache` call lines in `_generate_graph` /
`_continuous_prefill_cache` there, so any rebase against #9077 should be
trivial.
- Plain batched `generate()` uses HF `DynamicCache` (concatenation
handles mixed dtypes) and already worked.
## Tests
Every new test fails on master. Reverting either half of the fix makes
some of them fail:
| Test | master | cast reverted | prefill routing reverted | this PR |
|---|---|---|---|---|
| `test_rollout_under_autocast_matches_hf_generate`: 6 cases = {static
graph, continuous graph, continuous eager} × {default,
`_supports_cache_class=True`}. Greedy rollout of an fp32 tiny Llama
under bf16 autocast, token-for-token vs HF `generate()` under the same
autocast | 6 fail | 6 fail | 4 fail | 6 pass |
| `test_static_layer_accepts_values_in_a_different_dtype_than_keys`:
fp32 keys + bf16 values through both write paths (prefill and per-row
decode positions) | 2 fail | 2 fail | pass | 2 pass |
| `test_prefill_cache_keeps_hf_static_cache_unless_full_attention_only`:
routing for full-attention, sliding-window and linear-attention configs
| 5 fail | pass | 5 fail | 5 pass |
Suites:
| Setup | Command | Result |
|---|---|---|
| 1x NVIDIA T1000 8GB (sm_75), driver 596.51, torch 2.6.0+cu124,
transformers 5.12.1, Windows 11, Python 3.11 | `pytest
unit/v1/test_hybrid_engine_rollout_v1.py unit/utils/test_static_cache.py
unit/runtime/rollout` | 240 passed, 6 failed, 10 skipped |
| CPU (WSL2 Ubuntu), torch 2.15.0+cpu, transformers 5.23.0, Python 3.12,
pytest 8.3.5, `DS_ACCELERATOR=cpu` | `pytest --forked -n 4
unit/runtime/rollout unit/utils/test_static_cache.py
unit/v1/test_hybrid_engine_rollout_v1.py` | 209 passed, 47 skipped |
The 6 GPU failures fail on master on the same machine with
byte-identical assertion output:
- `test_static_graph_uses_prefill_kv_shape[1,2,4]`
- `test_static_graph_matches_native_llama_generation[eager]`
- `test_decode_repetition_penalty_matches_hf_generate[0.0-True-None]`
and `[0.7-True-None]`
They look specific to this setup (sm_75 with bf16 emulation, torch 2.6,
transformers 5.12).
`pre-commit run --files <changed files>` passes.
**Not validated:** bf16-native GPUs (sm_80+), fp16 autocast, hybrid
(GDN) models, ZeRO-3 / AutoTP rollout under autocast, and multi-GPU.
Without a GPU, upstream CI only runs the continuous-eager cases, the
static-cache tests and the routing test; the graph-capture cases need a
CUDA run.
## AI assistance
AI assistance (Claude Code) was used to reproduce the bug, trace the
root cause, draft the change and tests, and run the commands above. I
reviewed every changed line and ran the tests myself.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Signed-off-by: ArchanaChetan07 <apatil@sandiego.edu>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Ma, Guokai <guokai.ma@gmail.com>