[mem_cache] Drop is_insert from cache_finished_req; release rows from release_kv_cache (#40988)
This commit is contained in:
@@ -1555,12 +1555,10 @@ class SchedulerDisaggregationPrefillMixin:
|
||||
)
|
||||
self._release_aborted_request(req)
|
||||
# Mamba insertion donates the checkpoint and clears its sequence marker.
|
||||
release_kv_cache(
|
||||
req,
|
||||
self.tree_cache,
|
||||
is_insert=not uses_write_through_cache
|
||||
and not self.tree_cache.supports_mamba(),
|
||||
is_insert = (
|
||||
not uses_write_through_cache and not self.tree_cache.supports_mamba()
|
||||
)
|
||||
release_kv_cache(req, self.tree_cache, is_insert=is_insert)
|
||||
req.reset_for_retract()
|
||||
req.output_ids = array("q")
|
||||
req.start_send_idx = 0
|
||||
|
||||
@@ -418,18 +418,12 @@ class BasePrefixCache(ABC, PrefixCacheTrait):
|
||||
return None
|
||||
|
||||
@abstractmethod
|
||||
def cache_finished_req(
|
||||
self, req: Req, is_insert: bool = True, *, owned_kv_len: int, **kwargs
|
||||
):
|
||||
"""Dispose of a finished request's KV.
|
||||
|
||||
``[0, req.kv.cache_protected_len)`` is cache-owned and must survive.
|
||||
Every slot in ``[req.kv.cache_protected_len, owned_kv_len)`` is this
|
||||
call's to account for: insert what can be keyed, release the rest.
|
||||
Slicing the kv row by the token-id count instead strands whatever
|
||||
lies between -- no caller releases those. ``release_kv_cache`` frees
|
||||
everything past ``owned_kv_len``.
|
||||
"""
|
||||
def cache_finished_req(self, req: Req, *, owned_kv_len: int, **kwargs):
|
||||
"""Hand a finished request's KV to the tree: insert what can be keyed
|
||||
(advancing ``cache_protected_len``), ``free_kv_row`` the rest of
|
||||
``[cache_protected_len, owned_kv_len)``, ``unpin``. Slicing the row by
|
||||
token count instead strands the slots up to ``owned_kv_len``; the
|
||||
caller frees everything past it."""
|
||||
|
||||
@abstractmethod
|
||||
def cache_unfinished_req(self, req: Req, **kwargs):
|
||||
@@ -476,6 +470,21 @@ class BasePrefixCache(ABC, PrefixCacheTrait):
|
||||
) -> DecLockRefResult:
|
||||
pass
|
||||
|
||||
def unpin(self, req: Req) -> None:
|
||||
"""Drop the tree lock the request holds on ``req.last_node``; a cache
|
||||
whose acquire returned a receipt releases with it here."""
|
||||
if req.last_node is not None:
|
||||
self.dec_lock_ref(req.last_node)
|
||||
|
||||
def claim_kv_row(self, req: Req) -> bool:
|
||||
"""A streaming session keeps the request's kv row for the next turn.
|
||||
Return True after taking the row; the caller then releases nothing."""
|
||||
return False
|
||||
|
||||
def on_release(self, req: Req, *, inserted: bool) -> None:
|
||||
"""The row is freed and the lock dropped; ``inserted`` says whether the
|
||||
KV went into the tree first. Drop per-request state kept outside the tree."""
|
||||
|
||||
def evictable_size(self):
|
||||
return 0
|
||||
|
||||
|
||||
@@ -76,12 +76,11 @@ class ChunkCache(BasePrefixCache):
|
||||
# ChunkCache does not support prefix caching, so insert is a no-op
|
||||
return InsertResult(prefix_len=0)
|
||||
|
||||
def cache_finished_req(
|
||||
self, req: Req, is_insert: bool = True, *, owned_kv_len: int
|
||||
):
|
||||
def cache_finished_req(self, req: Req, *, owned_kv_len: int):
|
||||
# For decode server: if req.output_ids is empty, we want to free all req.origin_input_ids
|
||||
# The protected prefix is not this req's to free.
|
||||
self.free_kv_row(req.kv, [(req.kv.cache_protected_len, owned_kv_len)])
|
||||
self.unpin(req)
|
||||
|
||||
def cache_unfinished_req(self, req: Req, chunked=False):
|
||||
kv_indices = self.req_to_token_pool.req_to_token[
|
||||
|
||||
@@ -160,7 +160,7 @@ def free_kv_row_segments(
|
||||
|
||||
|
||||
def maybe_cache_unfinished_req(req: Req, tree_cache: BasePrefixCache, **kwargs):
|
||||
if getattr(req, "skip_radix_cache_insert", False):
|
||||
if req.skip_radix_cache_insert:
|
||||
return
|
||||
|
||||
tree_cache.cache_unfinished_req(req, **kwargs)
|
||||
@@ -280,6 +280,8 @@ def discard_kv_cache_backup(
|
||||
|
||||
|
||||
def release_kv_cache(req: Req, tree_cache: BasePrefixCache, is_insert: bool = True):
|
||||
"""Give the request's kv row back; with ``is_insert`` the tree first keeps
|
||||
what it can key."""
|
||||
assert (not req.kv.holds_kv) == req.kv.is_kv_released
|
||||
# A mamba-capable cache may alloc mamba state before alloc KV cache
|
||||
if not req.kv.holds_kv:
|
||||
@@ -293,22 +295,23 @@ def release_kv_cache(req: Req, tree_cache: BasePrefixCache, is_insert: bool = Tr
|
||||
)
|
||||
req.kv.mamba_pool_idx = None
|
||||
return
|
||||
|
||||
owned_kv_len = req.owned_kv_len()
|
||||
tree_cache.cache_finished_req(
|
||||
req,
|
||||
is_insert=is_insert and not getattr(req, "skip_radix_cache_insert", False),
|
||||
owned_kv_len=owned_kv_len,
|
||||
)
|
||||
|
||||
# StreamingSession.cache_finished_req handles speculative tail trim
|
||||
# internally, then sets req_pool_idx = None.
|
||||
assert (not req.kv.holds_kv) == req.kv.is_kv_released
|
||||
if not req.kv.holds_kv:
|
||||
if tree_cache.claim_kv_row(req):
|
||||
# A streaming session detached the kv record to keep the row.
|
||||
assert not req.kv.holds_kv
|
||||
return
|
||||
|
||||
start_p, end_p = owned_kv_len, req.kv.kv_allocated_len
|
||||
_release_overallocated_kv_indices(req, start_p, end_p, tree_cache)
|
||||
owned_kv_len = req.owned_kv_len()
|
||||
is_insert = is_insert and not req.skip_radix_cache_insert
|
||||
if is_insert:
|
||||
tree_cache.cache_finished_req(req, owned_kv_len=owned_kv_len)
|
||||
else:
|
||||
# The protected prefix is not this req's to free.
|
||||
tree_cache.free_kv_row(req.kv, [(req.kv.cache_protected_len, owned_kv_len)])
|
||||
tree_cache.unpin(req)
|
||||
_release_overallocated_kv_indices(
|
||||
req, owned_kv_len, req.kv.kv_allocated_len, tree_cache
|
||||
)
|
||||
tree_cache.on_release(req, inserted=is_insert)
|
||||
|
||||
# If the prefix cache doesn't manage mamba states, we must free them here.
|
||||
if isinstance(tree_cache.req_to_token_pool, HybridReqToTokenPool) and (
|
||||
|
||||
@@ -5,15 +5,10 @@ from __future__ import annotations
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import torch
|
||||
|
||||
from sglang.srt.mem_cache.base_prefix_cache import (
|
||||
EvictParams,
|
||||
EvictResult,
|
||||
InsertParams,
|
||||
)
|
||||
from sglang.srt.mem_cache.base_prefix_cache import EvictParams, EvictResult
|
||||
from sglang.srt.mem_cache.cache_init_params import CacheInitParams
|
||||
from sglang.srt.mem_cache.radix_cache import RadixCache, RadixKey
|
||||
from sglang.srt.mem_cache.radix_cache import RadixCache
|
||||
from sglang.srt.utils.common import ceil_align
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from sglang.srt.managers.schedule_batch import Req
|
||||
@@ -62,53 +57,22 @@ class PureSWARadixCache(RadixCache):
|
||||
num_tokens = max(params.num_tokens, params.swa_num_tokens)
|
||||
return super().evict(EvictParams(num_tokens=num_tokens))
|
||||
|
||||
def cache_finished_req(
|
||||
self, req: Req, is_insert: bool = True, *, owned_kv_len: int
|
||||
):
|
||||
def cache_finished_req(self, req: Req, *, owned_kv_len: int):
|
||||
"""Insert only the prefill portion [0, evict_floor); free_kv_row skips
|
||||
the span _evict_swa already freed during decode."""
|
||||
if self.disable:
|
||||
self.free_kv_row(req.kv, [(req.kv.cache_protected_len, owned_kv_len)])
|
||||
return
|
||||
|
||||
token_ids = (req.origin_input_ids + req.output_ids)[:owned_kv_len]
|
||||
kv_indices = self.req_to_token_pool.req_to_token[
|
||||
req.kv.req_pool_idx, :owned_kv_len
|
||||
]
|
||||
|
||||
radix_key = RadixKey(
|
||||
token_ids,
|
||||
req.extra_key,
|
||||
is_bigram=self.is_eagle,
|
||||
cache_salt=req.cache_salt,
|
||||
).page_aligned(self.page_size)
|
||||
keys_len = len(radix_key)
|
||||
|
||||
old_prefix_len = req.kv.cache_protected_len
|
||||
swa_evict_floor = req.kv.swa_evict_floor
|
||||
if self.page_size > 1 and swa_evict_floor > 0:
|
||||
swa_evict_floor = -(-swa_evict_floor // self.page_size) * self.page_size
|
||||
if swa_evict_floor > 0:
|
||||
insert_end = min(swa_evict_floor, keys_len)
|
||||
else:
|
||||
insert_end = keys_len
|
||||
|
||||
release_from = old_prefix_len
|
||||
if is_insert and insert_end > 0:
|
||||
insert_values = kv_indices[:insert_end].to(dtype=torch.int64, copy=True)
|
||||
result = self.insert(
|
||||
InsertParams(key=radix_key[:insert_end], value=insert_values)
|
||||
if not self.disable:
|
||||
token_ids = (req.origin_input_ids + req.output_ids)[:owned_kv_len]
|
||||
swa_evict_floor = req.kv.swa_evict_floor
|
||||
key_limit = (
|
||||
ceil_align(swa_evict_floor, self.page_size)
|
||||
if swa_evict_floor > 0
|
||||
else None
|
||||
)
|
||||
self.token_to_kv_pool_allocator.free_segment(
|
||||
kv_indices[old_prefix_len : result.prefix_len],
|
||||
start_pos=old_prefix_len,
|
||||
)
|
||||
release_from = insert_end
|
||||
|
||||
self.free_kv_row(req.kv, [(release_from, owned_kv_len)])
|
||||
|
||||
if req.last_node is not None:
|
||||
self.dec_lock_ref(req.last_node)
|
||||
radix_key, _, _ = self._adopt(req, token_ids, key_limit=key_limit)
|
||||
req.kv.cache_protected_len = len(radix_key)
|
||||
# The protected prefix is not this req's to free.
|
||||
self.free_kv_row(req.kv, [(req.kv.cache_protected_len, owned_kv_len)])
|
||||
self.unpin(req)
|
||||
|
||||
def cache_unfinished_req(self, req: Req, chunked=False):
|
||||
"""During chunked prefill, swa_evicted_seqlen is 0 and no SWA eviction
|
||||
|
||||
@@ -433,127 +433,81 @@ class RadixCache(BasePrefixCache):
|
||||
)
|
||||
return InsertResult(prefix_len=prefix_len, last_device_node=last_node)
|
||||
|
||||
def cache_finished_req(
|
||||
self, req: Req, is_insert: bool = True, *, owned_kv_len: int
|
||||
):
|
||||
"""Cache request when it finishes."""
|
||||
if self.disable:
|
||||
# The protected prefix is not this req's to free.
|
||||
kv_indices = self.req_to_token_pool.req_to_token[
|
||||
req.kv.req_pool_idx, req.kv.cache_protected_len : owned_kv_len
|
||||
]
|
||||
self.token_to_kv_pool_allocator.free_segment(
|
||||
kv_indices, start_pos=req.kv.cache_protected_len
|
||||
)
|
||||
return
|
||||
|
||||
if not is_insert:
|
||||
# Frees committed slots that no token id names, which the insert
|
||||
# path below cannot reach; the protected prefix stays with the cache.
|
||||
kv_indices = self.req_to_token_pool.req_to_token[
|
||||
req.kv.req_pool_idx, req.kv.cache_protected_len : owned_kv_len
|
||||
]
|
||||
self.token_to_kv_pool_allocator.free_segment(
|
||||
kv_indices, start_pos=req.kv.cache_protected_len
|
||||
)
|
||||
if req.last_node is not None:
|
||||
self.dec_lock_ref(req.last_node)
|
||||
return
|
||||
|
||||
token_ids = (req.origin_input_ids + req.output_ids)[:owned_kv_len]
|
||||
def _adopt(
|
||||
self,
|
||||
req: Req,
|
||||
token_ids,
|
||||
*,
|
||||
chunked: bool = False,
|
||||
key_limit: Optional[int] = None,
|
||||
split_prompt: bool = False,
|
||||
) -> Tuple[RadixKey, torch.Tensor, int]:
|
||||
"""Insert the page-aligned key of ``token_ids`` (cut at ``key_limit``)
|
||||
and free the duplicates it exposed; returns (key, row slice, matched)."""
|
||||
kv_indices = self.req_to_token_pool.req_to_token[
|
||||
req.kv.req_pool_idx, :owned_kv_len
|
||||
req.kv.req_pool_idx, : len(token_ids)
|
||||
]
|
||||
|
||||
radix_key = RadixKey(
|
||||
token_ids,
|
||||
req.extra_key,
|
||||
is_bigram=self.is_eagle,
|
||||
cache_salt=req.cache_salt,
|
||||
).page_aligned(self.page_size)
|
||||
if key_limit is not None:
|
||||
radix_key = radix_key[:key_limit]
|
||||
key_len = len(radix_key)
|
||||
values = kv_indices[:key_len].to(dtype=torch.int64, copy=True)
|
||||
|
||||
# Radix Cache takes one ref in memory pool
|
||||
priority = getattr(req, "priority", 0) or 0
|
||||
priority = req.priority or 0
|
||||
result = self.insert(
|
||||
InsertParams(key=radix_key, value=values, priority=priority)
|
||||
)
|
||||
# A request that was never cached while unfinished can add its
|
||||
# whole prompt and generated output as one leaf. Split that leaf at
|
||||
# the prompt boundary so LRU eviction can discard output KV without
|
||||
# also losing the reusable prompt KV. Reinserting a prefix only
|
||||
# changes radix topology; it reuses the indices inserted above.
|
||||
prompt_key = RadixKey(
|
||||
token_ids[: len(req.origin_input_ids)],
|
||||
req.extra_key,
|
||||
is_bigram=self.is_eagle,
|
||||
cache_salt=req.cache_salt,
|
||||
).page_aligned(self.page_size)
|
||||
if 0 < len(prompt_key) < key_len:
|
||||
self.insert(
|
||||
InsertParams(
|
||||
key=prompt_key,
|
||||
value=values[: len(prompt_key)],
|
||||
priority=priority + 1,
|
||||
# Topology-only re-insert: this request created these
|
||||
# nodes moments ago, so counting it as a hit is the
|
||||
# same self-referencing inflation `chunked` exists to
|
||||
# suppress. hit_count drives eviction order, so an
|
||||
# extra bump would silently promote every prompt node.
|
||||
chunked=True,
|
||||
)
|
||||
InsertParams(
|
||||
key=radix_key, value=values, chunked=chunked, priority=priority
|
||||
)
|
||||
freed_end = result.prefix_len
|
||||
|
||||
# duplicates / uninserted range, then the unaligned tail
|
||||
self.token_to_kv_pool_allocator.free_segments(
|
||||
[
|
||||
(
|
||||
kv_indices[req.kv.cache_protected_len : freed_end],
|
||||
req.kv.cache_protected_len,
|
||||
),
|
||||
(kv_indices[key_len:], key_len),
|
||||
]
|
||||
)
|
||||
if split_prompt:
|
||||
# Split the leaf at the prompt boundary so eviction can drop the
|
||||
# output KV without the prompt; a prefix re-insert only changes topology.
|
||||
prompt_key = RadixKey(
|
||||
token_ids[: len(req.origin_input_ids)],
|
||||
req.extra_key,
|
||||
is_bigram=self.is_eagle,
|
||||
cache_salt=req.cache_salt,
|
||||
).page_aligned(self.page_size)
|
||||
if 0 < len(prompt_key) < key_len:
|
||||
self.insert(
|
||||
InsertParams(
|
||||
key=prompt_key,
|
||||
value=values[: len(prompt_key)],
|
||||
priority=priority + 1,
|
||||
# The request created these nodes moments ago; another
|
||||
# hit_count bump would promote every prompt node.
|
||||
chunked=True,
|
||||
)
|
||||
)
|
||||
|
||||
# Remove req slot release the cache lock
|
||||
if req.last_node is not None:
|
||||
self.dec_lock_ref(req.last_node)
|
||||
self.token_to_kv_pool_allocator.free_segment(
|
||||
kv_indices[req.kv.cache_protected_len : result.prefix_len],
|
||||
start_pos=req.kv.cache_protected_len,
|
||||
)
|
||||
return radix_key, kv_indices, result.prefix_len
|
||||
|
||||
def cache_finished_req(self, req: Req, *, owned_kv_len: int):
|
||||
"""Cache request when it finishes."""
|
||||
if not self.disable:
|
||||
token_ids = (req.origin_input_ids + req.output_ids)[:owned_kv_len]
|
||||
radix_key, _, _ = self._adopt(req, token_ids, split_prompt=True)
|
||||
req.kv.cache_protected_len = len(radix_key)
|
||||
# The protected prefix is not this req's to free.
|
||||
self.free_kv_row(req.kv, [(req.kv.cache_protected_len, owned_kv_len)])
|
||||
self.unpin(req)
|
||||
|
||||
def cache_unfinished_req(self, req: Req, chunked=False):
|
||||
"""Cache request when it is unfinished."""
|
||||
if self.disable:
|
||||
return
|
||||
|
||||
token_ids = req.get_fill_ids()
|
||||
kv_indices = self.req_to_token_pool.req_to_token[
|
||||
req.kv.req_pool_idx, : len(token_ids)
|
||||
]
|
||||
|
||||
radix_key = RadixKey(
|
||||
token_ids,
|
||||
req.extra_key,
|
||||
is_bigram=self.is_eagle,
|
||||
cache_salt=req.cache_salt,
|
||||
).page_aligned(self.page_size)
|
||||
values = kv_indices[: len(radix_key)].to(dtype=torch.int64, copy=True)
|
||||
|
||||
# Radix Cache takes one ref in memory pool
|
||||
result = self.insert(
|
||||
InsertParams(
|
||||
key=radix_key,
|
||||
value=values,
|
||||
chunked=chunked,
|
||||
priority=getattr(req, "priority", 0) or 0,
|
||||
)
|
||||
)
|
||||
new_prefix_len = result.prefix_len
|
||||
|
||||
self.token_to_kv_pool_allocator.free_segment(
|
||||
kv_indices[req.kv.cache_protected_len : new_prefix_len],
|
||||
start_pos=req.kv.cache_protected_len,
|
||||
)
|
||||
radix_key, kv_indices, _ = self._adopt(req, req.get_fill_ids(), chunked=chunked)
|
||||
|
||||
# The prefix indices could be updated, reuse it
|
||||
match_result = self.match_prefix(MatchPrefixParams(key=radix_key))
|
||||
|
||||
@@ -385,14 +385,15 @@ class FlexKVRadixCache(RadixCache):
|
||||
# cache_finished_req (STORE)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def on_release(self, req: Req, *, inserted: bool) -> None:
|
||||
if not inserted:
|
||||
self._load_markers.pop(req.cache_request_handle, None)
|
||||
|
||||
def cache_finished_req( # type: ignore[override]
|
||||
self, req: Req, is_insert: bool = True, *, owned_kv_len: int
|
||||
self, req: Req, *, owned_kv_len: int
|
||||
) -> None:
|
||||
"""Base cache_finished_req then fire an async FlexKV store."""
|
||||
super().cache_finished_req(req, is_insert=is_insert, owned_kv_len=owned_kv_len)
|
||||
if not is_insert:
|
||||
self._load_markers.pop(req.cache_request_handle, None)
|
||||
return
|
||||
super().cache_finished_req(req, owned_kv_len=owned_kv_len)
|
||||
|
||||
# Compute the committed prefix mirroring LMCRadixCache's logic.
|
||||
topk = get_spec().speculative_eagle_topk
|
||||
|
||||
@@ -438,17 +438,15 @@ class LMCRadixCache(RadixCache):
|
||||
)
|
||||
)
|
||||
|
||||
def cache_finished_req(
|
||||
self, req: Req, is_insert: bool = True, *, owned_kv_len: int
|
||||
) -> None:
|
||||
def on_release(self, req: Req, *, inserted: bool) -> None:
|
||||
if not inserted and self._mode is LMCacheMode.MP:
|
||||
self._mp_load_back_markers.pop(req.rid, None)
|
||||
self.lmcache_connector.end_session(req.rid)
|
||||
|
||||
def cache_finished_req(self, req: Req, *, owned_kv_len: int) -> None:
|
||||
"""On request completion, insert device KV into radix and store to LMCache."""
|
||||
|
||||
super().cache_finished_req(req, is_insert=is_insert, owned_kv_len=owned_kv_len)
|
||||
if not is_insert:
|
||||
if self._mode is LMCacheMode.MP:
|
||||
self._mp_load_back_markers.pop(req.rid, None)
|
||||
self.lmcache_connector.end_session(req.rid)
|
||||
return
|
||||
super().cache_finished_req(req, owned_kv_len=owned_kv_len)
|
||||
|
||||
topk = get_spec().speculative_eagle_topk
|
||||
enable_kv_committed_len = topk is None or topk == 1
|
||||
|
||||
@@ -228,16 +228,16 @@ receipt proves were taken. The eventual full release must pass
|
||||
|
||||
---
|
||||
|
||||
### `cache_finished_req(req: Req, is_insert: bool = True, *, owned_kv_len: int)`
|
||||
### `cache_finished_req(req: Req, *, owned_kv_len: int)`
|
||||
|
||||
Cache a completed request's KV data into the tree.
|
||||
|
||||
| Aspect | Detail |
|
||||
|--------|--------|
|
||||
| **Purpose** | After a request finishes, insert its token/KV data into the tree for future reuse |
|
||||
| **Inputs** | `req` — the finished request; `is_insert` — insert the owned range into the tree (True) or free it (False); `owned_kv_len` — end of the request-owned KV range; slots past it are freed by `release_kv_cache` |
|
||||
| **Inputs** | `req` — the finished request; `owned_kv_len` — end of the request-owned KV range; slots past it are freed by `release_kv_cache`. A request that leaves without inserting goes through `release_kv_cache(is_insert=False)` instead, which frees the row and calls `on_release(req, inserted=False)` for component cleanup |
|
||||
| **Output** | `None` |
|
||||
| **Mutation** | Calls component hooks → `insert` → `dec_lock_ref` → component cleanup. Frees unaligned tail KV indices; frees non-inserted KV indices when `is_insert=False`. |
|
||||
| **Mutation** | Calls component hooks → `insert` → `dec_lock_ref` → component cleanup. Frees unaligned tail KV indices. |
|
||||
| **Complexity** | **O(K + D·C)** — insert O(K + D·C) + lock release O(D). Simplifies to **O(K)**. |
|
||||
|
||||
**Algorithm detail:**
|
||||
|
||||
@@ -363,7 +363,7 @@ class UnifiedCacheLinkerWrapper:
|
||||
req.kv.swa_evicted_seqlen if req.kv is not None else 0
|
||||
),
|
||||
chunked=True,
|
||||
priority=getattr(req, "priority", 0) or 0,
|
||||
priority=req.priority or 0,
|
||||
track_adopted_ranges=True,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -927,6 +927,11 @@ class UnifiedRadixCache(BasePrefixCache):
|
||||
receipt its acquire returned, so it never drops a lock it never took."""
|
||||
self.dec_lock_ref(req.last_node, req.lock_receipt, skip_swa=skip_swa)
|
||||
|
||||
def unpin(self, req: Req) -> None:
|
||||
# Synthetic profiling requests may own KV without locking a tree node.
|
||||
if req.last_node is not None:
|
||||
self._dec_req_lock(req, skip_swa=req.swa_prefix_lock_released)
|
||||
|
||||
def dec_swa_lock_only(
|
||||
self,
|
||||
node_id: NodeId,
|
||||
@@ -949,10 +954,7 @@ class UnifiedRadixCache(BasePrefixCache):
|
||||
return DecLockRefResult()
|
||||
return self.tree_core.dec_host_lock_ref(node_id, params)
|
||||
|
||||
@rank_consensus(same_params=["req.rid", "is_insert", "owned_kv_len"])
|
||||
def cache_finished_req(
|
||||
self, req: Req, is_insert: bool = True, *, owned_kv_len: int, **kwargs
|
||||
) -> None:
|
||||
def claim_kv_row(self, req: Req) -> bool:
|
||||
# Retraction also enters here: retain its ticket until actual finish.
|
||||
if (
|
||||
self.cache_controller is not None
|
||||
@@ -960,11 +962,19 @@ class UnifiedRadixCache(BasePrefixCache):
|
||||
and req.finished()
|
||||
):
|
||||
self.cache_controller.release_pp_prefetch(req.rid)
|
||||
if self.session.try_cache_finished_req(req, is_insert=is_insert, **kwargs):
|
||||
return
|
||||
return self.session.try_cache_finished_req(req)
|
||||
|
||||
@rank_consensus(same_params=["req.rid", "inserted"])
|
||||
def on_release(self, req: Req, *, inserted: bool) -> None:
|
||||
if inserted:
|
||||
return
|
||||
for comp in self._components_tuple:
|
||||
comp.cleanup_after_caching_req(req, is_finished=True)
|
||||
|
||||
@rank_consensus(same_params=["req.rid", "owned_kv_len"])
|
||||
def cache_finished_req(self, req: Req, *, owned_kv_len: int, **kwargs) -> None:
|
||||
if self.disable:
|
||||
self.free_kv_row(req.kv, [(0, owned_kv_len)])
|
||||
self.free_kv_row(req.kv, [(req.kv.cache_protected_len, owned_kv_len)])
|
||||
for comp in self._components_tuple:
|
||||
comp.cleanup_after_caching_req(req, is_finished=True)
|
||||
return
|
||||
@@ -974,118 +984,101 @@ class UnifiedRadixCache(BasePrefixCache):
|
||||
req.kv.req_pool_idx, :owned_kv_len
|
||||
]
|
||||
|
||||
result = None
|
||||
insert_params = None
|
||||
insert_params = InsertParams(
|
||||
prev_prefix_len=req.kv.cache_protected_len,
|
||||
priority=req.priority or 0,
|
||||
session_id=req.session_id,
|
||||
rotation_base=req.kv_rotation_base,
|
||||
)
|
||||
|
||||
if is_insert:
|
||||
insert_params = InsertParams(
|
||||
prev_prefix_len=req.kv.cache_protected_len,
|
||||
priority=getattr(req, "priority", 0) or 0,
|
||||
session_id=req.session_id,
|
||||
rotation_base=req.kv_rotation_base,
|
||||
# components prepare insert data + return effective cache_len
|
||||
effective_cache_len = len(token_ids)
|
||||
for comp in self._components_tuple:
|
||||
cl = comp.prepare_for_caching_req(
|
||||
req=req,
|
||||
insert_params=insert_params,
|
||||
token_ids_len=len(token_ids),
|
||||
is_finished=True,
|
||||
)
|
||||
if cl is not None:
|
||||
effective_cache_len = min(effective_cache_len, cl)
|
||||
for comp in self._components_tuple:
|
||||
effective_cache_len = comp.floor_cache_len(effective_cache_len)
|
||||
|
||||
# Truncate if needed; the tail free is deferred and batched with
|
||||
# the unaligned tail below so a shared boundary page is emitted once.
|
||||
kv_indices_full = kv_indices
|
||||
tail_free_start = None
|
||||
if effective_cache_len < len(token_ids):
|
||||
tail_free_start = max(effective_cache_len, req.kv.cache_protected_len)
|
||||
token_ids = token_ids[:effective_cache_len]
|
||||
kv_indices = kv_indices[:effective_cache_len]
|
||||
|
||||
radix_key = RadixKey(
|
||||
token_ids,
|
||||
req.extra_key,
|
||||
is_bigram=self.tree_core.is_eagle,
|
||||
cache_salt=req.cache_salt,
|
||||
).page_aligned(self.page_size)
|
||||
page_aligned_len = len(radix_key)
|
||||
values = kv_indices[:page_aligned_len].to(dtype=torch.int64, copy=True)
|
||||
|
||||
insert_params.key = radix_key
|
||||
insert_params.value = values
|
||||
result = self.insert(insert_params)
|
||||
|
||||
# Split the leaf at the prompt boundary so eviction can drop the output
|
||||
# KV without the prompt. prev_prefix_len keeps the overlapping indices
|
||||
# from being freed as duplicates; skipped after a declined rotation,
|
||||
# whose rows are freed below.
|
||||
prompt_key = RadixKey(
|
||||
req.origin_input_ids,
|
||||
req.extra_key,
|
||||
is_bigram=self.tree_core.is_eagle,
|
||||
cache_salt=req.cache_salt,
|
||||
).page_aligned(self.page_size)
|
||||
if (
|
||||
not result.rotation_tail_declined
|
||||
and len(self._components_tuple) == 1
|
||||
and self._components_tuple[0].component_type == BASE_COMPONENT_TYPE
|
||||
and 0 < len(prompt_key) < len(radix_key)
|
||||
):
|
||||
self.insert(
|
||||
replace(
|
||||
insert_params,
|
||||
key=prompt_key,
|
||||
value=values[: len(prompt_key)],
|
||||
prev_prefix_len=len(prompt_key),
|
||||
priority=insert_params.priority + 1,
|
||||
# The request created these nodes moments ago; another
|
||||
# hit_count bump would promote every prompt node.
|
||||
chunked=True,
|
||||
)
|
||||
)
|
||||
|
||||
# components prepare insert data + return effective cache_len
|
||||
effective_cache_len = len(token_ids)
|
||||
for comp in self._components_tuple:
|
||||
cl = comp.prepare_for_caching_req(
|
||||
req=req,
|
||||
insert_params=insert_params,
|
||||
token_ids_len=len(token_ids),
|
||||
is_finished=True,
|
||||
)
|
||||
if cl is not None:
|
||||
effective_cache_len = min(effective_cache_len, cl)
|
||||
for comp in self._components_tuple:
|
||||
effective_cache_len = comp.floor_cache_len(effective_cache_len)
|
||||
# Free the unaligned tail and the deferred truncation tail; after a
|
||||
# rotation decline nothing was inserted, so everything past the
|
||||
# protected prefix goes.
|
||||
free_from = (
|
||||
# min(): the protected prefix can already run past a truncated
|
||||
# cache_len, and free_kv_row takes ascending ranges only.
|
||||
min(req.kv.cache_protected_len, len(kv_indices))
|
||||
if result.rotation_tail_declined
|
||||
else page_aligned_len
|
||||
)
|
||||
ranges = [(free_from, len(kv_indices))]
|
||||
if tail_free_start is not None:
|
||||
if free_from < len(kv_indices) and tail_free_start <= len(kv_indices):
|
||||
# The two halves touch at the truncation boundary and share
|
||||
# that page; free the union as one range.
|
||||
ranges[0] = (free_from, len(kv_indices_full))
|
||||
else:
|
||||
ranges.append((tail_free_start, len(kv_indices_full)))
|
||||
self.free_kv_row(req.kv, ranges)
|
||||
|
||||
# Truncate if needed; the tail free is deferred and batched with
|
||||
# the unaligned tail below so a shared boundary page is emitted once.
|
||||
kv_indices_full = kv_indices
|
||||
tail_free_start = None
|
||||
if effective_cache_len < len(token_ids):
|
||||
tail_free_start = max(effective_cache_len, req.kv.cache_protected_len)
|
||||
token_ids = token_ids[:effective_cache_len]
|
||||
kv_indices = kv_indices[:effective_cache_len]
|
||||
self.unpin(req)
|
||||
|
||||
radix_key = RadixKey(
|
||||
token_ids,
|
||||
req.extra_key,
|
||||
is_bigram=self.tree_core.is_eagle,
|
||||
cache_salt=req.cache_salt,
|
||||
).page_aligned(self.page_size)
|
||||
page_aligned_len = len(radix_key)
|
||||
values = kv_indices[:page_aligned_len].to(dtype=torch.int64, copy=True)
|
||||
|
||||
insert_params.key = radix_key
|
||||
insert_params.value = values
|
||||
result = self.insert(insert_params)
|
||||
|
||||
# Keep the prompt as an independent radix node. Finished requests
|
||||
# append a short, request-specific output to a much longer prompt;
|
||||
# without this split the prompt and output form one leaf and are
|
||||
# evicted together. Re-inserting the prompt only changes topology:
|
||||
# prev_prefix_len prevents the overlapping KV indices from being
|
||||
# treated as duplicate allocations and freed. A declined rotation
|
||||
# tail releases everything past the protected prefix below, so the
|
||||
# split is skipped there rather than handing the tree rows that
|
||||
# are about to be freed.
|
||||
prompt_key = RadixKey(
|
||||
req.origin_input_ids,
|
||||
req.extra_key,
|
||||
is_bigram=self.tree_core.is_eagle,
|
||||
cache_salt=req.cache_salt,
|
||||
).page_aligned(self.page_size)
|
||||
if (
|
||||
not result.rotation_tail_declined
|
||||
and len(self._components_tuple) == 1
|
||||
and self._components_tuple[0].component_type == BASE_COMPONENT_TYPE
|
||||
and 0 < len(prompt_key) < len(radix_key)
|
||||
):
|
||||
self.insert(
|
||||
replace(
|
||||
insert_params,
|
||||
key=prompt_key,
|
||||
value=values[: len(prompt_key)],
|
||||
prev_prefix_len=len(prompt_key),
|
||||
priority=insert_params.priority + 1,
|
||||
# Topology-only re-insert: the request itself created
|
||||
# these nodes moments ago, so counting it as a hit is
|
||||
# the same self-referencing inflation `chunked` exists
|
||||
# to suppress. hit_count drives eviction order, so an
|
||||
# extra bump here would silently promote every prompt
|
||||
# node into the protected segment.
|
||||
chunked=True,
|
||||
)
|
||||
)
|
||||
|
||||
# Free unaligned tail (+ deferred truncation tail). A rotation
|
||||
# decline inserted nothing, so the whole span past the protected
|
||||
# prefix stayed request-owned and is released here instead.
|
||||
free_from = (
|
||||
# min(): the protected prefix can already run past a truncated
|
||||
# cache_len, and free_kv_row takes ascending ranges only.
|
||||
min(req.kv.cache_protected_len, len(kv_indices))
|
||||
if result.rotation_tail_declined
|
||||
else page_aligned_len
|
||||
)
|
||||
ranges = [(free_from, len(kv_indices))]
|
||||
if tail_free_start is not None:
|
||||
if free_from < len(kv_indices) and tail_free_start <= len(kv_indices):
|
||||
# The two halves touch at the truncation boundary and share
|
||||
# that page; free the union as one range.
|
||||
ranges[0] = (free_from, len(kv_indices_full))
|
||||
else:
|
||||
ranges.append((tail_free_start, len(kv_indices_full)))
|
||||
self.free_kv_row(req.kv, ranges)
|
||||
else:
|
||||
self.free_kv_row(req.kv, [(req.kv.cache_protected_len, owned_kv_len)])
|
||||
|
||||
# Synthetic profiling requests may own KV without locking a tree node.
|
||||
if req.last_node is not None:
|
||||
self._dec_req_lock(req, skip_swa=req.swa_prefix_lock_released)
|
||||
|
||||
if is_insert and result is not None and result.last_device_node is not None:
|
||||
if result is not None and result.last_device_node is not None:
|
||||
req.last_node = result.last_device_node
|
||||
|
||||
# cleanup
|
||||
@@ -1112,7 +1105,7 @@ class UnifiedRadixCache(BasePrefixCache):
|
||||
insert_params = InsertParams(
|
||||
prev_prefix_len=req.kv.cache_protected_len,
|
||||
chunked=chunked,
|
||||
priority=getattr(req, "priority", 0) or 0,
|
||||
priority=req.priority or 0,
|
||||
rotation_base=req.kv_rotation_base,
|
||||
)
|
||||
effective_cache_len = len(token_ids)
|
||||
@@ -1164,7 +1157,7 @@ class UnifiedRadixCache(BasePrefixCache):
|
||||
insert_params = InsertParams(
|
||||
prev_prefix_len=req.kv.cache_protected_len,
|
||||
chunked=chunked,
|
||||
priority=getattr(req, "priority", 0) or 0,
|
||||
priority=req.priority or 0,
|
||||
session_id=req.session_id,
|
||||
rotation_base=req.kv_rotation_base,
|
||||
)
|
||||
|
||||
@@ -264,9 +264,7 @@ class StreamingSession(BasePrefixCache):
|
||||
cache_protected_len=slot.kv.cache_protected_len,
|
||||
)
|
||||
|
||||
def try_cache_finished_req(
|
||||
self, req: Req, is_insert: bool = True, **kwargs
|
||||
) -> bool:
|
||||
def try_cache_finished_req(self, req: Req) -> bool:
|
||||
"""Handles a streaming-session finish (save slot / mid-abort nuke).
|
||||
Returns True if handled; False means caller runs its raw path."""
|
||||
if not _is_streaming(req):
|
||||
@@ -354,16 +352,23 @@ class StreamingSession(BasePrefixCache):
|
||||
return result
|
||||
return self.inner.match_prefix(params)
|
||||
|
||||
def cache_finished_req(self, req: Req, is_insert: bool = True, **kwargs):
|
||||
if self.try_cache_finished_req(req, is_insert=is_insert, **kwargs):
|
||||
return
|
||||
self.inner.cache_finished_req(req, is_insert=is_insert, **kwargs)
|
||||
def claim_kv_row(self, req: Req) -> bool:
|
||||
return self.try_cache_finished_req(req)
|
||||
|
||||
def on_release(self, req: Req, *, inserted: bool) -> None:
|
||||
self.inner.on_release(req, inserted=inserted)
|
||||
|
||||
def cache_finished_req(self, req: Req, **kwargs):
|
||||
self.inner.cache_finished_req(req, **kwargs)
|
||||
|
||||
def cache_unfinished_req(self, req: Req, **kwargs):
|
||||
if self.try_cache_unfinished_req(req, **kwargs):
|
||||
return
|
||||
self.inner.cache_unfinished_req(req, **kwargs)
|
||||
|
||||
def unpin(self, req: Req) -> None:
|
||||
self.inner.unpin(req)
|
||||
|
||||
def finish(self, handle: CacheRequestHandle, outcome: CacheRequestOutcome) -> None:
|
||||
self.inner.finish(handle, outcome)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user