kv_cache_utils.py 123 KB

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