MCPcopy Create free account
hub / github.com/OSU-NLP-Group/In-Context-Reranking / DynamicCacheWithQuery

Class DynamicCacheWithQuery

src/custom/custom_cache.py:5–68  ·  view source on GitHub ↗

Cache class used for In-context RAG

Source from the content-addressed store, hash-verified

3import torch
4
5class DynamicCacheWithQuery(DynamicCache):
6 '''
7 Cache class used for In-context RAG
8 '''
9 def __init__(self, query_indices=[]) -> None:
10 super().__init__()
11 self._query_indices = query_indices # indices for query vectors to save
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":
62 """Converts a cache in the legacy cache format into an equivalent `DynamicCache`."""

Callers 1

score_documentsMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected