diff --git a/python/sglang/benchmark/one_batch.py b/python/sglang/benchmark/one_batch.py index 00b2dfb583..31a5f7c71d 100644 --- a/python/sglang/benchmark/one_batch.py +++ b/python/sglang/benchmark/one_batch.py @@ -424,7 +424,7 @@ def prepare_inputs_for_correctness_test(bench_args, tokenizer, custom_prompts): ) req.full_untruncated_fill_ids = req.origin_input_ids req.logprob_start_len = -1 - req.set_extend_range(len(req.prefix_indices), len(req.origin_input_ids)) + req.set_extend_range(req.prefix_len, len(req.origin_input_ids)) reqs.append(req) return input_ids, reqs @@ -438,13 +438,13 @@ def prepare_extend_inputs_for_correctness_test( req.full_untruncated_fill_ids.extend(input_ids[i][bench_args.cut_len :]) if model_runner is not None: # Use req.kv.req_pool_idx instead of i to handle slot 0 padding correctly - req.prefix_indices = model_runner.req_to_token_pool.req_to_token[ - req.kv.req_pool_idx, : bench_args.cut_len - ].to(req.prefix_indices.dtype) + req.set_prefix_indices( + model_runner.req_to_token_pool.req_to_token[ + req.kv.req_pool_idx, : bench_args.cut_len + ].to(torch.int64) + ) req.logprob_start_len = -1 - req.set_extend_range( - len(req.prefix_indices), len(req.full_untruncated_fill_ids) - ) + req.set_extend_range(req.prefix_len, len(req.full_untruncated_fill_ids)) return reqs @@ -471,7 +471,7 @@ def prepare_synthetic_inputs_for_latency_test( ) req.full_untruncated_fill_ids = req.origin_input_ids req.logprob_start_len = -1 - req.set_extend_range(len(req.prefix_indices), len(req.origin_input_ids)) + req.set_extend_range(req.prefix_len, len(req.origin_input_ids)) reqs.append(req) return reqs diff --git a/python/sglang/srt/disaggregation/decode.py b/python/sglang/srt/disaggregation/decode.py index f1b2ac80b4..db9c0f1e52 100644 --- a/python/sglang/srt/disaggregation/decode.py +++ b/python/sglang/srt/disaggregation/decode.py @@ -145,7 +145,7 @@ def _bootstrap_addr(req: Req) -> str: def _bind_root_prefix(req: Req, tree_cache: BasePrefixCache) -> None: """Start a decode-radix request that owns its whole KV row at the root.""" - req.prefix_indices = torch.empty((0,), dtype=torch.int64) + req.set_prefix_indices(torch.empty((0,), dtype=torch.int64)) req.last_node = tree_cache.root_node_handle(req.extra_key) req.last_host_node = req.last_node req.best_match_node = req.last_node @@ -2202,11 +2202,9 @@ class DecodePreallocQueue(DecodeHiCachePreallocMixin): # inserts committed KV into the radix tree. The last output token # hasn't had KV committed yet (output_ids is 1 ahead). req.full_untruncated_fill_ids = req.origin_input_ids + req.output_ids - # Set prefix_indices so downstream consumers (init_next_round_input, - # prepare_for_extend) see the correct prefix length. In the agg path - # this is done inside init_next_round_input, but decode-disagg needs - # allocation info before batch assembly so we set it here. - req.prefix_indices = ( + # Decode-disagg allocates before batch assembly, so it binds the prefix + # here instead of in init_next_round_input. + req.set_prefix_indices( prefix_indices if prefix_len > 0 else torch.empty((0,), dtype=torch.int64) ) req.set_extend_range(total_prefix_len, req.kv.kv_committed_len) @@ -3162,9 +3160,7 @@ class SchedulerDisaggregationDecodeMixin: # only sees committed KV (full array includes one uncommitted # token because init_next_round_input rebuilt it as full). if req.kv.kv_committed_len is not None: - req.set_extend_range( - len(req.prefix_indices), req.kv.kv_committed_len - ) + req.set_extend_range(req.prefix_len, req.kv.kv_committed_len) else: waiting_queue.append(req) diff --git a/python/sglang/srt/disaggregation/decode_hicache_mixin.py b/python/sglang/srt/disaggregation/decode_hicache_mixin.py index 36084e4937..86cbb475ab 100644 --- a/python/sglang/srt/disaggregation/decode_hicache_mixin.py +++ b/python/sglang/srt/disaggregation/decode_hicache_mixin.py @@ -316,8 +316,10 @@ class DecodeHiCacheTransferMixin: ), decode_req.hicache_restored_kv_indices, ) - req.prefix_indices = torch.cat( - [prefix_match.prefix_indices, decode_req.hicache_restored_kv_indices] + req.set_prefix_indices( + torch.cat( + [prefix_match.prefix_indices, decode_req.hicache_restored_kv_indices] + ) ) req.last_node = restore_lock.node req.lock = restore_lock diff --git a/python/sglang/srt/disaggregation/decode_schedule_batch_mixin.py b/python/sglang/srt/disaggregation/decode_schedule_batch_mixin.py index 23dad06d19..0698334b8f 100644 --- a/python/sglang/srt/disaggregation/decode_schedule_batch_mixin.py +++ b/python/sglang/srt/disaggregation/decode_schedule_batch_mixin.py @@ -44,7 +44,7 @@ class ScheduleBatchDisaggregationDecodeMixin: offset = 0 for i, req in enumerate(reqs): req_pool_indices.append(req.kv.req_pool_idx) - pre_len = len(req.prefix_indices) + pre_len = req.prefix_len chunk = self.req_to_token_pool.req_to_token[req.kv.req_pool_idx][ pre_len : pre_len + req.extend_range.length @@ -98,7 +98,7 @@ class ScheduleBatchDisaggregationDecodeMixin: self.token_ids_logprobs = [r.logprob.token_ids_logprob for r in reqs] self.extend_num_tokens = extend_num_tokens - self.prefix_lens = [len(r.prefix_indices) for r in reqs] + self.prefix_lens = [r.prefix_len for r in reqs] self.extend_lens = [r.extend_range.length for r in reqs] self.extend_logprob_start_lens = None self.extend_input_logprob_token_ids = None diff --git a/python/sglang/srt/disaggregation/prefill.py b/python/sglang/srt/disaggregation/prefill.py index df2974c485..baa4bf3959 100644 --- a/python/sglang/srt/disaggregation/prefill.py +++ b/python/sglang/srt/disaggregation/prefill.py @@ -593,6 +593,7 @@ class SchedulerDisaggregationPrefillMixin: cache = self.tree_cache if req.pending_bootstrap and _uses_write_through_cache(cache): cache.advance_unpublished_req(req) + req.prefix_len = req.extend_range.end return checkpoint_kv_cache(req, cache) @@ -1426,9 +1427,7 @@ class SchedulerDisaggregationPrefillMixin: # must stay stable across the request's batches: snapshot the at-rest # prefix on the first batch. Non-staging reads the live prefix. if self.enable_staging and req.early_send_prefix_end is None: - req.early_send_prefix_end = max( - 0, len(req.prefix_indices) - req.host_hit_length - ) + req.early_send_prefix_end = max(0, req.prefix_len - req.host_hit_length) if req.pending_bootstrap: return @@ -1437,7 +1436,7 @@ class SchedulerDisaggregationPrefillMixin: cached_end = ( req.early_send_prefix_end if self.enable_staging - else len(req.prefix_indices) - req.host_hit_length + else req.prefix_len - req.host_hit_length ) if cached_end <= req.start_send_idx: return diff --git a/python/sglang/srt/dllm/mixin/req.py b/python/sglang/srt/dllm/mixin/req.py index e6501e55cc..589e16044d 100644 --- a/python/sglang/srt/dllm/mixin/req.py +++ b/python/sglang/srt/dllm/mixin/req.py @@ -47,7 +47,7 @@ class ReqDllmMixin: self.dllm_phase = DllmReqPhase.STAGING_DECODE return - prefix_length = len(self.prefix_indices) + prefix_length = self.prefix_len if self.dllm_config.requires_separate_context_encoding: self.dllm_phase = ( DllmReqPhase.STAGING_PREFILL @@ -69,7 +69,7 @@ class ReqDllmMixin: def _init_fill_ids_for_dllm(self: Req): if self.dllm_incomplete_ids: - prefix_len = len(self.prefix_indices) + prefix_len = self.prefix_len assert len(self.dllm_incomplete_ids) == self.dllm_config.block_size self.full_untruncated_fill_ids = ( self.full_untruncated_fill_ids[:prefix_len] + self.dllm_incomplete_ids @@ -101,7 +101,7 @@ class ReqDllmMixin: self.dllm_initialized = True def _update_block_offset_for_dllm(self): - prefix_len = len(self.prefix_indices) + prefix_len = self.prefix_len if self.dllm_config.requires_separate_context_encoding: assert prefix_len <= self.dllm_block_offset else: diff --git a/python/sglang/srt/hardware_backend/mlx/tp_worker.py b/python/sglang/srt/hardware_backend/mlx/tp_worker.py index dd16541d25..e8eb576833 100644 --- a/python/sglang/srt/hardware_backend/mlx/tp_worker.py +++ b/python/sglang/srt/hardware_backend/mlx/tp_worker.py @@ -492,7 +492,14 @@ class MlxTpModelWorker(TpModelWorker): elif route == "decode": mixed_decode_rids.append(req.rid) else: # "prefill" - prefix_slot_ids = req.prefix_indices.tolist() + # The allocation wrote the matched prefix into the request's row. + prefix_slot_ids = ( + self.req_to_token_pool.req_to_token[ + req.kv.req_pool_idx, : req.prefix_len + ].tolist() + if req.prefix_len + else [] + ) full_token_ids = list(req.get_fill_ids()) pending_prefills.append( self._mlx_runner.prefill_start( diff --git a/python/sglang/srt/managers/schedule_batch.py b/python/sglang/srt/managers/schedule_batch.py index a5ab74ae39..2aef3c5793 100755 --- a/python/sglang/srt/managers/schedule_batch.py +++ b/python/sglang/srt/managers/schedule_batch.py @@ -1176,8 +1176,14 @@ class Req(ReqDllmMixin): self.mm_video_tokens: int = 0 # Prefix info - # The indices to kv cache for the shared prefix. - self.prefix_indices: torch.Tensor = torch.empty((0,), dtype=torch.int64) + # Tokens [0, prefix_len) are already in the row or come from a match; + # the next extend starts at prefix_len. + self.prefix_len: int = 0 + # The matched prefix's KV indices, consumed when the next allocation + # writes them into the row; None once written. + self.prefix_indices: Optional[torch.Tensor] = torch.empty( + (0,), dtype=torch.int64 + ) # TODO(ispobock): rename to last_device_node self.last_node: Any = None self.last_host_node: Any = None @@ -1190,7 +1196,7 @@ class Req(ReqDllmMixin): # match, it will be the tracked seqlen in the ping pong buffer for the # right prefill pass. self.mamba_branching_seqlen: Optional[int] = None - # Total cached prefix length (on-device prefix_indices + host_hit_length), + # Total cached prefix length (on-device prefix_len + host_hit_length), # capped at the max allowed prefix. Set during prefix matching at schedule # time and used to estimate uncached tokens / sort by longest prefix for # load reporting. @@ -1565,6 +1571,10 @@ class Req(ReqDllmMixin): def set_extend_range(self, start: int, end: int) -> None: self.extend_range = Range(start, end) + def set_prefix_indices(self, prefix_indices: torch.Tensor) -> None: + self.prefix_indices = prefix_indices + self.prefix_len = len(prefix_indices) + def get_fill_ids(self) -> array: return self.full_untruncated_fill_ids[: self.extend_range.end] @@ -1640,7 +1650,7 @@ class Req(ReqDllmMixin): ) self.mamba_branching_seqlen = match_result.mamba_branching_seqlen if match_result.cache_protected_len is None: - self.kv.cache_protected_len = len(self.prefix_indices) + self.kv.cache_protected_len = self.prefix_len if self.is_dllm(): self._update_block_offset_for_dllm() @@ -1924,7 +1934,7 @@ class Req(ReqDllmMixin): # since we are tracking the total number of retractions for each request. self.retraction_count += 1 - self.prefix_indices = torch.empty((0,), dtype=torch.int64) + self.set_prefix_indices(torch.empty((0,), dtype=torch.int64)) self.routed_experts = None self.indexer_topk = None self.last_node = None @@ -2592,7 +2602,7 @@ class ScheduleBatch(ScheduleBatchDisaggregationDecodeMixin): encoder_lens_cpu.append(im.num_image_tokens) encoder_cached.append( self.forward_mode.is_decode() - or len(req.prefix_indices) >= im.num_image_tokens + or req.prefix_len >= im.num_image_tokens ) self.encoder_lens_cpu = encoder_lens_cpu self.encoder_cached = encoder_cached @@ -2611,9 +2621,9 @@ class ScheduleBatch(ScheduleBatchDisaggregationDecodeMixin): encoder_len = self.encoder_lens_cpu[i] seq_lens[i] -= encoder_len - if len(req.prefix_indices) < encoder_len: + if req.prefix_len < encoder_len: # NOTE: the encoder part should be considered as a whole - assert len(req.prefix_indices) == 0 + assert req.prefix_len == 0 input_ids[i] = input_ids[i][encoder_len:] encoder_out_cache_loc.append(self.out_cache_loc[pt : pt + encoder_len]) decoder_out_cache_loc.append( @@ -2667,7 +2677,7 @@ class ScheduleBatch(ScheduleBatchDisaggregationDecodeMixin): old_start_len = extend_logprob_start_lens[i] old_contribution = req.extend_range.length - old_start_len - if len(req.prefix_indices) < encoder_len: + if req.prefix_len < encoder_len: tokens_to_strip = max(0, encoder_len - old_start_len) new_token_ids_parts.append( self.extend_input_logprob_token_ids[ @@ -2694,8 +2704,8 @@ class ScheduleBatch(ScheduleBatchDisaggregationDecodeMixin): encoder_len = self.encoder_lens_cpu[i] if encoder_len == 0: continue - if len(req.prefix_indices) < encoder_len: - assert len(req.prefix_indices) == 0 + if req.prefix_len < encoder_len: + assert req.prefix_len == 0 req.extend_range = req.extend_range._replace( start=req.extend_range.start + encoder_len ) @@ -2710,11 +2720,11 @@ class ScheduleBatch(ScheduleBatchDisaggregationDecodeMixin): # Init tensors reqs = self.reqs - input_ids = [r.get_fill_ids()[len(r.prefix_indices) :] for r in reqs] + input_ids = [r.get_fill_ids()[r.prefix_len :] for r in reqs] extend_num_tokens = sum(len(ids) for ids in input_ids) seq_lens = [r.extend_range.end for r in reqs] orig_seq_lens = [max(r.extend_range.end, len(r.origin_input_ids)) for r in reqs] - prefix_lens = [len(r.prefix_indices) for r in reqs] + prefix_lens = [r.prefix_len for r in reqs] extend_lens = [r.extend_range.length for r in reqs] extend_logprob_start_lens = [ compute_extend_logprob_start_len( @@ -2836,7 +2846,7 @@ class ScheduleBatch(ScheduleBatchDisaggregationDecodeMixin): req.cached_tokens_host, req.cached_tokens_storage, ) = split_cached_prefix_by_tier( - prefix_len=len(req.prefix_indices), + prefix_len=req.prefix_len, host_hit_len=req.materialized_host_hit_len(), storage_hit_len=req.storage_hit_length, storage_hit_start=req.storage_hit_start, @@ -2868,7 +2878,7 @@ class ScheduleBatch(ScheduleBatchDisaggregationDecodeMixin): # get_fill_ids() = [3, 4] # extend_input_logprob_token_id = [4, 0] global_start_idx, global_end_idx = ( - len(req.prefix_indices), + req.prefix_len, req.extend_range.end, ) if req.logprob_start_len == -1: @@ -2998,10 +3008,10 @@ class ScheduleBatch(ScheduleBatchDisaggregationDecodeMixin): def _force_track_h(i: int) -> int: # h is indexed relative to the extend start, so check that offset. - assert (i - len(req.prefix_indices)) % cache_chunk_size == 0, ( + assert (i - req.prefix_len) % cache_chunk_size == 0, ( f"The force track calculation only handles last-position or " f"unaligned seqlens, so it needs a chunk-aligned offset to " - f"start from. But i={i} prefix_len={len(req.prefix_indices)} " + f"start from. But i={i} prefix_len={req.prefix_len} " f"chunk_size={cache_chunk_size} checkpoint_grid={checkpoint_grid}" ) # There are 3 cases for mamba_track_seqlen passed to mamba_track_seqlens_cpu: @@ -3013,7 +3023,7 @@ class ScheduleBatch(ScheduleBatchDisaggregationDecodeMixin): # to force the math calculation to retrieve the correct mamba state from h. return i + 1 - prefix_len = len(req.prefix_indices) + prefix_len = req.prefix_len seq_end = prefix_len + req.extend_range.length if get_parallel().dcp_enabled: # DCP widens radix pages beyond scheduler chunk boundaries. Pick an @@ -3049,7 +3059,7 @@ class ScheduleBatch(ScheduleBatchDisaggregationDecodeMixin): # A coarser checkpoint grid may not be a model-state boundary, so # force retrieval from the intermediate h state in that case. mamba_track_fla_chunk_aligned = ( - len(req.prefix_indices) + req.prefix_len + (req.extend_range.length // state_chunk_size) * state_chunk_size ) if mamba_track_fla_chunk_aligned != mamba_track_seqlen_aligned: @@ -3071,10 +3081,10 @@ class ScheduleBatch(ScheduleBatchDisaggregationDecodeMixin): # track branching point in this forward if the branching point # is within the current extend batch. branching_seqlen_aligned_mask = ( - req.mamba_branching_seqlen - len(req.prefix_indices) + req.mamba_branching_seqlen - req.prefix_len ) % cache_chunk_size == 0 if ( - req.mamba_branching_seqlen > len(req.prefix_indices) + req.mamba_branching_seqlen > req.prefix_len and req.mamba_branching_seqlen < mamba_track_seqlen and branching_seqlen_aligned_mask ): @@ -3181,7 +3191,7 @@ class ScheduleBatch(ScheduleBatchDisaggregationDecodeMixin): merged[-running_bs:] = tail_base + 1 self.seq_lens = merged - # NOTE: prefix_indices is what has been cached, but we don't cache each decode step + # NOTE: prefix_len is what has been cached, but we don't cache each decode step self.prefix_lens = self.prefix_lens + running_prefix_lens self.extend_lens = self.extend_lens + [1] * running_bs self.extend_num_tokens = self.extend_num_tokens + running_bs diff --git a/python/sglang/srt/managers/schedule_policy.py b/python/sglang/srt/managers/schedule_policy.py index 62305baf74..78dec2d4b7 100644 --- a/python/sglang/srt/managers/schedule_policy.py +++ b/python/sglang/srt/managers/schedule_policy.py @@ -329,7 +329,7 @@ class SchedulePolicy: # We prefer to set IN_BATCH_PREFIX_CACHING_CHECK_THRESHOLD > 0 because too small # threshold means we cannot use in-batch prefix caching for short prefixes. # It is kind of common when the engine is long running (e.g., imagine the prefix "the"). - if len(r.prefix_indices) <= IN_BATCH_PREFIX_CACHING_CHECK_THRESHOLD: + if r.prefix_len <= IN_BATCH_PREFIX_CACHING_CHECK_THRESHOLD: match_result = self.waiting_queue_radix_tree.match_prefix( MatchPrefixParams( key=RadixKey( @@ -392,9 +392,7 @@ class SchedulePolicy: or budget < 2 * page_size ): return None - remaining = len(chunked_req.full_untruncated_fill_ids) - len( - chunked_req.prefix_indices - ) + remaining = len(chunked_req.full_untruncated_fill_ids) - chunked_req.prefix_len reserved = 0 for req in waiting_queue: work = self._shortest_prefill_work(req) @@ -1002,16 +1000,14 @@ class PrefillAdder: return AddReqResult.NO_TOKEN # Truncate input length to available tokens and update request metadata - cand_extend_input_len = len(req.full_untruncated_fill_ids) - len( - req.prefix_indices - ) + cand_extend_input_len = len(req.full_untruncated_fill_ids) - req.prefix_len if ( self.dllm_config.requires_separate_context_encoding and req.is_dllm_prefill() ): cand_extend_input_len = min( cand_extend_input_len, - req.dllm_block_offset - len(req.prefix_indices), + req.dllm_block_offset - req.prefix_len, ) if ( req.dllm_incomplete_ids @@ -1023,7 +1019,7 @@ class PrefillAdder: return AddReqResult.NO_TOKEN truncated = cand_extend_input_len > _rem_tokens new_len = min(cand_extend_input_len, _rem_tokens) - req.set_extend_range(len(req.prefix_indices), len(req.prefix_indices) + new_len) + req.set_extend_range(req.prefix_len, req.prefix_len + new_len) self.can_run_list.append(req) # Update budget: reserve max_new_tokens only if not truncated @@ -1059,7 +1055,7 @@ class PrefillAdder: if self.kv_shard_granule: # Align the absolute boundary to keep pages within one scratch region. # If no budget remains, use a full chunk to make progress. - prefix_len = len(req.prefix_indices) + prefix_len = req.prefix_len floored = ( prefix_len + _rem_tokens ) // self.kv_shard_granule * self.kv_shard_granule - prefix_len @@ -1080,9 +1076,7 @@ class PrefillAdder: assert self.chunked_req_limit > 0 _rem_tokens = min(_rem_tokens, self.chunked_req_limit) - cand_extend_input_len = len(req.full_untruncated_fill_ids) - len( - req.prefix_indices - ) + cand_extend_input_len = len(req.full_untruncated_fill_ids) - req.prefix_len _rem_tokens = self.memory_budget.fit_chunk( extend_input_len=cand_extend_input_len, max_new_tokens=self._swa_new_tokens(req), @@ -1094,11 +1088,11 @@ class PrefillAdder: new_len = min(cand_extend_input_len, _rem_tokens) # The continuing chunk must fit. Keep reservation outside assert for -O. reserved = self._kv_shard_reserve_scratch( - prefix_len=len(req.prefix_indices), extend_len=new_len + prefix_len=req.prefix_len, extend_len=new_len ) if not reserved: raise RuntimeError("chunked request exceeds the sharded assembly scratch") - req.set_extend_range(len(req.prefix_indices), len(req.prefix_indices) + new_len) + req.set_extend_range(req.prefix_len, req.prefix_len + new_len) self.can_run_list.append(req) self._update_prefill_budget( 0, @@ -1135,9 +1129,7 @@ class PrefillAdder: self.tree_cache.dec_host_lock_ref(last_node, host_lock_params) def add_one_req_ignore_eos(self, req: Req): - cand_extend_input_len = len(req.full_untruncated_fill_ids) - len( - req.prefix_indices - ) + cand_extend_input_len = len(req.full_untruncated_fill_ids) - req.prefix_len paged_input = ( self.ceil_paged_tokens(cand_extend_input_len) + self.per_req_token_overhead ) @@ -1232,13 +1224,11 @@ class PrefillAdder: # Non-chunked prefill — the whole sequence is committed this iter. if not self._kv_shard_reserve_scratch( - prefix_len=len(req.prefix_indices), + prefix_len=req.prefix_len, extend_len=cand_extend_input_len, ): return AddReqResult.OTHER - req.set_extend_range( - len(req.prefix_indices), len(req.full_untruncated_fill_ids) - ) + req.set_extend_range(req.prefix_len, len(req.full_untruncated_fill_ids)) self.can_run_list.append(req) self._update_prefill_budget( 0, @@ -1264,10 +1254,8 @@ class PrefillAdder: if not self._kv_shard_reserve_scratch(prefix_len=0, extend_len=trunc_len): return AddReqResult.OTHER - assert len(req.prefix_indices) == 0 - req.set_extend_range( - len(req.prefix_indices), len(req.prefix_indices) + trunc_len - ) + assert req.prefix_len == 0 + req.set_extend_range(req.prefix_len, req.prefix_len + trunc_len) self.can_run_list.append(req) self.new_chunked_req = req self._update_prefill_budget( @@ -1297,9 +1285,7 @@ class PrefillAdder: max(req.sampling_params.max_new_tokens - len(req.output_ids), 0), CLIP_MAX_NEW_TOKENS, ) - cand_extend_input_len = len(req.full_untruncated_fill_ids) - len( - req.prefix_indices - ) + cand_extend_input_len = len(req.full_untruncated_fill_ids) - req.prefix_len total_tokens = cand_extend_input_len + max_new + self.per_req_token_overhead # Shared Mamba pool: fold the new mamba state's shared-gap cost into # `total_tokens` so both `rem_total_tokens` gates reflect the joint budget. @@ -1397,7 +1383,7 @@ class PrefillAdder: if req.host_loaded_length > promised_host_hit: # A load can expose resident FULL behind host-only aux state; its # H2D is queued, so keep the approved budget and shrink the work. - prefix_len = len(req.prefix_indices) + req.host_loaded_length + prefix_len = req.prefix_len + req.host_loaded_length extend_len = admission.extend_len if self.dllm_config is None: extend_len = min( @@ -1426,8 +1412,8 @@ class PrefillAdder: ) if isinstance(admission, AddReqResult): return admission - req.prefix_indices = torch.cat([req.prefix_indices, new_indices]) - req.kv.cache_protected_len = len(req.prefix_indices) + req.set_prefix_indices(torch.cat([req.prefix_indices, new_indices])) + req.kv.cache_protected_len = req.prefix_len # Sharded pools cannot load host KV; reserve scratch after all other gates. if not self._kv_shard_reserve_scratch( @@ -1451,7 +1437,7 @@ class PrefillAdder: has_chunked_req: bool = False, ) -> _PrefillAdmission | AddReqResult: """Select a prefill shape without allocating or publishing cached KV.""" - prefix_len = len(req.prefix_indices) + host_hit_length + prefix_len = req.prefix_len + host_hit_length extend_len = len(req.full_untruncated_fill_ids) - prefix_len input_tokens = self.ceil_paged_tokens(extend_len) # Whether the request fits whole. Against the raw length under @@ -1526,7 +1512,7 @@ class PrefillAdder: def _commit_prefill_admission( self, req: Req, admission: _PrefillAdmission, mamba_gap_reserve: int ) -> None: - assert len(req.prefix_indices) == admission.prefix_len + assert req.prefix_len == admission.prefix_len req.set_extend_range( admission.prefix_len, admission.prefix_len + admission.extend_len ) @@ -1576,7 +1562,7 @@ class PrefillAdder: preemptible_reqs = [] min_tokens_to_remove = ( len(req.full_untruncated_fill_ids) - - len(req.prefix_indices) + - req.prefix_len + min(req.sampling_params.max_new_tokens, CLIP_MAX_NEW_TOKENS) - self.rem_total_tokens ) diff --git a/python/sglang/srt/managers/scheduler.py b/python/sglang/srt/managers/scheduler.py index 0c254d7dc7..8122547aef 100644 --- a/python/sglang/srt/managers/scheduler.py +++ b/python/sglang/srt/managers/scheduler.py @@ -3153,7 +3153,7 @@ class Scheduler( ): last_host_node = req.last_node - matched_len = len(req.prefix_indices) + req.host_hit_length + matched_len = req.prefix_len + req.host_hit_length req.storage_prefetch_last_match_len = matched_len if ( @@ -3227,7 +3227,7 @@ class Scheduler( and buffer_pipeline.has_staged(req.cache_request_handle) ): return False - current_match_len = len(req.prefix_indices) + req.host_hit_length + current_match_len = req.prefix_len + req.host_hit_length if current_match_len >= previous_match_len: return False if ( @@ -3676,12 +3676,9 @@ class Scheduler( # only finished requests to running_batch. chunked_req_to_exclude.add(self.chunked_req) - # Stash (cache) the previous chunk only when it produced new KV - # beyond what is already cached. A parked chunk (add_chunked_req - # hybrid-SWA early-return) leaves extend_range.end == - # len(prefix_indices), so there is nothing new to cache and - # stashing would be a no-op. - if self.chunked_req.extend_range.end > len(self.chunked_req.prefix_indices): + # A parked chunk (add_chunked_req hybrid-SWA early-return) leaves + # extend_range.end at prefix_len: it computed no new KV, so nothing to stash. + if self.chunked_req.extend_range.end > self.chunked_req.prefix_len: self.stash_chunked_request(self.chunked_req) # HiSparse has its own prefill-to-decode transition; skip last_batch merge. @@ -3905,7 +3902,7 @@ class Scheduler( # Determine chunked_prefill_size for this batch chunked_prefill_size = self.chunked_prefill_size if self.chunked_req is not None and self.dynamic_chunk_sizer is not None: - history_len = len(self.chunked_req.prefix_indices) + history_len = self.chunked_req.prefix_len dynamic_size = self.dynamic_chunk_sizer.predict(history_len) if dynamic_size is not None: chunked_prefill_size = dynamic_size diff --git a/python/sglang/srt/managers/scheduler_components/dynamic_chunk_sizer.py b/python/sglang/srt/managers/scheduler_components/dynamic_chunk_sizer.py index 76919db379..ad27b6e758 100644 --- a/python/sglang/srt/managers/scheduler_components/dynamic_chunk_sizer.py +++ b/python/sglang/srt/managers/scheduler_components/dynamic_chunk_sizer.py @@ -170,9 +170,7 @@ class DynamicChunkSizer: # request so release_kv_cache can release it symmetrically. req.init_next_round_input(self.tree_cache) req.lock = self.tree_cache.lock(req.last_node) - req.set_extend_range( - len(req.prefix_indices), len(req.full_untruncated_fill_ids) - ) + req.set_extend_range(req.prefix_len, len(req.full_untruncated_fill_ids)) # Prepare batch batch = ScheduleBatch.init_new( diff --git a/python/sglang/srt/managers/scheduler_components/load_inquirer.py b/python/sglang/srt/managers/scheduler_components/load_inquirer.py index 4764a76873..8808a53793 100644 --- a/python/sglang/srt/managers/scheduler_components/load_inquirer.py +++ b/python/sglang/srt/managers/scheduler_components/load_inquirer.py @@ -64,15 +64,15 @@ class SchedulerLoadInquirer: Args: chunk_deduct: extra tokens to subtract from the chunked request's remaining count. At batch-scheduling time the current chunk - has been planned but ``prefix_indices`` does not yet include it, + has been planned but ``prefix_len`` does not yet include it, so callers pass ``extend_input_len`` here. At load-reporting - time ``prefix_indices`` is already up-to-date, so the default + time ``prefix_len`` is already up-to-date, so the default 0 is correct. """ num_pending_tokens = sum(req.seqlen for req in self.get_waiting_queue()) if self.get_chunked_req() is not None: req = self.get_chunked_req() - num_pending_tokens += req.seqlen - len(req.prefix_indices) - chunk_deduct + num_pending_tokens += req.seqlen - req.prefix_len - chunk_deduct return num_pending_tokens def get_num_waiting_uncached_tokens(self) -> int: @@ -89,7 +89,7 @@ class SchedulerLoadInquirer: num_tokens += int(req.seqlen * cache_miss_rate) cr = self.get_chunked_req() if cr is not None: - num_tokens += max(0, cr.seqlen - len(cr.prefix_indices)) + num_tokens += max(0, cr.seqlen - cr.prefix_len) return num_tokens def get_loads(self) -> LoadSnapshot: diff --git a/python/sglang/srt/mem_cache/allocation.py b/python/sglang/srt/mem_cache/allocation.py index b546b526f5..02292cfc11 100644 --- a/python/sglang/srt/mem_cache/allocation.py +++ b/python/sglang/srt/mem_cache/allocation.py @@ -361,7 +361,17 @@ def alloc_for_extend( # free out-of-window swa tokens batch.maybe_evict_swa() - prefix_tensors = [r.prefix_indices for r in batch.reqs] + # A request holding its row (a later chunk, a borrowed session record) + # already has its prefix there; a new one writes its matched prefix. + req_to_token = batch.req_to_token_pool.req_to_token + prefix_tensors = [ + ( + req_to_token[r.kv.req_pool_idx, : r.prefix_len].to(torch.int64) + if r.kv.holds_kv + else r.prefix_indices + ) + for r in batch.reqs + ] reuse_kv = None if batch.is_dllm(): @@ -393,6 +403,7 @@ def alloc_for_extend( out_cache_loc = _alloc_extend_loc_with_kv_reuse( batch, reuse_kv, + prefix_tensors, req_pool_indices_cpu, prefix_lens_cpu, extend_lens_cpu, @@ -454,6 +465,7 @@ def alloc_for_extend( for req, seq_len in zip(batch.reqs, batch.seq_lens_cpu.tolist()): req.kv.kv_allocated_len = seq_len req.kv.kv_committed_len = seq_len + req.prefix_indices = None batch.tree_cache.maybe_hand_to_session(req) return out_cache_loc, req_pool_indices_device, req_pool_indices_cpu @@ -462,6 +474,7 @@ def alloc_for_extend( def _alloc_extend_loc_with_kv_reuse( batch: ScheduleBatch, reuse_kv: list[bool], + prefix_tensors: list[torch.Tensor], req_pool_indices_cpu: torch.Tensor, prefix_lens_cpu: torch.Tensor, extend_lens_cpu: torch.Tensor, @@ -505,7 +518,7 @@ def _alloc_extend_loc_with_kv_reuse( ) last_loc = [ (t[-1:] if len(t) > 0 else torch.tensor([-1], device=device)) - for t in (r.prefix_indices for r in batch.reqs) + for t in prefix_tensors ] fresh_slots = alloc_paged_token_slots_extend( tree_cache=batch.tree_cache, diff --git a/python/sglang/srt/mem_cache/buffer_mode/pipeline.py b/python/sglang/srt/mem_cache/buffer_mode/pipeline.py index 45c1e358cf..78361076ed 100644 --- a/python/sglang/srt/mem_cache/buffer_mode/pipeline.py +++ b/python/sglang/srt/mem_cache/buffer_mode/pipeline.py @@ -1225,7 +1225,7 @@ class BufferModePipeline: if not (req.host_hit_is_storage and req.host_loaded_length > 0): self._clear_storage_hit(req) return True - joint_len = len(req.prefix_indices) + joint_len = req.prefix_len if joint_len >= f.matched_len + f.num_tokens: # The joint match already covers the staged span; a shorter FULL-only # prefix would strand the slots recomputed below cache_protected_len. @@ -1254,7 +1254,7 @@ class BufferModePipeline: node_id, root_id )[:matched_len] assert len(full_indices) == matched_len - req.prefix_indices = full_indices + req.set_prefix_indices(full_indices) req.last_node = node_id req.kv.cache_protected_len = matched_len full_tokens = max(0, f.matched_len + f.num_tokens - matched_len) @@ -1440,7 +1440,7 @@ class BufferModePipeline: req.staged_prefetch_plan = None splice_base = plan.device_prefix_len - assert len(req.prefix_indices) == splice_base + assert req.prefix_len == splice_base trim_tokens = splice_base - f.matched_len assert trim_tokens % cache.page_size == 0, ( f"staged splice trim not page-aligned req={req.rid}: " diff --git a/python/sglang/srt/mem_cache/chunk_cache.py b/python/sglang/srt/mem_cache/chunk_cache.py index fb05edd283..b1932b6b64 100644 --- a/python/sglang/srt/mem_cache/chunk_cache.py +++ b/python/sglang/srt/mem_cache/chunk_cache.py @@ -77,9 +77,7 @@ class ChunkCache(BasePrefixCache): return InsertResult(prefix_len=0) def checkpoint(self, req: Req, *, up_to: int): - kv_indices = self.req_to_token_pool.req_to_token[req.kv.req_pool_idx, :up_to] - # `req.prefix_indices` will be used in `PrefillAdder::add_chunked_req` later - req.prefix_indices = kv_indices.to(dtype=torch.int64, copy=True) + pass def evict(self, params: EvictParams) -> EvictResult: return EvictResult() diff --git a/python/sglang/srt/mem_cache/common.py b/python/sglang/srt/mem_cache/common.py index d8dd3c0a9a..22106735bc 100644 --- a/python/sglang/srt/mem_cache/common.py +++ b/python/sglang/srt/mem_cache/common.py @@ -209,8 +209,8 @@ def match_kv_cache( match_result = zero_match_result( tree_cache, match_result, extra_key=req.extra_key ) + req.set_prefix_indices(match_result.device_indices) ( - req.prefix_indices, req.last_node, req.last_host_node, req.best_match_node, @@ -218,7 +218,6 @@ def match_kv_cache( req.swa_host_hit_length, req.mamba_host_hit_length, ) = ( - match_result.device_indices, match_result.last_device_node, match_result.last_host_node, match_result.best_match_node, @@ -227,9 +226,7 @@ def match_kv_cache( match_result.mamba_host_hit_length, ) max_len = req._compute_max_prefix_len(len(token_ids)) - req.num_matched_prefix_tokens = min( - len(req.prefix_indices) + req.host_hit_length, max_len - ) + req.num_matched_prefix_tokens = min(req.prefix_len + req.host_hit_length, max_len) req.swa_branching_seqlen = match_result.swa_branching_seqlen # A probe match keeps what it did not report; a new round resets both. if match_result.mamba_branching_seqlen is not None: @@ -245,14 +242,10 @@ def checkpoint_kv_cache(req: Req, tree_cache: BasePrefixCache) -> None: # The tree reads req.finished() to tell a checkpoint from the final # insert; a finished request belongs in release_kv_cache. assert not req.finished(), f"checkpointing finished request {req.rid}" - if req.skip_radix_cache_insert: - # Kept out of the tree; the next extend still resumes from prefix_indices. - req.prefix_indices = tree_cache.req_to_token_pool.req_to_token[ - req.kv.req_pool_idx, : req.extend_range.end - ].to(dtype=torch.int64, copy=True) - return - - tree_cache.checkpoint(req, up_to=req.extend_range.end) + if not req.skip_radix_cache_insert: + tree_cache.checkpoint(req, up_to=req.extend_range.end) + # The next extend resumes after this one, published or not. + req.prefix_len = req.extend_range.end def evict_from_tree_cache( diff --git a/python/sglang/srt/mem_cache/radix_cache.py b/python/sglang/srt/mem_cache/radix_cache.py index 6a0968eab0..6753427769 100644 --- a/python/sglang/srt/mem_cache/radix_cache.py +++ b/python/sglang/srt/mem_cache/radix_cache.py @@ -503,7 +503,7 @@ class RadixCache(BasePrefixCache): key_limit = ( ceil_align(swa_evict_floor, self.page_size) if swa_evict_floor > 0 else None ) - radix_key, kv_indices, _ = self._insert_cache( + radix_key, _, _ = self._insert_cache( req, token_ids, key_limit=key_limit, split_prompt=True ) @@ -522,23 +522,13 @@ class RadixCache(BasePrefixCache): new_indices[req.kv.cache_protected_len :], ) - # With page_size > 1 the partial page sits in req.prefix_indices but not + # With page_size > 1 the partial page stays in the request's row but not # in the tree; cache_protected_len marks the tree-owned part so the next # checkpoint or release_kv_cache frees the rest. req.kv.cache_protected_len = len(new_indices) self.unlock(req.lock) req.lock = self.lock(new_last_node) - - # `req.prefix_indices` will be used in `PrefillAdder::add_chunked_req` later - # - page_size != 1: there is a partial page at the end, keep the full kv_indices - # - eagle case: bigram keys will only cache len - 1 kv indices - if len(new_indices) < len(kv_indices): - req.prefix_indices = torch.cat( - [new_indices, kv_indices[len(new_indices) :]] - ) - else: - req.prefix_indices = new_indices req.last_node = new_last_node def pretty_print(self): diff --git a/python/sglang/srt/mem_cache/storage/lmcache/lmcache_unified_radix_cache.py b/python/sglang/srt/mem_cache/storage/lmcache/lmcache_unified_radix_cache.py index 1fdf3811fd..b56ecb57a5 100644 --- a/python/sglang/srt/mem_cache/storage/lmcache/lmcache_unified_radix_cache.py +++ b/python/sglang/srt/mem_cache/storage/lmcache/lmcache_unified_radix_cache.py @@ -834,12 +834,6 @@ class LMCacheUnifiedRadixCache(UnifiedRadixCache): # Move the request lock to the published boundary. self.unlock(req.lock) req.lock = self.lock(matched.last_device_node) - if total_hit < token_ids_len: - req.prefix_indices = torch.cat( - [canonical, kv_indices[total_hit:].to(dtype=torch.int64, copy=True)] - ) - else: - req.prefix_indices = canonical req.kv.cache_protected_len = total_hit req.last_node = matched.last_device_node flow.request_mamba_value = None diff --git a/python/sglang/srt/mem_cache/unified_cache/components/README.md b/python/sglang/srt/mem_cache/unified_cache/components/README.md index 8ad58d06b5..3fb021564b 100644 --- a/python/sglang/srt/mem_cache/unified_cache/components/README.md +++ b/python/sglang/srt/mem_cache/unified_cache/components/README.md @@ -240,7 +240,7 @@ Insert a request's KV into the tree: at every checkpoint while it runs, and once | **Purpose** | Publish the request's KV `[cache_protected_len, up_to)` so other requests can match it; nodes past `req.kv.cache_inserted_len` count one hit (a request counts each node once). `checkpoint_kv_cache` calls it with `req.extend_range.end` while the request runs; `release_kv_cache` calls it with the request-owned length when it finishes (`req.finished()`), then frees `[cache_protected_len, up_to)` and everything past it and unlocks `req.lock`; with `checkpoint=False` it skips the insert and calls `on_release(req, checkpointed=False)` for component cleanup | | **Inputs** | `req` — the request; `up_to` — row position the insert may read up to | | **Output** | `None` | -| **Mutation** | Component hooks → `insert` → re-match → writes the tree's indices back into the row → moves `req.lock` to the node the insert ended on → updates `req.prefix_indices`, `req.kv.cache_protected_len`, `req.kv.cache_inserted_len`, `req.last_node` → component cleanup. A finished request's component state (Mamba) is handed to the tree instead of forked, and what it still held is freed. Frees no KV slot: `release_kv_cache` does that afterwards. | +| **Mutation** | Component hooks → `insert` → re-match → writes the tree's indices back into the row → moves `req.lock` to the node the insert ended on → updates `req.kv.cache_protected_len`, `req.kv.cache_inserted_len`, `req.last_node` (`checkpoint_kv_cache` then advances `req.prefix_len`) → component cleanup. A finished request's component state (Mamba) is handed to the tree instead of forked, and what it still held is freed. Frees no KV slot: `release_kv_cache` does that afterwards. | | **Complexity** | **O(K + D·C)** — insert O(K + D·C) + re-match O(K + D·C) + lock transfer O(D). Simplifies to **O(K)**. | **Algorithm detail:** diff --git a/python/sglang/srt/mem_cache/unified_radix_cache.py b/python/sglang/srt/mem_cache/unified_radix_cache.py index 28ac43bbb6..0b8ff186d9 100644 --- a/python/sglang/srt/mem_cache/unified_radix_cache.py +++ b/python/sglang/srt/mem_cache/unified_radix_cache.py @@ -1088,10 +1088,6 @@ class UnifiedRadixCache(BasePrefixCache): token_ids = req.full_untruncated_fill_ids[:up_to] if self.disable: - kv_indices = self.req_to_token_pool.req_to_token[ - req.kv.req_pool_idx, : len(token_ids) - ] - req.prefix_indices = kv_indices.to(dtype=torch.int64, copy=True) if is_finished: for comp in self._components_tuple: comp.cleanup_after_caching_req(req, is_finished=True) @@ -1143,7 +1139,6 @@ class UnifiedRadixCache(BasePrefixCache): comp.free_out_of_window_slots(req, len(radix_key) - 1, insert_params) if effective_cache_len <= 0: - req.prefix_indices = kv_indices_orig.to(dtype=torch.int64, copy=True) for comp in self._components_tuple: comp.cleanup_after_caching_req( req, is_finished=is_finished, insert_params=insert_params @@ -1170,7 +1165,6 @@ class UnifiedRadixCache(BasePrefixCache): # declined before its walk, so nothing was freed underneath us. The # release_kv_cache releases everything past the protected # prefix. - req.prefix_indices = kv_indices_orig.to(dtype=torch.int64, copy=True) for comp in self._components_tuple: comp.cleanup_after_caching_req( req, is_finished=is_finished, insert_params=insert_params @@ -1238,12 +1232,6 @@ class UnifiedRadixCache(BasePrefixCache): ) # Update req fields - if len(new_indices) < len(kv_indices_orig): - req.prefix_indices = torch.cat( - [new_indices, kv_indices_orig[len(new_indices) :]] - ) - else: - req.prefix_indices = new_indices req.kv.cache_protected_len = len(new_indices) req.last_node = new_last_node @@ -1268,9 +1256,6 @@ class UnifiedRadixCache(BasePrefixCache): def advance_unpublished_req(self, req: Req) -> None: assert not self.supports_mamba() token_ids = req.get_fill_ids() - kv_indices = self.req_to_token_pool.req_to_token[ - req.kv.req_pool_idx, : len(token_ids) - ] insert_params = InsertParams( prev_prefix_len=req.kv.cache_protected_len, priority=req.priority or 0, @@ -1297,7 +1282,6 @@ class UnifiedRadixCache(BasePrefixCache): for comp in self._components_tuple: comp.free_out_of_window_slots(req, len(radix_key) - 1, insert_params) - req.prefix_indices = kv_indices.to(dtype=torch.int64, copy=True) for comp in self._components_tuple: comp.cleanup_after_caching_req( req, is_finished=False, insert_params=insert_params diff --git a/python/sglang/srt/model_executor/model_runner_components/ngram_embedding_manager.py b/python/sglang/srt/model_executor/model_runner_components/ngram_embedding_manager.py index f3347b3340..c0e5389cc0 100644 --- a/python/sglang/srt/model_executor/model_runner_components/ngram_embedding_manager.py +++ b/python/sglang/srt/model_executor/model_runner_components/ngram_embedding_manager.py @@ -124,7 +124,7 @@ class NgramEmbeddingManager: column_starts = [] request_lengths = [] for req in batch.reqs: - start = len(req.prefix_indices) + start = req.prefix_len end = start + req.extend_range.length fill_ids = req.origin_input_ids + req.output_ids if start == 0: diff --git a/python/sglang/srt/session/streaming_session.py b/python/sglang/srt/session/streaming_session.py index efd521eaac..f93cb8a6d3 100644 --- a/python/sglang/srt/session/streaming_session.py +++ b/python/sglang/srt/session/streaming_session.py @@ -188,10 +188,8 @@ class StreamingSession: return True def try_checkpoint(self, req: Req, *, up_to: int, **kwargs) -> bool: - """A turn on the slot's record publishes nothing of its own, so only - the chunk cursor is kept. The exception is the first prompt: the slot - publishes it for other requests to share, and its lock follows the - insert.""" + # A turn publishes nothing of its own, except the first prompt: the slot + # publishes it for other requests to share, and its lock follows the insert. slot = self.borrowed_slot(req) if slot is None: return False @@ -199,11 +197,6 @@ class StreamingSession: req.lock, slot.lock = slot.lock, None self.cache.checkpoint_into_tree(req, up_to=up_to, **kwargs) self._lock_to_slot(req, slot) - return True - kv_indices = self.cache.req_to_token_pool.req_to_token[ - req.kv.req_pool_idx, :up_to - ] - req.prefix_indices = kv_indices.to(dtype=torch.int64, copy=True) return True # -- Record ownership -- diff --git a/test/registered/unit/disaggregation/test_disaggregation_wire.py b/test/registered/unit/disaggregation/test_disaggregation_wire.py index c6c6abcd51..306ff9dc33 100644 --- a/test/registered/unit/disaggregation/test_disaggregation_wire.py +++ b/test/registered/unit/disaggregation/test_disaggregation_wire.py @@ -666,6 +666,7 @@ class TestDisaggregationWire(unittest.TestCase): req = SimpleNamespace( kv=ReqKvInfo(req_pool_idx=0), prefix_indices=[0, 1], + prefix_len=2, extend_range=SimpleNamespace(length=3), origin_input_ids=[0, 1, 2, 3, 4], output_ids=[], diff --git a/test/registered/unit/disaggregation/test_specv2_kvcache_offloading.py b/test/registered/unit/disaggregation/test_specv2_kvcache_offloading.py index 024e8901d4..832e5aa7b6 100644 --- a/test/registered/unit/disaggregation/test_specv2_kvcache_offloading.py +++ b/test/registered/unit/disaggregation/test_specv2_kvcache_offloading.py @@ -55,6 +55,7 @@ def _make_mock_req( kv_allocated_len=kv_allocated_len, ) req.prefix_indices = list(range(prefix_indices_len)) + req.prefix_len = len(req.prefix_indices) req.owned_kv_len = lambda: req.kv.kv_committed_len return req diff --git a/test/registered/unit/dllm/test_gemma4_uniform_lifecycle.py b/test/registered/unit/dllm/test_gemma4_uniform_lifecycle.py index f126b63b0c..0441355b86 100644 --- a/test/registered/unit/dllm/test_gemma4_uniform_lifecycle.py +++ b/test/registered/unit/dllm/test_gemma4_uniform_lifecycle.py @@ -28,6 +28,7 @@ class _Req: "q", [0] * block_size ) self.prefix_indices = torch.arange(context_len, dtype=torch.int64) + self.prefix_len = len(self.prefix_indices) self.dllm_block_offset = context_len self.dllm_incomplete_ids = array("q") self.dllm_algo_state = None @@ -202,6 +203,7 @@ class TestGemma4ContextLifecycle(unittest.TestCase): req = _Req(context_len=300, block_size=256, prefill=True) req.host_hit_length = req.storage_hit_length = 0 req.prefix_indices = torch.empty(0, dtype=torch.int64) + req.prefix_len = len(req.prefix_indices) admission = adder._select_prefill_admission( req, total_tokens=1024, @@ -227,6 +229,7 @@ class TestGemma4ContextLifecycle(unittest.TestCase): req = _Req(context_len=10, block_size=4, prefill=True) req.prefix_indices = torch.arange(7) + req.prefix_len = len(req.prefix_indices) result = PrefillAdder.add_dllm_staging_req(adder, req) @@ -301,6 +304,7 @@ class TestGemma4ContextLifecycle(unittest.TestCase): reused = _alloc_extend_loc_with_kv_reuse( alloc_batch, [True], + [req_to_token[slot, :context_len]], torch.tensor([slot]), torch.tensor([context_len]), torch.tensor([block_size]), diff --git a/test/registered/unit/hardware_backend/mlx/test_tp_worker_routing.py b/test/registered/unit/hardware_backend/mlx/test_tp_worker_routing.py index 695f246081..4b5c467325 100644 --- a/test/registered/unit/hardware_backend/mlx/test_tp_worker_routing.py +++ b/test/registered/unit/hardware_backend/mlx/test_tp_worker_routing.py @@ -168,6 +168,7 @@ class _FakeReq: def __init__(self, rid, req_pool_idx=0): self.rid = rid self.prefix_indices = torch.empty(0, dtype=torch.long) + self.prefix_len = len(self.prefix_indices) self.fill_ids = [0] self.kv = ReqKvInfo(req_pool_idx=req_pool_idx) # Mirrors Req's chunk-finality contract read by diff --git a/test/registered/unit/managers/test_load_inquirer.py b/test/registered/unit/managers/test_load_inquirer.py index 7fdfdef610..4691f637fc 100644 --- a/test/registered/unit/managers/test_load_inquirer.py +++ b/test/registered/unit/managers/test_load_inquirer.py @@ -43,7 +43,9 @@ class TestSchedulePolicyWaitingQueueMatching(unittest.TestCase): class TestSchedulerLoadInquirer(unittest.TestCase): def make_inquirer(self, waiting_queue_prefix_matched): waiting_req = SimpleNamespace(seqlen=100, num_matched_prefix_tokens=20) - chunked_req = SimpleNamespace(seqlen=50, prefix_indices=range(10)) + chunked_req = SimpleNamespace( + seqlen=50, prefix_indices=range(10), prefix_len=10 + ) return SimpleNamespace( disaggregation_mode=DisaggregationMode.NULL, get_waiting_queue=lambda: [waiting_req], diff --git a/test/registered/unit/managers/test_mamba_checkpoint_depth.py b/test/registered/unit/managers/test_mamba_checkpoint_depth.py index 9f9fe305ba..b3250a6917 100644 --- a/test/registered/unit/managers/test_mamba_checkpoint_depth.py +++ b/test/registered/unit/managers/test_mamba_checkpoint_depth.py @@ -54,6 +54,7 @@ def _track_seqlen( vocab_size=128, ) req.prefix_indices = torch.arange(prefix_len, dtype=torch.int64) + req.prefix_len = len(req.prefix_indices) req.set_extend_range(prefix_len, prefix_len + extend_len) req.kv.mamba_ping_pong_track_buffer = torch.tensor([0, 1], dtype=torch.int64) req.kv.mamba_next_track_idx = 0 diff --git a/test/registered/unit/managers/test_prefill_adder.py b/test/registered/unit/managers/test_prefill_adder.py index 44a5d95b83..e7cd0d1c18 100644 --- a/test/registered/unit/managers/test_prefill_adder.py +++ b/test/registered/unit/managers/test_prefill_adder.py @@ -1,3 +1,4 @@ +import functools import unittest from types import SimpleNamespace from unittest.mock import MagicMock, patch @@ -123,7 +124,8 @@ class TestPrefillAdder(CustomTestCase): req.rid = str(rid) req.cache_request_handle = CacheRequestHandle(req.rid, 0) req.priority = priority - req.prefix_indices = [] + req.set_prefix_indices = functools.partial(Req.set_prefix_indices, req) + req.set_prefix_indices(torch.empty((0,), dtype=torch.int64)) req.full_untruncated_fill_ids = [] req.output_ids = [0] * output_len req.sampling_params = SimpleNamespace(max_new_tokens=max_new_tokens) @@ -260,6 +262,7 @@ class TestPrefillAdder(CustomTestCase): req = self.create_shared_req("host-miss") req.full_untruncated_fill_ids = list(range(1024)) req.prefix_indices = torch.empty(0, dtype=torch.int64) + req.prefix_len = len(req.prefix_indices) req.host_hit_length = 768 req.best_match_node = req.last_node req.needs_host_load_back.return_value = True @@ -841,6 +844,7 @@ class TestPrefillAdder(CustomTestCase): def create_sharded_req(self, rid, *, prefix_len=12, extend_len=4): req = self.create_shared_req(rid, max_new_tokens=1) req.prefix_indices = list(range(prefix_len)) + req.prefix_len = len(req.prefix_indices) req.full_untruncated_fill_ids = list(range(prefix_len + extend_len)) return req @@ -1040,6 +1044,7 @@ class TestPrefillAdder(CustomTestCase): req = self.create_mock_req("chunked", priority=0, max_new_tokens=128) req.prefix_indices = [] + req.prefix_len = len(req.prefix_indices) req.full_untruncated_fill_ids = list(range(extend_input_len)) # set_extend_range is the only writer of extend_range; the production # path reads req.extend_range.length right after calling it, so the mock @@ -1152,6 +1157,7 @@ class TestPrefillAdder(CustomTestCase): "resume", priority=0, max_new_tokens=40, output_len=10 ) req.prefix_indices = list(range(PREFIX)) + req.prefix_len = len(req.prefix_indices) req.full_untruncated_fill_ids = list(range(PREFIX + EXTEND)) req.host_hit_length = 0 req.swa_host_hit_length = 0 @@ -1202,6 +1208,7 @@ class TestPrefillAdder(CustomTestCase): ) req = self.create_mock_req("dropped-fetch", priority=0, max_new_tokens=8) req.prefix_indices = torch.empty(0, dtype=torch.int64) + req.prefix_len = len(req.prefix_indices) req.full_untruncated_fill_ids = list(range(SPAN)) req.host_hit_length = HOST_HIT req.swa_host_hit_length = WINDOW @@ -1435,6 +1442,7 @@ class TestPrefillAdder(CustomTestCase): def _create_host_hit_req(self, *, prefix_len=0, host_hit=8192, tail=1024): req = self._create_delayer_req(prefix_len + host_hit + tail) req.prefix_indices = torch.arange(prefix_len) + req.prefix_len = len(req.prefix_indices) req.host_hit_length = host_hit req.needs_host_load_back.return_value = True req.best_match_node = req.last_node diff --git a/test/registered/unit/managers/test_priority_scheduling_disaggregation.py b/test/registered/unit/managers/test_priority_scheduling_disaggregation.py index cb1960cd19..ade294a128 100644 --- a/test/registered/unit/managers/test_priority_scheduling_disaggregation.py +++ b/test/registered/unit/managers/test_priority_scheduling_disaggregation.py @@ -33,6 +33,7 @@ from sglang.srt.observability import req_time_stats from sglang.srt.observability.req_time_stats import SchedulerReqTimeStats from sglang.srt.runtime_context import get_context, publish, reset_context # noqa: E402 from sglang.srt.server_args import ServerArgs +from sglang.srt.utils.common import Range from sglang.test.ci.ci_register import register_cpu_ci from sglang.test.separate_buffer_allocator_double import ( bind_separate_buffer_capacity, @@ -208,6 +209,7 @@ class TestOptimisticPrefillCacheOwnership(unittest.TestCase): cache_protected_len=2, ), prefix_indices=torch.tensor([8, 9], dtype=torch.int64), + prefix_len=2, priority=3, extra_key=None, cache_salt=None, @@ -279,7 +281,6 @@ class TestOptimisticPrefillCacheOwnership(unittest.TestCase): with envs.SGLANG_OPT_UNIFIED_CACHE_FREE_OUT_OF_WINDOW_SLOTS.override(True): cache.advance_unpublished_req(req) - self.assertTrue(torch.equal(req.prefix_indices, torch.tensor([8, 9, 10, 11]))) self.assertEqual(req.kv.cache_protected_len, 2) self.assertIs(req.last_node, last_node) prepare_params = component.prepare_for_caching_req.call_args.kwargs[ @@ -343,12 +344,21 @@ class TestOptimisticPrefillCacheOwnership(unittest.TestCase): cache = UnifiedRadixCache.__new__(UnifiedRadixCache) cache.cache_controller = SimpleNamespace(write_policy="write_through") cache.advance_unpublished_req = MagicMock() + cache.req_to_token_pool = SimpleNamespace( + req_to_token=torch.arange(8, dtype=torch.int32).reshape(1, 8) + ) scheduler.tree_cache = cache - req = SimpleNamespace(pending_bootstrap=True) + req = SimpleNamespace( + pending_bootstrap=True, + kv=SimpleNamespace(req_pool_idx=0), + extend_range=Range(0, 5), + ) SchedulerDisaggregationPrefillMixin.checkpoint_disagg_prefill(scheduler, req) cache.advance_unpublished_req.assert_called_once_with(req) + # The next chunk still resumes after this one. + self.assertEqual(req.prefix_len, 5) def test_bootstrap_success_publishes_once(self): scheduler = SimpleNamespace( diff --git a/test/registered/unit/managers/test_schedule_batch_out_of_place.py b/test/registered/unit/managers/test_schedule_batch_out_of_place.py index 0da8845ea2..74cadc23ed 100644 --- a/test/registered/unit/managers/test_schedule_batch_out_of_place.py +++ b/test/registered/unit/managers/test_schedule_batch_out_of_place.py @@ -243,6 +243,7 @@ class TestPrepareEncoderInfoExtendOutOfPlace(unittest.TestCase): rid="img", multimodal_inputs=types.SimpleNamespace(num_image_tokens=2), prefix_indices=[], + prefix_len=0, extend_range=Range(0, 5), logprob_start_len=0, ) @@ -250,6 +251,7 @@ class TestPrepareEncoderInfoExtendOutOfPlace(unittest.TestCase): rid="txt", multimodal_inputs=None, prefix_indices=[], + prefix_len=0, extend_range=Range(0, 4), logprob_start_len=0, ) diff --git a/test/registered/unit/managers/test_schedule_policy.py b/test/registered/unit/managers/test_schedule_policy.py index 45ce93734a..80833f051b 100644 --- a/test/registered/unit/managers/test_schedule_policy.py +++ b/test/registered/unit/managers/test_schedule_policy.py @@ -140,6 +140,7 @@ class TestShortestPrefillFirst(CustomTestCase): req.full_untruncated_fill_ids = req.origin_input_ids[:] req.num_matched_prefix_tokens = cached req.prefix_indices = list(range(cached)) + req.prefix_len = len(req.prefix_indices) req.time_stats.wait_queue_entry_time = arrived return req diff --git a/test/registered/unit/managers/test_scheduler_chunked_req_gate.py b/test/registered/unit/managers/test_scheduler_chunked_req_gate.py index a9198ed10a..97674c5ca9 100644 --- a/test/registered/unit/managers/test_scheduler_chunked_req_gate.py +++ b/test/registered/unit/managers/test_scheduler_chunked_req_gate.py @@ -35,6 +35,7 @@ def _make_req( req.output_ids = array("q") req.full_untruncated_fill_ids = array("q", fill_ids) req.prefix_indices = prefix_indices + req.prefix_len = len(req.prefix_indices) req.extend_range = Range(fill_len - extend_input_len, fill_len) req.inflight_middle_chunks = 0 req.host_hit_length = 0 @@ -117,7 +118,7 @@ def _scheduler_for_get_next_batch(*, tree_cache, chunked_req) -> Scheduler: return s -class TestStashGatePreservesPrefixIndices(CustomTestCase): +class TestStashGatePreservesPrefix(CustomTestCase): """Consumer side: real ChunkCache.checkpoint mutates req.prefix_indices iff stash actually runs, so prefix_indices content is the bug-detection signal. The stash gate is content-based: @@ -146,32 +147,28 @@ class TestStashGatePreservesPrefixIndices(CustomTestCase): s = _scheduler_for_get_next_batch(tree_cache=cache, chunked_req=req) return s, req, initial_prefix, pool - def test_parked_chunked_req_keeps_real_prefix_indices(self): - # A parked chunk has fill_len == len(prefix_indices): no new KV was - # computed, so the gate must skip stash and leave prefix_indices intact. + def test_parked_chunked_req_keeps_its_prefix(self): + # A parked chunk has fill_len == prefix_len: no new KV was computed, + # so the gate must skip stash and leave the prefix intact. s, req, initial_prefix, _ = self._build(fill_len=self.INITIAL_PREFIX_LEN) Scheduler.get_next_batch_to_run( s, running_batch=s.running_batch, last_batch=s.last_batch ) - self.assertEqual(req.prefix_indices.shape[0], self.INITIAL_PREFIX_LEN) + self.assertEqual(req.prefix_len, self.INITIAL_PREFIX_LEN) self.assertTrue(torch.equal(req.prefix_indices, initial_prefix)) - def test_scheduled_chunked_req_advances_prefix_indices_via_real_stash(self): + def test_scheduled_chunked_req_advances_prefix_via_real_stash(self): # Symmetric guard against over-gating: when fill_len has advanced past - # the cached prefix, stash must run and advance prefix_indices. + # the cached prefix, stash must run and advance prefix_len. s, req, _, pool = self._build(fill_len=self.POST_RESET_FILL_LEN) Scheduler.get_next_batch_to_run( s, running_batch=s.running_batch, last_batch=s.last_batch ) - expected = pool.req_to_token[self.POOL_IDX, : self.POST_RESET_FILL_LEN].to( - dtype=torch.int64 - ) - self.assertEqual(req.prefix_indices.shape[0], self.POST_RESET_FILL_LEN) - self.assertTrue(torch.equal(req.prefix_indices, expected)) + self.assertEqual(req.prefix_len, self.POST_RESET_FILL_LEN) def test_no_chunked_req_never_mutates_state(self): # The outer `if chunked_req is not None` guard must hold on the retract diff --git a/test/registered/unit/mem_cache/test_decode_radix_lock_ref.py b/test/registered/unit/mem_cache/test_decode_radix_lock_ref.py index d5c0ccfa12..6dbb9d3af3 100644 --- a/test/registered/unit/mem_cache/test_decode_radix_lock_ref.py +++ b/test/registered/unit/mem_cache/test_decode_radix_lock_ref.py @@ -101,6 +101,7 @@ class MockReq: self.extra_key = None self.cache_salt = None self.prefix_indices = torch.empty(0, dtype=torch.int64) + self.prefix_len = len(self.prefix_indices) self.priority = 0 self.kv = ReqKvInfo( req_pool_idx=req_pool_idx, diff --git a/test/registered/unit/mem_cache/test_dllm_fdfo_kv_reuse.py b/test/registered/unit/mem_cache/test_dllm_fdfo_kv_reuse.py index 2a43d7d466..0ced064bd9 100644 --- a/test/registered/unit/mem_cache/test_dllm_fdfo_kv_reuse.py +++ b/test/registered/unit/mem_cache/test_dllm_fdfo_kv_reuse.py @@ -66,6 +66,7 @@ def _make_req(rid, prefix, block_size, *, req_pool_idx=None, reuse=False): return SimpleNamespace( rid=rid, prefix_indices=torch.tensor(prefix, dtype=torch.int32), + prefix_len=len(prefix), dllm_incomplete_ids=array("q", range(block_size)) if reuse else array("q"), inflight_middle_chunks=1 if req_pool_idx is not None else 0, kv=ReqKvInfo( diff --git a/test/registered/unit/mem_cache/test_hicache_staged_write_back_dispatch.py b/test/registered/unit/mem_cache/test_hicache_staged_write_back_dispatch.py index 2f9ecbb156..088bf246ce 100644 --- a/test/registered/unit/mem_cache/test_hicache_staged_write_back_dispatch.py +++ b/test/registered/unit/mem_cache/test_hicache_staged_write_back_dispatch.py @@ -9,6 +9,7 @@ from unittest import mock import torch from sglang.srt.managers.cache_controller import CacheOperation, HiCacheController +from sglang.srt.managers.schedule_batch import Req from sglang.srt.mem_cache import l2_transfer as transfer_module from sglang.srt.mem_cache.base_prefix_cache import CacheRequestHandle from sglang.srt.mem_cache.buffer_mode.pipeline import BufferModePipeline @@ -34,6 +35,11 @@ from sglang.srt.mem_cache.pool_host.mla import MLATokenToKVPoolHost from sglang.test.ci.ci_register import register_cpu_ci from sglang.test.test_utils import CustomTestCase + +class _ReqStub(SimpleNamespace): + set_prefix_indices = Req.set_prefix_indices + + register_cpu_ci(est_time=10, suite="base-a-test-cpu") MEMORY_POOL_HOST_MODULE = "sglang.srt.mem_cache.memory_pool_host" @@ -310,10 +316,11 @@ class TestHiCacheStagedWriteBackDispatch(CustomTestCase): pipeline._cache.tree_core.collect_full_device_indices.return_value = _indices( 0, 6 ) - req = SimpleNamespace( + req = _ReqStub( rid="r", cache_request_handle=handle, prefix_indices=_indices(0, 0), + prefix_len=0, kv=SimpleNamespace(cache_protected_len=0), ) self.assertTrue(pipeline.prepare_staged_prefetch(req)) @@ -326,10 +333,11 @@ class TestHiCacheStagedWriteBackDispatch(CustomTestCase): pipeline._cache.tree_core.collect_full_device_indices.return_value = _indices( 0, 6 ) - req = SimpleNamespace( + req = _ReqStub( rid="r", cache_request_handle=handle, prefix_indices=_indices(0, 0), + prefix_len=0, kv=SimpleNamespace(cache_protected_len=0), ) self.assertTrue(pipeline.prepare_staged_prefetch(req)) diff --git a/test/registered/unit/mem_cache/test_hisparse_allocator.py b/test/registered/unit/mem_cache/test_hisparse_allocator.py index 6da4199370..84510b1b0d 100644 --- a/test/registered/unit/mem_cache/test_hisparse_allocator.py +++ b/test/registered/unit/mem_cache/test_hisparse_allocator.py @@ -247,6 +247,12 @@ class TestDeepSeekV4HiSparseAllocator(CustomTestCase): req.set_extend_range = set_extend_range + def set_prefix_indices(prefix_indices): + req.prefix_indices = prefix_indices + req.prefix_len = len(prefix_indices) + + req.set_prefix_indices = set_prefix_indices + class ReqToTokenPool: def __init__(self): self.writes = [] diff --git a/test/registered/unit/mem_cache/test_lmcache_component_cursors.py b/test/registered/unit/mem_cache/test_lmcache_component_cursors.py index 5313b2fc83..3c82186fbe 100644 --- a/test/registered/unit/mem_cache/test_lmcache_component_cursors.py +++ b/test/registered/unit/mem_cache/test_lmcache_component_cursors.py @@ -121,7 +121,6 @@ def test_mamba_publication_snapshots_component_cursors(cache_class, swa_enabled) assert req.lock.receipt.node_id == 42 assert flow.prefix_published assert flow.mamba_value is None - assert req.prefix_indices.tolist() == list(range(12)) if __name__ == "__main__": diff --git a/test/registered/unit/mem_cache/test_page_interleave_shard.py b/test/registered/unit/mem_cache/test_page_interleave_shard.py index e0a8592b02..8e0f0fd1d5 100644 --- a/test/registered/unit/mem_cache/test_page_interleave_shard.py +++ b/test/registered/unit/mem_cache/test_page_interleave_shard.py @@ -785,6 +785,7 @@ class _GraftReq: self.extra_key = None self.cache_salt = None self.prefix_indices = torch.empty(0, dtype=torch.int64) + self.prefix_len = len(self.prefix_indices) self.last_node = None self.priority = 0 self.kv_rotation_base = None @@ -918,7 +919,8 @@ class TestRotationGraftDecline(_TreeCoreBackendCase): tree.checkpoint(req, up_to=len(req.fill_ids)) # No dedup free, no rebind: the request keeps its own locs whole. self.assertEqual([t.tolist() for t in freed], []) - self.assertTrue(torch.equal(req.prefix_indices, own_locs)) + row = tree.req_to_token_pool.req_to_token[req.kv.req_pool_idx, :12] + self.assertTrue(torch.equal(row.to(dtype=torch.int64), own_locs)) self.assertEqual(req.kv.cache_protected_len, 0) self.assertTrue( torch.equal(tree.req_to_token_pool.req_to_token[0, :12], own_locs) diff --git a/test/registered/unit/mem_cache/test_prefill_memory_budget.py b/test/registered/unit/mem_cache/test_prefill_memory_budget.py index c686c377ce..f86ff1f152 100644 --- a/test/registered/unit/mem_cache/test_prefill_memory_budget.py +++ b/test/registered/unit/mem_cache/test_prefill_memory_budget.py @@ -205,6 +205,7 @@ class TestSharedPrefillAdmission(unittest.TestCase): with self.subTest(page_size=page_size): allocator, req, adder = self._new_admission(page_size, pool_pages=6) req.prefix_indices = allocator.alloc(page_size) + req.prefix_len = len(req.prefix_indices) self.assertIsNotNone(req.prefix_indices) self.assertTrue(allocator.can_reserve(page_size + 2, page_size + 2)) diff --git a/test/registered/unit/mem_cache/test_radix_force_miss.py b/test/registered/unit/mem_cache/test_radix_force_miss.py index 071a391587..4d3ba3019a 100644 --- a/test/registered/unit/mem_cache/test_radix_force_miss.py +++ b/test/registered/unit/mem_cache/test_radix_force_miss.py @@ -16,6 +16,7 @@ from types import SimpleNamespace import torch from sglang.srt.environ import envs +from sglang.srt.managers.schedule_batch import Req from sglang.srt.mem_cache.base_prefix_cache import ( InsertParams, MatchPrefixParams, @@ -33,6 +34,7 @@ class _StubReq: self.extra_key = None self.cache_salt = None self.prefix_indices = None + self.prefix_len = 0 self.last_node = None self.last_host_node = None self.best_match_node = None @@ -41,6 +43,8 @@ class _StubReq: self.swa_branching_seqlen = None self.kv = SimpleNamespace(cache_protected_len=None) + set_prefix_indices = Req.set_prefix_indices + def _compute_max_prefix_len(self, input_len): return max(input_len - 1, 0) diff --git a/test/registered/unit/mem_cache/test_storage_prefetch_lifecycle.py b/test/registered/unit/mem_cache/test_storage_prefetch_lifecycle.py index a1dfab1608..890b7f5867 100644 --- a/test/registered/unit/mem_cache/test_storage_prefetch_lifecycle.py +++ b/test/registered/unit/mem_cache/test_storage_prefetch_lifecycle.py @@ -11,7 +11,7 @@ from unittest.mock import Mock import torch -from sglang.srt.managers.schedule_batch import split_cached_prefix_by_tier +from sglang.srt.managers.schedule_batch import Req, split_cached_prefix_by_tier from sglang.srt.mem_cache.base_prefix_cache import ( CacheRequestHandle, InitLoadBackParams, @@ -33,6 +33,11 @@ from sglang.srt.mem_cache.unified_radix_cache import ( from sglang.srt.mem_cache.utils import get_hash_str from sglang.test.ci.ci_register import register_cpu_ci + +class _ReqStub(SimpleNamespace): + set_prefix_indices = Req.set_prefix_indices + + register_cpu_ci(est_time=20, suite="base-a-test-cpu") _REQ = CacheRequestHandle("r", 0) @@ -109,10 +114,11 @@ def _staged_fixture(full_match=2): hash_values=["a", "b", "c"], operation_id=1, ) - req = SimpleNamespace( + req = _ReqStub( rid="r", cache_request_handle=_REQ, prefix_indices=torch.arange(2), + prefix_len=2, last_node=1, kv=SimpleNamespace(cache_protected_len=2), extra_key=None, @@ -202,6 +208,7 @@ def _two_rank_retry_trace(rank, rendezvous): full_match, ) req.prefix_indices = torch.arange(full_match) + req.prefix_len = len(req.prefix_indices) if cache.buffer_pipeline.prepare_staged_prefetch(req): assert ( cache.init_load_back( @@ -303,6 +310,7 @@ class TestStagedPrefetchLifecycle(unittest.TestCase): ) # A joint match counts bigrams, not their extra raw boundary token. req.prefix_indices = torch.arange(10) + req.prefix_len = len(req.prefix_indices) req.kv.cache_protected_len = 10 self.assertTrue(pipeline.prepare_staged_prefetch(req)) self.assertFalse(pipeline.has_staged(req.cache_request_handle)) @@ -345,6 +353,7 @@ class TestStagedPrefetchLifecycle(unittest.TestCase): # A twin made [0, 6) jointly reusable while the fetch was held. cache.tree_core.match_full_device_prefix.return_value = (8, 1, 8) req.prefix_indices = torch.arange(6) + req.prefix_len = len(req.prefix_indices) self.assertTrue(pipeline.prepare_staged_prefetch(req)) self.assertEqual( split_cached_prefix_by_tier( @@ -382,6 +391,7 @@ class TestStagedPrefetchLifecycle(unittest.TestCase): # A twin finished first: the next pass's joint match runs past the # staged span and is kept as is (a shrink would strand its recompute). req.prefix_indices = torch.arange(12) + req.prefix_len = len(req.prefix_indices) req.last_node = 9 req.kv.cache_protected_len = 12 self.assertTrue(cache.buffer_pipeline.prepare_staged_prefetch(req)) @@ -416,6 +426,7 @@ class TestStagedPrefetchLifecycle(unittest.TestCase): cache.tree_core.match_full_device_prefix.reset_mock() for attempt in range(1, 4): req.prefix_indices = torch.arange(2) + req.prefix_len = len(req.prefix_indices) self.assertTrue(cache.buffer_pipeline.prepare_staged_prefetch(req)) self.assertIsNone( cache.init_load_back( @@ -457,6 +468,7 @@ class TestStagedPrefetchLifecycle(unittest.TestCase): # Tree changes occur while queued, before the next preparation pass. cache.tree_core.match_full_device_prefix.return_value = (6, 1, 6) req.prefix_indices = torch.arange(2) + req.prefix_len = len(req.prefix_indices) self.assertTrue(cache.buffer_pipeline.prepare_staged_prefetch(req)) self.assertEqual((req.host_hit_length, req.swa_host_hit_length), (2, 4)) self.assertTrue(pipeline.has_staged(req.cache_request_handle)) @@ -464,6 +476,7 @@ class TestStagedPrefetchLifecycle(unittest.TestCase): cache.tree_core.match_full_device_prefix.return_value = (0, 0, 0) req.prefix_indices = torch.arange(0) + req.prefix_len = len(req.prefix_indices) self.assertFalse(cache.buffer_pipeline.prepare_staged_prefetch(req)) self.assertFalse(pipeline.has_staged(req.cache_request_handle)) self.assertEqual( @@ -516,6 +529,7 @@ class TestStagedPrefetchLifecycle(unittest.TestCase): params = lambda: InitLoadBackParams(None, req.host_hit_length, req=req) for attempt in range(1, 4): req.prefix_indices = torch.arange(2) + req.prefix_len = len(req.prefix_indices) self.assertTrue(pipeline.prepare_staged_prefetch(req)) self.assertIsNone(cache.init_load_back(params())) self.assertEqual(pipeline.has_staged(req.cache_request_handle), attempt < 3) diff --git a/test/registered/unit/mem_cache/test_unified_cache_linker.py b/test/registered/unit/mem_cache/test_unified_cache_linker.py index 01760d66ed..79fe0795c3 100644 --- a/test/registered/unit/mem_cache/test_unified_cache_linker.py +++ b/test/registered/unit/mem_cache/test_unified_cache_linker.py @@ -1316,6 +1316,7 @@ def test_linker_load_preserves_swa_boundaries( rid="rid", kv=kv, prefix_indices=torch.empty(0, dtype=torch.int64), + prefix_len=0, last_node=0, priority=0, ) diff --git a/test/registered/unit/mem_cache/test_unified_radix_cache_unittest.py b/test/registered/unit/mem_cache/test_unified_radix_cache_unittest.py index 67986f71b5..dcefa86a3f 100644 --- a/test/registered/unit/mem_cache/test_unified_radix_cache_unittest.py +++ b/test/registered/unit/mem_cache/test_unified_radix_cache_unittest.py @@ -1,6 +1,7 @@ """Unit tests for UnifiedRadixCache""" import atexit +import functools import json import shutil import sys @@ -121,6 +122,11 @@ from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci from sglang.test.mem_cache_utils import finish_req from sglang.test.test_utils import CustomTestCase + +class _ReqStub(SimpleNamespace): + set_prefix_indices = Req.set_prefix_indices + + register_cuda_ci(est_time=60, stage="base-b", runner_config="1-gpu-small") register_amd_ci(est_time=50, suite="stage-b-test-1-gpu-small-amd") @@ -1597,6 +1603,7 @@ class UnifiedRadixCacheSuite: def _apply_match_to_req(self, req, match): req.prefix_indices = match.device_indices + req.prefix_len = len(req.prefix_indices) req.last_node = match.last_device_node req.last_host_node = match.last_host_node req.best_match_node = match.best_match_node @@ -2012,8 +2019,7 @@ class UnifiedRadixCacheSuite: cache.checkpoint(req, up_to=req.extend_range.end) - self.assertGreater(len(req.prefix_indices), 0) - self.assertEqual(req.kv.cache_protected_len, len(req.prefix_indices)) + self.assertGreater(req.kv.cache_protected_len, 0) self.assertIsNotNone(req.last_node) self.assertFalse(req.lock.swa_released) @@ -3476,12 +3482,14 @@ class UnifiedRadixCacheSuite: # bogus slots into the tree). assert len(prefix_indices) == prefix_len req.prefix_indices = prefix_indices + req.prefix_len = len(req.prefix_indices) else: req.prefix_indices = torch.zeros( prefix_len, dtype=torch.int64, device=cache.tree_core.empty_match_result.device_indices.device, ) + req.prefix_len = len(req.prefix_indices) req.last_node = cache.root_node_handle() if last_node is None else last_node joint = cache.match_prefix( MatchPrefixParams( @@ -3491,6 +3499,7 @@ class UnifiedRadixCacheSuite: ) ) req.prefix_indices = joint.device_indices + req.prefix_len = len(req.prefix_indices) joint_covers_span = len(joint.device_indices) >= len(f.key_tokens) adder = PrefillAdder.__new__(PrefillAdder) adder.tree_cache = cache @@ -4513,6 +4522,7 @@ class UnifiedRadixCacheSuite: dtype=torch.int64, device=cons.tree_core.empty_match_result.device_indices.device, ) + req.prefix_len = len(req.prefix_indices) self.assertTrue(cons.buffer_pipeline.prepare_staged_prefetch(req)) spliced, _last = cons.init_load_back( InitLoadBackParams( @@ -4876,10 +4886,11 @@ class UnifiedRadixCacheSuite: self.assertIsNotNone(cons_alloc.swa_attn_allocator.alloc(hold // ps * ps)) # The adder's SWA gate for this request (_swa_budget_for_req). - req = SimpleNamespace( + req = _ReqStub( rid=req_id.rid, cache_request_handle=req_id, prefix_indices=cons.tree_core.empty_match_result.device_indices, + prefix_len=len(cons.tree_core.empty_match_result.device_indices), kv=SimpleNamespace(cache_protected_len=0), ) self.assertTrue(cons.buffer_pipeline.prepare_staged_prefetch(req)) @@ -4905,6 +4916,7 @@ class UnifiedRadixCacheSuite: dtype=torch.int64, device=cons.tree_core.empty_match_result.device_indices.device, ) + req.prefix_len = len(req.prefix_indices) self.assertTrue(cons.buffer_pipeline.prepare_staged_prefetch(req)) spliced, last_node = cons.init_load_back( InitLoadBackParams( @@ -5344,6 +5356,7 @@ class UnifiedRadixCacheSuite: dtype=torch.int64, device=cons.tree_core.empty_match_result.device_indices.device, ) + req.prefix_len = len(req.prefix_indices) req.last_node = cons.root_node_handle() self.assertTrue(cons.buffer_pipeline.prepare_staged_prefetch(req)) with mock.patch.object(cons.cache_controller, "load", adversarial_load): @@ -5429,10 +5442,11 @@ class UnifiedRadixCacheSuite: self.assertGreater(aux_max, len(seq) - len(head)) # The surfaced host hit is the splice-able tail, not the full span. - req = SimpleNamespace( + req = _ReqStub( rid=req_id.rid, cache_request_handle=req_id, prefix_indices=sib.device_indices, + prefix_len=len(sib.device_indices), kv=SimpleNamespace(cache_protected_len=len(sib.device_indices)), ) self.assertTrue(cons.buffer_pipeline.prepare_staged_prefetch(req)) @@ -5500,8 +5514,10 @@ class UnifiedRadixCacheSuite: rid=req_id.rid, cache_request_handle=req_id, prefix_indices=live.device_indices, + prefix_len=len(live.device_indices), last_node=live.last_device_node, ) + req.set_prefix_indices = functools.partial(Req.set_prefix_indices, req) self.assertTrue(cons.buffer_pipeline.prepare_staged_prefetch(req)) self.assertEqual((req.host_hit_length, req.swa_host_hit_length), (0, 0)) self.assertFalse(cons.buffer_pipeline.has_staged(req_id)) diff --git a/tools/sglang-simulator/src/sglang_simulator/simulation/sglang/scheduler.py b/tools/sglang-simulator/src/sglang_simulator/simulation/sglang/scheduler.py index cd9ae04b60..eedf4cde7a 100644 --- a/tools/sglang-simulator/src/sglang_simulator/simulation/sglang/scheduler.py +++ b/tools/sglang-simulator/src/sglang_simulator/simulation/sglang/scheduler.py @@ -74,7 +74,7 @@ class C_SglangPrefillAdderHook(BaseHook): **kwargs, ) req_infos = request_stats_manager.get_req_stats(req.rid) - req_infos.before_adder_device_hit_len = len(req.prefix_indices) + req_infos.before_adder_device_hit_len = req.prefix_len req_infos.final_host_hit_len = req.host_hit_length return original_add_one_req(self, *args, **kwargs) @@ -411,7 +411,7 @@ class C_SchedulerHook(BaseHook): **kwargs, ) req_stats = request_stats_manager.get_req_stats(req.rid) - req_stats.recv_device_hit_len = len(req.prefix_indices) + req_stats.recv_device_hit_len = req.prefix_len req_stats.recv_host_hit_len = req.host_hit_length def wrapped_run_batch(self, *args, **kwargs): @@ -432,8 +432,7 @@ class C_SchedulerHook(BaseHook): simulation_batch.reqs.append( ScheduleRequest( extend_length=extend_length, - past_kv_length=len(req.prefix_indices) - + len(req.output_ids), + past_kv_length=req.prefix_len + len(req.output_ids), ) ) elif batch.forward_mode.is_decode(): @@ -441,8 +440,7 @@ class C_SchedulerHook(BaseHook): simulation_batch.reqs.append( ScheduleRequest( extend_length=1, - past_kv_length=len(req.prefix_indices) - + len(req.output_ids), + past_kv_length=req.prefix_len + len(req.output_ids), ) )