CUDA-graph-compatible static KV cache. Drop-in replacement for ``transformers.StaticCache`` in the graph-capture decode path of ``HybridEngineRollout``. All layers share a single ``write_position`` tensor that the caller updates before each graph replay. Parameters ----------
| 192 | |
| 193 | |
| 194 | class DeepSpeedStaticCache: |
| 195 | """CUDA-graph-compatible static KV cache. |
| 196 | |
| 197 | Drop-in replacement for ``transformers.StaticCache`` in the graph-capture |
| 198 | decode path of ``HybridEngineRollout``. All layers share a single |
| 199 | ``write_position`` tensor that the caller updates before each graph replay. |
| 200 | |
| 201 | Parameters |
| 202 | ---------- |
| 203 | config : PreTrainedConfig |
| 204 | HuggingFace model config (used to determine number of layers and head |
| 205 | dimensions). |
| 206 | batch_size : int |
| 207 | Batch size for eager initialization. |
| 208 | max_cache_len : int |
| 209 | Maximum sequence length (prompt + generated tokens). |
| 210 | device : torch.device | int | str | None |
| 211 | Device for eager initialization. |
| 212 | dtype : torch.dtype | None |
| 213 | Dtype for eager initialization. |
| 214 | """ |
| 215 | |
| 216 | def __init__( |
| 217 | self, |
| 218 | config, |
| 219 | batch_size: int = 1, |
| 220 | max_cache_len: int = 4096, |
| 221 | device=None, |
| 222 | dtype=None, |
| 223 | ): |
| 224 | self.config = config |
| 225 | text_config = getattr(config, "text_config", config) |
| 226 | num_layers = getattr(text_config, "num_hidden_layers", 1) |
| 227 | self._layers = [DeepSpeedStaticLayer(max_cache_len) for _ in range(num_layers)] |
| 228 | self._max_cache_len = max_cache_len |
| 229 | self._write_position: torch.Tensor | None = None |
| 230 | |
| 231 | if dtype is not None and device is not None and batch_size > 0: |
| 232 | num_heads = getattr(text_config, "num_key_value_heads", getattr(text_config, "num_attention_heads", 1)) |
| 233 | # head_dim is not always hidden_size // num_attention_heads, so prefer the config value |
| 234 | head_dim = getattr(text_config, "head_dim", None) or (getattr(text_config, "hidden_size", 1) // |
| 235 | getattr(text_config, "num_attention_heads", 1)) |
| 236 | self.early_initialization(batch_size, num_heads, head_dim, dtype, device) |
| 237 | |
| 238 | @property |
| 239 | def layers(self): |
| 240 | return self._layers |
| 241 | |
| 242 | def memory_bytes(self) -> int: |
| 243 | """Return the bytes held by the layers' cache tensors.""" |
| 244 | return sum(layer.memory_bytes() for layer in self._layers) |
| 245 | |
| 246 | def set_write_position(self, pos: torch.Tensor): |
| 247 | """Set the write position shared by all layers. |
| 248 | |
| 249 | Must be called before each graph replay. A scalar tensor preserves the |
| 250 | fixed-batch path; a vector supplies one decode position per cache row. |
| 251 | The tensor is stored by reference so subsequent in-place updates are |
no outgoing calls