Skip to content

vllm.v1.worker.mamba_utils

Classes:

Functions:

MambaSpecDecodeGPUContext dataclass

Context for GPU-side Mamba state copy operations during the fused postprocess path.

Used for hybrid speculative state maintenance and for model-owned ReplaySSM tracker prefix-cache lifecycle maintenance.

Precomputes memory layout metadata (base addresses, strides, element sizes) so the GPU kernel can perform state copies without CPU-GPU sync.

State types are distinguished by conv_width: >0 for conv states (sliding window with offset-based copies), 0 for temporal states (full block copies).

Methods:

compute_aligned_state_indices(seq_lens, num_reqs)

Compute every Mamba group's aligned physical state IDs in one launch.

create(max_num_reqs, kv_cache_config, copy_funcs, forward_context, device) classmethod

Create context with allocated buffers (metadata populated later).

initialize_from_forward_context(kv_cache_config, forward_context, mamba_state_copy_funcs, block_tables, aligned_index_block_tables=None)

Extract and cache memory layout metadata from Mamba state tensors.

This method populates the pre-allocated metadata tensors with information needed by postprocess_mamba_fused_kernel to perform state copies entirely on the GPU without CPU-GPU synchronization.

For each Mamba layer and state type, the following metadata is extracted: - state_base_addrs: GPU memory address (data_ptr) of the state tensor - state_block_strides: Bytes between consecutive blocks (stride * elem_size) - state_elem_sizes: Element size in bytes (e.g., 2 for float16) - state_inner_sizes: For conv states, elements per conv position (stride(1)), used to compute offset when slicing state[block, offset:]. For temporal states, this field is unused (set to 1). - state_conv_widths: Conv dimension size for conv states, 0 for temporal states

The conv vs temporal state type is detected by inspecting the copy function name: functions containing "conv" are treated as conv states.

This method is idempotent - it only executes once (guarded by is_initialized flag) since the metadata is static after model loading.

Parameters:

  • kv_cache_config

    (KVCacheConfig) –

    Configuration containing KV cache group info and layer name mappings.

  • forward_context

    (dict[str, Any]) –

    Dictionary mapping layer names to attention objects, populated after the model is loaded. Each attention object must have a kv_cache attribute containing the list of state tensors.

  • mamba_state_copy_funcs

    (MambaStateCopyFuncsByType) –

    Mapping from MambaAttentionBackendEnum to copy functions.

  • block_tables

    (list[Tensor]) –

    per-mamba-group persistent block-table tensors, in the same order as mamba_group_ids, with one row per request state slot. Their data_ptr() / stride(0) are captured once for the state-copy kernels to index into.

  • aligned_index_block_tables

    (list[Tensor] | None, default: None ) –

    per-mamba-group persistent tables read by compute_aligned_state_indices, with one row per batch row. Defaults to block_tables.

run_fused_postprocess_align(num_reqs, num_accepted_tokens_gpu, state_idx_gpu, new_num_computed_tokens_gpu, idx_mapping)

V2 align postprocess: save the running state to the block-aligned position after spec-decode acceptance leaves the sequence non-aligned.

num_accepted_tokens_gpu is updated in place while the kernel reads from a snapshot to avoid cross-program races when the accepted position stays in the running block and the count is reset to 1. new_num_computed_tokens already holds the post-step computed count (PRECOMPUTED_NEW_COMPUTED). idx_mapping maps batch row -> req-state slot (HAS_IDX_MAPPING).

run_fused_precopy(num_reqs, state_idx_gpu, src_col_gpu, token_bias_gpu, idx_mapping)

Pre-copy each request's previous running block into its new window block before the forward pass (align boundary migration).

Parameters:

  • num_reqs

    (int) –

    Number of active requests (batch order).

  • state_idx_gpu

    (Tensor) –

    [max_reqs] post-advance dst block column per req slot.

  • src_col_gpu

    (Tensor) –

    [max_reqs] pre-advance src block column (-1 = fresh).

  • token_bias_gpu

    (Tensor) –

    [max_reqs] accepted-token bias (num_accepted - 1).

  • idx_mapping

    (Tensor | None) –

    optional [num_reqs] batch_idx -> req_state_idx. None means batch order already equals request state order.

_copy_mamba_state_block(state_idx, bt_row_idx, src_col, dst_col, token_bias, block_table_ptrs_ptr, block_table_stride_req, state_base_addrs_ptr, state_block_strides_ptr, state_elem_sizes_ptr, state_inner_sizes_ptr, state_conv_widths_ptr, state_group_indices_ptr, state_dim_row_count_ptr, state_dim_row_stride_ptr, tile_idx, COPY_BLOCK_SIZE, CONV_STATE_DIM_FIRST, TEMPORAL_TILES)

Copy one (layer, state-type) mamba state block between block columns.

Shared copy body of postprocess_mamba_fused_kernel and precopy_mamba_align_fused_kernel: - conv state (conv_width > 0): shift the window by token_bias tokens, state[bt[src_col], token_bias:] -> state[bt[dst_col], :conv_width - token_bias] - temporal state: token_bias selects the accepted speculative column, state[bt[src_col + token_bias]] -> state[bt[dst_col]]

The caller owns the decision logic (which columns, whether to copy); this device function only performs the byte copy for the given metadata slot.

