Updates the cache with the new `key_states` and `value_states` for the layer `layer_idx`. Parameters: query_states (`torch.Tensor`): The new query states to cache. key_states (`torch.Tensor`): The new key states to cache.
(
self,
query_states: torch.Tensor,
key_states: torch.Tensor,
value_states: torch.Tensor,
layer_idx: int,
cache_kwargs: Optional[Dict[str, Any]] = None,
)
| 12 | self.query_cache = [] |
| 13 | |
| 14 | def update( |
| 15 | self, |
| 16 | query_states: torch.Tensor, |
| 17 | key_states: torch.Tensor, |
| 18 | value_states: torch.Tensor, |
| 19 | layer_idx: int, |
| 20 | cache_kwargs: Optional[Dict[str, Any]] = None, |
| 21 | ) -> Tuple[torch.Tensor, torch.Tensor]: |
| 22 | """ |
| 23 | Updates the cache with the new `key_states` and `value_states` for the layer `layer_idx`. |
| 24 | |
| 25 | Parameters: |
| 26 | query_states (`torch.Tensor`): |
| 27 | The new query states to cache. |
| 28 | key_states (`torch.Tensor`): |
| 29 | The new key states to cache. |
| 30 | value_states (`torch.Tensor`): |
| 31 | The new value states to cache. |
| 32 | layer_idx (`int`): |
| 33 | The index of the layer to cache the states for. |
| 34 | cache_kwargs (`Dict[str, Any]`, `optional`): |
| 35 | Additional arguments for the cache subclass. No additional arguments are used in `DynamicCache`. |
| 36 | |
| 37 | Return: |
| 38 | A tuple containing the updated key and value states. |
| 39 | """ |
| 40 | # Update the number of seen tokens |
| 41 | if layer_idx == 0: |
| 42 | self._seen_tokens += key_states.shape[-2] |
| 43 | |
| 44 | # Update the cache |
| 45 | if len(self.key_cache) <= layer_idx: |
| 46 | self.key_cache.append(key_states) |
| 47 | self.value_cache.append(value_states) |
| 48 | else: |
| 49 | self.key_cache[layer_idx] = torch.cat([self.key_cache[layer_idx], key_states], dim=-2) |
| 50 | self.value_cache[layer_idx] = torch.cat([self.value_cache[layer_idx], value_states], dim=-2) |
| 51 | |
| 52 | # IC-RAG |
| 53 | if query_states is not None: |
| 54 | if len(self.query_cache) <= layer_idx: |
| 55 | self.query_cache.append(query_states) |
| 56 | else: |
| 57 | self.query_cache[layer_idx] = torch.cat([self.query_cache[layer_idx], query_states], dim=-2) |
| 58 | return self.key_cache[layer_idx], self.value_cache[layer_idx] |
| 59 | |
| 60 | @classmethod |
| 61 | def from_legacy_cache(cls, past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None) -> "DynamicCache": |
no outgoing calls
no test coverage detected