Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions python/freetoken/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,12 @@ class Req:
mamba_next_track_idx: int = 0 # which ping-pong slot is the next snapshot dst (0/1)
mamba_last_track_seqlen: int | None = None # chunk-aligned committed len of the last snapshot
mamba_restore_src: int | None = None # on a prefix hit: tree snapshot slot to COW into the live slot (first chunk only)
# The same boundary one tier down: the checkpoint sits in the host bank and is copied up on
# the engine stream, before the first forward reads the live slot.
mamba_restore_host: int | None = None
# Intermediate chunks are never cache_req'd (their pages would double-free), but each freezes a
# x64 GDN checkpoint: the drain archives (boundary, bank slot) here, the final commit attaches.
mamba_host_tracks: list | None = None # the last continuation owns it, else it is freed
swa_evicted_seqlen: int = 0 # SWA radix: positions < this had their swa KV freed (slid out of window) during decode
decode_batch_idx: int = 0 # SWA radix: # of decode forwards done; the proactive free_swa skips the first (overlap guard)
# Set once, at the first sampled tool-call opener token (scheduler detection): the state
Expand Down
3 changes: 3 additions & 0 deletions python/freetoken/engine/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ class EngineConfig:
# `--cache-type naive` opts out. linear_state_cache_ratio sizes the GDN snapshot cache as
# ceil(ratio * max_running_req) extra slots.
linear_state_cache_ratio: float = 2.0
# GDN checkpoints in PINNED host RAM instead of VRAM (hybrid GDN + radix only). ~110 MB each, so
# a bank costs host RAM and keeps every prefill-chunk boundary resumable. 0 = off: one per prompt.
mamba_host_slots: int = 0
# Window/full ratio for the SWA radix cache (`--cache-type radix` on SWA models) and the DSV4
# window tier: the DEFAULT window-pool size = max(working-set floor, ratio x full-pool tokens).
# < 1.0 trades retained window-prefix capacity for memory savings; must be in (0, 1]. It is the
Expand Down
9 changes: 9 additions & 0 deletions python/freetoken/engine/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -428,14 +428,23 @@ def __init__(self, config: EngineConfig):
if linear_group is not None:
from freetoken.kvcache.linear_state_pool import LinearStatePool

# Naive caching has no tree to hang a checkpoint on, so the bank would be dead RAM.
host_slots = 0 if config.cache_type == "naive" else config.mamba_host_slots
self.linear_state_pool = LinearStatePool(
group=linear_group,
num_slots=_linear_pool_num_slots(config),
dtype=self.dtype,
device=self.device,
tp_size=config.tp_info.size,
slot_states=config.model_config.slot_states,
host_slots=host_slots,
)
if host_slots > 1:
per_slot = self.linear_state_pool.host_bytes_per_slot()
logger.info_rank0(
f"GDN host snapshot bank: {host_slots - 1} pinned host slots x "
f"{mem_GB(per_slot)} = {mem_GB(host_slots * per_slot)} pinned in total (slot 0 "
"is the padding sink; not charged against the GPU cache budget)")
self.ctx.linear_state_pool = self.linear_state_pool
else:
self.linear_state_pool = None
Expand Down
3 changes: 3 additions & 0 deletions python/freetoken/kvcache/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,9 @@ class MatchResult(NamedTuple):
# Hybrid (GDN) models: the restored GDN state snapshot slot for this prefix (None = cold /
# non-hybrid). Surfaced by HybridRadixCache via CacheManager.match_req.
mamba_value: int | None = None
# Same boundary in the host bank: costs no VRAM to keep, so it is what makes an
# intermediate-chunk boundary resumable at all. Restored only when there is no device slot.
mamba_host: int | None = None
# TODO: support HiCache


Expand Down
109 changes: 99 additions & 10 deletions python/freetoken/kvcache/hybrid_radix_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,17 @@ class HybridMatch(NamedTuple):
cached_len: int # truncated to the deepest LIVE-snapshot boundary
mamba_value: Optional[int] # GDN snapshot slot to restore from (None = cold start)
node: RadixTreeNode # the matched node (lock target)
# Same boundary, host-tier copy. Only the device one is preferred: a resume needs one
# checkpoint, not two, and the bank slot stays attached for whoever asks next.
mamba_host: Optional[int] = None


class EvictResult(NamedTuple):
kv_indices: torch.Tensor # KV page indices to free
mamba_slots: List[int] # GDN state slots to free
# Bank slots freed alongside (KV eviction kills a host checkpoint too: resuming needs the
# KV of the prefix the checkpoint describes).
host_slots: List[int] = []


class HybridRadixCache:
Expand All @@ -71,24 +77,29 @@ def __init__(self, device: torch.device, page_size: int) -> None:
self.full_protected = 0
self.mamba_evictable = 0 # number of live, unlocked snapshots
self.mamba_protected = 0
# Host-tier snapshots: counted separately so every existing device-slot conservation
# check keeps meaning exactly what it did before.
self.mamba_host_evictable = 0
self.mamba_host_protected = 0