tile_idx in [0, TEMPORAL_TILES) partitions the temporal state's u64 range into TEMPORAL_TILES contiguous, COPY_BLOCK_SIZE-aligned slices, giving more CTAs to fill the SMs at small batch (multi-MiB temporal copies otherwise leave the GPU under-filled). Conv states are small; only tile_idx == 0 copies them. TEMPORAL_TILES == 1 and tile_idx == 0 reproduces the untiled behavior.

_memcpy_u64_tiled(src_addr, dst_addr, copy_size, tile_idx, COPY_BLOCK_SIZE, NUM_TILES)

Head/body/tail memcpy with the u64 body split across NUM_TILES CTAs.

Fast path (src and dst share sub-8B alignment): tile 0 owns the byte head that lifts dst to 8B and the 0-7 byte tail; body tiles vectorize as u64 over the aligned interior. NUM_TILES=1 collapses to a single- CTA memcpy. Production callers derive both addresses from the same state_base_addr + block_id * stride and always take this path.

Slow path (mismatched sub-8B alignment): byte-wide tiled copy. Some NVIDIA parts (e.g. GB200) reject misaligned u64 loads with cudaErrorMisalignedAddress instead of accepting the misaligned-sector cost, so we can't just let the fast path run with a misaligned src.

get_mamba_group_ids(mamba_groups)

Return the sorted group ids of all mamba groups, without duplicates.

A group whose layers use different MambaSpecs is listed under one key per spec, so the same group id can appear more than once.

get_mamba_group_params(kv_cache_config, mamba_group_ids)

Return the block size and speculative block count shared by the mamba groups.

get_mamba_groups(kv_cache_config)

Return a mapping from each distinct MambaSpec to its sorted group_ids.

postprocess_mamba_fused_kernel(num_accepted_tokens_ptr, mamba_state_idx_ptr, num_scheduled_tokens_ptr, num_computed_tokens_ptr, num_draft_tokens_ptr, block_table_ptrs_ptr, block_table_stride_req, state_base_addrs_ptr, state_block_strides_ptr, state_elem_sizes_ptr, state_inner_sizes_ptr, state_conv_widths_ptr, state_group_indices_ptr, state_dim_row_count_ptr, state_dim_row_stride_ptr, num_accepted_tokens_out_ptr, idx_mapping_ptr, num_reqs, block_size, COPY_BLOCK_SIZE, CONV_STATE_DIM_FIRST, HAS_IDX_MAPPING=False, PRECOMPUTED_NEW_COMPUTED=False, SKIP_TEMPORAL_STATE_COPY=False, TEMPORAL_TILES=1)

Fused GPU kernel for postprocess_mamba that computes decisions AND performs mamba state copies without any CPU-GPU synchronization.

Grid: (num_reqs, num_states [, TEMPORAL_TILES]) - program_id(0) = request/batch index - program_id(1) = state_idx (flattened index into layer/state_type metadata) - program_id(2) = temporal-copy tile index (0 when TEMPORAL_TILES == 1)

The kernel indexes directly into pre-flattened metadata arrays using program_id(1). The grid dimensions encode the total state count.

precopy_mamba_align_fused_kernel(mamba_state_idx_ptr, src_col_ptr, token_bias_ptr, block_table_ptrs_ptr, block_table_stride_req, state_base_addrs_ptr, state_block_strides_ptr, state_elem_sizes_ptr, state_inner_sizes_ptr, state_conv_widths_ptr, state_group_indices_ptr, state_dim_row_count_ptr, state_dim_row_stride_ptr, idx_mapping_ptr, num_reqs, COPY_BLOCK_SIZE, CONV_STATE_DIM_FIRST, HAS_IDX_MAPPING=True, ZERO_TEMPORAL_TOKEN_BIAS=False, TEMPORAL_TILES=1)

Pre-copy mamba state across block boundaries.

Before the forward pass, copy each request's last SSM/conv state from its previous block column into the new window block column, so the kernels read the initial state from the write-side block as usual. Same per-(layer, state) copy semantics as postprocess_mamba_fused_kernel (shared _copy_mamba_state_block body), but driven by the GPU-resident src columns so it needs no CPU-GPU sync (async-scheduling safe).

Grid: (num_reqs, num_states [, TEMPORAL_TILES]). The runner passes a batch-to-state idx_mapping; HAS_IDX_MAPPING=False is for arrays already staged in batch order.

preprocess_mamba_align_fused_kernel(idx_mapping_ptr, state_idx_ptr, num_computed_tokens_ptr, query_start_loc_ptr, num_accepted_tokens_ptr, src_col_ptr, src_off_ptr, num_reqs, BLOCK_SIZE, MAMBA_BLOCK_SIZE, HAS_IDX_MAPPING=True)

Fused align preprocess: emit the pre-copy src column/offset AND advance state_idx in a single launch (V2 align).

Per batch_idx (0..num_reqs-1), resolving req slot via idx_mapping: 1. Read pre-advance state_idx and num_accepted (last step's values). 2. Store the pre-copy src columns for precopy_mamba_align_fused_kernel: - src_col = state_idx (the previous running block column) - src_off = max(num_accepted - 1, 0) (the accepted-token bias) 3. Advance state_idx to the new running block. Reset num_accepted to 1 when the block changes: the migrated convolution state now sits at the start of the new block and must be read with the neutral accepted-token bias. ReplaySSM ring cursors are migrated separately.