cache_utils.py 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574
  1. from abc import ABC, abstractmethod
  2. from collections.abc import Iterable
  3. import torch
  4. from .configuration_utils import PreTrainedConfig
  5. from .utils import (
  6. is_hqq_available,
  7. is_optimum_quanto_available,
  8. is_quanto_greater,
  9. is_torch_greater_or_equal,
  10. is_torchdynamo_compiling,
  11. logging,
  12. )
  13. if is_hqq_available():
  14. from hqq.core.quantize import Quantizer as HQQQuantizer
  15. _is_torch_greater_or_equal_than_2_7 = is_torch_greater_or_equal("2.7", accept_dev=True)
  16. logger = logging.get_logger(__name__)
  17. class CacheLayerMixin(ABC):
  18. """Base, abstract class for a single layer's cache."""
  19. is_compileable = False
  20. def __init__(self):
  21. self.keys: torch.Tensor | None = None
  22. self.values: torch.Tensor | None = None
  23. self.is_initialized = False
  24. def __repr__(self):
  25. return f"{self.__class__.__name__}"
  26. @abstractmethod
  27. def lazy_initialization(self, key_states: torch.Tensor, value_states: torch.Tensor) -> None: ...
  28. @abstractmethod
  29. def update(
  30. self, key_states: torch.Tensor, value_states: torch.Tensor, *args, **kwargs
  31. ) -> tuple[torch.Tensor, torch.Tensor]: ...
  32. @abstractmethod
  33. def get_mask_sizes(self, query_length: int) -> tuple[int, int]: ...
  34. @abstractmethod
  35. def get_seq_length(self) -> int: ...
  36. @abstractmethod
  37. def get_max_cache_shape(self) -> int: ...
  38. def offload(self):
  39. """Offload this layer's data to CPU device."""
  40. if self.is_initialized:
  41. self.keys = self.keys.to("cpu", non_blocking=True)
  42. self.values = self.values.to("cpu", non_blocking=True)
  43. def prefetch(self):
  44. """In case of layer offloading, this allows to move the data back to the layer's device ahead of time."""
  45. if self.is_initialized and self.keys.device != self.device:
  46. self.keys = self.keys.to(self.device, non_blocking=True)
  47. self.values = self.values.to(self.device, non_blocking=True)
  48. def reset(self) -> None:
  49. """Resets the cache values while preserving the objects"""
  50. if self.is_initialized:
  51. self.keys.zero_()
  52. self.values.zero_()
  53. # This attribute is set on several Layers
  54. if hasattr(self, "cumulative_length"):
  55. # It can either be an int for dynamic layers, or a tensor for static layers
  56. if isinstance(self.cumulative_length, int):
  57. self.cumulative_length = 0
  58. else:
  59. self.cumulative_length.zero_()
  60. def reorder_cache(self, beam_idx: torch.LongTensor) -> None:
  61. """Reorders this layer's cache for beam search."""
  62. if self.get_seq_length() > 0:
  63. self.keys = self.keys.index_select(0, beam_idx.to(self.keys.device))
  64. self.values = self.values.index_select(0, beam_idx.to(self.values.device))
  65. class DynamicLayer(CacheLayerMixin):
  66. """
  67. A cache layer that grows dynamically as more tokens are generated. This is the default for generative models.
  68. It stores the key and value states as tensors of shape `[batch_size, num_heads, seq_len, head_dim]`.
  69. """
  70. is_sliding = False
  71. def lazy_initialization(self, key_states: torch.Tensor, value_states: torch.Tensor) -> None:
  72. self.dtype, self.device = key_states.dtype, key_states.device
  73. self.keys = torch.tensor([], dtype=self.dtype, device=self.device)
  74. self.values = torch.tensor([], dtype=self.dtype, device=self.device)
  75. self.is_initialized = True
  76. def update(
  77. self, key_states: torch.Tensor, value_states: torch.Tensor, *args, **kwargs
  78. ) -> tuple[torch.Tensor, torch.Tensor]:
  79. """
  80. Update the key and value caches in-place, and return the necessary keys and value states.
  81. Args:
  82. key_states (`torch.Tensor`): The new key states to cache.
  83. value_states (`torch.Tensor`): The new value states to cache.
  84. Returns:
  85. tuple[`torch.Tensor`, `torch.Tensor`]: The key and value states.
  86. """
  87. # Lazy initialization
  88. if not self.is_initialized:
  89. self.lazy_initialization(key_states, value_states)
  90. self.keys = torch.cat([self.keys, key_states], dim=-2)
  91. self.values = torch.cat([self.values, value_states], dim=-2)
  92. return self.keys, self.values
  93. def get_mask_sizes(self, query_length: int) -> tuple[int, int]:
  94. """Return the length and offset of the cache, used to generate the mask"""
  95. kv_offset = 0
  96. kv_length = self.get_seq_length() + query_length
  97. return kv_length, kv_offset
  98. def get_seq_length(self) -> int:
  99. """Returns the sequence length of the cached states."""
  100. if not self.is_initialized or self.keys.numel() == 0:
  101. return 0
  102. return self.keys.shape[-2]
  103. def get_max_cache_shape(self) -> int:
  104. """Returns the maximum sequence length of the cache object. DynamicLayer does not have a maximum length."""
  105. return -1
  106. def crop(self, max_length: int) -> None:
  107. """
  108. Crop the past key values up to a new `max_length` in terms of tokens. `max_length` can also be negative
  109. to remove `max_length` tokens.
  110. """
  111. if max_length < 0:
  112. max_length = self.get_seq_length() - abs(max_length)
  113. if self.get_seq_length() <= max_length:
  114. return
  115. self.keys = self.keys[..., :max_length, :]
  116. self.values = self.values[..., :max_length, :]
  117. def batch_repeat_interleave(self, repeats: int) -> None:
  118. """Repeat the cache `repeats` times in the batch dimension."""
  119. if self.get_seq_length() > 0:
  120. self.keys = self.keys.repeat_interleave(repeats, dim=0)
  121. self.values = self.values.repeat_interleave(repeats, dim=0)
  122. def batch_select_indices(self, indices: torch.Tensor) -> None:
  123. """Only keep the `indices` in the batch dimension of the cache."""
  124. if self.get_seq_length() > 0:
  125. self.keys = self.keys[indices, ...]
  126. self.values = self.values[indices, ...]
  127. class DynamicSlidingWindowLayer(DynamicLayer):
  128. """
  129. A cache layer that grows dynamically as more tokens are generated, up until the sliding window size.
  130. It stores the key and value states as tensors of shape `[batch_size, num_heads, min(seq_len, sliding_window), head_dim]`.
  131. """
  132. is_sliding = True
  133. def __init__(self, sliding_window: int):
  134. super().__init__()
  135. self.sliding_window = sliding_window
  136. self.cumulative_length = 0
  137. self._sliding_window_tensor = torch.tensor(self.sliding_window, dtype=torch.long)
  138. def lazy_initialization(self, key_states: torch.Tensor, value_states: torch.Tensor) -> None:
  139. super().lazy_initialization(key_states, value_states)
  140. self._sliding_window_tensor = self._sliding_window_tensor.to(self.device)
  141. def update(
  142. self, key_states: torch.Tensor, value_states: torch.Tensor, *args, **kwargs
  143. ) -> tuple[torch.Tensor, torch.Tensor]:
  144. """
  145. Update the key and value caches in-place, and return the necessary keys and value states.
  146. Args:
  147. key_states (`torch.Tensor`): The new key states to cache.
  148. value_states (`torch.Tensor`): The new value states to cache.
  149. Returns:
  150. tuple[`torch.Tensor`, `torch.Tensor`]: The key and value states.
  151. """
  152. # Lazy initialization
  153. if not self.is_initialized:
  154. self.lazy_initialization(key_states, value_states)
  155. self.cumulative_length += key_states.shape[-2]
  156. # Compute the full states
  157. full_key_states = torch.cat([self.keys, key_states], dim=-2)
  158. full_value_states = torch.cat([self.values, value_states], dim=-2)
  159. # Only cache the last `self.sliding_window - 1` tokens (or all of them if lower than that)
  160. self.keys = full_key_states[:, :, -self.sliding_window + 1 :, :]
  161. self.values = full_value_states[:, :, -self.sliding_window + 1 :, :]
  162. # Return the full states
  163. return full_key_states, full_value_states
  164. def get_mask_sizes(self, query_length: int) -> tuple[int, int]:
  165. """Return the length and offset of the cache, used to generate the attention mask"""
  166. is_full = self.cumulative_length >= self.sliding_window
  167. kv_offset = max(self.cumulative_length - self.sliding_window + 1, 0)
  168. if is_full:
  169. kv_length = self.sliding_window - 1 + query_length
  170. else:
  171. kv_length = self.cumulative_length + query_length
  172. return kv_length, kv_offset
  173. def get_seq_length(self) -> int:
  174. """Returns the sequence length of the cached states."""
  175. return self.cumulative_length
  176. def get_max_cache_shape(self) -> int:
  177. """Return the maximum cache shape of the cache"""
  178. return self.sliding_window
  179. def crop(self, max_length: int) -> None:
  180. """
  181. Crop the past key values up to a new `max_length` in terms of tokens. `max_length` can also be
  182. negative to remove `max_length` tokens.
  183. """
  184. if self.get_seq_length() >= self.sliding_window:
  185. raise ValueError(
  186. "Cannot `crop` a `DynamicSlidingWindowLayer` after it has seen more tokens than its"
  187. "sliding window (otherwise some states are lost)"
  188. )
  189. super().crop(max_length)
  190. self.cumulative_length = self.keys.shape[-2]
  191. class StaticLayer(CacheLayerMixin):
  192. """
  193. A static cache layer that stores the key and value states as static tensors of shape `[batch_size, num_heads, max_cache_len), head_dim]`.
  194. It lazily allocates its full backing tensors, and then mutates them in-place. Built for `torch.compile` support.
  195. Args:
  196. max_cache_len (`int`):
  197. Maximum number of tokens that can be stored, used for tensor preallocation.
  198. """
  199. is_compileable = True
  200. is_sliding = False
  201. def __init__(self, max_cache_len: int):
  202. super().__init__()
  203. self.max_cache_len = max_cache_len
  204. # Very important that it's a tensor here, to avoid recompiling when we update it and use it to create positions
  205. self.cumulative_length = torch.tensor([0], dtype=int)
  206. def lazy_initialization(self, key_states: torch.Tensor, value_states: torch.Tensor) -> None:
  207. """
  208. Lazy initialization of the keys and values tensors. This allows to get all properties (dtype, device,
  209. num_heads in case of TP etc...) at runtime directly, which is extremely practical as it avoids moving
  210. devices, dtypes etc later on for each `update` (which could break the static dynamo addresses as well).
  211. If this is unwanted, one can call `early_initialization(...)` on the Cache directly, which will call this
  212. function ahead-of-time (this is required for `torch.export` for example). Note that for `compile`, as we
  213. internally don't compile the prefill, this is guaranteed to have been called already when compiling.
  214. If compiling the prefill as well, e.g. calling `model.compile(...)` before `generate` with a static cache,
  215. it is still supported in general, but without guarantees depending on the compilation options (e.g. cuda graphs,
  216. i.e. `mode="reduce-overhead"` is known to fail). But it will in general work correctly, and prefill should
  217. not be compiled anyway for performances!
  218. """
  219. self.dtype, self.device = key_states.dtype, key_states.device
  220. self.max_batch_size, self.num_heads = key_states.shape[:2]
  221. self.v_head_dim = value_states.shape[-1]
  222. self.k_head_dim = key_states.shape[-1]
  223. self.keys = torch.zeros(
  224. (self.max_batch_size, self.num_heads, self.max_cache_len, self.k_head_dim),
  225. dtype=self.dtype,
  226. device=self.device,
  227. )
  228. self.values = torch.zeros(
  229. (self.max_batch_size, self.num_heads, self.max_cache_len, self.v_head_dim),
  230. dtype=self.dtype,
  231. device=self.device,
  232. )
  233. self.cumulative_length = self.cumulative_length.to(self.device)
  234. # Note: `mark_static_address` is used to tag the tensors as a fixed data pointer, preventing compiled graph
  235. # breaks or cudagraph skips due to inplace mutations when updating the cache. However, it is not supported when
  236. # tracing the graph, so we skip it in this case. As prefill should never be compiled, this is not an issue and it
  237. # will still be run (except when users compile prefill explicitly, but this should be avoided!)
  238. # Without this, we cannot use cudagraphs!!
  239. if not is_torchdynamo_compiling():
  240. torch._dynamo.mark_static_address(self.keys)
  241. torch._dynamo.mark_static_address(self.values)
  242. torch._dynamo.mark_static_address(self.cumulative_length)
  243. self.is_initialized = True
  244. def update(
  245. self, key_states: torch.Tensor, value_states: torch.Tensor, *args, **kwargs
  246. ) -> tuple[torch.Tensor, torch.Tensor]:
  247. """
  248. Update the key and value caches in-place, and return the necessary keys and value states.
  249. Args:
  250. key_states (`torch.Tensor`): The new key states to cache.
  251. value_states (`torch.Tensor`): The new value states to cache.
  252. Returns:
  253. tuple[`torch.Tensor`, `torch.Tensor`]: The key and value states.
  254. """
  255. # Lazy initialization
  256. if not self.is_initialized:
  257. self.lazy_initialization(key_states, value_states)
  258. # Create a tensor to slice the static kv at the correct indices
  259. kv_length = key_states.shape[-2]
  260. cache_position = torch.arange(kv_length, device=self.device) + self.cumulative_length
  261. # Note that has to be performed in-place, as we have a static address that we need to keep
  262. self.cumulative_length.add_(kv_length)
  263. # Update the cache
  264. try:
  265. self.keys.index_copy_(2, cache_position, key_states)
  266. self.values.index_copy_(2, cache_position, value_states)
  267. except NotImplementedError:
  268. # Fallback for devices like MPS where index_copy_ might not be supported.
  269. self.keys[:, :, cache_position] = key_states
  270. self.values[:, :, cache_position] = value_states
  271. return self.keys, self.values
  272. def get_mask_sizes(self, query_length: int) -> tuple[int, int]:
  273. """Return the length and offset of the cache, used to generate the attention mask"""
  274. kv_offset = 0
  275. kv_length = self.max_cache_len
  276. return kv_length, kv_offset
  277. def get_seq_length(self) -> int:
  278. """Returns the sequence length of the cached states."""
  279. return self.cumulative_length if self.is_initialized else 0
  280. def get_max_cache_shape(self) -> int:
  281. """Return the maximum cache shape of the cache"""
  282. return self.max_cache_len
  283. class StaticSlidingWindowLayer(StaticLayer):
  284. """
  285. A static cache layer that stores the key and value states as static tensors of shape
  286. `[batch_size, num_heads, min(max_cache_len, sliding_window), head_dim]`. It lazily allocates its full backing
  287. tensors, and then mutates them in-place. Built for `torch.compile` support.
  288. Args:
  289. max_cache_len (`int`):
  290. Maximum number of tokens that can be stored, used for tensor preallocation.
  291. sliding_window (`int`):
  292. The size of the sliding window.
  293. """
  294. is_sliding = True
  295. def __init__(self, max_cache_len: int, sliding_window: int):
  296. effective_max_cache_len = min(sliding_window, max_cache_len)
  297. super().__init__(max_cache_len=effective_max_cache_len)
  298. # Here, to avoid data-dependent control flows, we also need to use a python int to keep track of the cumulative length
  299. self.cumulative_length_int = 0
  300. def update(
  301. self, key_states: torch.Tensor, value_states: torch.Tensor, *args, **kwargs
  302. ) -> tuple[torch.Tensor, torch.Tensor]:
  303. """
  304. Update the key and value caches in-place, and return the necessary keys and value states.
  305. Args:
  306. key_states (`torch.Tensor`): The new key states to cache.
  307. value_states (`torch.Tensor`): The new value states to cache.
  308. Returns:
  309. tuple[`torch.Tensor`, `torch.Tensor`]: The key and value states.
  310. """
  311. # Lazy initialization
  312. if not self.is_initialized:
  313. self.lazy_initialization(key_states, value_states)
  314. kv_length = key_states.shape[-2]
  315. current_length = self.cumulative_length_int
  316. is_full = current_length >= self.max_cache_len
  317. # Update it now that we saved the value above
  318. self.cumulative_length_int += kv_length
  319. if is_full:
  320. # In general, we should use a much simpler `cat` here as well, independently of the states size. However,
  321. # dynamo is currently bugged when doing it - see https://github.com/pytorch/pytorch/issues/159855 for more details
  322. if key_states.shape[-2] == 1:
  323. # Roll all values to the left by 1 position
  324. new_keys = self.keys.roll(-1, dims=-2)
  325. new_values = self.values.roll(-1, dims=-2)
  326. # Overwrite the last position with new states
  327. # (note: very important to use a tensor to index here, see https://github.com/pytorch/pytorch/issues/159855)
  328. index = torch.tensor([-1], dtype=int, device=self.device)
  329. new_keys[:, :, index] = key_states
  330. new_values[:, :, index] = value_states
  331. # Copy back into `self` (do not just assign again) in order to keep the static dynamo address
  332. self.keys.copy_(new_keys)
  333. self.values.copy_(new_values)
  334. # Very important to return the `self` tensors here, as they have the static dynamo address
  335. return self.keys, self.values
  336. # Already full but using more than 1 new token (e.g. prefill caching, chat continuation, etc...)
  337. else:
  338. full_key_states = torch.cat((self.keys[:, :, 1:, :], key_states), dim=-2)
  339. full_value_states = torch.cat((self.values[:, :, 1:, :], value_states), dim=-2)
  340. # Not yet full, but becoming full on this update
  341. elif current_length + kv_length > self.max_cache_len:
  342. # Fast prefill path, no need to cat() in this case, as the cache is currently empty
  343. if current_length == 0:
  344. full_key_states = key_states
  345. full_value_states = value_states
  346. else:
  347. full_key_states = torch.cat((self.keys[:, :, :current_length, :], key_states), dim=-2)
  348. full_value_states = torch.cat((self.values[:, :, :current_length, :], value_states), dim=-2)
  349. else:
  350. # Note: very important to use the tensor version of the cumulative length here, as otherwise cudagraphs
  351. # (triggered by mode="reduced_overhead") will lead to random crashes, as the int would be overwritten
  352. cache_position = torch.arange(kv_length, device=self.device) + self.cumulative_length
  353. try:
  354. self.keys.index_copy_(2, cache_position, key_states)
  355. self.values.index_copy_(2, cache_position, value_states)
  356. except NotImplementedError:
  357. self.keys[:, :, cache_position] = key_states
  358. self.values[:, :, cache_position] = value_states
  359. # Update the tensor version of the length in-place (we don't need to update it if we are already outside
  360. # of this branch, as we don't need the tensor anymore)
  361. self.cumulative_length.add_(kv_length)
  362. # Very important to return the `self` tensors here, as they have the static dynamo address
  363. return self.keys, self.values
  364. # We only cache the last `sliding_window` tokens
  365. self.keys.copy_(full_key_states[:, :, -self.max_cache_len :, :])
  366. self.values.copy_(full_value_states[:, :, -self.max_cache_len :, :])
  367. # we should return the whole states instead of `self.keys/values` here, as otherwise we lose some context
  368. return full_key_states, full_value_states
  369. def get_mask_sizes(self, query_length: int) -> tuple[int, int]:
  370. """Return the length and offset of the cache, used to generate the attention mask"""
  371. sliding_window = self.max_cache_len
  372. is_full = self.cumulative_length_int >= self.max_cache_len
  373. kv_offset = max(self.cumulative_length_int - sliding_window + 1, 0)
  374. # The cache is already full
  375. if is_full:
  376. kv_length = sliding_window + query_length - 1
  377. # Not yet full, but becoming full on this update
  378. elif self.cumulative_length_int + query_length > sliding_window:
  379. kv_length = self.cumulative_length_int + query_length
  380. # Here the Cache is still smaller than the local size, but we return the local size as it's static
  381. else:
  382. kv_length = sliding_window
  383. return kv_length, kv_offset
  384. def get_seq_length(self) -> int:
  385. """Returns the sequence length of the cached states."""
  386. return self.cumulative_length_int
  387. def reset(self):
  388. super().reset()
  389. self.cumulative_length_int = 0
  390. class QuantizedLayer(DynamicLayer):
  391. """
  392. A quantized layer similar to what is described in the [KIVI: A Tuning-Free Asymmetric 2bit Quantization for KV Cache paper](https://huggingface.co/papers/2402.02750).
  393. It allows the model to generate longer sequence length without allocating too much memory for the key and value caches by
  394. applying quantization.
  395. The cache has two types of storage, one for original precision and one for the quantized cache. A `residual length`
  396. is set as a maximum capacity for the original precision cache. When the length goes beyond maximum capacity, the original
  397. precision cache is discarded and moved into the quantized cache. The quantization is done per-channel with a set `q_group_size`
  398. for both Keys and Values, in contrast to what was described in the paper.
  399. """
  400. def __init__(
  401. self,
  402. nbits: int = 4,
  403. axis_key: int = 0,
  404. axis_value: int = 0,
  405. q_group_size: int = 64,
  406. residual_length: int = 128,
  407. ):
  408. super().__init__()
  409. self.nbits = nbits
  410. self.axis_key = axis_key
  411. self.axis_value = axis_value
  412. self.q_group_size = q_group_size
  413. self.residual_length = residual_length
  414. self.cumulative_length = 0
  415. def update(
  416. self, key_states: torch.Tensor, value_states: torch.Tensor, *args, **kwargs
  417. ) -> tuple[torch.Tensor, torch.Tensor]:
  418. """
  419. Update the key and value caches in-place, and return the necessary keys and value states.
  420. Args:
  421. key_states (`torch.Tensor`): The new key states to cache.
  422. value_states (`torch.Tensor`): The new value states to cache.
  423. Returns:
  424. tuple[`torch.Tensor`, `torch.Tensor`]: The key and value states.
  425. """
  426. self.cumulative_length += key_states.shape[-2]
  427. # Lazy initialization
  428. if not self.is_initialized:
  429. self.lazy_initialization(key_states, value_states)
  430. self._quantized_keys = self._quantize(key_states.contiguous(), axis=self.axis_key)
  431. self._quantized_values = self._quantize(value_states.contiguous(), axis=self.axis_value)
  432. return key_states, value_states
  433. dequant_keys = self._dequantize(self._quantized_keys)
  434. dequant_values = self._dequantize(self._quantized_values)
  435. keys_to_return = torch.cat([dequant_keys, self.keys, key_states], dim=-2)
  436. values_to_return = torch.cat([dequant_values, self.values, value_states], dim=-2)
  437. if self.keys.dim() == 4 and self.keys.shape[-2] + 1 >= self.residual_length:
  438. self._quantized_keys = self._quantize(keys_to_return.contiguous(), axis=self.axis_key)
  439. self._quantized_values = self._quantize(values_to_return.contiguous(), axis=self.axis_value)
  440. self.keys = torch.tensor([], dtype=key_states.dtype, device=key_states.device)
  441. self.values = torch.tensor([], dtype=key_states.dtype, device=key_states.device)
  442. else:
  443. self.keys = torch.cat([self.keys, key_states], dim=-2)
  444. self.values = torch.cat([self.values, value_states], dim=-2)
  445. return keys_to_return, values_to_return
  446. @abstractmethod
  447. def _quantize(self, tensor, axis): ...
  448. @abstractmethod
  449. def _dequantize(self, q_tensor): ...
  450. def get_seq_length(self) -> int:
  451. """Returns the sequence length of the cached states."""
  452. return self.cumulative_length
  453. class QuantoQuantizedLayer(QuantizedLayer):
  454. def __init__(
  455. self,
  456. nbits: int = 4,
  457. axis_key: int = 0,
  458. axis_value: int = 0,
  459. q_group_size: int = 64,
  460. residual_length: int = 128,
  461. ):
  462. super().__init__(
  463. nbits=nbits,
  464. axis_key=axis_key,
  465. axis_value=axis_value,
  466. q_group_size=q_group_size,
  467. residual_length=residual_length,
  468. )
  469. # We need to import quanto here to avoid circular imports due to optimum/quanto/models/transformers_models.py
  470. if not is_optimum_quanto_available():
  471. raise ImportError(
  472. "You need to install optimum-quanto in order to use KV cache quantization with optimum-quanto "
  473. "backend. Please install it via with `pip install optimum-quanto`"
  474. )
  475. elif is_quanto_greater("0.2.5", accept_dev=True):
  476. from optimum.quanto import MaxOptimizer, qint2, qint4
  477. else:
  478. raise ImportError(
  479. "You need optimum-quanto package version to be greater or equal than 0.2.5 to use `QuantoQuantizedLayer`. "
  480. )
  481. if self.nbits not in [2, 4]:
  482. raise ValueError(f"`nbits` for `quanto` backend has to be one of [`2`, `4`] but got {self.nbits}")
  483. if self.axis_key not in [0, -1]:
  484. raise ValueError(f"`axis_key` for `quanto` backend has to be one of [`0`, `-1`] but got {self.axis_key}")
  485. if self.axis_value not in [0, -1]:
  486. raise ValueError(
  487. f"`axis_value` for `quanto` backend has to be one of [`0`, `-1`] but got {self.axis_value}"
  488. )
  489. self.qtype = qint4 if self.nbits == 4 else qint2
  490. self.optimizer = MaxOptimizer() # hardcode as it's the only one for per-channel quantization
  491. def _quantize(self, tensor, axis):
  492. from optimum.quanto import quantize_weight
  493. scale, zeropoint = self.optimizer(tensor, self.qtype, axis, self.q_group_size)
  494. qtensor = quantize_weight(tensor, self.qtype, axis, scale, zeropoint, self.q_group_size)
  495. return qtensor
  496. def _dequantize(self, qtensor):
  497. return qtensor.dequantize()
  498. class HQQQuantizedLayer(QuantizedLayer):
  499. def __init__(
  500. self,
  501. nbits: int = 4,
  502. axis_key: int = 0,
  503. axis_value: int = 0,
  504. q_group_size: int = 64,
  505. residual_length: int = 128,
  506. ):
  507. super().__init__(
  508. nbits=nbits,
  509. axis_key=axis_key,
  510. axis_value=axis_value,
  511. q_group_size=q_group_size,
  512. residual_length=residual_length,
  513. )
  514. if not is_hqq_available():
  515. raise ImportError(
  516. "You need to install `HQQ` in order to use KV cache quantization with HQQ backend. "
  517. "Please install it via with `pip install hqq`"
  518. )
  519. if self.nbits not in [1, 2, 3, 4, 8]:
  520. raise ValueError(
  521. f"`nbits` for `HQQ` backend has to be one of [`1`, `2`, `3`, `4`, `8`] but got {self.nbits}"
  522. )
  523. if self.axis_key not in [0, 1]:
  524. raise ValueError(f"`axis_key` for `HQQ` backend has to be one of [`0`, `1`] but got {self.axis_key}")
  525. if self.axis_value not in [0, 1]:
  526. raise ValueError(f"`axis_value` for `HQQ` backend has to be one of [`0`, `1`] but got {self.axis_value}")
  527. self.quantizer = HQQQuantizer
  528. def _quantize(self, tensor, axis):
  529. qtensor, meta = self.quantizer.quantize(
  530. tensor,
  531. axis=axis,
  532. device=self.keys.device,
  533. compute_dtype=self.keys.dtype,
  534. nbits=self.nbits,
  535. group_size=self.q_group_size,
  536. )
  537. meta["compute_dtype"] = self.keys.dtype
  538. self.quantizer.cuda(qtensor, meta=meta, device=self.keys.device) # Move to device and cast to dtype
  539. meta["scale"] = meta["scale"].to(qtensor.device)
  540. meta["zero"] = meta["zero"].to(qtensor.device)
  541. return qtensor, meta
  542. def _dequantize(self, qtensor):
  543. quant_tensor, meta = qtensor
  544. tensor = self.quantizer.dequantize(quant_tensor, meta)
  545. return tensor
  546. class LinearAttentionCacheLayerMixin(ABC):
  547. """Base, abstract class for a linear attention single layer's cache."""
  548. # All shapes are static by essence in a LinearAttention layer, so it is compileable
  549. is_compileable = True
  550. def __init__(self):
  551. self.conv_states: torch.Tensor | None = None
  552. self.recurrent_states: torch.Tensor | None = None
  553. self.is_conv_states_initialized = False
  554. self.is_recurrent_states_initialized = False
  555. self.has_previous_state = False
  556. def __repr__(self):
  557. return f"{self.__class__.__name__}"
  558. @abstractmethod
  559. def lazy_initialization(
  560. self, conv_states: torch.Tensor | None = None, recurrent_states: torch.Tensor | None = None
  561. ) -> None: ...
  562. @abstractmethod
  563. def update_conv_state(self, conv_states: torch.Tensor) -> torch.Tensor: ...
  564. @abstractmethod
  565. def update_recurrent_state(self, recurrent_states: torch.Tensor) -> torch.Tensor: ...
  566. def offload(self):
  567. """Offload this layer's data to CPU device."""
  568. if self.is_conv_states_initialized:
  569. self.conv_states = self.conv_states.to("cpu", non_blocking=True)
  570. if self.is_recurrent_states_initialized:
  571. self.recurrent_states = self.recurrent_states.to("cpu", non_blocking=True)
  572. def prefetch(self):
  573. """In case of layer offloading, this allows to move the data back to the layer's device ahead of time."""
  574. if self.is_conv_states_initialized and self.conv_states.device != self.device:
  575. self.conv_states = self.conv_states.to(self.device, non_blocking=True)
  576. if self.is_recurrent_states_initialized and self.recurrent_states.device != self.device:
  577. self.recurrent_states = self.recurrent_states.to(self.device, non_blocking=True)
  578. def reset(self) -> None:
  579. """Resets the cache values while preserving the objects"""
  580. if self.is_conv_states_initialized:
  581. self.conv_states.zero_()
  582. if self.is_recurrent_states_initialized:
  583. self.recurrent_states.zero_()
  584. self.has_previous_state = False
  585. def reorder_cache(self, beam_idx: torch.LongTensor):
  586. """Reorders the cache for beam search, given the selected beam indices."""
  587. if self.is_conv_states_initialized:
  588. self.conv_states = self.conv_states.index_select(0, beam_idx.to(self.device))
  589. # recurrent_states can stay empty sometimes, see e.g. lfm2 which only uses the conv_states
  590. if self.is_recurrent_states_initialized:
  591. self.recurrent_states = self.recurrent_states.index_select(0, beam_idx.to(self.device))
  592. def crop(self, max_length: int):
  593. # We don't crop the linear attention cache, so simply do nothing here
  594. pass
  595. class LinearAttentionLayer(LinearAttentionCacheLayerMixin):
  596. def lazy_initialization(
  597. self, conv_states: torch.Tensor | None = None, recurrent_states: torch.Tensor | None = None
  598. ) -> None:
  599. # Here, we will lazy init both states separately, each in their own update function
  600. if conv_states is not None:
  601. self.dtype, self.device = conv_states.dtype, conv_states.device
  602. # Even if prefill is larfer/shorter than the conv_size, the tensor is always either padded or truncated
  603. self.max_batch_size, self.conv_kernel_size = conv_states.shape[0], conv_states.shape[-1]
  604. # The shape is always static, so we init as such
  605. self.conv_states = torch.zeros_like(conv_states, dtype=self.dtype, device=self.device)
  606. # Mark as static address to be able to use cudagraphs
  607. if not is_torchdynamo_compiling():
  608. torch._dynamo.mark_static_address(self.conv_states)
  609. self.is_conv_states_initialized = True
  610. if recurrent_states is not None:
  611. # The shape is always static, so we init as such
  612. self.recurrent_states = torch.zeros_like(recurrent_states, dtype=self.dtype, device=self.device)
  613. # Mark as static address to be able to use cudagraphs
  614. if not is_torchdynamo_compiling():
  615. torch._dynamo.mark_static_address(self.recurrent_states)
  616. self.is_recurrent_states_initialized = True
  617. def update_conv_state(self, conv_states: torch.Tensor, **kwargs) -> torch.Tensor:
  618. """
  619. Update the linear attention cache in-place, and return the necessary conv states.
  620. Args:
  621. conv_states (`torch.Tensor`): The new conv states to cache.
  622. Returns:
  623. `torch.Tensor`: The updated conv states.
  624. """
  625. # Lazy initialization
  626. if not self.is_conv_states_initialized:
  627. self.lazy_initialization(conv_states=conv_states)
  628. if not self.has_previous_state:
  629. # Note that we copy instead of assigning, to preserve the static address for cudagraphs
  630. self.conv_states.copy_(conv_states)
  631. self.has_previous_state = True
  632. # Technically, this update is not logically correct if the prefill is smaller than `conv_kernel_size`,
  633. # as it will `roll` anyway in the first decoding step, even though it should `roll` ONLY if the cache is already full.
  634. # But since `conv_kernel_size=4` in practice, it's almost impossible to have a smaller prefill so it's mostly fine for now
  635. else:
  636. # Note that we copy instead of assigning, to preserve the static address for cudagraphs
  637. num_new_tokens = conv_states.shape[-1]
  638. if num_new_tokens >= self.conv_kernel_size:
  639. self.conv_states.copy_(conv_states[..., -self.conv_kernel_size :])
  640. else:
  641. new_conv_states = self.conv_states.roll(shifts=-num_new_tokens, dims=-1)
  642. new_conv_states[:, :, -num_new_tokens:] = conv_states
  643. self.conv_states.copy_(new_conv_states)
  644. return self.conv_states
  645. def update_recurrent_state(self, recurrent_states: torch.Tensor, **kwargs) -> torch.Tensor:
  646. """
  647. Update the linear attention cache in-place, and return the necessary ssm states.
  648. Args:
  649. smm_states (`torch.Tensor`): The new ssm states to cache.
  650. Returns:
  651. `torch.Tensor`: The updated ssm states.
  652. """
  653. if not self.is_recurrent_states_initialized:
  654. self.lazy_initialization(recurrent_states=recurrent_states)
  655. # Note that we copy instead of assigning, to preserve the static address for cudagraphs
  656. self.recurrent_states.copy_(recurrent_states)
  657. return self.recurrent_states
  658. class LinearAttentionAndFullAttentionLayer(LinearAttentionLayer, DynamicLayer):
  659. # The dynamic Attention part makes it non-compileable
  660. is_compileable = False
  661. def __init__(self):
  662. DynamicLayer.__init__(self)
  663. LinearAttentionLayer.__init__(self)
  664. def lazy_initialization(self, *args, **kwargs) -> None:
  665. # When the Attention cache is used with `update`, `lazy_initialization` is called with 2 positional args
  666. if len(args) == 2 and len(kwargs) == 0:
  667. DynamicLayer.lazy_initialization(self, *args)
  668. # Otherwise, for the LinearAttention cache, when it's called in `update_conv_state` or `update_recurrent_state`, it's
  669. # always called with 1 single kwarg (cause it needs to know if it's for the conv or ssm states)
  670. if len(args) == 0 and len(kwargs) == 1:
  671. LinearAttentionLayer.lazy_initialization(self, **kwargs)
  672. def reset(self) -> None:
  673. LinearAttentionLayer.reset(self)
  674. DynamicLayer.reset(self)
  675. def reorder_cache(self, beam_idx: torch.LongTensor):
  676. """Reorders the cache for beam search, given the selected beam indices."""
  677. LinearAttentionLayer.reorder_cache(self, beam_idx)
  678. DynamicLayer.reorder_cache(self, beam_idx)
  679. class Cache:
  680. """
  681. A `Cache` is mostly a list of `CacheLayerMixin` objects, one per model layer. It serves as a container for
  682. the Cache of each layer.
  683. Args:
  684. layers (`Optional`, *optional*):
  685. A list of pre-created `CacheLayerMixin` or `LinearAttentionCacheLayerMixin`. If omitted (`None`), then `layer_class_to_replicate`
  686. will be used.
  687. layer_class_to_replicate (`type[CacheLayerMixin | LinearAttentionCacheLayerMixin]`, *optional*):
  688. Only used if `layers` is omitted (`None`), in which case it will be used as the base class for each layer,
  689. and the layers will be added lazily as soon as `update` is called with a `layer_idx` greater than the current
  690. list of layers.
  691. offloading (`bool`, *optional*, defaults to `False`):
  692. Whether to perform offloading of the layers to `cpu`, to save GPU memory.
  693. offload_only_non_sliding (`bool`, *optional*, defaults to `True`):
  694. If `offloading` is `True`, this further decides if only the non-sliding layers will be offloaded (because
  695. usually the sliding layers are small in size, so there is no need to offload them, and skipping it is faster).
  696. """
  697. def __init__(
  698. self,
  699. layers: list[CacheLayerMixin | LinearAttentionCacheLayerMixin] | None = None,
  700. layer_class_to_replicate: type[CacheLayerMixin | LinearAttentionCacheLayerMixin] | None = None,
  701. offloading: bool = False,
  702. offload_only_non_sliding: bool = True,
  703. ):
  704. if layers is not None and layer_class_to_replicate is not None:
  705. raise ValueError(
  706. "You can construct a Cache either from a list `layers` of all the predefined `CacheLayer`, or from a "
  707. "`layer_class_to_replicate`, in which case the Cache will append a new layer corresponding to "
  708. "`layer_class_to_replicate` for each new call to `update` with an idx not already in the Cache."
  709. )
  710. if layers is None and layer_class_to_replicate is None:
  711. raise ValueError(
  712. "You should provide exactly one of `layers` or `layer_class_to_replicate` to initialize a Cache."
  713. )
  714. self.layers = layers if layers is not None else []
  715. self.layer_class_to_replicate = layer_class_to_replicate
  716. self.offloading = offloading
  717. if self.offloading:
  718. self.only_non_sliding = offload_only_non_sliding
  719. self.prefetch_stream = torch.Stream() if _is_torch_greater_or_equal_than_2_7 else torch.cuda.Stream()
  720. def __repr__(self):
  721. return f"{self.__class__.__name__}(layers={self.layers})"
  722. def prefetch(self, layer_idx: int, only_non_sliding: bool = True):
  723. """
  724. Prefetch a given layer on its device. If `only_non_sliding` is True, it will try to prefetch only the layers
  725. which are non-sliding. If the `layer_idx` is outside the range, this will circle back to the first layers.
  726. Note that we use a non-default stream for this, to avoid blocking.
  727. """
  728. if only_non_sliding:
  729. # Try to find next non-sliding, starting at `layer_idx`
  730. try:
  731. layer_idx = layer_idx + self.is_sliding[layer_idx:].index(False)
  732. # In this case, we need to circle back to the beginning
  733. except ValueError:
  734. layer_idx = self.is_sliding.index(False)
  735. else:
  736. layer_idx = layer_idx if layer_idx < len(self.layers) else 0
  737. # Prefetch
  738. with self.prefetch_stream if _is_torch_greater_or_equal_than_2_7 else torch.cuda.stream(self.prefetch_stream):
  739. self.layers[layer_idx].prefetch()
  740. def offload(self, layer_idx: int, only_non_sliding: bool = True):
  741. """
  742. Offload a given `layer_idx`. If `only_non_sliding` is True, it will offload `layer_idx` only if it is a
  743. non-sliding layer. Note that we do it on the default stream, so that we ensure all earlier
  744. computation in the layer's `update` methods are finished.
  745. """
  746. if not (only_non_sliding and self.is_sliding[layer_idx]):
  747. self.layers[layer_idx].offload()
  748. def update(
  749. self, key_states: torch.Tensor, value_states: torch.Tensor, layer_idx: int, *args, **kwargs
  750. ) -> tuple[torch.Tensor, torch.Tensor]:
  751. """
  752. Updates the cache with the new `key_states` and `value_states` for the layer `layer_idx`.
  753. Parameters:
  754. key_states (`torch.Tensor`):
  755. The new key states to cache.
  756. value_states (`torch.Tensor`):
  757. The new value states to cache.
  758. layer_idx (`int`):
  759. The index of the layer to cache the states for.
  760. Return:
  761. A tuple containing the updated key and value states.
  762. """
  763. # In this case, the `layers` were not provided, and we must append as much as `layer_idx`
  764. if self.layer_class_to_replicate is not None:
  765. while len(self.layers) <= layer_idx:
  766. self.layers.append(self.layer_class_to_replicate())
  767. if self.offloading:
  768. # Wait for the stream to finish if needed, and start prefetching the next layer
  769. torch.cuda.default_stream(key_states.device).wait_stream(self.prefetch_stream)
  770. self.prefetch(layer_idx + 1, self.only_non_sliding)
  771. keys, values = self.layers[layer_idx].update(key_states, value_states, *args, **kwargs)
  772. if self.offloading:
  773. self.offload(layer_idx, self.only_non_sliding)
  774. return keys, values
  775. def update_conv_state(self, conv_states: torch.Tensor, layer_idx: int, **kwargs) -> torch.Tensor:
  776. """
  777. Updates the cache with the new `conv_states` for the layer `layer_idx`.
  778. Parameters:
  779. conv_states (`torch.Tensor`):
  780. The new conv states to cache.
  781. layer_idx (`int`):
  782. The index of the layer to cache the states for.
  783. Return:
  784. `torch.Tensor`: The updated conv states.
  785. """
  786. # NOTE: if we slightly break `update` arg order, we could combine this with it, and allow offloading support
  787. # out of the box
  788. if not isinstance(self.layers[layer_idx], LinearAttentionCacheLayerMixin):
  789. raise ValueError("Cannot call `update_conv_state` on a non-LinearAttention layer!")
  790. conv_states = self.layers[layer_idx].update_conv_state(conv_states, **kwargs)
  791. return conv_states
  792. def update_recurrent_state(self, recurrent_states: torch.Tensor, layer_idx: int, **kwargs) -> torch.Tensor:
  793. """
  794. Updates the cache with the new `recurrent_states` for the layer `layer_idx`.
  795. Parameters:
  796. smm_states (`torch.Tensor`):
  797. The new ssm states to cache.
  798. layer_idx (`int`):
  799. The index of the layer to cache the states for.
  800. Return:
  801. `torch.Tensor`: The updated ssm states.
  802. """
  803. # NOTE: if we slightly break `update` arg order, we could combine this with it, and allow offloading support
  804. # out of the box
  805. if not isinstance(self.layers[layer_idx], LinearAttentionCacheLayerMixin):
  806. raise ValueError("Cannot call `update_conv_state` on a non-LinearAttention layer!")
  807. recurrent_states = self.layers[layer_idx].update_recurrent_state(recurrent_states, **kwargs)
  808. return recurrent_states
  809. def early_initialization(
  810. self,
  811. batch_size: int,
  812. num_heads: int | list[int],
  813. head_dim: int | list[int],
  814. dtype: torch.dtype,
  815. device: torch.device,
  816. ):
  817. """
  818. Initialize all the layers in advance (it's otherwise lazily initialized on the first `update` call).
  819. This is useful for our `export` recipes, as `export` needs everything in advance.
  820. """
  821. # To allow different num_heads and head_dim depending on layers, we accept lists
  822. if isinstance(num_heads, int):
  823. num_heads = [num_heads] * len(self)
  824. if isinstance(head_dim, int):
  825. head_dim = [head_dim] * len(self)
  826. if len(num_heads) != len(self.layers):
  827. raise ValueError(
  828. f"`num_head` was provided as a list of length {len(num_heads)}, but the Cache currently has {len(self.layers)} layers"
  829. )
  830. if len(head_dim) != len(self.layers):
  831. raise ValueError(
  832. f"`head_dim` was provided as a list of length {len(num_heads)}, but the Cache currently has {len(self.layers)} layers"
  833. )
  834. for layer, layer_num_heads, layer_head_dim in zip(self.layers, num_heads, head_dim):
  835. # Note that the initialization needs all dimensions (except -2), as well as device and dtype, so we use
  836. # this fake tensor approach. It has size 0 on the -2 dimension, so it does not allocate any data (it only
  837. # creates an empty tensor with correct shape, dtype and device), which is very efficient and practical
  838. fake_kv_tensor = torch.zeros((batch_size, layer_num_heads, 0, layer_head_dim), dtype=dtype, device=device)
  839. # Init the layer
  840. layer.lazy_initialization(fake_kv_tensor, fake_kv_tensor)
  841. def get_seq_length(self, layer_idx: int = 0) -> int:
  842. """Returns the sequence length of the cache for the given layer."""
  843. if layer_idx >= len(self.layers):
  844. return 0
  845. # For alternating attention/linear attention caches, `get_seq_length` needs to use attention layer idx when called with default layer_idx
  846. if not isinstance(self.layers[layer_idx], CacheLayerMixin):
  847. # If this is called with non-default arg, raise
  848. if layer_idx != 0:
  849. raise ValueError(
  850. f"You called `get_seq_length` on layer index {layer_idx}, but this layer is a LinearAttention layer, which "
  851. "does not track sequence length."
  852. )
  853. try:
  854. # Use the first attention layer
  855. layer_idx = next(idx for idx in range(len(self)) if isinstance(self.layers[idx], CacheLayerMixin))
  856. except StopIteration:
  857. raise ValueError(
  858. "`get_seq_length` can only be called on Attention layers, and the current Cache seem to only contain "
  859. "LinearAttention layers."
  860. )
  861. return self.layers[layer_idx].get_seq_length()
  862. def has_previous_state(self, layer_idx: int | None = None) -> bool:
  863. """Returns whether the LinearAttention layer at index `layer_idx` has previous state or not."""
  864. if layer_idx is not None and layer_idx >= len(self.layers):
  865. return False
  866. # In this case, use last LinearAttention layer
  867. if layer_idx is None:
  868. try:
  869. layer_idx = next(
  870. idx
  871. for idx in range(len(self) - 1, -1, -1)
  872. if isinstance(self.layers[idx], LinearAttentionCacheLayerMixin)
  873. )
  874. except StopIteration:
  875. raise ValueError(
  876. "`has_previous_state` can only be called on LinearAttention layers, and the current Cache seem to "
  877. "only contain Attention layers."
  878. )
  879. elif not isinstance(self.layers[layer_idx], LinearAttentionCacheLayerMixin):
  880. raise ValueError(
  881. f"You called `has_previous_state` on layer index {layer_idx}, but this layer is an Attention layer, which "
  882. "does not support calling it."
  883. )
  884. return self.layers[layer_idx].has_previous_state
  885. def get_mask_sizes(self, query_length: int, layer_idx: int) -> tuple[int, int]:
  886. """
  887. Return a tuple (kv_length, kv_offset) corresponding to the length and offset that will be returned for
  888. the given layer at `layer_idx`.
  889. The masks are then prepared according to the given lengths (kv_length, kv_offset) and patterns for each layer.
  890. """
  891. # For DynamicCache, where the layers are created at runtime -> if it was not yet created, the size is
  892. # simply the query_length
  893. if layer_idx >= len(self.layers):
  894. return query_length, 0
  895. # For alternating attention/linear attention caches, `get_mask_sizes` needs to use attention layer idx when called with default layer_idx
  896. if not isinstance(self.layers[layer_idx], CacheLayerMixin):
  897. # If this is called with non-default arg, raise
  898. if layer_idx != 0:
  899. raise ValueError(
  900. f"You called `get_mask_sizes` on layer index {layer_idx}, but this layer is a LinearAttention layer, which "
  901. "does not track sequence length."
  902. )
  903. try:
  904. # Use the first attention layer
  905. layer_idx = next(idx for idx in range(len(self)) if isinstance(self.layers[idx], CacheLayerMixin))
  906. except StopIteration:
  907. raise ValueError(
  908. "`get_mask_sizes` can only be called on Attention layers, and the current Cache seem to only contain "
  909. "LinearAttention layers."
  910. )
  911. return self.layers[layer_idx].get_mask_sizes(query_length)
  912. def get_max_cache_shape(self, layer_idx: int = 0) -> int:
  913. """Returns maximum sequence length of the cache object. Dynamic caches do not have a maximum length."""
  914. # For DynamicCache, where the layers are created at runtime -> if it was not yet created, return -1
  915. # as DynamicLayer does
  916. if layer_idx >= len(self.layers):
  917. return -1
  918. return self.layers[layer_idx].get_max_cache_shape()
  919. def reset(self):
  920. """Recursively reset all layers tensors"""
  921. for layer_idx in range(len(self.layers)):
  922. self.layers[layer_idx].reset()
  923. def reorder_cache(self, beam_idx: torch.LongTensor):
  924. """Reorder the cache for beam search"""
  925. for layer_idx in range(len(self.layers)):
  926. self.layers[layer_idx].reorder_cache(beam_idx)
  927. def crop(self, max_length: int):
  928. """Crop the cache to the given length"""
  929. for layer_idx in range(len(self.layers)):
  930. self.layers[layer_idx].crop(max_length)
  931. def batch_repeat_interleave(self, repeats: int):
  932. """Repeat and interleave the cache"""
  933. for layer_idx in range(len(self.layers)):
  934. self.layers[layer_idx].batch_repeat_interleave(repeats)
  935. def batch_select_indices(self, indices: torch.Tensor):
  936. """Select indices from the cache"""
  937. for layer_idx in range(len(self.layers)):
  938. self.layers[layer_idx].batch_select_indices(indices)
  939. @property
  940. def max_batch_size(self) -> int:
  941. """Return the maximum batch size of the cache"""
  942. values = [layer.max_batch_size for layer in self.layers]
  943. if len(set(values)) > 1:
  944. raise ValueError(f"Max batch size is not consistent across layers: {values}")
  945. return values[0]
  946. @property
  947. def max_cache_len(self) -> int:
  948. """Return the maximum cache length of the cache"""
  949. values = [layer.max_cache_len for layer in self.layers]
  950. return max(values)
  951. @property
  952. def is_compileable(self) -> bool:
  953. """Return whether the cache is compilable"""
  954. # For DynamicCache dispatching the layers lazily (otherwise, all([]) is True)
  955. if len(self.layers) == 0:
  956. return False
  957. return all(layer.is_compileable for layer in self.layers)
  958. @property
  959. def is_initialized(self) -> bool:
  960. """Return whether the cache data is initialized"""
  961. return len(self.layers) > 0 and all(layer.is_initialized for layer in self.layers)
  962. @property
  963. def is_sliding(self) -> list[bool]:
  964. """Return whether the layers of the cache are sliding window"""
  965. return [getattr(layer, "is_sliding", False) for layer in self.layers]
  966. def __len__(self):
  967. """
  968. This value corresponds to the number of layers in the model.
  969. """
  970. # Note: for DynamicCache, layers are initialized lazily, so this will not be accurate before the first
  971. # forward through all the layers
  972. return len(self.layers)
  973. class DynamicCache(Cache):
  974. """
  975. A cache that grows dynamically as more tokens are generated. This is the default for generative models.
  976. It stores the key and value states as a list of `CacheLayer`, one for each layer. The expected shape for each tensor
  977. in the `CacheLayer`s is `[batch_size, num_heads, seq_len, head_dim]`.
  978. If a config is passed, it will additionally check for sliding or hybrid cache structure, greatly reducing the
  979. memory requirement of the cached tensors to `[batch_size, num_heads, min(seq_len, sliding_window), head_dim]`.
  980. See `Cache` for details on common methods that are implemented by all cache classes.
  981. Args:
  982. ddp_cache_data (`Iterable[tuple[torch.Tensor, torch.Tensor]]`, *optional*):
  983. It was originally added for compatibility with `torch.distributed` (DDP). In a nutshell, it is
  984. `map(gather_map, zip(*caches))`, i.e. each item in the iterable contains the key and value states
  985. for a layer gathered across replicas by torch.distributed (shape=[global batch size, num_heads, seq_len, head_dim]).
  986. Note: it needs to be the 1st arg as well to work correctly
  987. config (`PreTrainedConfig`, *optional*):
  988. The config of the model for which this Cache will be used. If passed, it will be used to check for sliding
  989. or hybrid layer structure, greatly reducing the memory requirement of the cached tensors to
  990. `[batch_size, num_heads, min(seq_len, sliding_window), head_dim]`.
  991. offloading (`bool`, *optional*, defaults to `False`):
  992. Whether to perform offloading of the layers to `cpu`, to save GPU memory.
  993. offload_only_non_sliding (`bool`, *optional*, defaults to `False`):
  994. If `offloading` is `True`, this further decides if only the non-sliding layers will be offloaded (because
  995. usually the sliding layers are small in size, so there is no need to offload them, and skipping it is faster).
  996. Example:
  997. ```python
  998. >>> from transformers import AutoTokenizer, AutoModelForCausalLM, DynamicCache
  999. >>> model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B-Instruct")
  1000. >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct")
  1001. >>> inputs = tokenizer(text="My name is Qwen2", return_tensors="pt")
  1002. >>> # Prepare a cache class and pass it to model's forward
  1003. >>> past_key_values = DynamicCache(config=model.config)
  1004. >>> outputs = model(**inputs, past_key_values=past_key_values, use_cache=True)
  1005. >>> outputs.past_key_values # access cache filled with key/values from generation
  1006. ```
  1007. """
  1008. def __init__(
  1009. self,
  1010. ddp_cache_data: Iterable[tuple[torch.Tensor | None, ...]] | None = None,
  1011. config: PreTrainedConfig | None = None,
  1012. offloading: bool = False,
  1013. offload_only_non_sliding: bool = False,
  1014. ):
  1015. layers = []
  1016. # If a config is passed, use it to infer the layer types and initialize accordingly
  1017. if config is not None:
  1018. decoder_config = config.get_text_config(decoder=True)
  1019. sliding_window = getattr(decoder_config, "sliding_window", None) or getattr(
  1020. decoder_config, "attention_chunk_size", None
  1021. )
  1022. layer_types = getattr(decoder_config, "layer_types", None)
  1023. if layer_types is None:
  1024. layer_types = []
  1025. for _ in range(decoder_config.num_hidden_layers):
  1026. if sliding_window is not None:
  1027. layer_types.append("sliding_attention")
  1028. else:
  1029. layer_types.append("full_attention")
  1030. # Some models have shared layers thus no cache is needed for them (e.g. Gemma3n)
  1031. if hasattr(decoder_config, "num_kv_shared_layers"):
  1032. layer_types = layer_types[: -decoder_config.num_kv_shared_layers]
  1033. for layer_type in layer_types:
  1034. # From a cache point of view, both sliding and chunked are the same in how they should behave and how many
  1035. # states they should return - only the mask changes to make them different at the end!
  1036. if layer_type in ("sliding_attention", "chunked_attention"):
  1037. layers.append(DynamicSlidingWindowLayer(sliding_window=sliding_window))
  1038. # Note: we want moe layers to be LinearAttentionLayer, so that we can correctly grab sequence length etc from attention layers.
  1039. # Since moe layers will stay empty (they don't need any cache), we don't want them to collide for mask creation etc
  1040. # TODO: maybe use a dummy layer in those cases, or a dictionary {idx: Layer} for self.layers, so that we can skip
  1041. # the indices we don't need
  1042. elif layer_type in ("mamba", "conv", "linear_attention", "moe"):
  1043. layers.append(LinearAttentionLayer())
  1044. elif layer_type == "hybrid":
  1045. layers.append(LinearAttentionAndFullAttentionLayer())
  1046. else:
  1047. layers.append(DynamicLayer())
  1048. # In this case, use the passed data to already fill in the Cache
  1049. if ddp_cache_data is not None:
  1050. # Init all the layers with the data
  1051. for layer_idx, kv_and_optional_sliding in enumerate(ddp_cache_data):
  1052. # If the config was not passed above, initialize a new cache layer for each entry of the ddp_data
  1053. if config is None:
  1054. # kv_and_optional_sliding contains at least two elements: the key and value states. It can also
  1055. # contain a third element, which is an optional sliding window tensor.
  1056. sliding_window_tensor = kv_and_optional_sliding[2] if len(kv_and_optional_sliding) == 3 else None
  1057. # If there is a sliding window tensor, use it to initialize the layer
  1058. if sliding_window_tensor is not None:
  1059. # Since the same layer is dispatched across replicas, sliding_window is the same for all
  1060. sliding_window = sliding_window_tensor[0].item()
  1061. layers.append(DynamicSlidingWindowLayer(sliding_window=sliding_window))
  1062. else:
  1063. layers.append(DynamicLayer())
  1064. # Update the layer with the data
  1065. _, _ = layers[layer_idx].update(kv_and_optional_sliding[0], kv_and_optional_sliding[1])
  1066. # If neither of config nor ddp_data was passed, then simply lazy init a full cache of DynamicLayer
  1067. if len(layers) == 0:
  1068. super().__init__(
  1069. layer_class_to_replicate=DynamicLayer,
  1070. offloading=offloading,
  1071. offload_only_non_sliding=offload_only_non_sliding,
  1072. )
  1073. else:
  1074. super().__init__(layers=layers, offloading=offloading, offload_only_non_sliding=offload_only_non_sliding)
  1075. def __iter__(self):
  1076. for layer in self.layers:
  1077. yield layer.keys, layer.values, getattr(layer, "_sliding_window_tensor", None)
  1078. class StaticCache(Cache):
  1079. """
  1080. Static Cache class to be used with `torch.compile(model)` and `torch.export()`. It will check the `config`
  1081. for potential hybrid cache structure, and initialize each layer accordingly.
  1082. See `Cache` for details on common methods that are implemented by all cache classes.
  1083. Args:
  1084. config (`PreTrainedConfig`):
  1085. The config of the model for which this Cache will be used. It will be used to check for sliding
  1086. or hybrid layer structure, and initialize each layer accordingly.
  1087. max_cache_len (`int`):
  1088. The maximum number of tokens that this Cache should hold.
  1089. offloading (`bool`, *optional*, defaults to `False`):
  1090. Whether to perform offloading of the layers to `cpu`, to save GPU memory.
  1091. offload_only_non_sliding (`bool`, *optional*, defaults to `True`):
  1092. If `offloading` is `True`, this further decides if only the non-sliding layers will be offloaded (because
  1093. usually the sliding layers are small in size, so there is no need to offload them, and skipping it is faster).
  1094. Example:
  1095. ```python
  1096. >>> from transformers import AutoTokenizer, AutoModelForCausalLM, StaticCache
  1097. >>> model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-chat-hf")
  1098. >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-chat-hf")
  1099. >>> inputs = tokenizer(text="My name is Llama", return_tensors="pt")
  1100. >>> # Prepare a cache class and pass it to model's forward
  1101. >>> # Leave empty space for 10 new tokens, which can be used when calling forward iteratively 10 times to generate
  1102. >>> max_generated_length = inputs.input_ids.shape[1] + 10
  1103. >>> past_key_values = StaticCache(config=model.config, max_cache_len=max_generated_length)
  1104. >>> outputs = model(**inputs, past_key_values=past_key_values, use_cache=True)
  1105. >>> outputs.past_key_values # access cache filled with key/values from generation
  1106. StaticCache()
  1107. ```
  1108. """
  1109. # Pass-in kwargs as well to avoid crashing for BC (it used more arguments before)
  1110. def __init__(
  1111. self,
  1112. config: PreTrainedConfig,
  1113. max_cache_len: int,
  1114. offloading: bool = False,
  1115. offload_only_non_sliding: bool = True,
  1116. **kwargs,
  1117. ):
  1118. config = config.get_text_config(decoder=True)
  1119. layer_types = getattr(config, "layer_types", None)
  1120. # If `layer_types` is not explicitly provided, infer if the model is fully sliding
  1121. if layer_types is None:
  1122. if getattr(config, "sliding_window", None) is not None:
  1123. layer_types = ["sliding_attention" for _ in range(config.num_hidden_layers)]
  1124. elif getattr(config, "attention_chunk_size", None) is not None:
  1125. layer_types = ["chunked_attention" for _ in range(config.num_hidden_layers)]
  1126. else:
  1127. layer_types = ["full_attention" for _ in range(config.num_hidden_layers)]
  1128. # Some models have shared layers thus no cache is needed for them (e.g. Gemma3n)
  1129. if hasattr(config, "num_kv_shared_layers"):
  1130. layer_types = layer_types[: -config.num_kv_shared_layers]
  1131. layers = []
  1132. for layer_type in layer_types:
  1133. if layer_type == "sliding_attention":
  1134. layer = StaticSlidingWindowLayer(max_cache_len=max_cache_len, sliding_window=config.sliding_window)
  1135. elif layer_type == "chunked_attention":
  1136. # From a cache point of view, both sliding and chunked are the same in how they should behave and how many
  1137. # states they should return - only the mask changes to make them different at the end!
  1138. layer = StaticSlidingWindowLayer(
  1139. max_cache_len=max_cache_len, sliding_window=config.attention_chunk_size
  1140. )
  1141. # LinearAttention layers are static by essence - using `"moe"` as well is a trick, see the comment about it on DynamicCache
  1142. elif layer_type in ("mamba", "conv", "linear_attention", "moe"):
  1143. layer = LinearAttentionLayer()
  1144. else:
  1145. layer = StaticLayer(max_cache_len=max_cache_len)
  1146. layers.append(layer)
  1147. super().__init__(layers=layers, offloading=offloading, offload_only_non_sliding=offload_only_non_sliding)
  1148. class QuantizedCache(Cache):
  1149. """
  1150. A quantizer cache similar to what is described in the
  1151. [KIVI: A Tuning-Free Asymmetric 2bit Quantization for KV Cache paper](https://huggingface.co/papers/2402.02750).
  1152. It allows the model to generate longer sequence length without allocating too much memory for keys and values
  1153. by applying quantization.
  1154. The cache has two types of storage, one for original precision and one for the
  1155. quantized cache. A `residual length` is set as a maximum capacity for the original precision cache. When the
  1156. length goes beyond maximum capacity, the original precision cache is discarded and moved into the quantized cache.
  1157. The quantization is done per-channel with a set `q_group_size` for both keys and values, in contrast to what was
  1158. described in the paper.
  1159. See `Cache` for details on common methods that are implemented by all cache classes.
  1160. Args:
  1161. backend (`str`):
  1162. The quantization backend to use. One of `("quanto", "hqq").
  1163. config (`PreTrainedConfig`):
  1164. The config of the model for which this Cache will be used.
  1165. nbits (`int`, *optional*, defaults to 4):
  1166. The number of bits for quantization.
  1167. axis_key (`int`, *optional*, defaults to 0):
  1168. The axis on which to quantize the keys.
  1169. axis_value (`int`, *optional*, defaults to 0):
  1170. The axis on which to quantize the values.
  1171. q_group_size (`int`, *optional*, defaults to 64):
  1172. Quantization is done per-channel according to a set `q_group_size` for both keys and values.
  1173. residual_length (`int`, *optional*, defaults to 128):
  1174. Maximum capacity for the original precision cache
  1175. """
  1176. def __init__(
  1177. self,
  1178. backend: str,
  1179. config: PreTrainedConfig,
  1180. nbits: int = 4,
  1181. axis_key: int = 0,
  1182. axis_value: int = 0,
  1183. q_group_size: int = 64,
  1184. residual_length: int = 128,
  1185. ):
  1186. if backend == "quanto":
  1187. layer_class = QuantoQuantizedLayer
  1188. elif backend == "hqq":
  1189. layer_class = HQQQuantizedLayer
  1190. else:
  1191. raise ValueError(f"Unknown quantization backend `{backend}`")
  1192. config = config.get_text_config(decoder=True)
  1193. layers = [
  1194. layer_class(nbits, axis_key, axis_value, q_group_size, residual_length)
  1195. for _ in range(config.num_hidden_layers)
  1196. ]
  1197. super().__init__(layers=layers)
  1198. class EncoderDecoderCache(Cache):
  1199. """
  1200. Base, abstract class for all encoder-decoder caches. Can be used to hold combinations of self-attention and
  1201. cross-attention caches.
  1202. See `Cache` for details on common methods that are implemented by all cache classes.
  1203. Args:
  1204. caches (`Iterable`):
  1205. Usually an iterable of length 2, containing 2 `Cache` objects, the first one for self-attention, the
  1206. second one for cross-attention. Can optionally also be an iterable of length 1, containing a
  1207. `tuple[tuple[torch.Tensor]]` (usually used for compatibility with torch dp and ddp).
  1208. Example:
  1209. ```python
  1210. >>> from transformers import AutoProcessor, AutoModelForCausalLM, DynamicCache, EncoderDecoderCache
  1211. >>> model = AutoModelForCausalLM.from_pretrained("openai/whisper-small")
  1212. >>> processor = AutoProcessor.from_pretrained("openai/whisper-small")
  1213. >>> inputs = processor(audio=YOUR-AUDIO, return_tensors="pt")
  1214. >>> # Prepare cache classes for encoder and decoder and pass it to model's forward
  1215. >>> self_attention_cache = DynamicCache(config=self.config)
  1216. >>> cross_attention_cache = DynamicCache(config=self.config)
  1217. >>> past_key_values = EncoderDecoderCache(self_attention_cache, cross_attention_cache)
  1218. >>> outputs = model(**inputs, past_key_values=past_key_values, use_cache=True)
  1219. >>> outputs.past_key_values # access cache filled with key/values from generation
  1220. EncoderDecoderCache()
  1221. ```
  1222. """
  1223. def __init__(self, *caches) -> None:
  1224. # For dp and ddp support, if only one argument is passed, it should be an iterable of DynamicCache ddp data
  1225. if len(caches) == 1:
  1226. self_attention_cache_data, cross_attention_cache_data = [], []
  1227. for combined_cache_data in caches[0]:
  1228. if len(combined_cache_data) == 6: # two tuple of style (self_attn_k, self_attn_v, self_attn_sliding)
  1229. self_attention_cache_data.append(combined_cache_data[:3])
  1230. cross_attention_cache_data.append(combined_cache_data[3:])
  1231. # To support old DDP-style init, we handle the case where the tuple has no sliding window tensor
  1232. elif len(combined_cache_data) == 4: # two tuple of style (self_attn_k, self_attn_v)
  1233. self_attention_cache_data.append(combined_cache_data[:2])
  1234. cross_attention_cache_data.append(combined_cache_data[2:])
  1235. else:
  1236. raise ValueError(f"Expected {len(combined_cache_data) = } to be 4 or 6.\n{combined_cache_data = }")
  1237. self.self_attention_cache = DynamicCache(self_attention_cache_data)
  1238. self.cross_attention_cache = DynamicCache(cross_attention_cache_data)
  1239. # Otherwise, we should get two arguments, a self-attention cache and a cross-attention cache
  1240. elif len(caches) == 2:
  1241. if not isinstance(caches[0], Cache) or not isinstance(caches[1], Cache):
  1242. raise TypeError(f"One of the two arguments is not a Cache: {type(caches[0]) = }, {type(caches[1]) = }")
  1243. self.self_attention_cache = caches[0]
  1244. self.cross_attention_cache = caches[1]
  1245. # Error case
  1246. else:
  1247. raise ValueError(f"Expected 1 or 2 arguments, got {len(caches)}")
  1248. self.is_updated = {}
  1249. for layer_idx in range(len(self.cross_attention_cache)):
  1250. self.is_updated[layer_idx] = bool(self.cross_attention_cache.get_seq_length(layer_idx) > 0)
  1251. def __iter__(self):
  1252. """Returns tuples of style (self_attn_k, self_attn_v, self_attn_sliding, cross_attn_k, cross_attn_v, cross_attn_sliding)"""
  1253. for self_attention_layer, cross_attention_layer in zip(self.self_attention_cache, self.cross_attention_cache):
  1254. yield self_attention_layer + cross_attention_layer
  1255. def __repr__(self) -> str:
  1256. return (
  1257. f"{self.__class__.__name__}(self_attention_cache={self.self_attention_cache}, cross_attention_cache="
  1258. f"{self.cross_attention_cache})"
  1259. )
  1260. def __len__(self):
  1261. """
  1262. Support for backwards-compatible `past_key_values` length, e.g. `len(past_key_values)`. This value corresponds
  1263. to the number of layers in the model.
  1264. """
  1265. return len(self.self_attention_cache)
  1266. def get_seq_length(self, layer_idx: int = 0) -> int:
  1267. """Returns the sequence length of the cached states. A layer index can be optionally passed."""
  1268. return self.self_attention_cache.get_seq_length(layer_idx)
  1269. def reset(self):
  1270. self.self_attention_cache.reset()
  1271. self.cross_attention_cache.reset()
  1272. for layer_idx in self.is_updated:
  1273. self.is_updated[layer_idx] = False
  1274. def reorder_cache(self, beam_idx: torch.LongTensor):
  1275. """Reorders the cache for beam search, given the selected beam indices."""
  1276. self.self_attention_cache.reorder_cache(beam_idx)
  1277. self.cross_attention_cache.reorder_cache(beam_idx)
  1278. def check_dynamic_cache(self, method: str):
  1279. if not (
  1280. isinstance(self.self_attention_cache, DynamicCache)
  1281. and isinstance(self.cross_attention_cache, DynamicCache)
  1282. ):
  1283. raise TypeError(
  1284. f"`{method}` is only defined for dynamic cache, got {self.self_attention_cache.__str__()} for the self "
  1285. f"attention cache and {self.cross_attention_cache.__str__()} for the cross attention cache."
  1286. )
  1287. # TODO(gante, sanchit-gandhi): move following functionality into `.generate`
  1288. def crop(self, maximum_length: int):
  1289. """
  1290. Crop the past key values up to a new `maximum_length` in terms of tokens. `maximum_length` can also be
  1291. negative to remove `maximum_length` tokens. This is used in assisted decoding and contrastive search (on the Hub).
  1292. """
  1293. self.check_dynamic_cache(self.crop.__name__)
  1294. self.self_attention_cache.crop(maximum_length)
  1295. def batch_repeat_interleave(self, repeats: int):
  1296. """Repeat the cache `repeats` times in the batch dimension. Used in contrastive search (on the Hub)."""
  1297. self.check_dynamic_cache(self.batch_repeat_interleave.__name__)
  1298. self.self_attention_cache.batch_repeat_interleave(repeats)
  1299. self.cross_attention_cache.batch_repeat_interleave(repeats)
  1300. def batch_select_indices(self, indices: torch.Tensor):
  1301. """Only keep the `indices` in the batch dimension of the cache. Used in contrastive search (on the Hub)."""
  1302. self.check_dynamic_cache(self.batch_select_indices.__name__)
  1303. self.self_attention_cache.batch_select_indices(indices)
  1304. self.cross_attention_cache.batch_select_indices(indices)
  1305. def get_max_cache_shape(self) -> int:
  1306. """Returns the maximum sequence length (i.e. max capacity) of the cache object"""
  1307. return self.self_attention_cache.get_max_cache_shape()
  1308. def get_mask_sizes(self, query_length: int, layer_idx: int) -> tuple[int, int]:
  1309. return self.self_attention_cache.get_mask_sizes(query_length, layer_idx)
  1310. @property
  1311. def is_sliding(self):
  1312. return self.self_attention_cache.is_sliding
  1313. @property
  1314. def is_compileable(self) -> bool:
  1315. return self.self_attention_cache.is_compileable
  1316. # Deprecated alias: SlidingWindowCache was removed in transformers v5. StaticCache is the replacement.
  1317. SlidingWindowCache = StaticCache