Compact only the row tensors; used by the multi-layer cache.
(self, active_indices: torch.Tensor, count: int | None = None)
| 171 | self.values.zero_() |
| 172 | |
| 173 | def _compact_rows(self, active_indices: torch.Tensor, count: int | None = None) -> None: |
| 174 | """Compact only the row tensors; used by the multi-layer cache.""" |
| 175 | if count is None: |
| 176 | count = active_indices.numel() |
| 177 | identity = torch.arange(count, device=active_indices.device, dtype=active_indices.dtype) |
| 178 | if count and not torch.equal(active_indices, identity): |
| 179 | keys = self.keys.index_select(0, active_indices).clone() |
| 180 | values = self.values.index_select(0, active_indices).clone() |
| 181 | self.keys[:count].copy_(keys) |
| 182 | self.values[:count].copy_(values) |
| 183 | # Clear retired rows so their stale KV cannot be observed after refill. |
| 184 | if count < self.max_batch_size: |
| 185 | self.keys[count:].zero_() |
| 186 | self.values[count:].zero_() |
| 187 | |
| 188 | def _trim_left(self, count: int) -> None: |
| 189 | """Shift the cache contents left while preserving tensor addresses.""" |