[Kernel] ReplaySSM: cache SSM inputs for faster Mamba2 standard decode (#48018)

Signed-off-by: Johnny-Liou <a897111@gmail.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
Co-authored-by: tomeras91 <57313761+tomeras91@users.noreply.github.com>
Co-authored-by: Cyrus Leung <tlleungac@connect.ust.hk>
This commit is contained in:
Johnny-Liou
2026-07-24 09:39:49 -07:00
committed by GitHub
co-authored by Claude Opus 4.8 mergify[bot] <37929162+mergify[bot]@users.noreply.github.com> tomeras91 Cyrus Leung
parent d02df748bf
commit 866fea2b99
23 changed files with 2954 additions and 31 deletions
+6
View File
@@ -480,6 +480,11 @@ class CommonAttentionMetadata:
fixed sliding window. None disables R-SWA. The attention backend copies this
into its own persistent buffer and reads ``rswa_window`` from model config."""
replayssm_decode_base_cpu: torch.Tensor | None = None
"""(batch_size,) CPU ring origin for Mamba2 ReplaySSM decode: num_computed
at the current decode run's last full-state write. write_pos counts from
here, so a preemption-resumed request re-anchors past the prompt boundary."""
# WARNING: Deprecated fields. Will be removed in a future release (v0.15.0)
_seq_lens_cpu: torch.Tensor | None = None
_num_computed_tokens_cpu: torch.Tensor | None = None
@@ -591,6 +596,7 @@ class CommonAttentionMetadata:
dcp_local_seq_lens_cpu=maybe_slice_reqs(self.dcp_local_seq_lens_cpu),
is_prefilling=maybe_slice_reqs(self.is_prefilling),
rswa_prefix_lens=maybe_slice_reqs(self.rswa_prefix_lens),
replayssm_decode_base_cpu=maybe_slice_reqs(self.replayssm_decode_base_cpu),
)
+144
View File
@@ -74,6 +74,12 @@ class BaseMambaAttentionMetadata:
nums_dict: dict | None = None
batch_ptr: torch.Tensor | None = None
token_chunk_offset_ptr: torch.Tensor | None = None
# ReplaySSM standard decode: per-row ring cursor and flush flag, plus the
# per-step (decode_rows, ngroups, replayssm_buffer_len) fp32 scratch for the
# precomputed k^T q products. All None when use_replayssm is disabled.
write_pos_d: torch.Tensor | None = None
is_flush_d: torch.Tensor | None = None
bc_pre_scratch: torch.Tensor | None = None
class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
@@ -98,6 +104,8 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
self.compilation_config = vllm_config.compilation_config
self.num_spec_tokens: int = vllm_config.num_speculative_tokens
self.use_spec_decode = self.num_spec_tokens > 0
self.use_replayssm = vllm_config.cache_config.use_replayssm
self.replayssm_buffer_len = vllm_config.cache_config.replayssm_buffer_len
assert isinstance(kv_cache_spec, MambaSpec)
scheduler_config = vllm_config.scheduler_config
@@ -158,6 +166,36 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
dtype=torch.int32,
device=device,
)
# ReplaySSM standard-decode CUDA-graph buffers: per-row ring cursor,
# flush flag, and the k^T q precompute scratch.
if self.use_replayssm:
self.decode_write_pos_d: torch.Tensor = torch.empty(
(self.decode_cudagraph_max_bs,),
dtype=torch.int32,
device=device,
)
self.decode_is_flush_d: torch.Tensor = torch.empty(
(self.decode_cudagraph_max_bs,),
dtype=torch.int8,
device=device,
)
# B_cache shape = (ngroups, replayssm_buffer_len, dstate); the page
# layout is (conv_state, ssm_state, x_cache, dt_cache, B_cache).
bc_ngroups = kv_cache_spec.shapes[4][0]
bc_scratch_bs = max(
self.decode_cudagraph_max_bs, scheduler_config.max_num_seqs
)
self.decode_bc_pre_scratch: torch.Tensor = torch.empty(
(
bc_scratch_bs,
bc_ngroups,
self.replayssm_buffer_len,
),
dtype=torch.float32,
device=device,
)
else:
self.decode_bc_pre_scratch = None
self._init_reorder_batch_threshold(1, self.use_spec_decode)
if self.use_spec_decode:
@@ -414,6 +452,8 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
has_prior_state = seq_lens_cpu > 1
prefill_to_decode = single_token_prefill_rows & has_prior_state
if torch.any(prefill_to_decode).item():
# ReplaySSM handles these rows as single-token flushes (see the
# write-position derivation below), same as the baseline decode path.
is_prefilling = is_prefilling.clone()
is_prefilling[prefill_to_decode] = False
common_attn_metadata = common_attn_metadata.replace(
@@ -444,6 +484,8 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
# for causal_conv1d
nums_dict, batch_ptr, token_chunk_offset_ptr = None, None, None
write_pos_d = None
is_flush_d = None
if self.vllm_config.cache_config.mamba_cache_mode == "all":
num_computed_tokens = common_attn_metadata.compute_num_computed_tokens()
@@ -530,6 +572,79 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
num_reqs - num_prefills : num_reqs
]
if self.use_replayssm and num_decodes > 0:
decode_base_cpu = common_attn_metadata.replayssm_decode_base_cpu
num_computed_tokens_cpu = common_attn_metadata._num_computed_tokens_cpu
if decode_base_cpu is None or num_computed_tokens_cpu is None:
raise ValueError(
"--use-replayssm requires CPU decode-base and "
"computed-token counts to derive decode write positions"
)
num_computed_d = num_computed_tokens_cpu[:num_decodes]
decode_base_d = decode_base_cpu[:num_decodes]
align_mode = self.vllm_config.cache_config.mamba_cache_mode == "align"
block_size = self.kv_cache_spec.block_size
if align_mode:
# After a boundary the align copy leaves an exact checkpoint at
# the block start and the new block's ring restarts empty, so
# re-anchor there; max() keeps the prompt-end anchor for the
# first (partial) block.
effective_base = torch.maximum(
decode_base_d, (num_computed_d // block_size) * block_size
)
else:
effective_base = decode_base_d
# write_pos counts decode steps since the ring's last full-state
# write (the anchor), so a resumed request re-anchors correctly.
decode_steps_cpu = num_computed_d - effective_base
query_lens_cpu = (
common_attn_metadata.query_start_loc_cpu[1 : num_decodes + 1]
- common_attn_metadata.query_start_loc_cpu[:num_decodes]
)
valid_decode_rows = query_lens_cpu > 0
# A single-token prefill row replayed as decode (query_len==1 with
# prior state) has decode_steps < 0; force it to a one-token flush
# (write_pos=0, is_flush=1). The flush branch reads an empty history
# window, so it applies exactly one recurrence step off the checkpoint
# -- identical to the baseline decode kernel for that row. The split
# (treat_short_extends_as_decodes=False) admits only such rows here.
leftover_prompt = valid_decode_rows & (decode_steps_cpu < 0)
decode_steps_cpu = torch.where(
valid_decode_rows & ~leftover_prompt,
decode_steps_cpu,
torch.zeros_like(decode_steps_cpu),
)
write_pos_cpu = torch.remainder(decode_steps_cpu, self.replayssm_buffer_len)
is_flush_cpu = (
write_pos_cpu == self.replayssm_buffer_len - 1
) | leftover_prompt
if align_mode:
# Force a flush on the step completing a mamba block so the exact
# boundary state is materialized for prefix caching.
is_flush_cpu = is_flush_cpu | (
valid_decode_rows
& ((num_computed_d + query_lens_cpu) % block_size == 0)
)
is_flush_cpu = is_flush_cpu.to(torch.int8)
write_pos_d = async_tensor_h2d(
write_pos_cpu.to(torch.int32).tolist(),
dtype=torch.int32,
device=common_attn_metadata.query_start_loc.device,
)
is_flush_d = async_tensor_h2d(
is_flush_cpu.tolist(),
dtype=torch.int8,
device=common_attn_metadata.query_start_loc.device,
)
bc_pre_scratch = None
if (
self.use_replayssm
and self.decode_bc_pre_scratch is not None
and num_decodes > 0
):
bc_pre_scratch = self.decode_bc_pre_scratch[:num_decodes]
metadata = self.metadata_cls(
num_prefills=num_prefills,
num_prefill_tokens=num_prefill_tokens,
@@ -539,6 +654,9 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
has_initial_states_p=has_initial_states_p,
state_indices_tensor_p=state_indices_tensor_p,
state_indices_tensor_d=state_indices_tensor_d,
write_pos_d=write_pos_d,
is_flush_d=is_flush_d,
bc_pre_scratch=bc_pre_scratch,
num_accepted_tokens=num_accepted_tokens,
query_start_loc_d=query_start_loc_d,
block_idx_last_scheduled_token=block_idx_last_scheduled_token,
@@ -573,6 +691,9 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
block_idx_last_scheduled_token_prev_step = (
metadata.block_idx_last_scheduled_token_prev_step
)
write_pos_d = metadata.write_pos_d
is_flush_d = metadata.is_flush_d
bc_pre_scratch = metadata.bc_pre_scratch
if (
metadata.num_prefills == 0
and metadata.num_decodes <= self.decode_cudagraph_max_bs
@@ -634,11 +755,34 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
)
block_idx_last_scheduled_token_prev_step[metadata.num_decodes :] = 0
if self.use_replayssm:
assert write_pos_d is not None
assert is_flush_d is not None
self.decode_write_pos_d[: metadata.num_decodes].copy_(
write_pos_d[: metadata.num_decodes],
non_blocking=True,
)
write_pos_d = self.decode_write_pos_d[:padded_bs]
write_pos_d[metadata.num_decodes :] = 0
self.decode_is_flush_d[: metadata.num_decodes].copy_(
is_flush_d[: metadata.num_decodes],
non_blocking=True,
)
is_flush_d = self.decode_is_flush_d[:padded_bs]
is_flush_d[metadata.num_decodes :] = 0
if self.decode_bc_pre_scratch is not None:
bc_pre_scratch = self.decode_bc_pre_scratch[:padded_bs]
return replace(
metadata,
state_indices_tensor_d=state_indices_tensor_d,
query_start_loc_d=query_start_loc_d,
num_accepted_tokens=num_accepted_tokens,
write_pos_d=write_pos_d,
is_flush_d=is_flush_d,
bc_pre_scratch=bc_pre_scratch,
block_idx_last_scheduled_token=block_idx_last_scheduled_token,
block_idx_last_computed_token=block_idx_last_computed_token,
block_idx_last_scheduled_token_prev_step=(
+26
View File
@@ -106,6 +106,7 @@ class InputBatch:
is_pooling_model: bool = False,
cp_kv_cache_interleave_size: int = 1,
reasoning_config: ReasoningConfig | None = None,
use_replayssm: bool = False,
slot_mapping_modes: list[SlotMappingMode] | None = None,
):
self.thinking_budget_state_holder = maybe_create_thinking_budget_state_holder(
@@ -170,6 +171,17 @@ class InputBatch:
)
self.num_computed_tokens_cpu = self.num_computed_tokens_cpu_tensor.numpy()
# Mamba2 ReplaySSM decode ring origin (num_computed at each request's
# last full-state write); populated only when the feature is on.
self.use_replayssm = use_replayssm
self.replayssm_decode_base_cpu_tensor = torch.zeros(
(max_num_reqs,),
device="cpu",
dtype=torch.int32,
pin_memory=PIN_MEMORY,
)
self.replayssm_decode_base = self.replayssm_decode_base_cpu_tensor.numpy()
# Block table.
self.block_table = MultiGroupBlockTable(
max_num_reqs=max_num_reqs,
@@ -377,6 +389,11 @@ class InputBatch:
# Number of tokens without spec decode tokens.
self.num_tokens_no_spec[req_index] = request.num_tokens
if self.use_replayssm:
# Ring origin = full context at (re)admission (prompt + any resumed
# output), so a resumed request re-anchors past the prompt.
self.replayssm_decode_base[req_index] = request.num_tokens
self.num_computed_tokens_cpu[req_index] = request.num_computed_tokens
self.block_table.add_row(request.block_ids, req_index)
@@ -597,6 +614,11 @@ class InputBatch:
self.num_prompt_tokens[i2],
self.num_prompt_tokens[i1],
)
if self.use_replayssm:
self.replayssm_decode_base[i1], self.replayssm_decode_base[i2] = (
self.replayssm_decode_base[i2],
self.replayssm_decode_base[i1],
)
self.num_computed_tokens_cpu[i1], self.num_computed_tokens_cpu[i2] = (
self.num_computed_tokens_cpu[i2],
self.num_computed_tokens_cpu[i1],
@@ -754,6 +776,10 @@ class InputBatch:
last_req_index
]
self.num_prompt_tokens[empty_index] = self.num_prompt_tokens[last_req_index]
if self.use_replayssm:
self.replayssm_decode_base[empty_index] = self.replayssm_decode_base[
last_req_index
]
self.num_computed_tokens_cpu[empty_index] = self.num_computed_tokens_cpu[
last_req_index
]
+9
View File
@@ -727,6 +727,7 @@ class GPUModelRunner(
is_pooling_model=self.is_pooling_model,
cp_kv_cache_interleave_size=self.parallel_config.cp_kv_cache_interleave_size,
reasoning_config=self.vllm_config.reasoning_config,
use_replayssm=self.cache_config.use_replayssm,
)
# Separate cuda stream for overlapping transfer of sampled token ids from
@@ -2413,6 +2414,12 @@ class GPUModelRunner(
if self.model_config.rswa_window is not None:
rswa_prefix_lens = num_prompt_tokens_cpu
replayssm_decode_base_cpu = None
if self.cache_config.use_replayssm:
replayssm_decode_base_cpu = (
self.input_batch.replayssm_decode_base_cpu_tensor[:num_reqs_padded]
)
cm_base = CommonAttentionMetadata(
query_start_loc=self.query_start_loc.gpu[: num_reqs_padded + 1],
query_start_loc_cpu=self.query_start_loc.cpu[: num_reqs_padded + 1],
@@ -2420,6 +2427,7 @@ class GPUModelRunner(
_seq_lens_cpu=seq_lens_cpu,
_num_computed_tokens_cpu=num_computed_tokens_cpu,
seq_lens_cpu_upper_bound=seq_lens_cpu_upper_bound,
replayssm_decode_base_cpu=replayssm_decode_base_cpu,
num_reqs=num_reqs_padded,
num_actual_tokens=num_tokens_padded,
max_query_len=max_query_len,
@@ -7262,6 +7270,7 @@ class GPUModelRunner(
is_pooling_model=self.is_pooling_model,
cp_kv_cache_interleave_size=self.parallel_config.cp_kv_cache_interleave_size,
reasoning_config=self.vllm_config.reasoning_config,
use_replayssm=self.cache_config.use_replayssm,
slot_mapping_modes=slot_mapping_modes,
)