kv_cache_utils.py 124 KB

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