| 86 | self.is_initialized = True |
| 87 | |
| 88 | def update( |
| 89 | self, |
| 90 | key_states: torch.Tensor, |
| 91 | value_states: torch.Tensor, |
| 92 | *args, |
| 93 | **kwargs, |
| 94 | ) -> tuple[torch.Tensor, torch.Tensor]: |
| 95 | if not self.is_initialized: |
| 96 | self.lazy_initialization(key_states, value_states) |
| 97 | |
| 98 | kv_length = key_states.shape[-2] |
| 99 | |
| 100 | if self._write_position is not None and self._write_position.dim() == 1: |
| 101 | if self._write_position.numel() < key_states.shape[0]: |
| 102 | raise ValueError("per-row write positions must cover the active batch size") |
| 103 | if kv_length != 1: |
| 104 | raise ValueError("per-row write positions currently support one decode token at a time") |
| 105 | cache_position = self._write_position[:key_states.shape[0]].to(self.device) |
| 106 | is_capturing = get_accelerator().is_current_stream_capturing() |
| 107 | if not is_capturing and ((cache_position < 0).any() or (cache_position >= self.max_cache_len).any()): |
| 108 | raise ValueError("per-row write positions must be within the cache bounds") |
| 109 | row_indices = torch.arange(key_states.shape[0], device=self.device) |
| 110 | self.keys[row_indices, :, cache_position, :] = key_states[:, :, 0, :] |
| 111 | self.values[row_indices, :, cache_position, :] = value_states[:, :, 0, :] |
| 112 | active_batch_size = key_states.shape[0] |
| 113 | return self.keys[:active_batch_size], self.values[:active_batch_size] |
| 114 | |
| 115 | if self._write_position is not None: |
| 116 | cache_position = torch.arange(kv_length, device=self.device) + self._write_position |
| 117 | else: |
| 118 | cache_position = torch.arange(kv_length, device=self.device) |
| 119 | |
| 120 | try: |
| 121 | self.keys.index_copy_(2, cache_position, key_states) |
| 122 | self.values.index_copy_(2, cache_position, value_states) |
| 123 | except NotImplementedError: |
| 124 | self.keys[:, :, cache_position] = key_states |
| 125 | self.values[:, :, cache_position] = value_states |
| 126 | |
| 127 | return self.keys, self.values |
| 128 | |
| 129 | def get_mask_sizes(self, query_length: int) -> tuple[int, int]: |
| 130 | return self.max_cache_len, 0 |