66from __future__ import annotations
77
88import time
9- from typing import TYPE_CHECKING
9+ from typing import TYPE_CHECKING , Any
1010
1111import numpy as np
1212from vllm .logger import logger
@@ -87,9 +87,9 @@ def _alloc_gvas_for_save(self, requests: list[ReqMeta]) -> None:
8787 request .load_spec is None or not request .load_spec .layerwise_previous_step
8888 ):
8989 worker ._snapshot_keys .pop (request .req_id , None )
90- if self ._alloc_gvas_for_save_for_request ([ request ] ) is False :
91- logger .error ("Memcache save preparation failed for %s" , request . req_id )
92- worker ._save_disabled .set ()
90+ if self ._alloc_gvas_for_save_batch ( requests ) is False :
91+ logger .error ("Memcache save preparation failed for the batch" )
92+ worker ._save_disabled .set ()
9393 if worker ._save_disabled .is_set ():
9494 # batch_alloc may return a shared allocation. Stop this step's
9595 # saves without deleting keys that another writer may have published.
@@ -103,21 +103,38 @@ def _alloc_gvas_for_save(self, requests: list[ReqMeta]) -> None:
103103 def _alloc_gvas_for_save_for_request (self , requests : list [ReqMeta ]) -> bool | None :
104104 """Allocate per-group GVA on the worker side right before batch_copy.
105105
106+ Kept for single-request callers (tests, direct instrumentation);
107+ the step entry point batches all requests in ``_alloc_gvas_for_save``.
108+ """
109+ worker = self ._worker
110+ if not worker .use_layerwise_transfer :
111+ return None
112+ if not worker .can_put :
113+ return None
114+ return self ._alloc_gvas_for_save_batch (requests )
115+
116+ def _alloc_gvas_for_save_batch (self , requests : list [ReqMeta ]) -> bool | None :
117+ """Allocate per-group GVA on the worker side right before batch_copy.
118+
106119 For multi-group models, iterates all KV cache groups and allocates
107120 per-group GVAs. Key format: model@group_id@hash@head_or_tp_rank
108121 (multi-group) or model@hash@head_or_tp_rank (single-group, backward
109122 compat with PR #11585).
110123
124+ Two phases so the store sees one exists check and one allocation
125+ per step instead of one round trip per request: collect every
126+ group's candidate keys without I/O, issue the merged checks, then
127+ distribute the replies in the collection order (which preserves
128+ per-request transfer ordering).
129+
111130 batch_alloc is idempotent, so every write target is allocated fresh
112131 within the step and no cross-step GVA cache is kept. Blocks already
113132 committed in the pool are filtered out with a medium-agnostic
114133 exists check to avoid re-transferring them.
115134 """
116135 worker = self ._worker
117- if not worker .use_layerwise_transfer :
118- return None
119- if not worker .can_put :
120- return None
136+ # Per (request, group) I/O-free collection result.
137+ works : list [dict [str , Any ]] = []
121138 for request in requests :
122139 if request .can_save is None or not request .can_save :
123140 continue
@@ -201,101 +218,163 @@ def _alloc_gvas_for_save_for_request(self, requests: list[ReqMeta]) -> bool | No
201218 all_group_gvas .append (np .zeros (len (block_ids_by_group ), dtype = np .int64 ))
202219 all_group_block_ids .append (np .asarray (block_ids_by_group , dtype = np .int64 ))
203220 continue
204- # Skip blocks already committed in the pool. The exists check
205- # is medium-agnostic on purpose: a committed block (DRAM or
206- # SSD) does not need re-saving, and the load path rewarms
207- # SSD blocks on read.
208- missing_keys = worker ._pool_keys_missing (candidate_keys )
209- transfer_blocks = [
210- block_idx for block_idx , key in zip (candidate_blocks , candidate_keys ) if key in missing_keys
211- ]
212-
213- # batch_alloc is idempotent: allocating an existing key
214- # returns its current, client-registered GVA. Every write
215- # target is therefore allocated fresh within this step; no
216- # cross-step GVA cache is kept.
217- block_gvas : list [int ] = []
218- if transfer_blocks :
219- transfer_keys = [key for key in candidate_keys if key in missing_keys ]
220- transfer_gvas = worker .m_store .batch_alloc (
221- transfer_keys , [alloc_size ] * len (transfer_keys ), LAYERWISE_READ_LEASE_TTL_MS
222- )
223- if transfer_gvas is None or len (transfer_gvas ) != len (transfer_keys ):
224- return False
225- if any (gva <= 0 for gva in transfer_gvas ):
226- logger .error (
227- "alloc_gvas FAIL: req=%s group=%d alloc_size=%d alloc_keys=%d gvas_sample=%s fail_count=%d" ,
228- request .req_id ,
229- group_id ,
230- alloc_size ,
231- len (transfer_keys ),
232- transfer_gvas [:5 ],
233- sum (1 for g in transfer_gvas if g <= 0 ),
234- )
235- # 0 means allocation failed; UINT64_MAX means a readable
236- # SSD hit. Filter both before converting GVAs to np.int64.
237- block_gvas = [gva if 0 < gva < MEMCACHE_SSD_HIT_GVA else 0 for gva in transfer_gvas ]
238- for key , gva in zip (transfer_keys , block_gvas ):
239- if gva > 0 :
240- all_group_save_keys .append (key )
241- if worker .layerwise_offload and any (gva <= 0 for gva in transfer_gvas ):
242- return False
243-
244- if partial_key is not None :
245- # Partial keys are request-scoped: allocate fresh each step.
246- allocated = worker .m_store .batch_alloc (
247- [partial_key ],
248- [alloc_size ],
249- LAYERWISE_READ_LEASE_TTL_MS ,
250- )
251- if not allocated or len (allocated ) != 1 :
252- return False
253- partial_gva = allocated [0 ]
254- if 0 < partial_gva < MEMCACHE_SSD_HIT_GVA :
255- all_group_save_keys .append (partial_key )
256- elif partial_gva <= 0 :
257- logger .error (
258- "alloc_gvas: partial allocation failed req=%s group=%d block=%d gva=%d" ,
221+ # Hold this group's slot so the published per-group lists keep
222+ # group order; the distribute phase replaces the placeholder.
223+ all_group_gvas .append (np .zeros (len (block_ids_by_group ), dtype = np .int64 ))
224+ all_group_block_ids .append (np .asarray (block_ids_by_group , dtype = np .int64 ))
225+ works .append (
226+ {
227+ "request" : request ,
228+ "group_id" : group_id ,
229+ "block_ids" : block_ids_by_group ,
230+ "candidate_blocks" : candidate_blocks ,
231+ "candidate_keys" : candidate_keys ,
232+ "partial_key" : partial_key ,
233+ "partial_block_index" : partial_block_index ,
234+ "alloc_size" : alloc_size ,
235+ "all_group_gvas" : all_group_gvas ,
236+ "all_group_block_ids" : all_group_block_ids ,
237+ "all_group_save_keys" : all_group_save_keys ,
238+ "log" : (
259239 request .req_id ,
260240 group_id ,
261- partial_block_index ,
262- partial_gva ,
263- )
264- if worker .layerwise_offload and partial_gva <= 0 :
265- return False
266- request .transfer .partial_save_gva_per_group [group_id ] = (
267- partial_gva if 0 < partial_gva < MEMCACHE_SSD_HIT_GVA else 0
268- )
241+ effective_block_size ,
242+ save_start_block ,
243+ save_end_block ,
244+ group_store_mask is not None ,
245+ ),
246+ }
247+ )
248+ # Publish the per-request group lists up front; owner groups are
249+ # appended later, in the distribute phase after the merged I/O.
250+ request .transfer .save_keys = all_group_save_keys
251+ request .transfer .block_gvas_by_group_np = all_group_gvas
252+ request .transfer .block_ids_by_group_np = all_group_block_ids
253+ if all_group_gvas :
254+ request .transfer .block_gvas_np = all_group_gvas [0 ]
255+ request .transfer .gva_block_offset = 0
256+ if not works :
257+ return None
269258
270- logger .debug (
271- "alloc_gvas: req=%s group=%d eff_bs=%d save_blocks=[%d,%d) "
272- "transfer_keys=%d committed=%d masked=%s alloc_size=%d" ,
273- request .req_id ,
274- group_id ,
275- effective_block_size ,
276- save_start_block ,
277- save_end_block ,
278- len (transfer_blocks ),
279- len (candidate_blocks ) - len (transfer_blocks ),
280- group_store_mask is not None ,
259+ # Merged exists check for every candidate key of every request.
260+ all_candidate_keys : list [str ] = []
261+ for work in works :
262+ all_candidate_keys .extend (work ["candidate_keys" ])
263+ missing_keys = worker ._pool_keys_missing (all_candidate_keys )
264+
265+ # Skip blocks already committed in the pool. The exists check
266+ # is medium-agnostic on purpose: a committed block (DRAM or
267+ # SSD) does not need re-saving, and the load path rewarms
268+ # SSD blocks on read.
269+ for work in works :
270+ work ["transfer_blocks" ] = [
271+ block_idx
272+ for block_idx , key in zip (work ["candidate_blocks" ], work ["candidate_keys" ])
273+ if key in missing_keys
274+ ]
275+
276+ # One allocation round trip for every missing key of every request.
277+ # batch_alloc is idempotent: allocating an existing key
278+ # returns its current, client-registered GVA. Every write
279+ # target is therefore allocated fresh within this step; no
280+ # cross-step GVA cache is kept.
281+ transfer_keys : list [str ] = []
282+ transfer_sizes : list [int ] = []
283+ for work in works :
284+ work_missing = [key for key in work ["candidate_keys" ] if key in missing_keys ]
285+ transfer_keys .extend (work_missing )
286+ transfer_sizes .extend ([work ["alloc_size" ]] * len (work_missing ))
287+ transfer_gvas : list [int ] | None = []
288+ if transfer_keys :
289+ transfer_gvas = worker .m_store .batch_alloc (transfer_keys , transfer_sizes , LAYERWISE_READ_LEASE_TTL_MS )
290+ if transfer_gvas is None or len (transfer_gvas ) != len (transfer_keys ):
291+ return False
292+ gva_by_key : dict [str , int ] = {}
293+ for key , gva in zip (transfer_keys , transfer_gvas or []):
294+ gva_by_key [key ] = gva
295+
296+ for work in works :
297+ request = work ["request" ]
298+ group_id = work ["group_id" ]
299+ block_ids_by_group = work ["block_ids" ]
300+ alloc_size = work ["alloc_size" ]
301+ req_id , gid , effective_block_size , save_start_block , save_end_block , masked = work ["log" ]
302+ candidate_keys = work ["candidate_keys" ]
303+ transfer_blocks = work ["transfer_blocks" ]
304+ block_gvas = [gva_by_key [key ] for key in candidate_keys if key in missing_keys ]
305+ if any (gva <= 0 for gva in block_gvas ):
306+ logger .error (
307+ "alloc_gvas FAIL: req=%s group=%d alloc_size=%d alloc_keys=%d gvas_sample=%s fail_count=%d" ,
308+ req_id ,
309+ gid ,
281310 alloc_size ,
311+ len (block_gvas ),
312+ block_gvas [:5 ],
313+ sum (1 for g in block_gvas if g <= 0 ),
314+ )
315+ # The failure gate reads the RAW replies: a UINT64_MAX sentinel is
316+ # a readable SSD hit, not a failure, even though it filters to 0.
317+ if worker .layerwise_offload and any (gva <= 0 for gva in block_gvas ):
318+ return False
319+ # 0 means allocation failed; UINT64_MAX means a readable
320+ # SSD hit. Filter both before converting GVAs to np.int64.
321+ block_gvas = [gva if 0 < gva < MEMCACHE_SSD_HIT_GVA else 0 for gva in block_gvas ]
322+ work ["all_group_save_keys" ].extend (
323+ key for key , gva in zip ((k for k in candidate_keys if k in missing_keys ), block_gvas ) if gva > 0
324+ )
325+
326+ partial_key = work ["partial_key" ]
327+ if partial_key is not None :
328+ # Partial keys are request-scoped: allocate fresh each step.
329+ allocated = worker .m_store .batch_alloc (
330+ [partial_key ],
331+ [alloc_size ],
332+ LAYERWISE_READ_LEASE_TTL_MS ,
333+ )
334+ if not allocated or len (allocated ) != 1 :
335+ return False
336+ partial_gva = allocated [0 ]
337+ if 0 < partial_gva < MEMCACHE_SSD_HIT_GVA :
338+ work ["all_group_save_keys" ].append (partial_key )
339+ elif partial_gva <= 0 :
340+ logger .error (
341+ "alloc_gvas: partial allocation failed req=%s group=%d block=%d gva=%d" ,
342+ req_id ,
343+ gid ,
344+ work ["partial_block_index" ],
345+ partial_gva ,
346+ )
347+ if worker .layerwise_offload and partial_gva <= 0 :
348+ return False
349+ request .transfer .partial_save_gva_per_group [group_id ] = (
350+ partial_gva if 0 < partial_gva < MEMCACHE_SSD_HIT_GVA else 0
282351 )
283352
284- # Pad block_gvas to match block_ids length (fill 0 for non-transferred blocks)
285- full_gvas = [0 ] * len (block_ids_by_group )
286- for blk_idx , gva in zip (transfer_blocks , block_gvas ):
287- if blk_idx < len (full_gvas ):
288- full_gvas [blk_idx ] = gva
289-
290- all_group_gvas .append (np .asarray (full_gvas , dtype = np .int64 ))
291- all_group_block_ids .append (np .asarray (block_ids_by_group , dtype = np .int64 ))
292-
293- if all_group_gvas :
294- request .transfer .save_keys = all_group_save_keys
295- request .transfer .block_gvas_by_group_np = all_group_gvas
296- request .transfer .block_ids_by_group_np = all_group_block_ids
297- request .transfer .block_gvas_np = all_group_gvas [0 ]
298- request .transfer .gva_block_offset = 0
353+ logger .debug (
354+ "alloc_gvas: req=%s group=%d eff_bs=%d save_blocks=[%d,%d) "
355+ "transfer_keys=%d committed=%d masked=%s alloc_size=%d" ,
356+ req_id ,
357+ gid ,
358+ effective_block_size ,
359+ save_start_block ,
360+ save_end_block ,
361+ len (transfer_blocks ),
362+ len (candidate_keys ) - len (transfer_blocks ),
363+ masked ,
364+ alloc_size ,
365+ )
366+
367+ # Pad block_gvas to match block_ids length (fill 0 for non-transferred blocks)
368+ full_gvas = [0 ] * len (block_ids_by_group )
369+ for blk_idx , gva in zip (transfer_blocks , block_gvas ):
370+ if blk_idx < len (full_gvas ):
371+ full_gvas [blk_idx ] = gva
372+
373+ work ["all_group_gvas" ][group_id ] = np .asarray (full_gvas , dtype = np .int64 )
374+ work ["all_group_block_ids" ][group_id ] = np .asarray (block_ids_by_group , dtype = np .int64 )
375+ # The group-0 view is only valid once at least one group landed.
376+ if work ["all_group_gvas" ]:
377+ request .transfer .block_gvas_np = work ["all_group_gvas" ][0 ]
299378 return None
300379
301380 # --- load path -----------------------------------------------------------
0 commit comments