| 255 | |
| 256 | |
| 257 | class DeepSpeedStaticCache: |
| 258 | # Mirrors HF StaticCache: static buffers answer mask builders with |
| 259 | # full-width masks (is_compileable), which must match the full-width |
| 260 | # K/V buffers update() returns; a position-truncated mask against a |
| 261 | # full-width buffer crashes SDPA at decode. |
| 262 | is_compileable = True |
| 263 | """CUDA-graph-compatible static KV cache. |
| 264 | |
| 265 | Drop-in replacement for ``transformers.StaticCache`` in the graph-capture |
| 266 | decode path of ``HybridEngineRollout``. All layers share a single |
| 267 | ``write_position`` tensor that the caller updates before each graph replay. |
| 268 | |
| 269 | Parameters |
| 270 | ---------- |
| 271 | config : PreTrainedConfig |
| 272 | HuggingFace model config (used to determine number of layers and head |
| 273 | dimensions). |
| 274 | batch_size : int |
| 275 | Batch size for eager initialization. |
| 276 | max_cache_len : int |
| 277 | Maximum sequence length (prompt + generated tokens). |
| 278 | device : torch.device | int | str | None |
| 279 | Device for eager initialization. |
| 280 | dtype : torch.dtype | None |
| 281 | Dtype for eager initialization. |
| 282 | """ |
| 283 | |
| 284 | is_compileable = True |
| 285 | |
| 286 | def __init__( |
| 287 | self, |
| 288 | config, |
| 289 | batch_size: int = 1, |
| 290 | max_cache_len: int = 4096, |
| 291 | device=None, |
| 292 | dtype=None, |
| 293 | ): |
| 294 | self.config = config |
| 295 | text_config = getattr(config, "text_config", config) |
| 296 | num_layers = getattr(text_config, "num_hidden_layers", 1) |
| 297 | # Hybrid families (e.g. qwen3_5) mix full_attention and |
| 298 | # linear_attention blocks behind one decoder-layer list; mirror the |
| 299 | # split so KV slots and GDN pass-through slots line up by index. |
| 300 | layer_types = getattr(text_config, "layer_types", None) or ["full_attention"] * num_layers |
| 301 | self._layers = [ |
| 302 | DSStaticGDNSlot(max_cache_len) if t == "linear_attention" else DeepSpeedStaticLayer(max_cache_len) |
| 303 | for t in layer_types |
| 304 | ] |
| 305 | self._max_cache_len = max_cache_len |
| 306 | self._write_position: torch.Tensor | None = None |
| 307 | |
| 308 | if dtype is not None and device is not None and batch_size > 0: |
| 309 | num_heads = getattr(text_config, "num_key_value_heads", getattr(text_config, "num_attention_heads", 1)) |
| 310 | # head_dim is not always hidden_size // num_attention_heads, so prefer the config value |
| 311 | head_dim = getattr(text_config, "head_dim", None) or (getattr(text_config, "hidden_size", 1) // |
| 312 | getattr(text_config, "num_attention_heads", 1)) |
| 313 | self.early_initialization(batch_size, num_heads, head_dim, dtype, device) |
| 314 |
no outgoing calls