Skip to content

Commit d7664ae

Browse files
committed
[None][fix] Bound Nemotron replay memory to resident requests
* Why? The V2 Mamba cache manager allocates replay history for every SSM pool slot, including cached snapshots, without reserving its cost in the cache budget. Larger snapshot pools can therefore cause startup OOMs. * What? Size replay history for admitted sequences plus required dummy slots, reserve its cost in the cache budget, and map SSM slots to replay slots; the replay kernels take the replay index separately from the recurrent-state index. A request owns its replay slot from first schedule until it is freed, including while suspended. Admitted requests, suspended ones included, are capped at `max_batch_size * pp_size`, so replay history never leaves the GPU. Relocation and resumption only refresh the SSM-to-replay lookup, which is updated in place so captured CUDA graphs see the new mapping. Nemotron replay now rejects `enable_kv_pool_rebalance`, as KDA replay already did, because the SSM-to-replay lookup is sized from the initial SSM pool. Signed-off-by: William Zhang <133824995+2ez4bz@users.noreply.github.com>
1 parent ec78256 commit d7664ae

8 files changed

Lines changed: 864 additions & 93 deletions

File tree

‎tensorrt_llm/_torch/modules/mamba/mamba2_metadata.py‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -385,6 +385,9 @@ def __init__(
385385
device="cuda")
386386
self.replay_n_writes = torch.zeros(1, dtype=torch.int32, device="cuda")
387387
self.replay_num_decodes = 0
388+
self.replay_state_indices = torch.zeros(max_batch_size,
389+
dtype=torch.int32,
390+
device="cuda")
388391

