Compact active rows after requests retire from a batch.
(self, active_indices: torch.Tensor)
| 333 | layer.set_write_position(pos) |
| 334 | |
| 335 | def compact(self, active_indices: torch.Tensor) -> None: |
| 336 | """Compact active rows after requests retire from a batch.""" |
| 337 | if not isinstance(active_indices, torch.Tensor) or active_indices.dim() != 1: |
| 338 | raise ValueError("active_indices must be a 1-D tensor") |
| 339 | # Hybrid caches mix KV layers with pass-through GDN slots; the GDN |
| 340 | # slots keep no per-row KV rows (their state is position-free and |
| 341 | # managed by HF), so compaction only touches the KV layers. |
| 342 | kv_layers = [layer for layer in self._layers if not isinstance(layer, DSStaticGDNSlot)] |
| 343 | if not kv_layers: |
| 344 | return |
| 345 | max_batch_size = kv_layers[0].max_batch_size |
| 346 | active_indices = active_indices.to(device=kv_layers[0].keys.device, dtype=torch.long) |
| 347 | if active_indices.numel() > max_batch_size: |
| 348 | raise ValueError("active_indices exceeds the cache batch size") |
| 349 | if active_indices.numel() and ((active_indices < 0).any() or (active_indices >= max_batch_size).any()): |
| 350 | raise ValueError("active_indices contains an out-of-range row") |
| 351 | if active_indices.unique().numel() != active_indices.numel(): |
| 352 | raise ValueError("active_indices must not contain duplicates") |
| 353 | for layer in kv_layers: |
| 354 | layer._compact_rows(active_indices) |
| 355 | if self._write_position is not None and self._write_position.dim() == 1: |
| 356 | positions = self._write_position |
| 357 | if positions.numel() != max_batch_size: |
| 358 | raise ValueError("per-row write positions must match the cache batch size") |
| 359 | position_indices = active_indices.to(positions.device) |
| 360 | count = active_indices.numel() |
| 361 | compacted = positions.index_select(0, position_indices).clone() if count else positions[:0] |
| 362 | positions[:count].copy_(compacted) |
| 363 | if count < positions.numel(): |
| 364 | positions[count:].fill_(-1) |
| 365 | |
| 366 | def trim_left(self, count: int) -> None: |
| 367 | """Shift all cache layers left to reclaim an unused prefix span.""" |