Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
5bf1f81
feat: port SWA branching-point caching to the Rust tree core
alphabetc1 Sep 5, 2026
335101b
Merge branch 'main' into feat/rust-swa-branching
alphabetc1 Sep 7, 2026
baf54d4
refactor: tighten the Rust SWA backup window after review
alphabetc1 Sep 7, 2026
b5225c4
Merge branch 'main' into feat/rust-swa-branching
alphabetc1 Sep 7, 2026
762e8d7
fix: expect the arena panic in the SWA backup commit test
alphabetc1 Sep 7, 2026
d0a19b0
Merge branch 'main' into feat/rust-swa-branching
alphabetc1 Sep 7, 2026
670bd06
Merge branch 'main' into feat/rust-swa-branching
alphabetc1 Sep 7, 2026
7d5bbed
Merge branch 'main' into feat/rust-swa-branching
alphabetc1 Sep 7, 2026
56ab385
Merge remote-tracking branch 'upstream/main' into feat/rust-swa-branc…
alphabetc1 Sep 9, 2026
960a6fa
fix: fail fast on non-device-only SWA backup targets and address revi…
alphabetc1 Sep 9, 2026
7743e3b
refactor: share the SWA unbacked-node collector across backup call sites
alphabetc1 Sep 9, 2026
3e8c185
refactor: name the SWA backup window helpers by what they collect
alphabetc1 Sep 9, 2026
369c823
refactor: match the Rust SWA backup local name to the Python core
alphabetc1 Sep 9, 2026
1cb1016
Merge remote-tracking branch 'upstream/main' into feat/rust-swa-branc…
alphabetc1 Sep 10, 2026
bd087fc
fix: keep the pending-ancestor SWA backup test balanced under the seg…
alphabetc1 Sep 10, 2026
1043fa0
fix: preserve Mamba checkpoint boundaries during SWA branching
alphabetc1 Sep 10, 2026
fe07297
test: remove dedicated Inkling branch checkpoint E2E
alphabetc1 Sep 10, 2026
5cc5f26
Merge branch 'main' into feat/rust-swa-branching
alphabetc1 Sep 10, 2026
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
10 changes: 10 additions & 0 deletions python/sglang/srt/mem_cache/rust_tree_core/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,7 @@ def _insert_step_from_binding(step) -> InsertStepResult:
prefix_len=step.result.prefix_len,
last_device_node=step.result.last_device_node,
mamba_exist=step.result.mamba_exist,
swa_branch_inserted=step.result.swa_branch_inserted,
host_insert_dropped=step.result.host_insert_dropped,
adopted_ranges=(
{
Expand All @@ -252,6 +253,7 @@ def _match_result_from_binding(result) -> MatchResult:
best_match_node=result.best_match_node_id,
host_hit_length=result.host_hit_length,
swa_host_hit_length=result.swa_host_hit_length,
swa_branching_seqlen=result.swa_branching_seqlen,
mamba_host_hit_length=result.mamba_host_hit_length,
mamba_branching_seqlen=result.mamba_branching_seqlen,
full_kv_hit_length=result.full_kv_hit_length,
Expand Down Expand Up @@ -589,6 +591,7 @@ def begin_insert(self, params: InsertParams) -> InsertStepResult:
mamba_value=params.mamba_value,
prev_prefix_len=params.prev_prefix_len,
swa_evicted_seqlen=params.swa_evicted_seqlen,
swa_branching_seqlen=params.swa_branching_seqlen,
chunked=params.chunked,
priority=0 if params.priority is None else params.priority,
track_adopted_ranges=params.track_adopted_ranges,
Expand Down Expand Up @@ -630,6 +633,13 @@ def evict_excess_path_states(
def set_hicache_enabled(self) -> None:
self._binding.set_hicache_enabled()

def set_host_memory_buffer_only(self) -> None:
self._binding.set_host_memory_buffer_only()

@property
def is_host_memory_buffer_only(self) -> bool:
return self._binding.is_host_memory_buffer_only()

@property
def page_size(self) -> int:
# Read-only: the Rust core freezes it at construction.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,13 +88,27 @@ def __init__(self, cache: UnifiedRadixCache, params: CacheInitParams):

component_type = ComponentType.SWA

def _dirty_backup_window(self, node: UnifiedTreeNode) -> list[UnifiedTreeNode]:
def _collect_unbacked_swa_nodes(
self, node: UnifiedTreeNode
) -> list[UnifiedTreeNode]:
"""Nodes whose SWA data needs a host backup, deepest first.

Buffer mode stages one node per FIFO backup intent; cache mode backs
up every device-only node within one sliding window of ``node``.
"""
if not self.tree_core.has_swa_host_pool:
return []
if self.tree_core.is_host_memory_buffer_only:
cd = node.component_data[self.component_type]
return [node] if cd.value is not None else []
return self._collect_unbacked_swa_nodes_in_window(node)

def _collect_unbacked_swa_nodes_in_window(
self, node: UnifiedTreeNode
) -> list[UnifiedTreeNode]:
ct = self.component_type
covered = 0
dirty: list[UnifiedTreeNode] = []
unbacked: list[UnifiedTreeNode] = []
cur = node
while (
cur is not self.tree_core.root_node and covered < self.sliding_window_size
Expand All @@ -108,12 +122,12 @@ def _dirty_backup_window(self, node: UnifiedTreeNode) -> list[UnifiedTreeNode]:
break
covered += len(value)
if cd.value is not None and cd.host_value is None:
dirty.append(cur)
unbacked.append(cur)
cur = cur.parent
return dirty
return unbacked

def needs_incremental_backup(self, node: UnifiedTreeNode) -> bool:
return bool(self._dirty_backup_window(node))
return bool(self._collect_unbacked_swa_nodes(node))

def reset_session_state(self) -> None:
super().reset_session_state()
Expand Down Expand Up @@ -920,6 +934,11 @@ def prepare_for_caching_req(
# that boundary so insertion creates a tombstone instead of live SWA KV.
insert_params.swa_evicted_seqlen = req.kv.swa_evicted_seqlen

# A recurrent checkpoint must stay attached to its exact token prefix.
# Let MambaComponent select the insertion length for hybrid caches.
if self.cache.is_mamba_enabled:
return None

branching_seqlen = req.swa_branching_seqlen
if branching_seqlen is None or branching_seqlen <= req.kv.cache_protected_len:
return None
Expand Down Expand Up @@ -992,8 +1011,7 @@ def prepare_prefetch(
elif prefetch_pages <= 0:
return PreparePrefetchResult()
elif (
self.tree_core.is_root(node_id)
or self.cache.host_memory_mode == "buffer_only"
self.tree_core.is_root(node_id) or self.tree_core.is_host_memory_buffer_only
):
# Sub-window fetch: at root the sequence IS its window; mid-tree
# (buffer mode) the window head is the device prefix's own ring
Expand Down Expand Up @@ -1031,22 +1049,17 @@ def build_hicache_transfers(
return None

if phase == CacheTransferPhase.BACKUP_HOST:
if self.cache.host_memory_mode == "buffer_only":
# Buffer mode stages one node/hash span per FIFO backup intent.
cd = node.component_data[ct]
dirty = [node] if cd.value is not None else []
else:
dirty = self._dirty_backup_window(node)
if not dirty:
unbacked_swa_nodes = self._collect_unbacked_swa_nodes(node)
if not unbacked_swa_nodes:
return None
dirty.reverse()
unbacked_swa_nodes.reverse()
return [
PoolTransfer(
name=PoolName.SWA,
device_indices=torch.cat(
[n.component_data[ct].value for n in dirty]
[n.component_data[ct].value for n in unbacked_swa_nodes]
).to(torch.int64),
nodes_to_load=[n.id for n in dirty],
nodes_to_load=[n.id for n in unbacked_swa_nodes],
)
]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,7 @@ def __init__(
self.page_size = params.page_size
self.is_eagle = params.is_eagle and ComponentType.MAMBA not in components
self.enable_hicache = False
self.is_host_memory_buffer_only = False
self.enable_storage = False
self.enable_external_cache_linker = False
self.write_through_threshold = 256
Expand Down Expand Up @@ -1952,6 +1953,9 @@ def _is_host_leaf(self, node: UnifiedTreeNode) -> bool:
def set_hicache_enabled(self) -> None:
self.enable_hicache = True

def set_host_memory_buffer_only(self) -> None:
self.is_host_memory_buffer_only = True

def insert_host(
self,
node_id: NodeId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,8 @@ class UnifiedTreeCoreInterface(ABC):
write_through_threshold: int
is_write_back: bool
has_swa_host_pool: bool
# Whether the host tier stages one node per FIFO backup intent.
is_host_memory_buffer_only: bool
kv_events: KVCacheEventRecorder

# ==== Tree API ====
Expand Down Expand Up @@ -440,6 +442,11 @@ def set_hicache_enabled(self) -> None:
"""Mark the host tier (HiCache) as wired."""
...

@abstractmethod
def set_host_memory_buffer_only(self) -> None:
"""Mark the host tier as buffer-only: one node staged per backup intent."""
...

@abstractmethod
def insert_host(
self,
Expand Down
1 change: 1 addition & 0 deletions python/sglang/srt/mem_cache/unified_radix_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,7 @@ def init_hicache(self, server_args: ServerArgs, params: CacheInitParams) -> None
self.tree_core.has_swa_host_pool = swa._swa_kv_pool_host is not None

if self.host_memory_mode == "buffer_only":
self.tree_core.set_host_memory_buffer_only()
swa = self.components.get(ComponentType.SWA)
validate_buffer_only_stack(
sidecar_pool_specs=self.sidecar_pool_specs,
Expand Down
141 changes: 127 additions & 14 deletions rust/sglang-radix-tree/src/components/swa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,60 @@ impl SwaComponent {
}
}

/// Nodes whose SWA data needs a host backup, deepest first. Buffer mode
/// stages one node per FIFO backup intent; cache mode backs up every
/// device-only node within one sliding window of `node_id`.
fn collect_unbacked_swa_nodes_<K: ChildKeyType>(
&self,
tree_core: &UnifiedTreeCore<K>,
node_id: NodeIdx_,
) -> Vec<NodeIdx_> {
if !tree_core.has_swa_host_pool {
return Vec::new();
}
if tree_core.is_host_memory_buffer_only {
return if tree_core.arena.node(node_id).has_device_value(SWA) {
vec![node_id]
} else {
Vec::new()
};
}
self.collect_unbacked_swa_nodes_in_window_(tree_core, node_id)
}

/// Nodes within one sliding window of `node_id` whose SWA data sits on
/// device with no host copy, deepest first. The walk stops at a node an
/// in-flight backup already covers: that ack owns everything above it, so
/// two acks can never claim the same node.
fn collect_unbacked_swa_nodes_in_window_<K: ChildKeyType>(
&self,
tree_core: &UnifiedTreeCore<K>,
node_id: NodeIdx_,
) -> Vec<NodeIdx_> {
let mut covered_tokens = 0;
let mut unbacked: Vec<NodeIdx_> = Vec::new();
let mut cur_id = node_id;
while covered_tokens < self.sliding_window_size {
let cur = tree_core.arena.node(cur_id);
if cur.is_root() || cur.write_through_pending_id.is_some() {
break;
}
let (on_device, on_host) = (cur.has_device_value(SWA), cur.has_host_value(SWA));
covered_tokens += if on_device {
cur.device_value_len(SWA)
} else if on_host {
cur.host_value_len(SWA)
} else {
break;
};
if on_device && !on_host {
unbacked.push(cur_id);
}
cur_id = cur.parent();
}
unbacked
}

fn next_host_unlocked_device_lru_node<K: ChildKeyType>(
tree_core: &UnifiedTreeCore<K>,
from: Option<NodeIdx_>,
Expand Down Expand Up @@ -305,6 +359,12 @@ impl SwaComponent {
}

impl<K: ChildKeyType> TreeComponent<K> for SwaComponent {
fn needs_incremental_backup(&self, tree_core: &UnifiedTreeCore<K>, node_id: NodeIdx_) -> bool {
!self
.collect_unbacked_swa_nodes_(tree_core, node_id)
.is_empty()
}

fn component_type(&self) -> ComponentType {
SWA
}
Expand Down Expand Up @@ -363,6 +423,14 @@ impl<K: ChildKeyType> TreeComponent<K> for SwaComponent {
value_chunks: &[Tensor],
best_value_len: usize,
) -> MatchResult {
let swa_boundary_len = result.device_indices.size()[0] as usize + result.host_hit_length;

// Branch at the last page-aligned Full-KV position past the SWA boundary.
let page_aligned_full_hit_len =
result.full_kv_hit_length / tree_core.page_size * tree_core.page_size;
result.swa_branching_seqlen =
(page_aligned_full_hit_len > swa_boundary_len).then_some(page_aligned_full_hit_len);

// Sum the SWA tokens backing the match, walking up from the best match
// until one sliding window is covered; host-resident chunks count
// toward the SWA host hit.
Expand Down Expand Up @@ -536,6 +604,10 @@ impl<K: ChildKeyType> TreeComponent<K> for SwaComponent {
result: &mut InsertResult,
cache_actions: &mut Vec<CacheAction>,
) {
if let Some(branching_seqlen) = params.swa_branching_seqlen {
result.swa_branch_inserted = params.key.atom_len() >= branching_seqlen;
}

if !is_new_leaf {
return;
}
Expand Down Expand Up @@ -860,19 +932,29 @@ impl<K: ChildKeyType> TreeComponent<K> for SwaComponent {
}
Ok(match phase {
CacheTransferPhase::BackupHost => {
let node = tree_core.arena.node(node_id);
if node.has_host_value(SWA) {
let unbacked_swa_nodes = self.collect_unbacked_swa_nodes_(tree_core, node_id);
if unbacked_swa_nodes.is_empty() {
return Ok(None);
}
// cd.value already holds SWA-pool indices (translated at insert time).
// Host pool indexing wants int64.
node.try_device_value(SWA).map(|value| {
vec![PoolTransfer {
name: PoolName::Swa,
device_indices: Some(value.to_kind(Kind::Int64)),
..Default::default()
}]
})
// Ancestors first: the host span is contiguous and the commit
// scatters it back in this order. Device values already hold
// SWA-pool indices (translated at insert time); host pool
// indexing wants int64.
let (device_indices, backup_node_ids): (Vec<Tensor>, Vec<NodeId>) =
unbacked_swa_nodes
.iter()
.rev()
.map(|&idx| {
let node = tree_core.arena.node(idx);
(node.device_value(SWA).to_kind(Kind::Int64), node.id)
})
.unzip();
Some(vec![PoolTransfer {
name: PoolName::Swa,
device_indices: Some(Tensor::cat(&device_indices, 0)),
nodes_to_load: Some(backup_node_ids),
..Default::default()
}])
}
CacheTransferPhase::LoadBack => {
// `node` is best_match_node; the SWA validator guarantees every
Expand Down Expand Up @@ -992,14 +1074,45 @@ impl<K: ChildKeyType> TreeComponent<K> for SwaComponent {
) {
match phase {
CacheTransferPhase::BackupHost => {
if let Some(transfer) = transfers.first()
&& let Some(host_indices) = &transfer.host_indices
{
let Some(transfer) = transfers.first() else {
return;
};
let Some(host_indices) = &transfer.host_indices else {
return;
};
// A missing or empty `nodes_to_load` means the span is this node's alone.
let target_ids = transfer
.nodes_to_load
.as_deref()
.filter(|ids| !ids.is_empty());
let Some(target_ids) = target_ids else {
let node = tree_core.arena.node_mut(node_id);
if !node.has_host_value(SWA) {
node.set_host_value(SWA, host_indices.copy());
}
return;
};
let mut offset = 0i64;
for &target_id in target_ids {
let target_idx = tree_core
.arena
.resolve(target_id)
.expect("backup transfers must reference live nodes");
let target = tree_core.arena.node(target_idx);
assert!(
target.has_device_value(SWA) && !target.has_host_value(SWA),
"SWA backup target {} is not device-only",
target.id
);
let size = target.device_value_len(SWA) as i64;
tree_core.arena.set_host_value(
target_idx,
SWA,
host_indices.narrow(0, offset, size).copy(),
);
offset += size;
}
assert_eq!(offset, host_indices.size()[0]);
}
CacheTransferPhase::LoadBack => {
let transfer = transfers
Expand Down
Loading
Loading