kv_cache_utils.py 108 KB

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