Compact active rows after requests retire from a batch.
(self, active_indices: torch.Tensor)
| 256 | layer.set_write_position(pos) |
| 257 | |
| 258 | def compact(self, active_indices: torch.Tensor) -> None: |
| 259 | """Compact active rows after requests retire from a batch.""" |
| 260 | if not isinstance(active_indices, torch.Tensor) or active_indices.dim() != 1: |
| 261 | raise ValueError("active_indices must be a 1-D tensor") |
| 262 | max_batch_size = self._layers[0].max_batch_size if self._layers else 0 |
| 263 | active_indices = active_indices.to(device=self._layers[0].keys.device, dtype=torch.long) |
| 264 | if active_indices.numel() > max_batch_size: |
| 265 | raise ValueError("active_indices exceeds the cache batch size") |
| 266 | if active_indices.numel() and ((active_indices < 0).any() or (active_indices >= max_batch_size).any()): |
| 267 | raise ValueError("active_indices contains an out-of-range row") |
| 268 | if active_indices.unique().numel() != active_indices.numel(): |
| 269 | raise ValueError("active_indices must not contain duplicates") |
| 270 | for layer in self._layers: |
| 271 | layer._compact_rows(active_indices) |
| 272 | if self._write_position is not None and self._write_position.dim() == 1: |
| 273 | positions = self._write_position |
| 274 | if positions.numel() != max_batch_size: |
| 275 | raise ValueError("per-row write positions must match the cache batch size") |
| 276 | position_indices = active_indices.to(positions.device) |
| 277 | count = active_indices.numel() |
| 278 | compacted = positions.index_select(0, position_indices).clone() if count else positions[:0] |
| 279 | positions[:count].copy_(compacted) |
| 280 | if count < positions.numel(): |
| 281 | positions[count:].fill_(-1) |
| 282 | |
| 283 | def trim_left(self, count: int) -> None: |
| 284 | """Shift all cache layers left to reclaim an unused prefix span.""" |