kv_cache_utils.py 109 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789
  1. # SPDX-License-Identifier: Apache-2.0
  2. # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
  3. """KV-Cache Utilities."""
  4. import copy
  5. import hashlib
  6. import math
  7. import os
  8. from collections import defaultdict
  9. from collections.abc import Callable, Iterable, Iterator, Sequence
  10. from dataclasses import dataclass, replace
  11. from functools import partial
  12. from typing import Any, NamedTuple, NewType, TypeAlias, cast, overload
  13. from vllm import envs
  14. from vllm.config import VllmConfig
  15. from vllm.logger import init_logger
  16. from vllm.utils.hashing import xxhash, xxhash_cbor
  17. from vllm.utils.math_utils import cdiv
  18. from vllm.utils.mem_utils import format_gib
  19. from vllm.utils.torch_utils import get_dtype_size
  20. from vllm.v1.kv_cache_interface import (
  21. AttentionSpec,
  22. ChunkedLocalAttentionSpec,
  23. CircularBufferSpec,
  24. FullAttentionSpec,
  25. HiddenStateCacheSpec,
  26. KpoolTailSpec,
  27. KVCacheConfig,
  28. KVCacheGroupSpec,
  29. KVCacheLayout,
  30. KVCacheSpec,
  31. KVCacheTensor,
  32. MambaSpec,
  33. MLAAttentionSpec,
  34. SlidingWindowMLASpec,
  35. SlidingWindowSpec,
  36. UniformTypeKVCacheSpecs,
  37. compute_layout_strides,
  38. iter_layer_specs,
  39. replace_as,
  40. )
  41. from vllm.v1.kv_cache_spec_registry import KVCacheSpecRegistry
  42. from vllm.v1.request import Request
  43. from vllm.v1.utils import tensor_data
  44. # BlockHash represents the hash of a single KV-cache block used for
  45. # prefix caching. Treating it as a distinct type from `bytes` helps
  46. # catch accidental misuse when passing around raw byte strings.
  47. BlockHash = NewType("BlockHash", bytes)
  48. # `BlockHashWithGroupId` combines a `BlockHash` with its KV cache group ID.
  49. # It is represented as raw bytes for compactness and efficiency. The helper
  50. # functions below pack/unpack the `BlockHash` and group id into/from the key.
  51. BlockHashWithGroupId = NewType("BlockHashWithGroupId", bytes)
  52. # ExternalBlockHash is used for reproducible prefix-cache block hashing.
  53. # It's a union of `bytes` and `int` to keep backward compatibility
  54. # after we default block hashing to use sha256 bytes.
  55. ExternalBlockHash: TypeAlias = bytes | int
  56. def make_block_hash_with_group_id(
  57. block_hash: BlockHash, group_id: int
  58. ) -> BlockHashWithGroupId:
  59. """Pack a `BlockHash` and group id into a `BlockHashWithGroupId`.
  60. The group id is encoded using 4 bytes in big-endian order and appended to
  61. the block hash bytes. This representation avoids creating tuples while
  62. still allowing us to recover both components when needed.
  63. """
  64. return BlockHashWithGroupId(block_hash + group_id.to_bytes(4, "big", signed=False))
  65. def get_block_hash(key: BlockHashWithGroupId) -> BlockHash:
  66. """Extract the `BlockHash` from a `BlockHashWithGroupId`."""
  67. return BlockHash(key[:-4])
  68. def get_group_id(key: BlockHashWithGroupId) -> int:
  69. """Extract the group id from a `BlockHashWithGroupId`."""
  70. return int.from_bytes(key[-4:], "big", signed=False)
  71. def maybe_convert_block_hash(hash_bytes: BlockHash) -> ExternalBlockHash:
  72. if not envs.VLLM_KV_EVENTS_USE_INT_BLOCK_HASHES:
  73. return hash_bytes
  74. return int.from_bytes(hash_bytes, byteorder="big") & ((1 << 64) - 1)
  75. logger = init_logger(__name__)
  76. # The hash seed for the first block of any prefix block sequence.
  77. #
  78. # For cryptographic hash algorithms it is derived deterministically from a fixed
  79. # default seed, so independent vLLM processes compute identical block hashes for
  80. # identical content and can share a prefix cache (e.g. KV cache reuse across
  81. # nodes) without extra configuration. This does not weaken collision resistance,
  82. # which for SHA-256 does not depend on keeping the seed secret; ``cache_salt``
  83. # remains the mechanism for intentional cache isolation.
  84. #
  85. # Non-cryptographic algorithms keep a per-process random seed, because a
  86. # predictable seed would let an attacker precompute colliding blocks offline
  87. # (see #12621). Setting PYTHONHASHSEED overrides the seed in both cases.
  88. #
  89. # The function `init_none_hash` initializes this variable globally.
  90. NONE_HASH: BlockHash
  91. # Fixed seed used when the PYTHONHASHSEED environment variable is not set and
  92. # the hash algorithm is cryptographic.
  93. DEFAULT_NONE_HASH_SEED = "vllm-none-hash"
  94. # Algorithms that are not collision resistant, so the seed must stay secret.
  95. _NON_CRYPTO_HASH_FUNCTIONS = frozenset({xxhash, xxhash_cbor})
  96. # The seed NONE_HASH was derived from, set by init_none_hash.
  97. _NONE_HASH_SEED: str | None = None
  98. def resolve_none_hash_seed(hash_fn: Callable[[Any], bytes]) -> str:
  99. """Resolve the seed to derive NONE_HASH from.
  100. PYTHONHASHSEED wins if set. Otherwise cryptographic algorithms get the
  101. fixed default (shareable across processes) and non-cryptographic ones get
  102. fresh random bytes, keeping the seed unpredictable where collision
  103. resistance depends on it.
  104. """
  105. hash_seed = os.getenv("PYTHONHASHSEED")
  106. if hash_seed is not None:
  107. return hash_seed
  108. if hash_fn in _NON_CRYPTO_HASH_FUNCTIONS:
  109. return os.urandom(32).hex()
  110. return DEFAULT_NONE_HASH_SEED
  111. def get_none_hash_seed() -> str:
  112. """Return the seed NONE_HASH was derived from.
  113. Components that must agree on NONE_HASH across processes (the P2P tier
  114. advertises this during its connect handshake) read the resolved seed here
  115. instead of re-deriving it, so they observe the random seed too. Falls back
  116. to the deterministic seed before ``init_none_hash`` has run.
  117. """
  118. if _NONE_HASH_SEED is None:
  119. return DEFAULT_NONE_HASH_SEED
  120. return _NONE_HASH_SEED
  121. def init_none_hash(hash_fn: Callable[[Any], bytes]):
  122. global NONE_HASH, _NONE_HASH_SEED
  123. _NONE_HASH_SEED = resolve_none_hash_seed(hash_fn)
  124. if hash_fn in _NON_CRYPTO_HASH_FUNCTIONS and os.getenv("PYTHONHASHSEED") is None:
  125. logger.warning(
  126. "Using a random per-process NONE_HASH seed because %s is not "
  127. "collision resistant. Block hashes are therefore not reproducible "
  128. "across processes; set PYTHONHASHSEED to a shared value to reuse "
  129. "the prefix cache across instances, or use sha256.",
  130. hash_fn.__name__,
  131. )
  132. NONE_HASH = BlockHash(hash_fn(_NONE_HASH_SEED))
  133. @dataclass(slots=True)
  134. class KVCacheBlock:
  135. """KV-cache block metadata."""
  136. # Block ID, ranging from 0 to num_gpu_blocks - 1.
  137. block_id: int
  138. # Reference count.
  139. ref_cnt: int = 0
  140. # The hash key (block hash + group id) of the block, only available
  141. # when the block is full and cached.
  142. _block_hash: BlockHashWithGroupId | None = None
  143. # Number of prefix tokens covered by _block_hash. For full blocks this is
  144. # the full block boundary; partial entries can end inside a cache block.
  145. _block_hash_num_tokens: int | None = None
  146. # Used to construct a doubly linked list for free blocks.
  147. # These two attributes should only be manipulated by FreeKVCacheBlockQueue.
  148. prev_free_block: "KVCacheBlock | None" = None
  149. next_free_block: "KVCacheBlock | None" = None
  150. # Whether the block is a null block that should never be cached.
  151. is_null: bool = False
  152. @property
  153. def block_hash(self) -> BlockHashWithGroupId | None:
  154. return self._block_hash
  155. @property
  156. def block_hash_num_tokens(self) -> int | None:
  157. return self._block_hash_num_tokens
  158. def set_block_hash(
  159. self,
  160. block_hash: BlockHashWithGroupId,
  161. num_tokens: int | None = None,
  162. ) -> None:
  163. assert self.block_hash is None and self._block_hash_num_tokens is None, (
  164. "The block already has a hash. This should not happen."
  165. )
  166. self._block_hash = block_hash
  167. self._block_hash_num_tokens = num_tokens
  168. def reset_hash(self):
  169. """Reset the block hash when the block is evicted."""
  170. self._block_hash = None
  171. self._block_hash_num_tokens = None
  172. def __repr__(self) -> str:
  173. # Use block_id instead of KVCacheBlock object to avoid calling __repr__
  174. # on KVCacheBlock object recursively.
  175. prev_block_id = self.prev_free_block.block_id if self.prev_free_block else None
  176. next_block_id = self.next_free_block.block_id if self.next_free_block else None
  177. return (
  178. f"KVCacheBlock(block_id={self.block_id}, "
  179. f"ref_cnt={self.ref_cnt}, "
  180. f"_block_hash={self._block_hash!r}, "
  181. f"_block_hash_num_tokens={self._block_hash_num_tokens}, "
  182. f"prev_free_block={prev_block_id}, "
  183. f"next_free_block={next_block_id})"
  184. )
  185. class KVCacheBlockCopy(NamedTuple):
  186. src_block_id: int
  187. dst_block_id: int
  188. class FreeKVCacheBlockQueue:
  189. """This class organizes a list of KVCacheBlock objects to a doubly linked
  190. list of free blocks. We implement this class instead of using Python
  191. builtin deque to support removing a block in the middle of the queue
  192. in O(1) time. To close the performance gap to the builtin deque which is
  193. implemented in C++, this class does not allocate any Python objects when
  194. manipulating the linked list. Instead, this class manipulates the
  195. prev_free_block and next_free_block attributes of the given blocks.
  196. The queue is ordered by block ID in the beginning. When a block is allocated
  197. and then freed, it will be appended back with the eviction order:
  198. 1. The least recent used block is at the front (LRU).
  199. 2. If two blocks have the same last accessed time (allocated by the
  200. same sequence), the one with more hash tokens (the tail of a block
  201. chain) is at the front.
  202. Note that we maintain this order by reversing the block order when free
  203. blocks of a request. This operation is outside of this class.
  204. Args:
  205. blocks: A list of KVCacheBlock objects.
  206. """
  207. def __init__(self, blocks: list[KVCacheBlock]) -> None:
  208. self.num_free_blocks = len(blocks)
  209. # Initialize doubly links of consecutive blocks
  210. for i in range(self.num_free_blocks):
  211. if i > 0:
  212. blocks[i].prev_free_block = blocks[i - 1]
  213. if i < self.num_free_blocks - 1:
  214. blocks[i].next_free_block = blocks[i + 1]
  215. # Create a fake head and a tail block for the doubly linked list to
  216. # reduce branching in the code
  217. #
  218. # The implementation guaranteed that the fake head and tail
  219. # are NEVER got popped, so we could safely assume each real blocks
  220. # in the queue has prev and next blocks.
  221. self.fake_free_list_head = KVCacheBlock(block_id=-1)
  222. self.fake_free_list_tail = KVCacheBlock(block_id=-1)
  223. if self.num_free_blocks > 0:
  224. # Connect fake_head and fake_tail to the first and last block
  225. # respectively.
  226. self.fake_free_list_head.next_free_block = blocks[0]
  227. blocks[0].prev_free_block = self.fake_free_list_head
  228. self.fake_free_list_tail.prev_free_block = blocks[-1]
  229. blocks[-1].next_free_block = self.fake_free_list_tail
  230. else:
  231. # For empty list, simply connect the fake head and tail.
  232. self.fake_free_list_head.next_free_block = self.fake_free_list_tail
  233. self.fake_free_list_tail.prev_free_block = self.fake_free_list_head
  234. def popleft(self) -> KVCacheBlock:
  235. """Pop the first free block and reduce num_free_blocks by 1.
  236. Returns:
  237. The first free block.
  238. """
  239. if (
  240. self.fake_free_list_head.next_free_block is self.fake_free_list_tail
  241. or self.fake_free_list_head.next_free_block is None
  242. ):
  243. assert self.num_free_blocks == 0, (
  244. f"num_free_blocks ({self.num_free_blocks}) is out of sync "
  245. "with the free list."
  246. )
  247. raise ValueError("No free blocks available")
  248. first_block: KVCacheBlock = self.fake_free_list_head.next_free_block
  249. if first_block.next_free_block is None:
  250. # This should not happen if the block is from the free list.
  251. # It indicates a bug in the caller's logic.
  252. raise RuntimeError(
  253. "Invalid block found in popleft() "
  254. "which doesn't have a valid next_free_block"
  255. )
  256. # Connect fake_head and the next block of first_block (i.e. second block
  257. # or fake tail).
  258. self.fake_free_list_head.next_free_block = first_block.next_free_block
  259. first_block.next_free_block.prev_free_block = self.fake_free_list_head
  260. # Remove the block from the linked list.
  261. first_block.prev_free_block = first_block.next_free_block = None
  262. self.num_free_blocks -= 1
  263. return first_block
  264. def popleft_n(self, n: int) -> list[KVCacheBlock]:
  265. """Pop the first n free blocks and reduce num_free_blocks by n.
  266. Args:
  267. n: The number of blocks to pop.
  268. Returns:
  269. A list of n free blocks.
  270. """
  271. if n == 0:
  272. return []
  273. assert self.num_free_blocks >= n
  274. self.num_free_blocks -= n
  275. curr_block = self.fake_free_list_head.next_free_block
  276. # Pop n blocks from the head of the list
  277. ret = []
  278. for _ in range(n):
  279. assert curr_block is not None
  280. ret.append(curr_block)
  281. last_block = curr_block
  282. curr_block = curr_block.next_free_block
  283. # Reset prev_free_block and next_free_block of all popped blocks
  284. last_block.prev_free_block = None
  285. last_block.next_free_block = None
  286. if curr_block is not None:
  287. # The queue is not empty, connect the fake head to
  288. # the new first block.
  289. self.fake_free_list_head.next_free_block = curr_block
  290. curr_block.prev_free_block = self.fake_free_list_head
  291. return ret
  292. def remove(self, block: KVCacheBlock) -> None:
  293. """Remove a block in the free list and reduce num_free_blocks by 1.
  294. Args:
  295. block: The block to remove.
  296. """
  297. if block.prev_free_block is None or block.next_free_block is None:
  298. # This should not happen if the block is from the free list.
  299. # It indicates a bug in the caller's logic.
  300. raise RuntimeError(f"remove() called on an invalid block: {block}")
  301. # Link the previous block to the next block.
  302. block.prev_free_block.next_free_block = block.next_free_block
  303. # Link the next block to the previous block.
  304. block.next_free_block.prev_free_block = block.prev_free_block
  305. # Remove the block from the linked list.
  306. block.prev_free_block = block.next_free_block = None
  307. self.num_free_blocks -= 1
  308. def append(self, block: KVCacheBlock) -> None:
  309. """Put a block back into the free list and increase
  310. num_free_blocks by 1.
  311. Args:
  312. block: The block to append.
  313. """
  314. if self.fake_free_list_tail.prev_free_block is None:
  315. raise RuntimeError(
  316. "prev_free_block of fake_free_list_tail should always exist"
  317. )
  318. last_block: KVCacheBlock = self.fake_free_list_tail.prev_free_block
  319. # Connect the new block after the last block.
  320. last_block.next_free_block = block
  321. block.prev_free_block = last_block
  322. # Connect the fake tail after the new block.
  323. block.next_free_block = self.fake_free_list_tail
  324. self.fake_free_list_tail.prev_free_block = block
  325. self.num_free_blocks += 1
  326. def prepend_n(self, blocks: list[KVCacheBlock]) -> None:
  327. """Put a list of blocks at the front of the free list."""
  328. if len(blocks) == 0:
  329. return
  330. first_block = self.fake_free_list_head.next_free_block
  331. assert first_block is not None, (
  332. "next_free_block of fake_free_list_head should always exist"
  333. )
  334. prev_block = self.fake_free_list_head
  335. for block in blocks:
  336. block.prev_free_block = prev_block
  337. prev_block.next_free_block = block
  338. prev_block = block
  339. prev_block.next_free_block = first_block
  340. first_block.prev_free_block = prev_block
  341. self.num_free_blocks += len(blocks)
  342. def append_n(self, blocks: list[KVCacheBlock]) -> None:
  343. """Put a list of blocks back into the free list
  344. Args:
  345. blocks: The blocks to append.
  346. """
  347. if len(blocks) == 0:
  348. return
  349. last_block = self.fake_free_list_tail.prev_free_block
  350. assert last_block is not None, (
  351. "prev_free_block of fake_free_list_tail should always exist"
  352. )
  353. # Add inter-connections between consecutive blocks
  354. for block in blocks:
  355. block.prev_free_block = last_block
  356. last_block.next_free_block = block
  357. last_block = block
  358. # Connect the last block of <blocks> to the fake tail
  359. last_block.next_free_block = self.fake_free_list_tail
  360. self.fake_free_list_tail.prev_free_block = last_block
  361. self.num_free_blocks += len(blocks)
  362. def get_all_free_blocks(self) -> list[KVCacheBlock]:
  363. """Get all free blocks in the free list. Mainly used for testing.
  364. Returns:
  365. A list of free blocks.
  366. """
  367. ret = []
  368. if self.fake_free_list_head.next_free_block is None:
  369. raise RuntimeError(
  370. "next_free_block of fake_free_list_head should always exist"
  371. )
  372. # Start from the first block
  373. curr_block: KVCacheBlock = self.fake_free_list_head.next_free_block
  374. # As long as next_free_block is available, we haven't reached to
  375. # the fake tail yet.
  376. while curr_block.next_free_block is not None:
  377. ret.append(curr_block)
  378. curr_block = curr_block.next_free_block
  379. return ret
  380. def iter_blocks_after(
  381. self,
  382. cursor: KVCacheBlock | None,
  383. ) -> Iterator[KVCacheBlock]:
  384. """Iterate free blocks in eviction order after the cursor."""
  385. if cursor is None:
  386. curr_block = self.fake_free_list_head.next_free_block
  387. else:
  388. curr_block = cursor.next_free_block
  389. while curr_block is not None and curr_block is not self.fake_free_list_tail:
  390. yield curr_block
  391. curr_block = curr_block.next_free_block
  392. def _gen_mm_extra_hash_keys(
  393. request: Request, start_token_idx: int, end_token_idx: int, start_mm_idx: int
  394. ) -> tuple[list[Any], int]:
  395. """Generate extra keys related to MultiModal request for block hash
  396. computation. For multi-modal inputs, the extra keys are
  397. (mm_hash, start_offset) that indicate a mm input contained in the
  398. block and its starting offset in the block tokens.
  399. Args:
  400. request: The request object.
  401. start_token_idx: The start token index of the block.
  402. end_token_idx: The end token index of the block.
  403. start_mm_idx: The start multi-modal index of the block.
  404. Returns:
  405. A tuple of extra keys and the next multi-modal index.
  406. """
  407. extra_keys: list[Any] = []
  408. mm_features = request.mm_features
  409. if not mm_features:
  410. return extra_keys, start_mm_idx
  411. # Note that we assume mm_features are sorted by mm_position.offset.
  412. # We do not need to check all mm inputs if the start token index is out of
  413. # range. This usually happens in the late prefill phase and decoding phase.
  414. last_pos = mm_features[-1].mm_position
  415. if last_pos.offset + last_pos.length <= start_token_idx:
  416. return extra_keys, start_mm_idx
  417. # Support start_mm_idx == -1 to indicate the last mm input.
  418. if start_mm_idx < 0:
  419. assert -start_mm_idx <= len(mm_features)
  420. start_mm_idx = len(mm_features) + start_mm_idx
  421. curr_mm_idx = start_mm_idx
  422. while mm_features and curr_mm_idx < len(mm_features):
  423. mm_feature = mm_features[curr_mm_idx]
  424. assert mm_feature.identifier is not None
  425. offset = mm_feature.mm_position.offset
  426. length = mm_feature.mm_position.length
  427. if end_token_idx > offset:
  428. if start_token_idx >= offset + length:
  429. # This block has passed the current mm input.
  430. curr_mm_idx += 1
  431. continue
  432. # The block contains the current mm input. Include its offset
  433. # relative to the start of the block so prefix-cache keys stay
  434. # distinct when the same MM item appears at different positions
  435. # within otherwise-identical placeholder blocks.
  436. extra_keys.append((mm_feature.identifier, offset - start_token_idx))
  437. if end_token_idx >= offset + length:
  438. # If this block contains the end of the current mm input,
  439. # move to the next mm input as this block may also contain
  440. # the next mm input.
  441. curr_mm_idx += 1
  442. else:
  443. # Otherwise this block is done with mm inputs.
  444. break
  445. else:
  446. # This block has not reached the current mm input.
  447. break
  448. return extra_keys, curr_mm_idx
  449. def _gen_lora_extra_hash_keys(request: Request) -> list[str]:
  450. """Generate extra keys related to LoRA for block hash computation.
  451. Args:
  452. request: The request object.
  453. Returns:
  454. Return LoRA name of the request if it is a LoRA request. Return empty
  455. list otherwise.
  456. """
  457. if not request.lora_request:
  458. return []
  459. return [request.lora_request.lora_name]
  460. def _gen_prompt_embeds_extra_hash_keys(
  461. request: Request, start_token_idx: int, end_token_idx: int
  462. ) -> list[bytes]:
  463. """Generate extra keys related to prompt embeds for block hash computation.
  464. Args:
  465. request: The request object.
  466. start_token_idx: The start token index of the block.
  467. end_token_idx: The end token index of the block.
  468. Returns:
  469. Return a stable hash of the block prompt embeddings if prompt embeds
  470. are present. Return empty list otherwise.
  471. """
  472. if request.prompt_embeds is None:
  473. return []
  474. block_range = (start_token_idx, end_token_idx)
  475. embeds_hash = request._prompt_embeds_per_block_hashes.get(block_range)
  476. if embeds_hash is None:
  477. block_prompt_embeds = request.prompt_embeds[start_token_idx:end_token_idx]
  478. # Hash prompt embeds once per block and cache on request
  479. embeds_hash = hashlib.sha256(tensor_data(block_prompt_embeds)).digest()
  480. request._prompt_embeds_per_block_hashes[block_range] = embeds_hash
  481. return [embeds_hash]
  482. def generate_block_hash_extra_keys(
  483. request: Request, start_token_idx: int, end_token_idx: int, start_mm_idx: int
  484. ) -> tuple[tuple[Any, ...] | None, int]:
  485. """Generate extra keys for the block hash. The extra keys can come from
  486. the multi-modal inputs, request specific metadata (e.g., LoRA names), and
  487. hashed data from prompt embeddings.
  488. Args:
  489. request: The request object.
  490. start_token_idx: The start token index of the block.
  491. end_token_idx: The end token index of the block.
  492. start_mm_idx: The start multi-modal index of the block.
  493. Returns:
  494. A tuple of extra keys and the next multi-modal index.
  495. """
  496. mm_extra_keys: list[Any]
  497. mm_extra_keys, new_start_mm_idx = _gen_mm_extra_hash_keys(
  498. request, start_token_idx, end_token_idx, start_mm_idx
  499. )
  500. lora_extra_keys: list[str] = _gen_lora_extra_hash_keys(request)
  501. cache_salt_keys: list[str] = (
  502. [request.cache_salt] if (start_token_idx == 0 and request.cache_salt) else []
  503. )
  504. prompt_embeds_keys = _gen_prompt_embeds_extra_hash_keys(
  505. request, start_token_idx, end_token_idx
  506. )
  507. extra_keys: list[Any] = (
  508. lora_extra_keys + mm_extra_keys + cache_salt_keys + prompt_embeds_keys
  509. )
  510. if not extra_keys:
  511. return None, new_start_mm_idx
  512. return tuple(extra_keys), new_start_mm_idx
  513. def hash_block_tokens(
  514. hash_function: Callable[[Any], bytes],
  515. parent_block_hash: BlockHash | None,
  516. curr_block_token_ids: Sequence[int],
  517. extra_keys: tuple[Any, ...] | None = None,
  518. ) -> BlockHash:
  519. """Computes a hash value corresponding to the contents of a block and
  520. the contents of the preceding block(s). The hash value is used for
  521. prefix caching. We use LRU cache for this function to avoid recomputing
  522. hash values for the same block contents.
  523. Args:
  524. hash_function: The hash function used to compute block hash.
  525. parent_block_hash: The hash of the parent block. None
  526. if this is the first block.
  527. curr_block_token_ids: A list of token ids in the current
  528. block. The current block is assumed to be full.
  529. extra_keys: Extra keys for the block.
  530. Returns:
  531. The hash value of the block and the token ids in the block.
  532. The entire tuple is used as the hash key of the block.
  533. """
  534. if not parent_block_hash:
  535. parent_block_hash = NONE_HASH
  536. curr_block_token_ids_tuple = tuple(curr_block_token_ids)
  537. return BlockHash(
  538. hash_function((parent_block_hash, curr_block_token_ids_tuple, extra_keys))
  539. )
  540. def resolve_dcp_kv_block_size(spec: KVCacheSpec, dcp_world_size: int) -> int:
  541. """Return the token span of a cache block under DCP."""
  542. layer_specs = iter_layer_specs(spec)
  543. if len(layer_specs) > 0 and all(
  544. isinstance(layer_spec, AttentionSpec) for layer_spec in layer_specs
  545. ):
  546. return spec.block_size * dcp_world_size
  547. return spec.block_size
  548. def resolve_dcp_kv_cache_spec(spec: KVCacheSpec, dcp_world_size: int) -> KVCacheSpec:
  549. """Return a KV cache spec with block sizes adjusted for DCP."""
  550. block_size = resolve_dcp_kv_block_size(spec, dcp_world_size)
  551. if block_size == spec.block_size:
  552. return spec
  553. if isinstance(spec, UniformTypeKVCacheSpecs):
  554. return replace(
  555. spec,
  556. block_size=block_size,
  557. kv_cache_specs={
  558. name: resolve_dcp_kv_cache_spec(layer_spec, dcp_world_size)
  559. for name, layer_spec in spec.kv_cache_specs.items()
  560. },
  561. )
  562. return replace(spec, block_size=block_size)
  563. def dcp_world_size_for_kv_cache_spec(spec: KVCacheSpec, dcp_world_size: int) -> int:
  564. """Return the DCP size that owns this group's block geometry.
  565. Full-attention KV (including MLA) is sharded across DCP ranks, so prefix
  566. hashing and manager ``block_size`` use the process DCP size. Other specs
  567. keep replicated per-rank state (Mamba, sliding window, chunked-local) and
  568. must keep ``dcp_world_size=1`` even when the process runs with DCP > 1.
  569. Draft MLA groups on the sharded DSpark path are ``FullAttentionSpec`` /
  570. ``MLAAttentionSpec`` and therefore keep the process DCP size. A replicated
  571. draft group would need a different spec, not this helper.
  572. """
  573. if dcp_world_size <= 1:
  574. return 1
  575. inner = spec
  576. if isinstance(spec, UniformTypeKVCacheSpecs):
  577. inner = next(iter(spec.kv_cache_specs.values()))
  578. if isinstance(inner, FullAttentionSpec):
  579. return dcp_world_size
  580. return 1
  581. def resolve_kv_cache_block_sizes(
  582. kv_cache_config: KVCacheConfig,
  583. vllm_config: VllmConfig,
  584. ) -> tuple[int, int]:
  585. """Resolve (scheduler_block_size, hash_block_size).
  586. - ``scheduler_block_size`` is the token-alignment invariant used by the
  587. scheduler (e.g. for ``num_computed_tokens`` rounding). Single group:
  588. ``cache_config.block_size * dcp``. Multiple groups: LCM of every
  589. group's effective block size. Attention groups are scaled by DCP;
  590. Mamba groups keep their full per-rank state and are not scaled.
  591. - ``hash_block_size`` is the granularity at which ``Request.block_hashes``
  592. is computed. Single group: equals scheduler block size. Multiple groups:
  593. ``cache_config.prefix_match_unit`` override if set, else the GCD of
  594. group block sizes; every group's block size must be divisible by it.
  595. Returns the scheduler block size (i.e. disables finer hashing) if block
  596. hashing is inactive or a mamba group is not using cache mode "align".
  597. """
  598. cache_config = vllm_config.cache_config
  599. dcp = vllm_config.parallel_config.decode_context_parallel_size
  600. groups = kv_cache_config.kv_cache_groups
  601. if len(groups) <= 1:
  602. bs = cache_config.block_size * dcp
  603. return bs, bs
  604. group_block_sizes = [
  605. resolve_dcp_kv_block_size(g.kv_cache_spec, dcp) for g in groups
  606. ]
  607. scheduler_block_size = math.lcm(*group_block_sizes)
  608. # Block hashes are only consumed by prefix caching and KV connectors
  609. # (P/D, offloading); when neither is active, keep hash_block_size equal
  610. # to the scheduler block size.
  611. connector_enabled = vllm_config.kv_transfer_config is not None
  612. if not (cache_config.enable_prefix_caching or connector_enabled):
  613. return scheduler_block_size, scheduler_block_size
  614. # Mamba groups outside align mode break divisibility; back off to the
  615. # scheduler block size. Read the mode from the resolved group spec because
  616. # its block size may have been updated independently of cache_config.
  617. if any(
  618. isinstance(spec, MambaSpec) and spec.mamba_cache_mode != "align"
  619. for group in groups
  620. for spec in iter_layer_specs(group.kv_cache_spec)
  621. ):
  622. return scheduler_block_size, scheduler_block_size
  623. hashing_sizes = [
  624. block_size
  625. for group, block_size in zip(groups, group_block_sizes)
  626. if group.kv_cache_spec.prefix_cacheable
  627. ] or group_block_sizes
  628. requested = cache_config.prefix_match_unit
  629. hash_block_size = requested if requested is not None else math.gcd(*hashing_sizes)
  630. if any(bs % hash_block_size != 0 for bs in hashing_sizes):
  631. raise ValueError(
  632. f"Invalid prefix_match_unit={hash_block_size}; prefix-cacheable "
  633. "KV cache group block sizes must be divisible by prefix_match_unit. "
  634. f"Got group block sizes={group_block_sizes}, "
  635. f"prefix-cacheable={hashing_sizes}."
  636. )
  637. prefix_alignments = {
  638. spec.tokens_per_state
  639. for group in groups
  640. for spec in iter_layer_specs(group.kv_cache_spec)
  641. if spec.prefix_cacheable
  642. and isinstance(spec.tokens_per_state, int)
  643. and spec.tokens_per_state > 1
  644. }
  645. has_partial_mamba_group = any(
  646. isinstance(spec, MambaSpec)
  647. and spec.mamba_cache_mode == "align"
  648. and (
  649. (dcp == 1 and block_size > hash_block_size)
  650. or (dcp > 1 and block_size >= hash_block_size)
  651. )
  652. for group, block_size in zip(groups, group_block_sizes)
  653. for spec in iter_layer_specs(group.kv_cache_spec)
  654. )
  655. cache_hit_alignment = (
  656. hash_block_size if has_partial_mamba_group else scheduler_block_size
  657. )
  658. if any(cache_hit_alignment % alignment for alignment in prefix_alignments):
  659. raise ValueError(
  660. f"Invalid prefix_match_unit={hash_block_size}; prefix-cache boundaries "
  661. "must align with each spec's per-state compression. "
  662. f"Got alignments={sorted(prefix_alignments)}."
  663. )
  664. return scheduler_block_size, hash_block_size
  665. def get_request_block_hasher(
  666. hash_block_size: int,
  667. caching_hash_fn: Callable[[Any], bytes],
  668. ) -> Callable[[Request], list[BlockHash]]:
  669. """
  670. Returns a function which computes the list of un-computed block hashes
  671. of a request.
  672. Hashes are computed at ``hash_block_size`` granularity and chained over the
  673. full prefix, so each hash uniquely fingerprints the prefix ending at its
  674. boundary. Coarser group block sizes and partial-cache boundaries reuse
  675. these hashes directly (see ``BlockHashListWithBlockSize``).
  676. """
  677. def request_block_hasher(request: Request) -> list[BlockHash]:
  678. start_token_idx = len(request.block_hashes) * hash_block_size
  679. num_tokens = request.num_tokens
  680. if start_token_idx + hash_block_size > num_tokens:
  681. # Early stop when there no new full blocks created.
  682. return []
  683. curr_mm_idx = 0
  684. if start_token_idx > 0:
  685. # Set curr_mm_idx = -1 to indicate the last mm input.
  686. # Note that since we reach to this branch only when the block is
  687. # completed with generated tokens, we only need to consider the
  688. # last mm input.
  689. curr_mm_idx = -1
  690. prev_block_hash_value = (
  691. request.block_hashes[-1] if request.block_hashes else None
  692. )
  693. new_block_hashes: list[BlockHash] = []
  694. while True:
  695. end_token_idx = start_token_idx + hash_block_size
  696. if end_token_idx > num_tokens:
  697. # We only hash full blocks
  698. break
  699. # MM and LoRA requests need extra keys for block-hash computation.
  700. extra_keys, curr_mm_idx = generate_block_hash_extra_keys(
  701. request, start_token_idx, end_token_idx, curr_mm_idx
  702. )
  703. # Compute the hash of the current block
  704. block_tokens = request.all_token_ids[start_token_idx:end_token_idx]
  705. block_hash = hash_block_tokens(
  706. caching_hash_fn, prev_block_hash_value, block_tokens, extra_keys
  707. )
  708. new_block_hashes.append(block_hash)
  709. start_token_idx += hash_block_size
  710. prev_block_hash_value = block_hash
  711. return new_block_hashes
  712. return request_block_hasher
  713. def _check_enough_kv_cache_memory(
  714. available_memory: int,
  715. get_needed_memory: Callable[[], int],
  716. max_model_len: int,
  717. estimate_max_model_len: Callable[[int], int],
  718. ):
  719. if available_memory <= 0:
  720. raise ValueError(
  721. "No available memory for the cache blocks. "
  722. "Try increasing `gpu_memory_utilization` when initializing the engine "
  723. "(this flag also controls CPU memory reservation on the CPU "
  724. "backend, despite its name). "
  725. "See https://docs.vllm.ai/en/latest/configuration/conserving_memory/ "
  726. "for more details."
  727. )
  728. needed_memory = get_needed_memory()
  729. if needed_memory > available_memory:
  730. estimated_max_len = estimate_max_model_len(available_memory)
  731. estimated_msg = ""
  732. if estimated_max_len > 0:
  733. estimated_msg = (
  734. "Based on the available memory, "
  735. f"the estimated maximum model length is {estimated_max_len}. "
  736. )
  737. raise ValueError(
  738. f"To serve at least one request with the model's max seq len "
  739. f"({max_model_len}), ({format_gib(needed_memory)} GiB KV "
  740. f"cache is needed, which is larger than the available KV cache "
  741. f"memory ({format_gib(available_memory)} GiB). {estimated_msg}"
  742. f"Try increasing `gpu_memory_utilization` (which also controls "
  743. f"CPU memory on the CPU backend) or decreasing `max_model_len` "
  744. f"when initializing the engine. "
  745. f"See https://docs.vllm.ai/en/latest/configuration/conserving_memory/ "
  746. f"for more details."
  747. )
  748. def max_memory_usage_bytes(
  749. vllm_config: VllmConfig, kv_cache_specs: Iterable[KVCacheSpec]
  750. ) -> int:
  751. """
  752. Get the maximum memory usage in bytes for the given KV cache specs.
  753. """
  754. return sum(spec.max_memory_usage_bytes(vllm_config) for spec in kv_cache_specs)
  755. def estimate_max_model_len(
  756. vllm_config: VllmConfig,
  757. kv_cache_spec: dict[str, KVCacheSpec],
  758. available_memory: int,
  759. ) -> int:
  760. """
  761. Estimates the maximum model length that can fit in the available memory
  762. using binary search.
  763. This function temporarily modifies max_model_len during estimation but
  764. restores the original value before returning, ensuring no side effects.
  765. Args:
  766. vllm_config: The global VllmConfig
  767. kv_cache_spec: The kv cache spec of each attention layer in the model
  768. available_memory: Memory available for KV cache in bytes.
  769. Returns:
  770. The estimated maximum model length that can fit in the available memory.
  771. """
  772. # Save the original max_model_len to restore after estimation
  773. original_max_model_len = vllm_config.model_config.max_model_len
  774. # Define a function to check if a given model length fits in memory
  775. def fits_in_memory(model_len: int) -> bool:
  776. # Temporarily modify the max_model_len for this calculation
  777. vllm_config.model_config.max_model_len = model_len
  778. # Calculate memory needed for the given model length
  779. memory_needed = max_memory_usage_bytes(vllm_config, kv_cache_spec.values())
  780. return memory_needed <= available_memory
  781. try:
  782. # Binary search for the maximum model length
  783. left, right = 1, original_max_model_len
  784. # If even the smallest model length doesn't fit, return 0
  785. if not fits_in_memory(left):
  786. return 0
  787. # Binary search for the maximum model length that fits
  788. result = 1
  789. while left <= right:
  790. mid = (left + right) // 2
  791. if fits_in_memory(mid):
  792. result = mid
  793. left = mid + 1
  794. else:
  795. right = mid - 1
  796. return result
  797. finally:
  798. # Always restore the original max_model_len to avoid side effects
  799. vllm_config.model_config.max_model_len = original_max_model_len
  800. def check_enough_kv_cache_memory(
  801. vllm_config: VllmConfig,
  802. kv_cache_spec: dict[str, KVCacheSpec],
  803. available_memory: int,
  804. ):
  805. """
  806. Checks whether `available_memory` is enough for the KV cache to hold at
  807. least one request with the model's max_model_len.
  808. Args:
  809. vllm_config: The global VllmConfig
  810. kv_cache_spec: The kv cache spec of each attention layer in the model
  811. available_memory: Memory available for KV cache in bytes.
  812. Raises:
  813. ValueError: If there is not enough memory available for the KV cache.
  814. """
  815. # No need to check for available memory if the kv_cache_spec is empty
  816. if kv_cache_spec:
  817. # Reserve the null block BlockPool permanently holds back, so the check
  818. # plans against usable blocks, as in get_kv_cache_configs. Group a copy
  819. # of the specs since grouping may unify them in-place.
  820. groups = get_kv_cache_groups(vllm_config, dict(kv_cache_spec))
  821. check_memory = (
  822. available_memory - _pool_bytes_per_block(groups)
  823. if groups
  824. else available_memory
  825. )
  826. _check_enough_kv_cache_memory(
  827. check_memory,
  828. lambda: max_memory_usage_bytes(vllm_config, kv_cache_spec.values()),
  829. vllm_config.model_config.max_model_len,
  830. lambda am: estimate_max_model_len(vllm_config, kv_cache_spec, am),
  831. )
  832. def create_kv_cache_group_specs(
  833. kv_cache_spec: dict[str, KVCacheSpec], grouped_layer_names: list[list[str]]
  834. ) -> list[KVCacheGroupSpec]:
  835. """
  836. Create KVCacheGroupSpec object for each kv cache group layer.
  837. The layers in the same group should share the same
  838. KVCacheSpec.
  839. Args:
  840. kv_cache_spec:
  841. A mapping from each layer name to its corresponding KVCacheSpec.
  842. grouped_layer_names:
  843. A list of kv cache groups, where each element is a list of layer
  844. names that belong to the same group and should share the same
  845. KVCacheSpec.
  846. Returns:
  847. A list of KVCacheGroupSpec objects, one for each group.
  848. """
  849. kv_cache_groups = []
  850. for layer_names_one_group in grouped_layer_names:
  851. layer_specs = [
  852. kv_cache_spec[layer_name] for layer_name in layer_names_one_group
  853. ]
  854. merged_layer_spec = layer_specs[0].merge(layer_specs)
  855. kv_cache_groups.append(
  856. KVCacheGroupSpec(layer_names_one_group, merged_layer_spec)
  857. )
  858. return kv_cache_groups
  859. def is_kv_cache_spec_uniform(kv_cache_spec: dict[str, KVCacheSpec]) -> bool:
  860. """
  861. Whether all layers in the given KVCacheSpec have the same KV cache spec.
  862. Note that we regard FullAttentionSpec with and without sliding window as
  863. the same type.
  864. Args:
  865. kv_cache_spec: The kv cache spec of each attention layer in the model
  866. Returns:
  867. True if all layers have the same type, False otherwise.
  868. """
  869. if not kv_cache_spec:
  870. # Encoder-only models do not have KV cache, kv_cache_type can be
  871. # regarded as uniform.
  872. return True
  873. try:
  874. kv_cache_spec_values = list(kv_cache_spec.values())
  875. _ = kv_cache_spec_values[0].merge(kv_cache_spec_values)
  876. except AssertionError:
  877. return False
  878. return True
  879. def get_max_concurrency_for_kv_cache_config(
  880. vllm_config: VllmConfig, kv_cache_config: KVCacheConfig
  881. ) -> float:
  882. """
  883. Get the maximum concurrency for the given KV cache configuration.
  884. A request at max_model_len consumes whole blocks from each group's block
  885. table — cdiv(per-request bytes, page bytes) of the group's spec — and all
  886. groups draw those block ids from one shared pool, so the per-request
  887. total is the sum over groups. The memory/page ratio is identical whether
  888. a group carries an aggregated UniformTypeKVCacheSpecs (worker config) or
  889. a representative per-layer spec (scheduler config), so both capacity
  890. call sites agree.
  891. """
  892. num_blocks_per_request = sum(
  893. cdiv(
  894. group.kv_cache_spec.max_memory_usage_bytes(vllm_config),
  895. group.kv_cache_spec.page_size_bytes,
  896. )
  897. for group in kv_cache_config.kv_cache_groups
  898. )
  899. max_concurrency = kv_cache_config.num_blocks / num_blocks_per_request
  900. return max_concurrency
  901. def may_override_num_blocks(vllm_config: VllmConfig, num_blocks: int) -> int:
  902. """
  903. Override the number of kv cache blocks if `num_gpu_blocks_override` is set.
  904. The override is logged once, at the call site in `get_kv_cache_configs`.
  905. """
  906. if vllm_config.cache_config.num_gpu_blocks_override is not None:
  907. num_blocks = vllm_config.cache_config.num_gpu_blocks_override
  908. return num_blocks
  909. def _pool_bytes_per_block(kv_cache_groups: list[KVCacheGroupSpec]) -> int:
  910. """
  911. Bytes consumed by one block in the worker's shared KV cache pool, mirroring
  912. the divisor used by `get_kv_cache_config_from_groups` to convert
  913. `available_memory` into `num_blocks`. Used to compute the effective KV cache
  914. capacity once `num_gpu_blocks_override` is applied.
  915. """
  916. return _get_kv_cache_bytes_per_block(kv_cache_groups)
  917. def get_uniform_page_size(kv_cache_specs: Iterable[KVCacheSpec]) -> int:
  918. """
  919. Get the page size of the KV cache.
  920. """
  921. page_sizes = {layer.page_size_bytes for layer in kv_cache_specs}
  922. assert len(page_sizes) == 1
  923. return page_sizes.pop()
  924. def _get_kv_cache_groups_uniform_spec(
  925. kv_cache_specs: dict[str, KVCacheSpec],
  926. ) -> list[KVCacheGroupSpec]:
  927. """
  928. Generates the KV cache configuration for a model with the same KV cache
  929. spec for all layers.
  930. Args:
  931. kv_cache_specs: The kv cache spec of each attention layer in the model
  932. Returns:
  933. The generated KVCacheGroupSpecs
  934. """
  935. return create_kv_cache_group_specs(kv_cache_specs, [list(kv_cache_specs.keys())])
  936. def _get_kv_cache_groups_uniform_type(
  937. spec: UniformTypeKVCacheSpecs,
  938. ) -> list[KVCacheGroupSpec]:
  939. """
  940. Generates the KV cache configuration for a model with one type of KV cache
  941. but different hidden sizes. All layers are merged into one group.
  942. Args:
  943. spec: The UniformTypeKVCacheSpecs of the model
  944. Returns:
  945. The generated KVCacheGroupSpecs
  946. """
  947. return [KVCacheGroupSpec(list(spec.kv_cache_specs.keys()), spec)]
  948. def _pp_balanced_mamba_group_count(
  949. vllm_config: VllmConfig,
  950. mamba_layer_names: list[str],
  951. mla_layer_names: list[str],
  952. ) -> int | None:
  953. """Return a Mamba group count whose PP projections fit the MLA slots."""
  954. num_groups = cdiv(len(mamba_layer_names), len(mla_layer_names))
  955. pp_size = vllm_config.parallel_config.pipeline_parallel_size
  956. if pp_size == 1:
  957. return num_groups
  958. from vllm.distributed.utils import get_pp_indices
  959. from vllm.model_executor.models.utils import extract_layer_index
  960. total_layers = vllm_config.model_config.get_total_num_hidden_layers()
  961. mamba_indices = [extract_layer_index(name) for name in mamba_layer_names]
  962. mla_indices = [extract_layer_index(name) for name in mla_layer_names]
  963. for rank in range(pp_size):
  964. start, end = get_pp_indices(total_layers, rank, pp_size)
  965. num_mamba = sum(start <= index < end for index in mamba_indices)
  966. num_mla = sum(start <= index < end for index in mla_indices)
  967. if not num_mamba:
  968. continue
  969. if not num_mla:
  970. return None
  971. num_groups = max(num_groups, cdiv(num_mamba, num_mla))
  972. return num_groups
  973. def _get_kv_cache_groups_glm5_next(
  974. vllm_config: VllmConfig,
  975. kv_cache_spec: dict[str, KVCacheSpec],
  976. ) -> list[KVCacheGroupSpec] | None:
  977. """Build GLM-5.3-Flash groups with Mamba/MLA and tail/indexer aliasing."""
  978. mamba_specs = {
  979. name: spec
  980. for name, spec in kv_cache_spec.items()
  981. if isinstance(spec, MambaSpec)
  982. }
  983. tail_specs = {
  984. name: spec
  985. for name, spec in kv_cache_spec.items()
  986. if isinstance(spec, KpoolTailSpec)
  987. }
  988. attn_specs = {
  989. name: spec
  990. for name, spec in kv_cache_spec.items()
  991. if not isinstance(spec, (MambaSpec, KpoolTailSpec))
  992. }
  993. if not mamba_specs or not all(
  994. type(spec) is MLAAttentionSpec for spec in attn_specs.values()
  995. ):
  996. return None
  997. mla_specs = cast(dict[str, MLAAttentionSpec], attn_specs)
  998. idx_pages = {
  999. spec.page_size_bytes for spec in mla_specs.values() if spec.tokens_per_state > 1
  1000. }
  1001. if not idx_pages:
  1002. return None
  1003. assert all(spec.page_size_padded is None for spec in mla_specs.values())
  1004. assert len(idx_pages) == 1
  1005. mla_names = [name for name, spec in mla_specs.items() if spec.tokens_per_state == 1]
  1006. mla_pages = {mla_specs[name].page_size_bytes for name in mla_names}
  1007. assert len(mla_pages) == 1
  1008. mla_page = mla_pages.pop()
  1009. uniform_spec = UniformTypeKVCacheSpecs.from_specs(attn_specs)
  1010. assert uniform_spec is not None
  1011. tail_group: KVCacheGroupSpec | None = None
  1012. if tail_specs:
  1013. idx_page = next(iter(idx_pages))
  1014. padded_tail_specs: dict[str, KVCacheSpec] = {
  1015. name: replace(spec, page_size_padded=idx_page)
  1016. for name, spec in tail_specs.items()
  1017. }
  1018. tail_uniform = UniformTypeKVCacheSpecs.from_specs(padded_tail_specs)
  1019. assert tail_uniform is not None
  1020. tail_group = KVCacheGroupSpec(list(padded_tail_specs), tail_uniform)
  1021. any_mamba = next(iter(mamba_specs.values()))
  1022. assert all(spec == any_mamba for spec in mamba_specs.values())
  1023. if any_mamba.real_page_size_bytes > mla_page:
  1024. raise ValueError(
  1025. f"the mamba state page ({any_mamba.real_page_size_bytes} bytes) "
  1026. f"does not fit the MLA page ({mla_page} bytes); increase tensor "
  1027. "parallelism or use a wider KV cache dtype"
  1028. )
  1029. padded_specs: dict[str, KVCacheSpec] = {
  1030. name: replace(any_mamba, page_size_padded=mla_page) for name in mamba_specs
  1031. }
  1032. num_groups = _pp_balanced_mamba_group_count(
  1033. vllm_config, list(mamba_specs), mla_names
  1034. )
  1035. if num_groups is None:
  1036. raise ValueError(
  1037. "a pipeline stage has mamba layers but no MLA layer to share "
  1038. "slots with; realign the stage boundaries (VLLM_PP_LAYER_PARTITION)"
  1039. )
  1040. mamba_grouped_names: list[list[str]] = [[] for _ in range(num_groups)]
  1041. for index, name in enumerate(mamba_specs):
  1042. mamba_grouped_names[index % num_groups].append(name)
  1043. return (
  1044. [KVCacheGroupSpec(list(attn_specs), uniform_spec)]
  1045. + ([tail_group] if tail_group is not None else [])
  1046. + create_kv_cache_group_specs(padded_specs, mamba_grouped_names)
  1047. )
  1048. def _glm5_next_tensor_layout(
  1049. kv_cache_groups: list[KVCacheGroupSpec],
  1050. ) -> (
  1051. tuple[
  1052. KVCacheGroupSpec,
  1053. list[KVCacheGroupSpec],
  1054. list[str],
  1055. list[str],
  1056. int,
  1057. int,
  1058. list[str],
  1059. int,
  1060. ]
  1061. | None
  1062. ):
  1063. """Recognize the GLM-5.3-Flash grouping after optional PP projection."""
  1064. uniform_groups = [
  1065. group
  1066. for group in kv_cache_groups
  1067. if isinstance(group.kv_cache_spec, UniformTypeKVCacheSpecs)
  1068. ]
  1069. mamba_groups = [
  1070. group for group in kv_cache_groups if isinstance(group.kv_cache_spec, MambaSpec)
  1071. ]
  1072. attn_group: KVCacheGroupSpec | None = None
  1073. tail_group: KVCacheGroupSpec | None = None
  1074. for group in uniform_groups:
  1075. inner = cast(UniformTypeKVCacheSpecs, group.kv_cache_spec).kv_cache_specs
  1076. if all(type(spec) is MLAAttentionSpec for spec in inner.values()):
  1077. attn_group = group
  1078. elif all(isinstance(spec, KpoolTailSpec) for spec in inner.values()):
  1079. tail_group = group
  1080. if attn_group is None or not mamba_groups:
  1081. return None
  1082. if len(uniform_groups) + len(mamba_groups) != len(kv_cache_groups):
  1083. return None
  1084. attn_uniform = cast(UniformTypeKVCacheSpecs, attn_group.kv_cache_spec)
  1085. mla_inner = cast(dict[str, MLAAttentionSpec], attn_uniform.kv_cache_specs)
  1086. if not all(
  1087. type(spec) is MLAAttentionSpec and spec.page_size_padded is None
  1088. for spec in mla_inner.values()
  1089. ):
  1090. return None
  1091. mla_names = [
  1092. name for name in attn_group.layer_names if mla_inner[name].tokens_per_state == 1
  1093. ]
  1094. idx_names = [
  1095. name for name in attn_group.layer_names if mla_inner[name].tokens_per_state > 1
  1096. ]
  1097. mla_pages = {mla_inner[name].page_size_bytes for name in mla_names}
  1098. idx_pages = {mla_inner[name].page_size_bytes for name in idx_names}
  1099. if len(mla_pages) != 1 or len(idx_pages) != 1:
  1100. return None
  1101. mla_page = mla_pages.pop()
  1102. idx_page = idx_pages.pop()
  1103. if any(group.kv_cache_spec.page_size_bytes != mla_page for group in mamba_groups):
  1104. return None
  1105. tail_names: list[str] = []
  1106. tail_page = 0
  1107. if tail_group is not None:
  1108. tail_names = list(tail_group.layer_names)
  1109. tail_inner = cast(
  1110. UniformTypeKVCacheSpecs, tail_group.kv_cache_spec
  1111. ).kv_cache_specs
  1112. tail_pages = {
  1113. cast(KpoolTailSpec, spec).unpadded_page_size_bytes
  1114. for spec in tail_inner.values()
  1115. }
  1116. if len(tail_pages) != 1 or len(tail_names) != len(idx_names):
  1117. return None
  1118. tail_page = tail_pages.pop()
  1119. if tail_page > idx_page:
  1120. return None
  1121. return (
  1122. attn_group,
  1123. mamba_groups,
  1124. mla_names,
  1125. idx_names,
  1126. mla_page,
  1127. idx_page,
  1128. tail_names,
  1129. tail_page,
  1130. )
  1131. def unify_kv_cache_spec_page_size(
  1132. kv_cache_spec: dict[str, KVCacheSpec],
  1133. ) -> dict[str, KVCacheSpec]:
  1134. """
  1135. Unify the page size of the given KVCacheSpec. If the page size of all layers
  1136. are the same, return the original KVCacheSpec. If not same, unify the page
  1137. size by increasing the block size of layers with smaller page size. Two
  1138. cases cannot be unified by block size alone and pad their physical page to
  1139. the maximum instead: Mamba layers, whose page size comes from state shapes
  1140. and is independent of block size; and non-MLA attention layers whose page
  1141. does not evenly divide the maximum (the padded page is read through a
  1142. strided view). MLA is excluded because sparse MLA indexes the cache in
  1143. whole token rows (see ``flat_kv_row_view``), so its block stride can only
  1144. be padded by its own row-aligned ``alignment``, not to an arbitrary page
  1145. size. Raise NotImplementedError if failed to unify the page size;
  1146. ``get_kv_cache_groups`` catches it to try the full-allocation fallback
  1147. (e.g. MLA next to an incompatible sliding-window draft).
  1148. Args:
  1149. kv_cache_spec: The KVCacheSpec of each attention layer in the model
  1150. Returns:
  1151. The updated KVCacheSpec with the same page_size_bytes.
  1152. """
  1153. page_sizes = {layer.page_size_bytes for layer in kv_cache_spec.values()}
  1154. if len(page_sizes) <= 1:
  1155. # All layers have the same page size, no need to unify.
  1156. return kv_cache_spec
  1157. max_page_size = max(page_sizes)
  1158. new_kv_cache_spec = {}
  1159. for layer_name, layer_spec in kv_cache_spec.items():
  1160. if layer_spec.page_size_bytes == max_page_size:
  1161. new_kv_cache_spec[layer_name] = layer_spec
  1162. elif isinstance(layer_spec, MambaSpec):
  1163. # MambaSpec's page size is determined by its state shapes and does
  1164. # not scale with block_size, so pad the page instead. This is the
  1165. # same padding mechanism the platform uses to align Mamba pages
  1166. # with the main model's attention page size; it is needed here
  1167. # when another layer (e.g. from a draft model) has a larger page
  1168. # than the already-aligned Mamba page.
  1169. new_spec: KVCacheSpec = replace(layer_spec, page_size_padded=max_page_size)
  1170. assert new_spec.page_size_bytes == max_page_size
  1171. new_kv_cache_spec[layer_name] = new_spec
  1172. else:
  1173. layer_page_size = layer_spec.page_size_bytes
  1174. if max_page_size % layer_page_size == 0:
  1175. ratio = max_page_size // layer_page_size
  1176. new_block_size = layer_spec.block_size * ratio
  1177. new_spec = replace(layer_spec, block_size=new_block_size)
  1178. elif isinstance(layer_spec, AttentionSpec) and not isinstance(
  1179. layer_spec, MLAAttentionSpec
  1180. ):
  1181. new_spec = replace(layer_spec, page_size_padded=max_page_size)
  1182. else:
  1183. raise NotImplementedError(
  1184. f"Layer {layer_name}: page size is not divisible by the "
  1185. "maximum page size and cannot be padded. Padding is only "
  1186. "supported for non-MLA attention layers."
  1187. )
  1188. assert new_spec.page_size_bytes == max_page_size
  1189. new_kv_cache_spec[layer_name] = new_spec
  1190. return new_kv_cache_spec
  1191. def is_kv_cache_type_attention_free(kv_cache_spec: dict[str, KVCacheSpec]) -> bool:
  1192. # kv_cache_spec is an empty dict for attention free models
  1193. return not kv_cache_spec
  1194. def _get_kv_cache_groups_uniform_page_size(
  1195. kv_cache_spec: dict[str, KVCacheSpec],
  1196. ) -> list[KVCacheGroupSpec]:
  1197. """
  1198. Generates the KV cache groups for hybrid models with multiple
  1199. attention types but still with a uniform page size (physical memory per
  1200. block per layer) for all layers.
  1201. Detailed explanation about kv cache management of hybrid models:
  1202. The layers in the models are repeated with some patterns, e.g., a model
  1203. with 10 full attention layers and 20 sliding window attention layers can be
  1204. regarded as repeating the pattern (1 * full, 2 * sw) 10 times.
  1205. The KVCacheManager allocates different block tables for each of the 3 layers
  1206. in the pattern, and repeats each of them 10 times to generate the
  1207. block_table for the 30 layers in the model.
  1208. Therefore, we can group the layers in the model into 3 kv_cache_groups, each
  1209. of which contains 10 layers in the model.
  1210. The KVCacheManager allocates the block_table for each group based on its
  1211. kv_cache spec, and the model runner applies the block table to each layer
  1212. in the group.
  1213. For example:
  1214. 1. A model only uses full attention. The pattern is
  1215. (num_hidden_layers * full), so there is only one group and the block table
  1216. is shared by all layers. It is already handled by
  1217. `_get_kv_cache_config_uniform_type`.
  1218. 2. A model with 10 full attention layers and 20 sliding window
  1219. attention layers. There are 3 layers in the pattern (1 * full, 2 * sw), so
  1220. there are 3 kv_cache_groups, each of which represents 10 layers.
  1221. To simplify the implementation, we make the following assumptions:
  1222. 1. Physical memory per block: Must be the same across all KV cache groups.
  1223. Breaking this assumption is non-trivial due to memory fragmentation concerns
  1224. when allocating blocks of different sizes.
  1225. 2. Tokens per block (block_size): Currently, we directly use
  1226. `CacheConfig.block_size` for all layers. It can be extended to vary by KV
  1227. cache group, but within each KV cache group, all layers must share the same
  1228. block size.
  1229. 3. Physical memory per token per layer: This property is decided by model
  1230. config. Currently we only support models that have the same physical memory
  1231. per token per layer for all layers. Can be relaxed with a simple extension,
  1232. but still need to keep physical memory per block the same for all groups.
  1233. 4. Number of layers per group: Currently assumed the same for all layers.
  1234. Can be relaxed with a simple extension, but still need to keep physical
  1235. memory per block the same for all groups.
  1236. 5. Attention type within groups: All layers in a group must share the same
  1237. attention type. One exception is that, when
  1238. `--disable-hybrid-kv-cache-manager` is true, the single group for full
  1239. attention layers may also include attention layers using sliding window or
  1240. LLaMA 4 local attention. See `unify_hybrid_kv_cache_specs` for more details.
  1241. 6. Support for multiple attention types: The design for most components is
  1242. general to an arbitrary number of attention types. But
  1243. `find_longest_cache_hit` only supports one attention type or two
  1244. types of full-attention plus exactly one another type. The general
  1245. implementation of this function is feasible but we don't know how to
  1246. implement it cleanly yet.
  1247. As we assume tokens per block, physical memory per token per layer, and
  1248. number of layers per group are the same now, we can ensure that physical
  1249. memory per block is the same for all groups.
  1250. Args:
  1251. kv_cache_spec: The KVCacheSpec of each attention layer in the model
  1252. Returns:
  1253. The generated KVCacheGroupSpecs
  1254. """
  1255. # Group all layers by kv_cache_spec.
  1256. # E.g., 2 full attention layers and 3 sliding window attention layers,
  1257. # -> (full.0, full.1), (sw.0, sw.1, sw.2).
  1258. same_type_layers: dict[KVCacheSpec, list[str]] = defaultdict(list)
  1259. for layer_name, layer_spec in kv_cache_spec.items():
  1260. same_type_layers[layer_spec].append(layer_name)
  1261. # Attempt to further merge same-type layers based on whether their KV
  1262. # cache specs can be merged, to minimize the group count. This benefits
  1263. # situations where specs share a block layout and differ only in a
  1264. # property it can reconcile (e.g. full attention layers differing only in
  1265. # sliding window / attention chunk size).
  1266. layer_buckets: list[list[str]] = []
  1267. spec_buckets: list[list[KVCacheSpec]] = []
  1268. for layer_spec, layer_names in same_type_layers.items():
  1269. for names, specs in zip(layer_buckets, spec_buckets):
  1270. try:
  1271. # A raise means that the specs are incompatible.
  1272. type(specs[0]).merge([*specs, layer_spec])
  1273. except (AssertionError, ValueError):
  1274. continue
  1275. names.extend(layer_names)
  1276. specs.append(layer_spec)
  1277. break
  1278. else:
  1279. layer_buckets.append(list(layer_names))
  1280. spec_buckets.append([layer_spec])
  1281. # Split each group into smaller groups, to make the number of layers in each
  1282. # group identical. Add padding to the last group of each type if necessary.
  1283. # E.g., (full.0, full.1), (sw.0, sw.1, sw.2)
  1284. # split to 3 groups with 2 layers each:
  1285. # (full.0, full.1), (sw.0, sw.2), (sw.1, padding).
  1286. # FIXME(Chen): At the moment of writing this code (2025-06-02), all
  1287. # open-source hybrid model follows a n:1 pattern between different attention
  1288. # types (e.g., Gemma3 5:1 between sw and full, LLaMA4 3:1 between local and
  1289. # full), so we can use the "1" in the n:1 pattern as the group size, which
  1290. # is the minimum number of layers among all attention types. Need a better
  1291. # strategy if we want to support more complex patterns (e.g., 20 full + 30
  1292. # sw, where the group size should be 10).
  1293. min_num_layers = min([len(layers) for layers in layer_buckets])
  1294. group_size = min_num_layers
  1295. max_num_layers = max([len(layers) for layers in layer_buckets])
  1296. if max_num_layers < min_num_layers * 1.5:
  1297. # If the number of layers is not much larger than the minimum number of
  1298. # layers, use the maximum number of layers as the group size to avoid
  1299. # too many padding layers. A typical example is gpt-oss-20b + eagle,
  1300. # with 12 sw + 13 full. We pad it to (13 sw, 13 full) instead of
  1301. # (12 sw, 24 full). 1.5 is a heuristic to avoid too many padding
  1302. # layers while accommodating speculative decoding drafters that add
  1303. # extra layers to one attention type.
  1304. group_size = max_num_layers
  1305. grouped_layers = []
  1306. for layers in layer_buckets:
  1307. num_padding_layers = group_size - len(layers) % group_size
  1308. if num_padding_layers != group_size:
  1309. logger.warning(
  1310. "Add %d padding layers, may waste at most %.2f%% KV cache memory", # noqa
  1311. num_padding_layers,
  1312. num_padding_layers / len(layers) * 100,
  1313. )
  1314. num_groups = cdiv(len(layers), group_size)
  1315. # In PP case, say if we have
  1316. # - stage 0: full.0, sw.0, sw.1
  1317. # - stage 1: full.1, sw.2, sw.3
  1318. # We should have 3 groups: (full.0, full.1), (sw.0, sw.2), (sw.1, sw.3)
  1319. # It can't be (full.0, full.1), (sw.0, sw.1), (sw.2, sw.3) because
  1320. # the 3 groups in stage 0 will be (full.0), (sw.0, sw.1), (empty group)
  1321. # and it will be padded to (full.0, padding), (sw.0, sw.1),
  1322. # (padding, padding) to ensure the number of layers in each group is
  1323. # the same and will cause memory waste.
  1324. # To avoid this, we assign layers[i::num_groups] to the i-th group
  1325. # instead of layers[i * group_size: (i + 1) * group_size]
  1326. for i in range(num_groups):
  1327. grouped_layers.append(layers[i::num_groups])
  1328. return create_kv_cache_group_specs(kv_cache_spec, grouped_layers)
  1329. def _get_per_layer_spec(
  1330. group: KVCacheGroupSpec,
  1331. layer_name: str,
  1332. ) -> KVCacheSpec:
  1333. spec = group.kv_cache_spec
  1334. if isinstance(spec, UniformTypeKVCacheSpecs):
  1335. return spec.kv_cache_specs[layer_name]
  1336. return spec
  1337. def _get_kv_cache_bytes_per_block(
  1338. kv_cache_groups: list[KVCacheGroupSpec],
  1339. ) -> int:
  1340. """Return the largest cache group's bytes per block."""
  1341. if (glm5_layout := _glm5_next_tensor_layout(kv_cache_groups)) is not None:
  1342. _, _, mla_names, idx_names, mla_page, idx_page, _, _ = glm5_layout
  1343. return len(mla_names) * mla_page + len(idx_names) * idx_page
  1344. bytes_per_block = max(
  1345. sum(
  1346. _get_per_layer_spec(group, layer_name).page_size_bytes
  1347. for layer_name in group.layer_names
  1348. )
  1349. for group in kv_cache_groups
  1350. )
  1351. assert bytes_per_block > 0
  1352. return bytes_per_block
  1353. def validate_kv_cache_layout(
  1354. layout: KVCacheLayout,
  1355. kv_cache_groups: list[KVCacheGroupSpec],
  1356. ) -> None:
  1357. """Validate that the resolved layout can express this model's packing.
  1358. The layout was chosen once in the engine core from the backends' supported
  1359. sets; a backend whose model packs pages side by side (e.g. the DeepSeek-V4
  1360. indexer) declares block-outermost layouts there, so an inexpressible
  1361. layout reaching this point is an error.
  1362. """
  1363. page_sizes = {
  1364. _get_per_layer_spec(group, layer_name).page_size_bytes
  1365. for group in kv_cache_groups
  1366. for layer_name in group.layer_names
  1367. }
  1368. if len(page_sizes) == 1:
  1369. # A rectangular layer dim exists; every layout can express it.
  1370. return
  1371. # Mixed page sizes pack pages side by side within a block, which needs each page
  1372. # to be one contiguous chunk inside its block (a block-compact layout) and, with
  1373. # multiple KV cache groups, the layer dim inside the block dim.
  1374. if not layout.is_block_compact or (
  1375. len(kv_cache_groups) > 1 and layout.is_layer_compact
  1376. ):
  1377. raise ValueError(
  1378. f"KV cache layout {layout.name} cannot express this model's "
  1379. f"mixed page sizes ({sorted(page_sizes)}); a backend should "
  1380. "declare block-outermost supported layouts (e.g. BLHNC), or "
  1381. "set VLLM_KV_CACHE_LAYOUT=BLHNC."
  1382. )
  1383. def get_kv_cache_config_from_groups(
  1384. vllm_config: VllmConfig,
  1385. kv_cache_groups: list[KVCacheGroupSpec],
  1386. available_memory: int,
  1387. ) -> KVCacheConfig:
  1388. """
  1389. Generate the KV cache configuration from the KV cache groups and spec
  1390. of each layer.
  1391. Args:
  1392. vllm_config: The global VllmConfig
  1393. kv_cache_groups: The KV cache groups
  1394. available_memory: Memory available for KV cache in bytes
  1395. Returns:
  1396. The generated KVCacheConfig
  1397. """
  1398. if len(kv_cache_groups) == 0:
  1399. # Attention free models do not have KV cache.
  1400. # Return num_blocks=1 as BlockPool always needs a null_block.
  1401. return KVCacheConfig(
  1402. num_blocks=1,
  1403. kv_cache_tensors=[],
  1404. kv_cache_groups=kv_cache_groups,
  1405. prefix_cache_retention_interval=(
  1406. vllm_config.cache_config.prefix_cache_retention_interval
  1407. ),
  1408. )
  1409. if (glm5_layout := _glm5_next_tensor_layout(kv_cache_groups)) is not None:
  1410. (
  1411. attn_group,
  1412. mamba_groups,
  1413. mla_names,
  1414. idx_names,
  1415. mla_page,
  1416. idx_page,
  1417. tail_names,
  1418. _,
  1419. ) = glm5_layout
  1420. bytes_per_block = len(mla_names) * mla_page + len(idx_names) * idx_page
  1421. num_blocks = may_override_num_blocks(
  1422. vllm_config, available_memory // bytes_per_block
  1423. )
  1424. size = bytes_per_block * num_blocks
  1425. attn_specs = cast(
  1426. UniformTypeKVCacheSpecs, attn_group.kv_cache_spec
  1427. ).kv_cache_specs
  1428. kv_cache_tensors: list[KVCacheTensor] = []
  1429. def add_tensor(layer_name: str, spec: KVCacheSpec, offset: int) -> None:
  1430. kv_cache_tensors.append(
  1431. KVCacheTensor(
  1432. size=size,
  1433. layers=[layer_name],
  1434. layer_stride=spec.page_size_bytes * num_blocks,
  1435. block_stride=spec.page_size_bytes,
  1436. offset=offset,
  1437. )
  1438. )
  1439. for index, mla_name in enumerate(mla_names):
  1440. offset = index * mla_page * num_blocks
  1441. add_tensor(mla_name, attn_specs[mla_name], offset)
  1442. for group in mamba_groups:
  1443. if index < len(group.layer_names):
  1444. add_tensor(group.layer_names[index], group.kv_cache_spec, offset)
  1445. idx_base = len(mla_names) * mla_page * num_blocks
  1446. for index, idx_name in enumerate(idx_names):
  1447. offset = idx_base + index * idx_page * num_blocks
  1448. add_tensor(idx_name, attn_specs[idx_name], offset)
  1449. if tail_names:
  1450. tail_name = tail_names[index]
  1451. tail_group = next(
  1452. group for group in kv_cache_groups if tail_name in group.layer_names
  1453. )
  1454. tail_specs = cast(
  1455. UniformTypeKVCacheSpecs, tail_group.kv_cache_spec
  1456. ).kv_cache_specs
  1457. add_tensor(tail_name, tail_specs[tail_name], offset)
  1458. return KVCacheConfig(
  1459. num_blocks=num_blocks,
  1460. kv_cache_tensors=kv_cache_tensors,
  1461. kv_cache_groups=kv_cache_groups,
  1462. prefix_cache_retention_interval=(
  1463. vllm_config.cache_config.prefix_cache_retention_interval
  1464. ),
  1465. )
  1466. layout = vllm_config.cache_config.get_resolved_kv_cache_layout()
  1467. validate_kv_cache_layout(layout, kv_cache_groups)
  1468. bytes_per_block = _get_kv_cache_bytes_per_block(kv_cache_groups)
  1469. interleaved_block_stride = bytes_per_block if layout.is_block_outermost else None
  1470. num_blocks = available_memory // bytes_per_block
  1471. num_blocks = may_override_num_blocks(vllm_config, num_blocks)
  1472. size = bytes_per_block * num_blocks
  1473. # Groups alias from byte 0. Spec regions are laid out differently:
  1474. #
  1475. # block-outer (the same packing repeats for every block):
  1476. # group 0: | blk 0 [ A | B | pad ] | blk 1 [ A | B | pad ] | ...
  1477. # group 1: | blk 0 [ C | D ] | blk 1 [ C | D ] | ...
  1478. # |<--- bytes_per_block -->|
  1479. #
  1480. # layer-outer (only supported for uniform page sizes or single-group models):
  1481. # group 0: | A [ blk 0 | blk 1 | ... ] | B [ blk 0 | blk 1 | ... ] |
  1482. # group 1: | C [ blk 0 | blk 1 | ... ] | D [ blk 0 | blk 1 | ... ] |
  1483. kv_cache_tensors = []
  1484. for group in kv_cache_groups:
  1485. group_spec = group.kv_cache_spec
  1486. layers_by_spec: defaultdict[KVCacheSpec, list[str]] = defaultdict(list)
  1487. if isinstance(group_spec, UniformTypeKVCacheSpecs):
  1488. for layer_name, spec in group_spec.kv_cache_specs.items():
  1489. layers_by_spec[spec].append(layer_name)
  1490. elif group.layer_names:
  1491. layers_by_spec[group_spec].extend(group.layer_names)
  1492. byte_offset = 0
  1493. for spec, layer_names in layers_by_spec.items():
  1494. layer_stride, block_stride, _, _, _ = compute_layout_strides(
  1495. spec,
  1496. num_blocks,
  1497. len(layer_names),
  1498. layout,
  1499. fixed_strides=(None, interleaved_block_stride, None, None, None),
  1500. )
  1501. offset = (
  1502. byte_offset
  1503. * max(layer_stride, spec.page_size_bytes)
  1504. // spec.page_size_bytes
  1505. )
  1506. kv_cache_tensors.append(
  1507. KVCacheTensor(
  1508. size=size,
  1509. layers=layer_names,
  1510. layer_stride=layer_stride,
  1511. block_stride=block_stride,
  1512. offset=offset,
  1513. )
  1514. )
  1515. byte_offset += len(layer_names) * spec.page_size_bytes
  1516. return KVCacheConfig(
  1517. num_blocks=num_blocks,
  1518. kv_cache_tensors=kv_cache_tensors,
  1519. kv_cache_groups=kv_cache_groups,
  1520. prefix_cache_retention_interval=(
  1521. vllm_config.cache_config.prefix_cache_retention_interval
  1522. ),
  1523. )
  1524. def _promote_local_kv_cache_specs(
  1525. kv_cache_spec: dict[str, KVCacheSpec],
  1526. ) -> dict[str, KVCacheSpec]:
  1527. """Use full-attention allocation for local-attention cache specs.
  1528. The returned specs affect KV cache management only. Attention modules keep
  1529. their original sliding-window or chunked-local compute behavior.
  1530. """
  1531. promoted_specs = kv_cache_spec.copy()
  1532. if is_kv_cache_spec_uniform(
  1533. promoted_specs
  1534. ) or UniformTypeKVCacheSpecs.is_uniform_type(promoted_specs):
  1535. return promoted_specs
  1536. has_full_attention = any(
  1537. isinstance(spec, FullAttentionSpec) for spec in promoted_specs.values()
  1538. )
  1539. has_sliding_window = any(
  1540. isinstance(spec, SlidingWindowSpec) for spec in promoted_specs.values()
  1541. )
  1542. has_chunked_local_attention = any(
  1543. isinstance(spec, ChunkedLocalAttentionSpec) for spec in promoted_specs.values()
  1544. )
  1545. full_block_sizes = {
  1546. spec.block_size
  1547. for spec in promoted_specs.values()
  1548. if isinstance(spec, FullAttentionSpec)
  1549. }
  1550. full_attention_block_size = (
  1551. next(iter(full_block_sizes)) if len(full_block_sizes) == 1 else None
  1552. )
  1553. def promoted_page_size_padded(spec: AttentionSpec, block_size: int) -> int | None:
  1554. if spec.page_size_padded is None:
  1555. return None
  1556. unpadded_page_size = (
  1557. spec.unpadded_page_size_bytes * block_size // spec.block_size
  1558. )
  1559. return max(spec.page_size_padded, unpadded_page_size)
  1560. promotions: dict[type[AttentionSpec], type[AttentionSpec]] = {
  1561. SlidingWindowMLASpec: MLAAttentionSpec,
  1562. SlidingWindowSpec: FullAttentionSpec,
  1563. ChunkedLocalAttentionSpec: FullAttentionSpec,
  1564. }
  1565. if has_full_attention and (has_sliding_window or has_chunked_local_attention):
  1566. for layer_name, spec in kv_cache_spec.items():
  1567. target_cls = next(
  1568. (promotions[c] for c in type(spec).__mro__ if c in promotions), None
  1569. )
  1570. if target_cls is None:
  1571. continue
  1572. assert isinstance(spec, AttentionSpec)
  1573. block_size = full_attention_block_size or spec.block_size
  1574. promoted_specs[layer_name] = replace_as(
  1575. spec,
  1576. target_cls,
  1577. # Promoted specs allocate blocks for all tokens and never free
  1578. # below the window, so the trailing-edge extension is moot.
  1579. drop=("extra_retained_tokens",),
  1580. block_size=block_size,
  1581. page_size_padded=promoted_page_size_padded(spec, block_size),
  1582. )
  1583. if not (
  1584. is_kv_cache_spec_uniform(promoted_specs)
  1585. or UniformTypeKVCacheSpecs.is_uniform_type(promoted_specs)
  1586. ):
  1587. raise ValueError("Failed to promote local KV cache specs to one unified type.")
  1588. return promoted_specs
  1589. def _try_get_full_allocation_fallback_groups(
  1590. kv_cache_spec: dict[str, KVCacheSpec],
  1591. ) -> list[KVCacheGroupSpec] | None:
  1592. """Try a supported full-allocation fallback for local-attention layers."""
  1593. if any(isinstance(spec, HiddenStateCacheSpec) for spec in kv_cache_spec.values()):
  1594. return None
  1595. if any(
  1596. isinstance(spec, (SlidingWindowMLASpec, ChunkedLocalAttentionSpec))
  1597. for spec in kv_cache_spec.values()
  1598. ):
  1599. return None
  1600. has_mla = any(isinstance(spec, MLAAttentionSpec) for spec in kv_cache_spec.values())
  1601. has_regular_swa = any(
  1602. isinstance(spec, SlidingWindowSpec) for spec in kv_cache_spec.values()
  1603. )
  1604. if not (has_mla and has_regular_swa):
  1605. return None
  1606. try:
  1607. promoted_specs = _promote_local_kv_cache_specs(kv_cache_spec)
  1608. except ValueError:
  1609. return None
  1610. uniform_spec = UniformTypeKVCacheSpecs.from_specs(promoted_specs)
  1611. if uniform_spec is None:
  1612. return None
  1613. logger.warning(
  1614. "KV cache page sizes cannot be unified; treating sliding-window "
  1615. "layers as full attention for cache allocation. Sliding-window "
  1616. "attention compute is unchanged."
  1617. )
  1618. return _get_kv_cache_groups_uniform_type(uniform_spec)
  1619. def unify_hybrid_kv_cache_specs(kv_cache_spec: dict[str, KVCacheSpec]):
  1620. """
  1621. This function tries to convert the KV cache specs to one type if the model
  1622. is a hybrid model with multiple type of KV cache. It will convert all
  1623. SlidingWindowSpec to FullAttentionSpec if both types are present.
  1624. Args:
  1625. kv_cache_spec: The kv cache spec of each attention layer in the model
  1626. """
  1627. if is_kv_cache_spec_uniform(
  1628. kv_cache_spec
  1629. ) or UniformTypeKVCacheSpecs.is_uniform_type(kv_cache_spec):
  1630. return
  1631. logger.warning(
  1632. "Hybrid KV cache manager is disabled for this hybrid model, "
  1633. "This means we do not enable any optimizations for saving KV cache "
  1634. "memory (e.g., dropping the KV cache outside the sliding window). "
  1635. "The compute of layers like sliding window is still saved."
  1636. )
  1637. kv_cache_spec.update(_promote_local_kv_cache_specs(kv_cache_spec))
  1638. def _approximate_gcd(values: Sequence[int], *, lower_bound: int | None = None) -> int:
  1639. """Pick a chunk size that minimizes total upward padding.
  1640. Each x is rounded up to a multiple of d:
  1641. x -> ceil(x / d) * d
  1642. Total padding is:
  1643. pad(d) = sum_i (ceil(x_i / d) * d - x_i)
  1644. We brute-force d in [lower_bound, max(values)] (fine for small lists / small
  1645. maxima) and return the d with minimum padding. Ties prefer larger d.
  1646. """
  1647. if not values:
  1648. raise ValueError("values must be non-empty")
  1649. if any(x <= 0 for x in values):
  1650. raise ValueError(f"values must be positive, got: {list(values)!r}")
  1651. min_d = max(1, lower_bound if lower_bound is not None else 1)
  1652. max_d = max(values)
  1653. if min_d > max_d:
  1654. return min_d
  1655. best_d = min_d
  1656. best_pad: int | None = None
  1657. for d in range(min_d, max_d + 1):
  1658. pad = sum((d - (x % d)) % d for x in values)
  1659. if best_pad is None or pad < best_pad or (pad == best_pad and d > best_d):
  1660. best_pad = pad
  1661. best_d = d
  1662. return best_d
  1663. def _get_packed_kv_cache_groups(
  1664. vllm_config: VllmConfig,
  1665. kv_cache_spec: dict[str, KVCacheSpec],
  1666. ) -> list[KVCacheGroupSpec] | None:
  1667. """Group mixed-page-size layers for contiguous block-outermost packing.
  1668. Greedily buckets layers into uniform-type specs. Buckets with equal layer
  1669. counts per page size are treated as a repeating layer pattern (one layer
  1670. per page size) and split into groups covering the same number of pattern
  1671. repeats (picked by ``_approximate_gcd`` to minimize padding), so all
  1672. groups pack into the same per-block layout. Mamba buckets are additionally
  1673. split to fit the block the attention buckets already need.
  1674. Returns None when the layout is not block-outermost or all layers already
  1675. share one page size.
  1676. """
  1677. layout = vllm_config.cache_config.get_resolved_kv_cache_layout()
  1678. page_sizes = {spec.page_size_bytes for spec in kv_cache_spec.values()}
  1679. if not layout.is_block_outermost or len(page_sizes) <= 1:
  1680. return None
  1681. buckets: list[dict[str, KVCacheSpec]] = []
  1682. for name, spec in kv_cache_spec.items():
  1683. for bucket in buckets:
  1684. candidate = {**bucket, name: spec}
  1685. if UniformTypeKVCacheSpecs.is_uniform_type(candidate):
  1686. bucket[name] = spec
  1687. break
  1688. else:
  1689. buckets.append({name: spec})
  1690. bucketed = []
  1691. for bucket in buckets:
  1692. uniform_spec = UniformTypeKVCacheSpecs.from_specs(bucket)
  1693. assert uniform_spec is not None
  1694. page_size_layers: dict[int, list[str]] = defaultdict(list)
  1695. for layer_name, layer_spec in bucket.items():
  1696. page_size_layers[layer_spec.page_size_bytes].append(layer_name)
  1697. # Only 1:1 patterns (one layer of each page size per repeat) are
  1698. # supported; counts sharing a gcd > 1 (e.g. 2:1) could in principle
  1699. # repeat too, but such buckets are emitted whole instead.
  1700. balanced = len(set(map(len, page_size_layers.values()))) == 1
  1701. bucketed.append((uniform_spec, page_size_layers, balanced))
  1702. # Balanced buckets that mix page sizes must stay whole, so the largest one
  1703. # sets a floor on the repeats per group; larger single-size buckets are
  1704. # split down toward it. No such bucket means nothing needs packing.
  1705. min_repeats_per_group = max(
  1706. (
  1707. spec.get_max_layers_per_page_size()
  1708. for spec, page_size_layers, balanced in bucketed
  1709. if balanced and len(page_size_layers) > 1
  1710. ),
  1711. default=0,
  1712. )
  1713. repeats_per_group = (
  1714. _approximate_gcd(
  1715. [
  1716. spec.get_max_layers_per_page_size()
  1717. for spec, _, balanced in bucketed
  1718. if balanced
  1719. ],
  1720. lower_bound=min_repeats_per_group,
  1721. )
  1722. if min_repeats_per_group
  1723. else None
  1724. )
  1725. def num_groups_for(spec: UniformTypeKVCacheSpecs, balanced: bool) -> int:
  1726. if balanced and repeats_per_group is not None:
  1727. return cdiv(spec.get_max_layers_per_page_size(), repeats_per_group)
  1728. return 1
  1729. def widest_group_bytes(page_size_layers: dict[int, list[str]], n: int) -> int:
  1730. """Page bytes of the largest of the n groups a bucket splits into."""
  1731. return sum(
  1732. cdiv(len(names), n) * page for page, names in page_size_layers.items()
  1733. )
  1734. # Bytes a block must hold however the state buckets end up split: mamba,
  1735. # circular-buffer and unsplit sliding-window buckets can go down to one
  1736. # state per group, every other bucket's split is fixed by the repeat pattern.
  1737. def is_state_bucket(spec: UniformTypeKVCacheSpecs) -> bool:
  1738. if isinstance(spec.first_spec, (MambaSpec, CircularBufferSpec)):
  1739. return True
  1740. return repeats_per_group is None and isinstance(
  1741. spec.first_spec, SlidingWindowSpec
  1742. )
  1743. anchor_bytes = max(
  1744. (
  1745. widest_group_bytes(
  1746. page_size_layers,
  1747. len(spec.kv_cache_specs)
  1748. if is_state_bucket(spec)
  1749. else num_groups_for(spec, balanced),
  1750. )
  1751. for spec, page_size_layers, balanced in bucketed
  1752. ),
  1753. default=0,
  1754. )
  1755. groups = []
  1756. for spec, page_size_layers, balanced in bucketed:
  1757. num_groups = num_groups_for(spec, balanced)
  1758. # Cap a state group at the states a block already fits rather than let
  1759. # it widen the block.
  1760. if anchor_bytes and is_state_bucket(spec):
  1761. states_per_block = max(anchor_bytes // spec.first_spec.page_size_bytes, 1)
  1762. num_groups = max(
  1763. num_groups, cdiv(len(spec.kv_cache_specs), states_per_block)
  1764. )
  1765. if num_groups == 1:
  1766. groups.append(KVCacheGroupSpec(list(spec.kv_cache_specs), spec))
  1767. continue
  1768. pattern_repeats = list(zip(*page_size_layers.values()))
  1769. for i in range(num_groups):
  1770. group_layer_names = [
  1771. name for repeat in pattern_repeats[i::num_groups] for name in repeat
  1772. ]
  1773. group_layer_specs = {
  1774. name: spec.kv_cache_specs[name] for name in group_layer_names
  1775. }
  1776. group_spec = UniformTypeKVCacheSpecs.from_specs(group_layer_specs)
  1777. assert group_spec is not None
  1778. groups.append(KVCacheGroupSpec(group_layer_names, group_spec))
  1779. _annotate_eagle_groups(
  1780. vllm_config,
  1781. kv_cache_spec,
  1782. groups,
  1783. use_deepseek_v4_fallback=_is_deepseek_v4_eagle(vllm_config),
  1784. )
  1785. _warn_if_unannotated_eagle_mamba(vllm_config, groups)
  1786. return groups
  1787. def _is_deepseek_v4_eagle(vllm_config: VllmConfig) -> bool:
  1788. spec_config = vllm_config.speculative_config
  1789. if spec_config is None or not spec_config.use_eagle():
  1790. return False
  1791. model_config = vllm_config.model_config
  1792. return model_config is not None and model_config.hf_config.model_type in (
  1793. "deepseek_v4",
  1794. "deepseek_v41",
  1795. )
  1796. def _annotate_eagle_groups(
  1797. vllm_config: VllmConfig,
  1798. kv_cache_spec: dict[str, KVCacheSpec],
  1799. kv_cache_groups: list[KVCacheGroupSpec],
  1800. use_deepseek_v4_fallback: bool = False,
  1801. ) -> None:
  1802. """Flag the KV cache groups that hold drafter attention layers.
  1803. Two detection rules, in order of preference:
  1804. 1. Spec-driven. ``non_causal_multi_token_decode`` is declared on
  1805. MLAAttentionSpec and set by drafter attention layers that run a
  1806. non-causal multi-token decode (today only Kimi-K3 DSpark). It survives
  1807. MLAAttentionSpec.merge, so it still identifies a group after per-group
  1808. spec merging, wherever grouping happens to land. It is sufficient but
  1809. not necessary: a drafter whose spec is indistinguishable from the
  1810. target's cannot be found this way.
  1811. 2. Model-scoped positional fallback for DeepseekV4/V4.1, whose MTP block
  1812. reuses the target's own decoder layer and so carries no spec marker. Its
  1813. draft attention layer is always the last registered layer, so flag whichever
  1814. group holds it. This rule is only valid where the groups partition
  1815. exactly the layers of ``kv_cache_spec``, which is true on the packed
  1816. grouping path and not in general; other callers must leave
  1817. ``use_deepseek_v4_fallback`` False. The caller gates this fallback on
  1818. the configured model type.
  1819. FIXME(yifan): avoid/generalize this hacky check.
  1820. Args:
  1821. vllm_config: Config supplying the speculative method, if any.
  1822. kv_cache_spec: The kv cache spec of each attention layer, in layer
  1823. registration order. Only read by rule 2.
  1824. kv_cache_groups: Groups to annotate in place.
  1825. use_deepseek_v4_fallback: Enable rule 2 for a DeepseekV4/V4.1 packed
  1826. group.
  1827. """
  1828. spec_config = vllm_config.speculative_config
  1829. if spec_config is None or not spec_config.use_eagle_block_drop():
  1830. return
  1831. for group in kv_cache_groups:
  1832. if any(
  1833. getattr(spec, "non_causal_multi_token_decode", False)
  1834. for spec in iter_layer_specs(group.kv_cache_spec)
  1835. ):
  1836. group.is_eagle_group = True
  1837. if not use_deepseek_v4_fallback:
  1838. return
  1839. last_layer = next(reversed(kv_cache_spec))
  1840. for group in kv_cache_groups:
  1841. if last_layer in group.layer_names:
  1842. group.is_eagle_group = True
  1843. break
  1844. def _warn_if_unannotated_eagle_mamba(
  1845. vllm_config: VllmConfig,
  1846. kv_cache_groups: list[KVCacheGroupSpec],
  1847. ) -> None:
  1848. """Warn when the flag-all eagle fallback will silently disable reuse.
  1849. With no group annotated, consumers flag every group as a draft group. That
  1850. widens a Mamba group's required lookup window to two consecutive chunks,
  1851. which align-mode checkpointing never produces, so reuse drops to zero with
  1852. no error and no metric to show it.
  1853. Args:
  1854. vllm_config: Config supplying the speculative method, if any.
  1855. kv_cache_groups: Groups as they will be handed to consumers.
  1856. """
  1857. spec_config = vllm_config.speculative_config
  1858. if spec_config is None or not spec_config.use_eagle():
  1859. return
  1860. if any(group.is_eagle_group for group in kv_cache_groups):
  1861. return
  1862. mamba_groups = [
  1863. idx
  1864. for idx, group in enumerate(kv_cache_groups)
  1865. if any(
  1866. isinstance(spec, MambaSpec)
  1867. for spec in iter_layer_specs(group.kv_cache_spec)
  1868. )
  1869. ]
  1870. if not mamba_groups:
  1871. return
  1872. logger.warning(
  1873. "Speculative decoding (method=%s) is enabled but no KV cache group "
  1874. "could be identified as the draft model's, so every group -- "
  1875. "including Mamba groups %s -- will be treated as a draft group. A "
  1876. "Mamba group cannot satisfy the widened lookup window that implies, "
  1877. "so prefix-cache reuse across requests will be disabled and any "
  1878. "external KV offload tier will store without ever serving a hit.",
  1879. spec_config.method,
  1880. mamba_groups,
  1881. )
  1882. def _largest_divisor_at_most(value: int, limit: int) -> int:
  1883. for candidate in range(min(value, limit), 0, -1):
  1884. if value % candidate == 0:
  1885. return candidate
  1886. return 1
  1887. def get_kv_cache_groups(
  1888. vllm_config: VllmConfig,
  1889. kv_cache_spec: dict[str, KVCacheSpec],
  1890. ) -> list[KVCacheGroupSpec]:
  1891. """
  1892. Split the layers in the model into groups with the same KV cache spec.
  1893. Args:
  1894. vllm_config: The global VllmConfig
  1895. kv_cache_spec: The kv cache spec of each attention layer in the model
  1896. Returns:
  1897. The generated KVCacheGroups
  1898. """
  1899. if vllm_config.scheduler_config.disable_hybrid_kv_cache_manager:
  1900. unify_hybrid_kv_cache_specs(kv_cache_spec)
  1901. if is_kv_cache_type_attention_free(kv_cache_spec):
  1902. # This returns an empty list to allow for the KVCacheManager to handle
  1903. # attention free models.
  1904. return []
  1905. if is_kv_cache_spec_uniform(kv_cache_spec):
  1906. # KV cache of all layers are the same, which is true for
  1907. # most models. Allocate the same amount of memory for
  1908. # each layer.
  1909. return _get_kv_cache_groups_uniform_spec(kv_cache_spec)
  1910. elif uniform_spec := UniformTypeKVCacheSpecs.from_specs(kv_cache_spec):
  1911. # All layers need the same number of token slots (e.g., all layers are
  1912. # full attention, or all layers are sliding window attention with the
  1913. # same window size). Put all layers into one group.
  1914. return _get_kv_cache_groups_uniform_type(uniform_spec)
  1915. elif glm5_groups := _get_kv_cache_groups_glm5_next(vllm_config, kv_cache_spec):
  1916. return glm5_groups
  1917. # Hidden-state layers use their own block table and must not be absorbed
  1918. # into a compatible attention bucket.
  1919. hidden_specs = {
  1920. k: v for k, v in kv_cache_spec.items() if isinstance(v, HiddenStateCacheSpec)
  1921. }
  1922. filtered_spec = {
  1923. k: v
  1924. for k, v in kv_cache_spec.items()
  1925. if not isinstance(v, HiddenStateCacheSpec)
  1926. }
  1927. if packed_groups := _get_packed_kv_cache_groups(vllm_config, filtered_spec):
  1928. # Block-outermost blocks are strided by the widest group, so hidden
  1929. # groups need no page alignment.
  1930. packed_groups += [
  1931. KVCacheGroupSpec([name], spec) for name, spec in hidden_specs.items()
  1932. ]
  1933. return packed_groups
  1934. # Prefer preserving each layer's cache semantics. If physical pages cannot
  1935. # be unified, try a supported allocation-only fallback before failing.
  1936. try:
  1937. filtered_spec = unify_kv_cache_spec_page_size(filtered_spec)
  1938. except NotImplementedError:
  1939. fallback_groups = _try_get_full_allocation_fallback_groups(kv_cache_spec)
  1940. if fallback_groups is None:
  1941. raise
  1942. return fallback_groups
  1943. groups = _get_kv_cache_groups_uniform_page_size(filtered_spec)
  1944. # Add hidden-state layers back with page aligned to the common page.
  1945. if hidden_specs:
  1946. common_page = get_uniform_page_size([g.kv_cache_spec for g in groups])
  1947. group_block_size = math.gcd(*(g.kv_cache_spec.block_size for g in groups))
  1948. for name, spec in hidden_specs.items():
  1949. per_token = spec.num_kv_heads * spec.head_size * get_dtype_size(spec.dtype)
  1950. max_block_size = max(common_page // per_token, 1)
  1951. new_bs = _largest_divisor_at_most(group_block_size, max_block_size)
  1952. wasted_bytes = common_page - new_bs * per_token
  1953. logger.info(
  1954. "Using block size %d for hidden-state cache layer %s; "
  1955. "page alignment wastes %d bytes (%.2f%%) per block",
  1956. new_bs,
  1957. name,
  1958. wasted_bytes,
  1959. wasted_bytes / common_page * 100,
  1960. )
  1961. aligned = replace(spec, block_size=new_bs, page_size_padded=common_page)
  1962. groups.append(KVCacheGroupSpec([name], aligned))
  1963. _annotate_eagle_groups(vllm_config, kv_cache_spec, groups)
  1964. _warn_if_unannotated_eagle_mamba(vllm_config, groups)
  1965. return groups
  1966. def generate_scheduler_kv_cache_config(
  1967. kv_cache_configs: list[KVCacheConfig],
  1968. ) -> KVCacheConfig:
  1969. """
  1970. Generate the KV cache configuration for the scheduler.
  1971. """
  1972. assert all(
  1973. [cfg.num_blocks == kv_cache_configs[0].num_blocks for cfg in kv_cache_configs]
  1974. )
  1975. # All workers have the same kv_cache_config except layer names, so use
  1976. # an arbitrary one to initialize the scheduler.
  1977. cfg = copy.deepcopy(kv_cache_configs[0])
  1978. for group in cfg.kv_cache_groups:
  1979. if isinstance(group.kv_cache_spec, UniformTypeKVCacheSpecs):
  1980. # All layers in the UniformTypeKVCacheSpecs have the same type,
  1981. # so use an arbitrary one to initialize the scheduler.
  1982. group.kv_cache_spec = next(
  1983. iter(group.kv_cache_spec.kv_cache_specs.values())
  1984. )
  1985. return cfg
  1986. def get_kv_cache_capacity(
  1987. vllm_config: VllmConfig, kv_cache_config: KVCacheConfig
  1988. ) -> tuple[int, float]:
  1989. """
  1990. Get the group-aware KV cache token capacity and max concurrency.
  1991. """
  1992. max_model_len = vllm_config.model_config.max_model_len
  1993. max_concurrency = get_max_concurrency_for_kv_cache_config(
  1994. vllm_config, kv_cache_config
  1995. )
  1996. return int(max_concurrency * max_model_len), max_concurrency
  1997. def update_kv_cache_capacity(
  1998. vllm_config: VllmConfig, kv_cache_config: KVCacheConfig
  1999. ) -> None:
  2000. """Store and log the resolved KV cache capacity."""
  2001. num_tokens, max_concurrency = get_kv_cache_capacity(vllm_config, kv_cache_config)
  2002. vllm_config.cache_config.kv_cache_size_tokens = num_tokens
  2003. vllm_config.cache_config.kv_cache_max_concurrency = max_concurrency
  2004. max_model_len = vllm_config.model_config.max_model_len
  2005. logger.info_once(
  2006. "GPU KV cache size: %s tokens, "
  2007. "Maximum concurrency for %s tokens per request: %.2fx",
  2008. f"{num_tokens:,}",
  2009. f"{max_model_len:,}",
  2010. max_concurrency,
  2011. )
  2012. def _max_memory_usage_bytes_from_groups(
  2013. vllm_config: VllmConfig,
  2014. kv_cache_groups: list[KVCacheGroupSpec],
  2015. ) -> int:
  2016. """
  2017. Calculate maximum memory usage in bytes from KV cache groups.
  2018. This correctly accounts for padding in hybrid models. For example, if a
  2019. model has 8 full attention layers and 9 sliding window layers, they will
  2020. be padded to 9 full + 9 sliding window for uniform group sizes.
  2021. Each group independently claims blocks from the shared pool, so a request consumes
  2022. the sum of the per-group block counts, i.e. ``bytes_per_block * total_blocks``.
  2023. """
  2024. if not kv_cache_groups:
  2025. return 0
  2026. if (glm5_layout := _glm5_next_tensor_layout(kv_cache_groups)) is not None:
  2027. (
  2028. attn_group,
  2029. mamba_groups,
  2030. mla_names,
  2031. idx_names,
  2032. mla_page,
  2033. idx_page,
  2034. tail_names,
  2035. _,
  2036. ) = glm5_layout
  2037. uniform_spec = cast(UniformTypeKVCacheSpecs, attn_group.kv_cache_spec)
  2038. total_blocks = uniform_spec.max_memory_usage_pages(vllm_config)
  2039. total_blocks += sum(
  2040. cdiv(
  2041. group.kv_cache_spec.max_memory_usage_bytes(vllm_config),
  2042. group.kv_cache_spec.page_size_bytes,
  2043. )
  2044. for group in mamba_groups
  2045. )
  2046. if tail_names:
  2047. total_blocks += 1
  2048. return total_blocks * (len(mla_names) * mla_page + len(idx_names) * idx_page)
  2049. bytes_per_block = _pool_bytes_per_block(kv_cache_groups)
  2050. total_blocks = 0
  2051. for group in kv_cache_groups:
  2052. spec = group.kv_cache_spec
  2053. if isinstance(spec, UniformTypeKVCacheSpecs):
  2054. total_blocks += spec.max_memory_usage_pages(vllm_config)
  2055. else:
  2056. total_blocks += cdiv(
  2057. spec.max_memory_usage_bytes(vllm_config),
  2058. spec.page_size_bytes,
  2059. )
  2060. return bytes_per_block * total_blocks
  2061. def _estimate_max_model_len_from_groups(
  2062. vllm_config: VllmConfig,
  2063. kv_cache_groups: list[KVCacheGroupSpec],
  2064. available_memory: int,
  2065. ) -> int:
  2066. """
  2067. Binary search for the maximum model length that fits in available memory.
  2068. Returns 0 if even 1 token doesn't fit.
  2069. """
  2070. original_max = vllm_config.model_config.max_model_len
  2071. def fits(model_len: int) -> bool:
  2072. vllm_config.model_config.max_model_len = model_len
  2073. return (
  2074. _max_memory_usage_bytes_from_groups(vllm_config, kv_cache_groups)
  2075. <= available_memory
  2076. )
  2077. try:
  2078. left, right = 1, original_max
  2079. if not fits(left):
  2080. return 0
  2081. result = 1
  2082. while left <= right:
  2083. mid = (left + right) // 2
  2084. if fits(mid):
  2085. result = mid
  2086. left = mid + 1
  2087. else:
  2088. right = mid - 1
  2089. return result
  2090. finally:
  2091. vllm_config.model_config.max_model_len = original_max
  2092. def _auto_fit_max_model_len(
  2093. vllm_config: VllmConfig,
  2094. projected_groups_per_worker: list[list[KVCacheGroupSpec]],
  2095. available_memory: list[int],
  2096. ) -> None:
  2097. """
  2098. When max_model_len is set to -1, this function estimates the largest
  2099. context length that can be supported with the available GPU memory.
  2100. It uses binary search to find the maximum length that fits across all
  2101. workers.
  2102. Args:
  2103. vllm_config: The global VllmConfig (will be modified in-place)
  2104. projected_groups_per_worker: KV cache groups projected to each worker.
  2105. available_memory: Memory available for KV cache in bytes for each
  2106. worker.
  2107. """
  2108. original_max = vllm_config.model_config.max_model_len
  2109. if all(not groups for groups in projected_groups_per_worker):
  2110. # All workers have empty specs (attention-free model)
  2111. logger.info_once(
  2112. "Auto-fit max_model_len: attention-free model, "
  2113. "using derived max_model_len=%d",
  2114. original_max,
  2115. )
  2116. return
  2117. # Find the max_model_len that fits across all workers.
  2118. auto_fit_max = original_max
  2119. limiting_worker_mem = available_memory[0]
  2120. for groups, avail_mem in zip(projected_groups_per_worker, available_memory):
  2121. if not groups:
  2122. continue
  2123. worker_max = _estimate_max_model_len_from_groups(vllm_config, groups, avail_mem)
  2124. if worker_max < auto_fit_max:
  2125. auto_fit_max = worker_max
  2126. limiting_worker_mem = avail_mem
  2127. if auto_fit_max <= 0:
  2128. raise ValueError(
  2129. "Cannot auto-fit max_model_len: not enough GPU memory available "
  2130. "to serve even a single token. Try increasing `gpu_memory_utilization`."
  2131. )
  2132. if auto_fit_max >= original_max:
  2133. # The model's full context length fits in memory
  2134. logger.info_once(
  2135. "Auto-fit max_model_len: full model context length %d fits in "
  2136. "available GPU memory",
  2137. original_max,
  2138. )
  2139. else:
  2140. # Need to reduce max_model_len to fit in memory
  2141. vllm_config.model_config.max_model_len = auto_fit_max
  2142. logger.info_once(
  2143. "Auto-fit max_model_len: reduced from %d to %d to fit in "
  2144. "available GPU memory (%s GiB available for KV cache)",
  2145. original_max,
  2146. auto_fit_max,
  2147. format_gib(limiting_worker_mem),
  2148. )
  2149. def _project_kv_cache_groups_to_worker(
  2150. global_kv_cache_groups: list[KVCacheGroupSpec],
  2151. worker_spec: dict[str, KVCacheSpec],
  2152. ) -> list[KVCacheGroupSpec]:
  2153. """
  2154. Projects global KV cache groups onto a single worker's assigned layers.
  2155. In pipeline parallelism, each worker only owns a subset of layers. This
  2156. function filters the global groups to include only layers present on the
  2157. given worker, adjusting UniformTypeKVCacheSpecs accordingly.
  2158. Args:
  2159. global_kv_cache_groups: The global KV cache groups for the whole model.
  2160. worker_spec: The KV cache spec of each layer on this worker.
  2161. Returns:
  2162. The projected KV cache groups containing only this worker's layers.
  2163. """
  2164. projected_groups: list[KVCacheGroupSpec] = []
  2165. for group in global_kv_cache_groups:
  2166. worker_layer_names = [
  2167. layer_name for layer_name in group.layer_names if layer_name in worker_spec
  2168. ]
  2169. group_spec = group.kv_cache_spec
  2170. if worker_layer_names and isinstance(group_spec, UniformTypeKVCacheSpecs):
  2171. group_spec = UniformTypeKVCacheSpecs(
  2172. block_size=group_spec.block_size,
  2173. kv_cache_specs={
  2174. layer_name: group_spec.kv_cache_specs[layer_name]
  2175. for layer_name in worker_layer_names
  2176. },
  2177. )
  2178. projected_groups.append(
  2179. KVCacheGroupSpec(
  2180. worker_layer_names,
  2181. group_spec,
  2182. is_eagle_group=group.is_eagle_group and bool(worker_layer_names),
  2183. )
  2184. )
  2185. return projected_groups
  2186. def get_kv_cache_configs(
  2187. vllm_config: VllmConfig,
  2188. kv_cache_specs: list[dict[str, KVCacheSpec]],
  2189. available_memory: list[int],
  2190. ) -> list[KVCacheConfig]:
  2191. """
  2192. Generates the KV cache configurations for a model.
  2193. Since we use a shared centralized controller for all workers, we need the
  2194. `kv_cache_config` to be consistent across all workers to make sure
  2195. the KV cache allocation can be applied to all workers. However, different
  2196. workers may have different memory available, and different type of layers
  2197. (when pipeline parallel is enabled). To handle the difference between
  2198. workers, the current implementation is:
  2199. 1. Merge the KV cache specs of all workers to get the KVCacheSpecs for
  2200. the whole model.
  2201. 2. Generate the KV cache groups based on the layer ratio of the whole model.
  2202. This also handles spec unification for hybrid models.
  2203. 3. Handle auto-fit max_model_len and memory checks using per-worker
  2204. projected groups to account for PP sharding.
  2205. 4. Generate the KV cache configs for each worker based on the KV cache
  2206. grouping strategy. (This is reasonable because the layer ratio of
  2207. different PP stages are similar.)
  2208. 5. Change the num_blocks of each worker to the smallest among all workers
  2209. and shrink tensor sizes proportionally to avoid allocating unused memory.
  2210. Args:
  2211. vllm_config: The global VllmConfig
  2212. kv_cache_specs: List of dict[layer_name, KVCacheSpec] for each worker.
  2213. available_memory: Memory available for KV cache in bytes for each
  2214. worker.
  2215. Returns:
  2216. The generated KVCacheConfigs for each worker.
  2217. """
  2218. # Merge the KV cache specs of all workers. Different PP stages may have
  2219. # different layer names, and different TP ranks of the same PP stage should
  2220. # have the same KV cache spec.
  2221. merged_kv_cache_specs: dict[str, KVCacheSpec] = {}
  2222. for kv_cache_spec_one_worker in kv_cache_specs:
  2223. for layer_name, layer_spec in kv_cache_spec_one_worker.items():
  2224. if layer_name not in merged_kv_cache_specs:
  2225. merged_kv_cache_specs[layer_name] = layer_spec
  2226. else:
  2227. assert merged_kv_cache_specs[layer_name] == layer_spec, (
  2228. "The KV cache specs for the same layer are different "
  2229. "across workers. This is not supported yet."
  2230. )
  2231. # Check if the KV cache specs are registered correctly.
  2232. # This is to prevent that some layers are initialized with unregistered specs.
  2233. KVCacheSpecRegistry.check_kv_cache_spec_registry(merged_kv_cache_specs)
  2234. # When speculating with more than 1 speculative module (e.g. multi-layered MTP)
  2235. # tag every SlidingWindowSpec with how many extra tokens to retain in the window.
  2236. extra_retained_tokens = (
  2237. vllm_config.speculative_config.num_speculative_tokens - 1
  2238. if vllm_config.speculative_config is not None
  2239. and vllm_config.speculative_config.use_multi_module_mtp()
  2240. else 0
  2241. )
  2242. for layer_name, layer_spec in merged_kv_cache_specs.items():
  2243. if isinstance(layer_spec, SlidingWindowSpec):
  2244. merged_kv_cache_specs[layer_name] = replace(
  2245. layer_spec, extra_retained_tokens=extra_retained_tokens
  2246. )
  2247. # Get global KV cache groups. This also handles spec unification for
  2248. # hybrid models when disable_hybrid_kv_cache_manager is enabled.
  2249. # After this call, merged_kv_cache_specs may be modified in-place.
  2250. global_kv_cache_groups = get_kv_cache_groups(vllm_config, merged_kv_cache_specs)
  2251. # If original_max_model_len was -1, automatically
  2252. # determine the maximum model length that fits in available GPU memory.
  2253. # We use per-worker projected groups to account for PP sharding.
  2254. projected_groups_per_worker = [
  2255. _project_kv_cache_groups_to_worker(global_kv_cache_groups, worker_spec)
  2256. for worker_spec in kv_cache_specs
  2257. ]
  2258. # If `num_gpu_blocks_override` is set, the cache size that will actually
  2259. # be allocated is decoupled from the profiled `available_memory`:
  2260. # `may_override_num_blocks` in `get_kv_cache_config_from_groups` clamps
  2261. # `num_blocks` to the override. Reflect that in `available_memory` here so
  2262. # auto-fit, the admission check, and the per-worker config builder all
  2263. # plan against the same effective capacity.
  2264. override = vllm_config.cache_config.num_gpu_blocks_override
  2265. if override is not None:
  2266. adjusted_memory: list[int] = []
  2267. for groups, avail_mem in zip(projected_groups_per_worker, available_memory):
  2268. if not groups:
  2269. adjusted_memory.append(avail_mem)
  2270. continue
  2271. bytes_per_block = _pool_bytes_per_block(groups)
  2272. logger.info(
  2273. "Overriding num_gpu_blocks=%d with num_gpu_blocks_override=%d",
  2274. avail_mem // bytes_per_block,
  2275. override,
  2276. )
  2277. adjusted_memory.append(override * bytes_per_block)
  2278. available_memory = adjusted_memory
  2279. # Reserve the null block BlockPool permanently holds back, so auto-fit and
  2280. # the capacity check both plan against usable blocks. Allocation below
  2281. # still uses the full memory.
  2282. check_memory = [
  2283. avail_mem - _pool_bytes_per_block(groups) if groups else avail_mem
  2284. for groups, avail_mem in zip(projected_groups_per_worker, available_memory)
  2285. ]
  2286. if vllm_config.model_config.original_max_model_len == -1:
  2287. _auto_fit_max_model_len(vllm_config, projected_groups_per_worker, check_memory)
  2288. # Check if the available memory is enough per worker.
  2289. for groups, avail_mem in zip(projected_groups_per_worker, check_memory):
  2290. if not groups:
  2291. continue
  2292. _check_enough_kv_cache_memory(
  2293. avail_mem,
  2294. partial(_max_memory_usage_bytes_from_groups, vllm_config, groups),
  2295. vllm_config.model_config.max_model_len,
  2296. partial(_estimate_max_model_len_from_groups, vllm_config, groups),
  2297. )
  2298. kv_cache_configs: list[KVCacheConfig] = []
  2299. for projected_groups, kv_cache_spec_one_worker, available_memory_one_worker in zip(
  2300. projected_groups_per_worker, kv_cache_specs, available_memory
  2301. ):
  2302. assert sum(len(group.layer_names) for group in projected_groups) == len(
  2303. kv_cache_spec_one_worker
  2304. ), "Some layers are not assigned to any group."
  2305. kv_cache_configs.append(
  2306. get_kv_cache_config_from_groups(
  2307. vllm_config, projected_groups, available_memory_one_worker
  2308. )
  2309. )
  2310. # Change the num_blocks of each rank to the smallest among all ranks.
  2311. # We also need to shrink the tensor size proportionally to avoid
  2312. # allocating unused memory.
  2313. min_num_blocks = min(
  2314. kv_cache_config.num_blocks for kv_cache_config in kv_cache_configs
  2315. )
  2316. for i, kv_cache_config in enumerate(kv_cache_configs):
  2317. if kv_cache_config.num_blocks == min_num_blocks:
  2318. continue
  2319. # Re-plan with exactly the memory the smallest rank can afford, so
  2320. # strides and offsets stay consistent with the shrunken allocation.
  2321. groups = kv_cache_config.kv_cache_groups
  2322. kv_cache_configs[i] = get_kv_cache_config_from_groups(
  2323. vllm_config, groups, min_num_blocks * _pool_bytes_per_block(groups)
  2324. )
  2325. return kv_cache_configs
  2326. class BlockHashListWithBlockSize:
  2327. """
  2328. Convert block-hash granularity from `hash_block_size` to `target_block_size`.
  2329. Used when KV cache groups have different block sizes: `hash_block_size`
  2330. is the size used to compute the original `block_hashes`; `target_block_size`
  2331. is the group's actual block size.
  2332. Currently, only scaling up by an integer factor is supported (i.e.,
  2333. `target_block_size` is a multiple of `hash_block_size`). Conversion is
  2334. performed lazily on access for efficiency. Each `hash_block_size` hash is
  2335. already chained over its entire prefix, so the hash at the last
  2336. `hash_block_size` boundary of a `target_block_size` block uniquely
  2337. fingerprints that block's prefix; we use it directly.
  2338. Example (`hash_block_size` = 16, `target_block_size` = 32):
  2339. the second 16-size hash already covers tokens 0-31, so it is the 32-size
  2340. hash:
  2341. Block hashes with block_size 16:
  2342. | Token Range | 0-15 | 16-31 | 32-47 | 48-63 |
  2343. |-------------|------|-------|-------|-------|
  2344. | Hash | A | B | C | D |
  2345. Block hashes with block_size 32:
  2346. | Token Range | 0-31 | 32-63 |
  2347. |-------------|------|-------|
  2348. | Hash | B | D |
  2349. Args:
  2350. block_hashes: Block hashes to convert, computed at `hash_block_size`.
  2351. hash_block_size: Block size at which `block_hashes` were computed.
  2352. target_block_size: Desired block size; must be a multiple of `hash_block_size`.
  2353. """
  2354. def __init__(
  2355. self,
  2356. block_hashes: list[BlockHash],
  2357. hash_block_size: int,
  2358. target_block_size: int,
  2359. ):
  2360. self.block_hashes = block_hashes
  2361. assert target_block_size % hash_block_size == 0
  2362. self.scale_factor = target_block_size // hash_block_size
  2363. def __len__(self) -> int:
  2364. return len(self.block_hashes) // self.scale_factor
  2365. @overload
  2366. def __getitem__(self, idx: int) -> BlockHash: ...
  2367. @overload
  2368. def __getitem__(self, idx: slice) -> list[BlockHash]: ...
  2369. def __getitem__(self, idx):
  2370. if isinstance(idx, int):
  2371. return self._get_value_at(idx)
  2372. if isinstance(idx, slice):
  2373. start, stop, step = idx.indices(len(self))
  2374. return [self._get_value_at(i) for i in range(start, stop, step)]
  2375. raise TypeError(f"Invalid index type: {type(idx)!r}")
  2376. def __iter__(self) -> Iterator[BlockHash]:
  2377. for i in range(len(self)):
  2378. yield self._get_value_at(i)
  2379. def _get_value_at(self, idx: int) -> BlockHash:
  2380. # The last hash_block_size hash within the target block already chains
  2381. # over the whole prefix, so it is the target block's hash.
  2382. return self.block_hashes[(idx + 1) * self.scale_factor - 1]
  2383. BlockHashList = list[BlockHash] | BlockHashListWithBlockSize
  2384. def resolve_block_hashes(
  2385. block_hashes: BlockHashList,
  2386. hash_block_size: int,
  2387. block_size: int,
  2388. *,
  2389. supports_fine_grained_hash_lookup: bool = False,
  2390. alignment_tokens: int | None = None,
  2391. ) -> BlockHashList:
  2392. """Resolve the block-hash view at ``block_size``.
  2393. When ``block_size`` equals ``hash_block_size``, reuse the precomputed block
  2394. hashes directly; otherwise view them at ``block_size`` granularity.
  2395. Fine-grained lookup keeps the original hashes for partial cache hits.
  2396. """
  2397. if block_size == hash_block_size:
  2398. return block_hashes
  2399. if isinstance(block_hashes, BlockHashListWithBlockSize):
  2400. # Already a block-size view
  2401. assert block_hashes.scale_factor == block_size // hash_block_size
  2402. return block_hashes
  2403. # Fine-grained partial hits keep the raw hashes. The caller passes
  2404. # alignment_tokens = hash_block_size to enable them, else >= block_size.
  2405. if (
  2406. supports_fine_grained_hash_lookup
  2407. and alignment_tokens is not None
  2408. and alignment_tokens < block_size
  2409. and block_size % alignment_tokens == 0
  2410. ):
  2411. return block_hashes
  2412. assert block_size % hash_block_size == 0
  2413. return BlockHashListWithBlockSize(block_hashes, hash_block_size, block_size)