389392
# Pre-allocated buffers.
390393
self._arange_buffer = torch.arange(max_batch_size + 1,
@@ -416,6 +419,10 @@ def _prepare_replay_work_items(self, kv_cache_manager, batch_size: int,
416419
if num_decodes < CACHED_REPLAY_PARTITION_MIN_BATCH_SIZE:
417420
return
418421

422+
self.replay_state_indices[:num_decodes].copy_(
423+
kv_cache_manager.get_replay_state_indices(
424+
self.state_indices[num_contexts:batch_size]))
425+
419426
if not hasattr(kv_cache_manager, 'get_replay_state_update_metadata'):
420427
raise RuntimeError(
421428
"Replay state update is enabled, but the KV cache manager "
@@ -438,7 +445,7 @@ def _prepare_replay_work_items(self, kv_cache_manager, batch_size: int,
438445
else:
439446
build_work_items = _build_replay_work_items_torch
440447
build_work_items(
441-
self.state_indices[num_contexts:batch_size],
448+
self.replay_state_indices[:num_decodes],
442449
prev_num_accepted_tokens,
443450
cache_buf_idx,
444451
self.replay_work_items,

‎tensorrt_llm/_torch/modules/mamba/mamba2_mixer.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -825,6 +825,8 @@ def convert_dt():
825825
dt_bias=dt_bias,
826826
dt_softplus=self.delta_softplus,
827827
state_batch_indices=state_batch_indices,
828+
replay_batch_indices=mamba_metadata.
829+
replay_state_indices[:num_decodes],
828830
out=out_4d,
829831
n_writes=mamba_metadata.replay_n_writes,
830832
replay_work_items=(

‎tensorrt_llm/_torch/modules/mamba/replay_selective_state_update.py‎

Lines changed: 44 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,7 @@ def _replay_precompute_impl(
205205
# [0, PNAT) of the active buffer; new tokens this step go after them
206206
# on no-replay-write steps).
207207
prev_num_accepted_tokens_ptr,
208-
state_batch_indices_ptr,
208+
replay_batch_indices_ptr,
209209
# Dimensions
210210
T: tl.constexpr,
211211
dstate: tl.constexpr,
@@ -271,7 +271,7 @@ def _replay_precompute_impl(
271271
pid_hg = tl.program_id(axis=1) # head-group index
272272
first_head = pid_hg * HEADS_PER_BLOCK
273273

274-
cache_batch_idx = tl.load(state_batch_indices_ptr + pid_b).to(tl.int64)
274+
cache_batch_idx = tl.load(replay_batch_indices_ptr + pid_b).to(tl.int64)
275275

276276
# --- Cache write semantics ---
277277
# cache_buf_idx names this step's "active" buffer — the one with the
@@ -458,7 +458,7 @@ def _rectangle_precompute_impl(
458458
old_dA_cumsum_ptr,
459459
cache_buf_idx_ptr,
460460
prev_num_accepted_tokens_ptr,
461-
state_batch_indices_ptr,
461+
replay_batch_indices_ptr,
462462
# Dimensions
463463
T: tl.constexpr,
464464
MAX_REPLAY_BUFFER_LENGTH: tl.constexpr, # rectangle window bound
@@ -519,7 +519,7 @@ def _rectangle_precompute_impl(
519519
pid_hg = tl.program_id(axis=1)
520520
first_head = pid_hg * HEADS_PER_BLOCK
521521

522-
cache_batch_idx = tl.load(state_batch_indices_ptr + pid_b).to(tl.int64)
522+
cache_batch_idx = tl.load(replay_batch_indices_ptr + pid_b).to(tl.int64)
523523

524524
# Nowrite-only: write_buf = active, write_offset = PNAT. No flip after.
525525
buf_active = tl.load(cache_buf_idx_ptr + cache_batch_idx).to(tl.int32)
@@ -809,7 +809,7 @@ def _dynamic_precompute_kernel(
809809
old_dA_cumsum_ptr,
810810
cache_buf_idx_ptr,
811811
prev_num_accepted_tokens_ptr,
812-
state_batch_indices_ptr,
812+
replay_batch_indices_ptr,
813813
# Dimensions
814814
T: tl.constexpr,
815815
MAX_REPLAY_BUFFER_LENGTH: tl.constexpr,
@@ -874,7 +874,7 @@ def _dynamic_precompute_kernel(
874874
tl.extra.cuda.gdc_launch_dependents()
875875

876876
pid_b = tl.program_id(axis=0)
877-
cache_batch_idx = tl.load(state_batch_indices_ptr + pid_b).to(tl.int64)
877+
cache_batch_idx = tl.load(replay_batch_indices_ptr + pid_b).to(tl.int64)
878878

879879
pnat_local = tl.load(prev_num_accepted_tokens_ptr + cache_batch_idx)
880880
needs_write_runtime = pnat_local + T > MAX_REPLAY_BUFFER_LENGTH
@@ -894,7 +894,7 @@ def _dynamic_precompute_kernel(
894894
old_dA_cumsum_ptr,
895895
cache_buf_idx_ptr,
896896
prev_num_accepted_tokens_ptr,
897-
state_batch_indices_ptr,
897+
replay_batch_indices_ptr,
898898
T,
899899
dstate,
900900
nheads_ngroups_ratio,
@@ -953,7 +953,7 @@ def _dynamic_precompute_kernel(
953953
old_dA_cumsum_ptr,
954954
cache_buf_idx_ptr,
955955
prev_num_accepted_tokens_ptr,
956-
state_batch_indices_ptr,
956+
replay_batch_indices_ptr,
957957
T,
958958
MAX_REPLAY_BUFFER_LENGTH,
959959
dstate,
@@ -1015,6 +1015,7 @@ def _persistent_main_impl(
10151015
pid_b,
10161016
pid_h,
10171017
cache_batch_idx,
1018+
state_batch_idx,
10181019
active_buf,
10191020
prev_num_accepted_tokens,
10201021
# Pointers
@@ -1192,11 +1193,11 @@ def _persistent_main_impl(
11921193
# when no TMA path is reachable).
11931194
state_mask = m_mask[:, None] & n_mask[None, :]
11941195
offs_y = (
1195-
cache_batch_idx.to(tl.int32) * (stride_state_batch // stride_state_dim).to(tl.int32)
1196+
state_batch_idx.to(tl.int32) * (stride_state_batch // stride_state_dim).to(tl.int32)
11961197
+ pid_h * dim
11971198
+ pid_m * BLOCK_SIZE_M
11981199
)
1199-
state_ptr_raw = state_ptr + cache_batch_idx * stride_state_batch + pid_h * stride_state_head
1200+
state_ptr_raw = state_ptr + state_batch_idx * stride_state_batch + pid_h * stride_state_head
12001201
state_ptrs = (
12011202
state_ptr_raw + offs_m[:, None] * stride_state_dim + offs_n[None, :] * stride_state_dstate
12021203
)
@@ -1219,7 +1220,7 @@ def _persistent_main_impl(
12191220
if QUANT_MAX > 0.0:
12201221
state_scales_base = (
12211222
state_scales_ptr
1222-
+ cache_batch_idx * stride_state_scales_cache
1223+
+ state_batch_idx * stride_state_scales_cache
12231224
+ pid_h * stride_state_scales_head
12241225
)
12251226
decode_scale = tl.load(
@@ -1332,7 +1333,7 @@ def _persistent_main_impl(
13321333
RAND_DIVISOR: tl.constexpr = 1 # unreachable; keeps constexpr initialized
13331334

13341335
rand_seed = tl.load(rand_seed_ptr)
1335-
base_rand = cache_batch_idx * stride_state_batch + pid_h * stride_state_head
1336+
base_rand = state_batch_idx * stride_state_batch + pid_h * stride_state_head
13361337
# Number of unique randoms per row = dstate / RAND_DIVISOR.
13371338
# randint4x emits 4 randoms per offset, so use that / 4 offsets.
13381339
offs_n_q = tl.arange(0, BLOCK_SIZE_DSTATE // (4 * RAND_DIVISOR))
@@ -1369,7 +1370,7 @@ def _persistent_main_impl(
13691370
decode_scale = 1.0 / encode_scale
13701371
state_scales_ptrs = (
13711372
state_scales_ptr
1372-
+ cache_batch_idx * stride_state_scales_cache
1373+
+ state_batch_idx * stride_state_scales_cache
13731374
+ pid_h * stride_state_scales_head
13741375
+ offs_m * stride_state_scales_dim
13751376
)
@@ -1500,6 +1501,7 @@ def _persistent_rectangle_impl(
15001501
pid_b,
15011502
pid_h,
15021503
cache_batch_idx,
1504+
state_batch_idx,
15031505
active_buf,
15041506
prev_num_accepted_tokens,
15051507
# Pointers
@@ -1602,14 +1604,14 @@ def _persistent_rectangle_impl(
16021604
# Load state. Quant scale hoist: defer `* decode_scale` post-matmul.
16031605
if USE_TMA_LOAD:
16041606
offs_y = (
1605-
cache_batch_idx.to(tl.int32) * (stride_state_batch // stride_state_dim).to(tl.int32)
1607+
state_batch_idx.to(tl.int32) * (stride_state_batch // stride_state_dim).to(tl.int32)
16061608
+ pid_h * dim
16071609
+ pid_m * BLOCK_SIZE_M
16081610
)
16091611
state = state_tma_descriptor.load([offs_y, 0])
16101612
else:
16111613
state_ptr_local = (
1612-
state_ptr + cache_batch_idx * stride_state_batch + pid_h * stride_state_head
1614+
state_ptr + state_batch_idx * stride_state_batch + pid_h * stride_state_head
16131615
)
16141616
state_ptrs = (
16151617
state_ptr_local
@@ -1621,7 +1623,7 @@ def _persistent_rectangle_impl(
16211623
if QUANT_MAX > 0.0:
16221624
state_scales_base = (
16231625
state_scales_ptr
1624-
+ cache_batch_idx * stride_state_scales_cache
1626+
+ state_batch_idx * stride_state_scales_cache
16251627
+ pid_h * stride_state_scales_head
16261628
)
16271629
decode_scale = tl.load(
@@ -1788,6 +1790,7 @@ def _persistent_main_kernel(
17881790
cb_scaled_ptr,
17891791
decay_vec_ptr,
17901792
state_batch_indices_ptr,
1793+
replay_batch_indices_ptr,
17911794
replay_work_items_ptr,
17921795
rand_seed_ptr,
17931796
# Persistent-loop work-distribution scalars. Caller pre-sorts the batch
@@ -1969,7 +1972,7 @@ def _persistent_main_kernel(
19691972
work_item_idx = pid_b_local + slot_lo
19701973
if IS_DYNAMIC:
19711974
pid_b = work_item_idx
1972-
cache_batch_idx = tl.load(state_batch_indices_ptr + pid_b).to(tl.int64)
1975+
cache_batch_idx = tl.load(replay_batch_indices_ptr + pid_b).to(tl.int64)
19731976
active_buf = tl.load(cache_buf_idx_ptr + cache_batch_idx).to(tl.int32)
19741977
pnat = tl.load(prev_num_accepted_tokens_ptr + cache_batch_idx)
19751978
else:
@@ -1978,6 +1981,7 @@ def _persistent_main_kernel(
19781981
cache_batch_idx = tl.load(work_item_base + _REPLAY_WORK_CACHE_SLOT).to(tl.int64)
19791982
pnat = tl.load(work_item_base + _REPLAY_WORK_PNAT)
19801983
active_buf = tl.load(work_item_base + _REPLAY_WORK_CACHE_BUF_IDX).to(tl.int32)
1984+
state_batch_idx = tl.load(state_batch_indices_ptr + pid_b).to(tl.int64)
19811985
# Dispatch: when RECTANGLE is set, send nowrite slots to the rectangle
19821986
# impl. `replay_work_items` carries the cache slot, PNAT and active
19831987
# buffer for persistent_main; persistent_dynamic resolves those once
@@ -2005,6 +2009,7 @@ def _persistent_main_kernel(
20052009
pid_b,
20062010
pid_h,
20072011
cache_batch_idx,
2012+
state_batch_idx,
20082013
active_buf,
20092014
pnat,
20102015
state_ptr,
@@ -2100,6 +2105,7 @@ def _persistent_main_kernel(
21002105
pid_b,
21012106
pid_h,
21022107
cache_batch_idx,
2108+
state_batch_idx,
21032109
active_buf,
21042110
pnat,
21052111
state_ptr,
@@ -2171,6 +2177,7 @@ def _persistent_main_kernel(
21712177
pid_b,
21722178
pid_h,
21732179
cache_batch_idx,
2180+
state_batch_idx,
21742181
active_buf,
21752182
pnat,
21762183
state_ptr,
@@ -3493,6 +3500,7 @@ def replay_selective_state_update(
34933500
_cta_per_sm_nowrite: int | None = None,
34943501
_num_loop_stages_write: int | None = None,
34953502
_num_loop_stages_nowrite: int | None = None,
3503+
replay_batch_indices: torch.Tensor | None = None,
34963504
):
34973505
"""
34983506
Replay SSM state update with precomputed CB and tl.dot fast-forward.
@@ -3537,7 +3545,9 @@ def replay_selective_state_update(
35373545
replay_work_items: (batch, 4) int32 device tensor, sorted write-first.
35383546
Persistent-main consumes all fields; persistent-dynamic only
35393547
requires the argument for a stable wrapper signature.
3540-
state_batch_indices: (batch,) int32 cache slot mapping.
3548+
state_batch_indices: (batch,) int32 recurrent-state slot mapping.
3549+
replay_batch_indices: Optional (batch,) int32 replay slot mapping.
3550+
Defaults to state_batch_indices for pools with shared indexing.
35413551
D: (nheads, dim) optional feed-through parameter.
35423552
z: (batch, T, nheads, dim) optional silu gate.
35433553
dt_bias: (nheads, dim) optional, with stride(-1)==0 (tie_hdim).
@@ -3837,6 +3847,13 @@ def replay_selective_state_update(
38373847
# larger when retaining replay history. Replay and rectangle window tile
38383848
# sizes are derived independently from MAX_REPLAY_BUFFER_LENGTH so
38393849
# max_window can exceed BLOCK_SIZE_T freely.
3850+
replay_cache_size = old_x.shape[0]
3851+
if replay_batch_indices is None:
3852+
replay_batch_indices = state_batch_indices
3853+
assert replay_batch_indices.shape == (batch,)
3854+
assert replay_batch_indices.dtype == torch.int32
3855+
assert replay_batch_indices.device == device
3856+
assert replay_batch_indices.is_contiguous()
38403857
max_window = old_x.shape[2]
38413858
assert T <= max_window, f"T={T} exceeds cache max_window={max_window}"
38423859

@@ -3845,15 +3862,15 @@ def replay_selective_state_update(
38453862
assert A.shape == (nheads, dim, dstate)
38463863
assert B.shape == (batch, T, ngroups, dstate)
38473864
assert C.shape == B.shape
3848-
assert old_x.shape == (cache_size, 2, max_window, nheads, dim)
3849-
assert old_B.shape == (cache_size, 2, max_window, ngroups, dstate)
3850-
assert old_dt.shape == (cache_size, 2, nheads, max_window)
3851-
assert old_dA_cumsum.shape == (cache_size, 2, nheads, max_window)
3852-
assert cache_buf_idx.shape == (cache_size,)
3865+
assert old_x.shape == (replay_cache_size, 2, max_window, nheads, dim)
3866+
assert old_B.shape == (replay_cache_size, 2, max_window, ngroups, dstate)
3867+
assert old_dt.shape == (replay_cache_size, 2, nheads, max_window)
3868+
assert old_dA_cumsum.shape == (replay_cache_size, 2, nheads, max_window)
3869+
assert cache_buf_idx.shape == (replay_cache_size,)
38533870
assert cache_buf_idx.dtype == torch.int32, (
38543871
f"cache_buf_idx must be int32, got {cache_buf_idx.dtype}"
38553872
)
3856-
assert prev_num_accepted_tokens.shape == (cache_size,)
3873+
assert prev_num_accepted_tokens.shape == (replay_cache_size,)
38573874
assert prev_num_accepted_tokens.dtype == torch.int32, (
38583875
f"prev_num_accepted_tokens must be int32, got {prev_num_accepted_tokens.dtype}"
38593876
)
@@ -4125,7 +4142,7 @@ def launch_dynamic_precompute(rectangle: bool):
41254142
old_dA_cumsum,
41264143
cache_buf_idx,
41274144
prev_num_accepted_tokens,
4128-
state_batch_indices,
4145+
replay_batch_indices,
41294146
T,
41304147
max_window,
41314148
dstate,
@@ -4247,6 +4264,7 @@ def launch_persistent_main(
42474264
cb_scaled,
42484265
decay_vec,
42494266
state_batch_indices,
4267+
replay_batch_indices,
42504268
replay_work_items_arg,
42514269
rand_seed,
42524270
n_writes,
@@ -4374,6 +4392,7 @@ def launch_persistent_dynamic_main(
43744392
cb_scaled,
43754393
decay_vec,
43764394
state_batch_indices,
4395+
replay_batch_indices,
43774396
replay_work_items_arg,
43784397
rand_seed,
43794398
n_writes_tensor,

‎tensorrt_llm/_torch/pyexecutor/_util.py‎

Lines changed: 7 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@
7070
CppMambaHybridCacheManager,
7171
MambaHybridCacheManagerV2,
7272
MixedMambaHybridCacheManager,
73+
_mamba_replay_disabled_reason,
7374
use_py_mamba_cache_manager)
7475
from .llm_request import ExecutorResponse, LlmRequestState
7576
from .model_engine import PyTorchModelEngine
@@ -3602,44 +3603,12 @@ def _create_kv_cache_manager(
36023603
quant_config, 'mamba_ssm_stochastic_rounding',
36033604
False) if quant_config is not None else False
36043605

3605-
use_replay = spec_config is not None and sm >= 80
3606-
if spec_config is None:
3607-
logger.info(
3608-
"Replay kernel requires speculative decoding; using non-replay path"
3609-
)
3610-
3611-
# Block reuse (prefix caching): replay leaves SSM state at a
3612-
# checkpoint after speculation. The next decode step replays forward
3613-
# to correct it. If block reuse feeds that stale state into a new
3614-
# prefill, the correction never happens.
3615-
# Currently we only save and reuse context tokens so this does not affect.
3616-
3617-
# Tree attention: replay assumes linear token sequence.
3618-
if (spec_config is not None
3619-
and getattr(spec_config, 'use_dynamic_tree', False)):
3620-
logger.info("Replay kernel incompatible with tree attention; "
3621-
"using legacy MTP path")
3622-
use_replay = False
3623-
3624-
# Replay Philox uses PTX cvt.rs.f16x2.f32 which needs 100 <= sm < 120.
3625-
# Flashinfer has a SW fallback at any SM.
3626-
if (stochastic_rounding
3627-
and mamba_params.mamba_ssm_cache_dtype == torch.float16
3628-
and (sm < 100 or sm in (120, 121))):
3629-
logger.info("Replay kernel Philox requires 100 <= sm < 120; "
3630-
"using legacy MTP path for stochastic rounding support")
3631-
use_replay = False
3632-
3633-
# Use replay algorithm for mamba (default is on).
3634-
enforce_disable_replay = os.environ.get('TRTLLM_USE_MAMBA_REPLAY',
3635-
'1') == '0'
3636-
if enforce_disable_replay:
3637-
logger.info(
3638-
"Replay kernel is disabled by TRTLLM_USE_MAMBA_REPLAY=0")
3639-
use_replay = False
3640-
else:
3641-
logger.info(
3642-
"Replay kernel is not changed since TRTLLM_USE_MAMBA_REPLAY=1")
3606+
disabled_reason = _mamba_replay_disabled_reason(
3607+
spec_config, mamba_params.mamba_ssm_cache_dtype,
3608+
stochastic_rounding, sm)
3609+
use_replay = disabled_reason is None
3610+
replay_status = "ENABLED" if use_replay else f"DISABLED ({disabled_reason})"
3611+
logger.info(f"Mamba replay state update: {replay_status}")
36433612

36443613
# Stochastic-rounding seeds must live on the cache manager (not be
36453614
# re-created with torch.randint per forward) whenever SR can fire

0 commit comments

Comments
 (0)