[Scheduler] Track prefill progress as prefix_len (#42824)

This commit is contained in:
Liangsheng Yin
2026-10-07 15:59:06 -07:00
committed by GitHub
parent 79ef49cb6b
commit e9240b3243
45 changed files with 239 additions and 200 deletions
+8 -8
View File
@@ -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
+5 -9
View File
@@ -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)
@@ -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
@@ -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
+3 -4
View File
@@ -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
+3 -3
View File
@@ -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:
@@ -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(
+32 -22
View File
@@ -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
+21 -35
View File
@@ -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
)
+6 -9
View File
@@ -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
@@ -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(
@@ -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:
+15 -2
View File
@@ -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,
@@ -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}: "
+1 -3
View File
@@ -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()
+6 -13
View File
@@ -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(
+2 -12
View File
@@ -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):
@@ -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
@@ -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:**
@@ -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
@@ -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:
@@ -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 --