# ---------------------------------------------------------------- match / insert
def match_prefix(self, input_ids: torch.Tensor) -> HybridMatch:
"""Match the token prefix, then truncate the reusable length to the deepest node on
the path that still owns a LIVE snapshot (a continuation can only resume the GDN
recurrence from a checkpointed boundary)."""
the path that still owns a checkpoint -- on the device OR in the host bank (a
continuation can only resume the GDN recurrence from a checkpointed boundary)."""
node, _ = self._walk(input_ids)
# walk up to the deepest node whose END boundary has a live snapshot
cur, end_len = node, self._path_len(node)
while not cur.is_root():
if cur.mamba_value is not None:
return HybridMatch(self._collect_kv(cur), end_len, cur.mamba_value, cur)
if cur.mamba_value is not None or cur.mamba_host is not None:
return HybridMatch(
self._collect_kv(cur), end_len, cur.mamba_value, cur, cur.mamba_host)
end_len -= cur.length
cur = cur.parent
return HybridMatch(self.empty, 0, None, self.root)

def insert(self, input_ids: torch.Tensor, kv_indices: torch.Tensor,
mamba_value: int) -> Tuple[int, bool]:
mamba_value: int, freed_host: List[int] | None = None) -> Tuple[int, bool]:
"""Insert the committed KV prefix and DONATE ``mamba_value`` at the (page-aligned) end
boundary node. Returns (matched_prefix_len, mamba_exist). If the boundary node already
owns a live snapshot, returns mamba_exist=True and does not attach (caller frees the
Expand All @@ -106,11 +117,47 @@ def insert(self, input_ids: torch.Tensor, kv_indices: torch.Tensor,
return prefix_len, True # root can't hold a snapshot; report exist so caller frees it
if node.mamba_value is not None:
return prefix_len, True # dedup: caller frees its donated slot
if (freed_host is not None and node.mamba_host is not None
and node.mamba_host_ref_count == 0):
# The device copy supersedes the bank one at the same boundary. A locked bank slot
# stays put: some request is copying from it right now.
self._detach_host(node, freed_host)
node.mamba_value = mamba_value # fills a fresh node or a tombstone
if node.mamba_ref_count == 0:
self.mamba_evictable += 1
return prefix_len, False

def attach_host(self, input_ids: torch.Tensor, host_idx: int) -> bool:
"""Checkpoint the node ending exactly at ``len(input_ids)`` with a host-tier snapshot.
Used for the boundaries an intermediate prefill chunk froze: its KV only becomes
tree-owned at the final commit, which is when this gets called. False means the caller
keeps the bank slot (boundary not in the tree, or the node is already checkpointed)."""
node, prefix_len = self._walk(input_ids)
# A checkpoint describes the state AT this length; attaching it shallower than the walk
# reached would resume a request with the state of different tokens.
if prefix_len != len(input_ids) or node.is_root():
return False
if node.mamba_value is not None or node.mamba_host is not None:
return False
node.mamba_host = host_idx
if node.mamba_host_ref_count == 0:
self.mamba_host_evictable += 1
return True

def evict_host(self, num: int) -> List[int]:
"""Drop host-tier checkpoints by LRU (node timestamp) to make room in the bank. Unlike
the device currency this frees no VRAM and deletes no node -- the KV stays, the boundary
just stops being resumable. Returns the bank slots the caller must return to the pool."""
cands = [n for n in self._host_nodes() if n.mamba_host_ref_count == 0]
heapq.heapify(cands)
dropped: List[int] = []
while len(dropped) < num and cands:
node = heapq.heappop(cands)
if node.mamba_host is None or node.mamba_host_ref_count != 0:
continue
self._detach_host(node, dropped)
return dropped

# ---------------------------------------------------------------- locking (dual)
def inc_lock(self, node: RadixTreeNode) -> None:
"""Protect a matched node's snapshot (mamba ref on the node) and its KV path
Expand All @@ -121,6 +168,13 @@ def inc_lock(self, node: RadixTreeNode) -> None:
self.mamba_evictable -= 1
self.mamba_protected += 1
node.mamba_ref_count += 1
if node.mamba_host is not None:
# Locked separately from the device copy: a request restoring from the bank must not
# have its source slot recycled mid-copy.
if node.mamba_host_ref_count == 0:
self.mamba_host_evictable -= 1
self.mamba_host_protected += 1
node.mamba_host_ref_count += 1
cur = node
while not cur.is_root():
if cur.ref_count == 0:
Expand All @@ -135,6 +189,11 @@ def dec_lock(self, node: RadixTreeNode) -> None:
if node.mamba_ref_count == 0:
self.mamba_evictable += 1
self.mamba_protected -= 1
if node.mamba_host is not None and node.mamba_host_ref_count > 0:
node.mamba_host_ref_count -= 1
if node.mamba_host_ref_count == 0:
self.mamba_host_evictable += 1
self.mamba_host_protected -= 1
cur = node
while not cur.is_root():
cur.ref_count -= 1
Expand All @@ -147,10 +206,11 @@ def dec_lock(self, node: RadixTreeNode) -> None:
# ---------------------------------------------------------------- eviction (dual)
def evict_full(self, num_tokens: int) -> EvictResult:
"""Evict KV tokens by LRU over UNLOCKED LEAF nodes (an internal node's KV is a prefix
dependency for all descendants). Frees each evicted node's snapshot too."""
dependency for all descendants). Frees each evicted node's snapshot too -- a checkpoint
is only good for the prefix whose KV it describes, so the bank copy dies with the KV."""
leaves = [n for n in self._leaves() if n.ref_count == 0]
heapq.heapify(leaves)
kv, mamba, freed = [], [], 0
kv, mamba, host, freed = [], [], [], 0
while freed < num_tokens and leaves:
node = heapq.heappop(leaves)
if node.ref_count != 0 or not node.is_leaf() or node.is_root():
Expand All @@ -159,11 +219,12 @@ def evict_full(self, num_tokens: int) -> EvictResult:
kv.append(node.value)
self.full_evictable -= node.length
self._free_node_mamba(node, mamba)
self._detach_host(node, host)
parent, casc = self._cascade_tombstone_leaves(self._unlink(node), kv)
freed += casc
if parent.is_leaf() and parent.ref_count == 0 and not parent.is_root():
heapq.heappush(leaves, parent)
return EvictResult(torch.cat(kv) if kv else self.empty, mamba)
return EvictResult(torch.cat(kv) if kv else self.empty, mamba, host)

def evict_mamba(self, num: int) -> EvictResult:
"""Evict GDN snapshots by LRU over UNLOCKED snapshot-bearing nodes -- internal nodes
Expand All @@ -177,7 +238,9 @@ def evict_mamba(self, num: int) -> EvictResult:
node = heapq.heappop(cands)
if node.mamba_value is None or node.mamba_ref_count != 0 or node.is_root():
continue
if node.is_leaf() and node.ref_count == 0:
if node.is_leaf() and node.ref_count == 0 and node.mamba_host is None:
# A leaf that keeps a bank checkpoint still has a reason to exist, so it is
# tombstoned (KV kept) rather than deleted -- that checkpoint is the resume point.
kv.append(node.value)
self.full_evictable -= node.length
self._free_node_mamba(node, mamba)
Expand Down Expand Up @@ -208,6 +271,13 @@ def check_integrity(self) -> None:
# (KV/page conservation is checked by CacheManager.check_integrity.)
for n in self._snapshot_nodes():
assert n.mamba_value is not None and n.mamba_ref_count >= 0 and n.ref_count >= 0
host_nodes = self._host_nodes()
for n in host_nodes:
assert n.mamba_host is not None and n.mamba_host_ref_count >= 0
assert self.mamba_host_evictable + self.mamba_host_protected == len(host_nodes), (
f"bank leak: evictable({self.mamba_host_evictable}) + "
f"protected({self.mamba_host_protected}) != nodes({len(host_nodes)})"
)

# ---------------------------------------------------------------- helpers
def _free_node_mamba(self, node: RadixTreeNode, out: List[int]) -> None:
Expand All @@ -217,6 +287,16 @@ def _free_node_mamba(self, node: RadixTreeNode, out: List[int]) -> None:
if node.mamba_ref_count == 0:
self.mamba_evictable -= 1

def _detach_host(self, node: RadixTreeNode, out: List[int]) -> None:
if node.mamba_host is None:
return
# A locked bank slot is some request's restore source; every caller here only reaches
# unlocked nodes, so hitting this means a currency got un-locked without its KV lock.
assert node.mamba_host_ref_count == 0, "recycling a locked mamba host slot"
out.append(node.mamba_host)
node.mamba_host = None
self.mamba_host_evictable -= 1

def _unlink(self, node: RadixTreeNode) -> RadixTreeNode:
parent = node.parent
del parent.children[self.key_fn(node._key)]
Expand All @@ -228,7 +308,7 @@ def _cascade_tombstone_leaves(self, parent: RadixTreeNode, kv_out: List[torch.Te
Keeps the 'a leaf always carries a live snapshot' invariant (sglang
_iteratively_delete_tombstone_leaf). Returns (highest surviving ancestor, freed_tokens)."""
freed = 0
while (parent.mamba_value is None and parent.is_leaf()
while (parent.mamba_value is None and parent.mamba_host is None and parent.is_leaf()
and parent.ref_count == 0 and not parent.is_root()):
kv_out.append(parent.value)
self.full_evictable -= parent.length
Expand Down Expand Up @@ -272,6 +352,15 @@ def _snapshot_nodes(self) -> List[RadixTreeNode]:
stack.extend(n.children.values())
return out

def _host_nodes(self) -> List[RadixTreeNode]:
out, stack = [], [self.root]
while stack:
n = stack.pop()
if n.mamba_host is not None and not n.is_root():
out.append(n)
stack.extend(n.children.values())
return out

def _walk(self, input_ids: torch.Tensor) -> Tuple[RadixTreeNode, int]:
prefix_len, total = 0, len(input_ids)
node = self.root
Expand Down
Loading