Repository navigation
[None][refactor] Move family-specific state out of the shared hybrid KV cache manager - #22121
Conversation
…ent) Pool sizing treats every lifecycle as elastic, so a PRIVATE SSM pool got the same ratio-derived slot count as the REQUIRED SSM pool, although its pages never enter the radix tree and only living caches use them, one slot each. Add KVCacheManagerConfig::maxLiveKvCaches (max_live_kv_caches), an upper bound on living (active or suspended) caches. When it is set, createKvCache() rejects a cache beyond the bound, and the PRIVATE SSM lifecycle gets a pool group of its own with a fixed GPU capacity of ceil(maxLiveKvCaches / maxUtilForResume) slots. ratioToSlotCountList() takes per-pool-group fixed slot counts out of the quota before splitting the rest by ratio. Construction, resize/adjust and tuner targets pass them, so adjust() never resizes the fixed group and the tuner does not chase it. A GPU quota that cannot hold the fixed group plus the other groups' minimum slots fails at construction, and beam widths above one are rejected. initialPoolRatio keeps one entry per layer group; the hot tier ignores the fixed group's entry. Other PRIVATE lifecycles stay ratio-sized, cold tiers are unchanged, and without the field the layout and slot counts are unchanged. The Python binding, stub and dataclass field list gain the field; no production caller sets it yet. Signed-off-by: Xiwen Yu <[email protected]>
…By Agent) A recurrent buffer with its own reuse policy places one SSM layer in two layer groups. get_layer_group_id() and layer_grouping raise for such a layer, so a hybrid V2 manager could not be constructed once a Mamba layer carried a PRIVATE buffer. Re-apply the buffer-API consumer forms from 25c879c, b91d86e, c624c86 and 2ffc2e5 (reverted by 256ac3b) for the sites the hybrid managers reach: - KVCacheManagerV2 counts pools and builds its layer, pool-mapping, page-table, event and stats metadata from buffer_grouping, resolving a split layer's execution group through one of its buffers. It again rejects attention layers whose K/V and scales need separate page tables and SWA scratch layouts that need split slot indices. - MambaHybridCacheManagerV2 resolves the recurrent-state group and a Mamba layer's execution group through SSM_STATE and describes a group without SSM_STATE by its own role. - Disaggregated transfer gives view-less groups no layers or slots and selects the Mamba state group by its pool views. Connector, sharing and non-hybrid sites keep the legacy API. Without a split layer every lookup returns the same group as before. Restore the three split-layer tests the revert deleted and add a test that a hybrid V2 manager whose Mamba layers carry a PRIVATE buffer constructs, serves state indices and builds its disaggregated page table. Signed-off-by: Xiwen Yu <[email protected]>
…By Agent) Mamba2 speculative-decoding replay history (old_x, old_B, old_dt, old_dA_cumsum, PNAT and the active buffer index) lived in standalone tensors indexed by the SSM state slot. A V2 suspend can move a request's SSM page to another slot on resume, and the history stayed behind. MambaHybridCacheManagerV2 gains a generic replay declaration: - _get_replay_layout() lets a model manager declare per-layer replay roles; _replay_reuse_policy() makes them PRIVATE (the default) or lets them inherit the layer's REQUIRED policy and share the state slot. - PRIVATE roles become PRIVATE buffers of the existing SSM layers. The manager resolves replay_layer_group_id, fills replay slots from get_ssm_block_base_index() next to the state slots, and serves them through get_replay_state_indices() and cuda_replay_state_indices. Without a PRIVATE group replay slots equal state slots, so GDN, KDA and the V1 managers keep their behaviour. - A request's replay slot is reset the first time it gets one, including generation-only dummies; free and preemption clear that mark, suspend does not, so resumed history is never reset. - A steady decode batch skips the state-index upload only while its requests also keep their replay base blocks, which suspend and resume can move without the SSM page. - max_live_kv_caches is set to the IndexMapper capacity, whose computation is hoisted into _compute_index_mapper_capacity(). _create_kv_cache() returns None at the bound instead of letting the native manager raise. Disaggregated context servers declare no replay buffers. - The fixed PRIVATE pool is a separate quota intercept, in the manager's quota and in the KV-cache estimate, not part of the per-state-slot bytes. A small GPU quota is raised so the fixed pool fits next to the other pools' minimum slots. - Replay roles are disaggregation-ignored and the PRIVATE group is left out of recurrent-cache movement logging. Mamba2 kernels and metadata take a separate replay slot: - replay_selective_state_update() accepts replay_batch_indices (default: state_batch_indices) and strided PNAT / active-buffer rows; the precompute kernels address only replay buffers through it, and the main kernels address the state by state slot and the history by replay slot. - Replay work items gain a replay-slot field; the builders read PNAT and the active buffer through the replay slots. The GDN all-layer commit accepts the wider rows. - Mamba2Metadata keeps a static replay_state_indices buffer, filled in prepare() (aliasing state_indices without a PRIVATE group), and update_mamba_states() passes it to the acceptance update through MambaAcceptanceBatch.replay_indices. NemotronHybridCacheManager declares ReplayHistory's roles as PRIVATE, with a 16-byte metadata row on the first local layer. GDN and KDA are unchanged. Tests cover the kernel with replay slots that differ from state slots, the work-item builders, the static metadata buffer, the PRIVATE layout and group, coupled declaration, fresh-page reset of generation dummies, the living-cache bound and its Python guard, the steady state-index upload with a moved replay slot, exclusion of replay history from prefix reuse, and a suspended request whose SSM slot is taken while it is suspended and that then decodes bit-identically to one never suspended. Signed-off-by: Xiwen Yu <[email protected]>
Qwen3.5 and Qwen4Exp kept Gated-DeltaNet speculative-decoding replay state in standalone tensors indexed by the SSM state slot. A V2 suspend can move a request's SSM page to another slot on resume, and the history stayed behind. Both GDN managers declare their replay buffers through the manager's replay hook (shared helpers in modules/fla/cache_manager.py): - Triton double-buffer mode (default): old_x, old_B and old_dt on every local GDN layer plus a 16-byte metadata row on the first local layer ([PNAT, active buffer, ring start, padding]) are PRIVATE buffers with their own replay slots. The unused old_dA_cumsum is no longer allocated. - FlashInfer ring mode (TRTLLM_USE_GDN_FLASHINFER_REPLAY): FlashInfer addresses the rings by the recurrent-state index, so k_ring, u_ring, g_ring and the metadata row inherit the layer's REQUIRED policy, share the recurrent-state slot and index, and move with the SSM page. FlashInfer's strided mode reads the block-strided ring views directly. - A disaggregated context server declares no replay buffers; there, and wherever no pool is bound, the state allocates its history per state slot as before. V1 managers keep their own buffers, and their replay slots are the state slots. - The cache estimate counts the Triton history as the fixed PRIVATE intercept and the rings as bytes of every recurrent-state slot. The kernels address the history by a replay slot of its own: - fused_recurrent_gated_delta_rule_cached_replay_update() takes replay_indices (default: state_indices), explicit history slot strides and element strides for PNAT and the active buffer, instead of requiring contiguous tensors. - commit_gdn_cached_replay_history_layers() reads the replay slot from full-width work items, takes explicit layer and slot strides of stacked history, or a per-layer descriptor table from build_gdn_history_descriptors() for views that are not evenly spaced. - _advance_replay_state() and _advance_ring_start() take replay indices; GDNReplayState.update() reads MambaAcceptanceBatch.replay_indices, and reset_replay_slots() clears fresh replay slots. - trtllm::gdn_verify, Qwen3.5's fused target verify (replay and gated RMSNorm in one launch), takes replay_indices (default: state_indices) and slot strides of the history and its bookkeeping; the mixer's fused-verify plan passes mamba_metadata.replay_state_indices. - _promote_mamba_state_triton(), whose conv-promotion launch also advances PNAT and the active buffer in GDNReplayState.update(), takes replay indices and strided bookkeeping rows. - The GDN mixer and the experimental Qwen4Exp engine pass mamba_metadata.replay_state_indices; the engine's replay checks size the bookkeeping and history by the replay slots, and its cached-replay op wrapper accepts replay_indices. Tests cover both replay kernels and the fused verify kernel with replay slots disjoint from the state slots in strided and descriptor-addressed buffers with strided bookkeeping (bit-exact against the coupled-index run), FlashInfer on block-strided rings and on the manager's ring views (bit-exact against contiguous rings), the PRIVATE layout, group and pool size, max_live_kv_caches, the cache estimate, fresh-page reset of generation dummies and exclusion from prefix reuse for Qwen3.5 and Qwen4Exp, the coupled ring layout, the one-launch bookkeeping update at replay slots, and a request suspended while its SSM slot is taken that then decodes bit for bit like one never suspended, with the Triton replay, the fused verify kernel and the FlashInfer ring. Signed-off-by: Xiwen Yu <[email protected]>
…ent) KimiK3 and Glm5Next kept every KDA fused-verify replay buffer (the conv windows, the k/g/v/beta caches or the draft records, and the accepted-draft count) in the REQUIRED SSM slot. Every snapshot slot therefore carried replay bytes, and because the replay state did not follow a request, a V2 suspend folded the pending drafts into the recurrent state and the resume re-seeded the replay caches; later verifies matched an unsuspended run only to the kernel's accuracy. The KDA replay buffers now go through MambaHybridCacheManagerV2's replay hook as PRIVATE buffers of the SSM layers: - KDAReplayState.replay_layout() declares the roles, with the count row on the first local layer, and bind_replay_pool() takes the manager's views of the replay group, which has a slot count of its own. This replaces bind_kda_replay_pool and the managers' buffer-config, disagg-role and model-state overrides. - Acceptance recording (also by the host drafter), context and fresh-page resets, disaggregated seeding and the pending-draft commit address the replay buffers by replay slot and the recurrent and conv states by state slot. - A suspend no longer commits the pending drafts and a resume no longer re-seeds: the PRIVATE pages follow the request. A disaggregated generation request suspended before its transferred state seeded the replay caches is seeded when it resumes. Disaggregated context servers still declare no replay buffers. - The replay bytes are a fixed intercept of one replay slot per living cache instead of per-state-slot bytes; only the stochastic-rounding seed stays per state slot. - The enable_kv_pool_rebalance restriction is unchanged. - With the drafts' records (kda_draft_records), the replay buffers stay in the recurrent-state slot (replay policy None): the experimental Kimi K3 engine's k3_kda_verify and k3_kda_attn kernels, the only readers of the records, address every replay buffer by the state slot. Its KDA module forwards the replay slots to the built-in verify and conv-window sync, and its fused acceptance records the accepted drafts at the replay slots. The kernels take a replay slot of their own, defaulting to the state slot: - trtllm::kda_mtp_decode, kda_mtp_decode_fp8 and kda_mtp_commit_pending_drafts take replay_state_indices (schema, compile key, validation and kernels, including the v2 and two-CTA verify kernels). The conv and replay caches and, on the packed path, the accepted counts are addressed by replay slot and no longer need to cover the recurrent-state rows. - The KDA Triton helpers (conv-window copy and store, draft-record replay, pending-draft commit) take replay indices. - KimiK3MambaMetadata keeps a static 16-byte-aligned copy of the generation requests' replay slots, and the KDA mixer passes the metadata's replay slots to prefill, decode and verify. Tests cover the op (v1, v2 and two-CTA verify kernels) and the Triton helpers with replay slots that differ from the state slots, bit for bit against shared slots; the aligned metadata copy; for both managers the PRIVATE layout, group and pool size, the fresh-page reset of generation dummies, exclusion of replay state from prefix reuse and a suspended request whose replay state follows it; the coupled layout with the drafts' records; and the living-cache bound. A request suspended with pending drafts, whose SSM slot another cache takes meanwhile, now verifies bit for bit like one never suspended. Signed-off-by: Xiwen Yu <[email protected]>
…y (By Agent) KVCM raised a GPU quota that could not hold the elastic pool groups' minimum slots, but rejected one that could not hold the fixed-capacity PRIVATE SSM group. The Mamba V2 manager worked around that by guessing KVCM's per-pool rounding in Python (_fit_fixed_replay_pool) and raising the quota itself. The fixed slot count is already the group's entry in mMinSlots, so drop the construction-time rejection and let the existing minimum-quota raise cover the fixed group too. Remove the Python workaround and its imports. The KDA byte-limit test goes back to its 16 MiB limits, and the tests that expected a rejection now check that the quota is raised and the fixed group keeps its full size. Signed-off-by: Xiwen Yu <[email protected]>
… (By Agent) Clean up what the hybrid replay series left behind: - KVCacheManagerV2 no longer rejects SWA scratch-reuse layouts whose coalesced share is not a whole layer block per slot. The check came back with the buffer-API adoption from a reverted series, but it only concerns non-hybrid SWA configurations; its test goes with it. The rejection of split coupled attention buffers and its test stay. - Drop buffer_to_pool_mapping_dict, which nothing reads. - Build _layer_ids_by_group once (functools.cached_property) instead of on every access, including the per-request get_page_indices_by_layer_group path: the buffer grouping is fixed once the native manager exists. - The KV-cache estimate and the runtime decide whether a guard page is reserved with the same parse of TRTLLM_KV_GUARD_PAGE (_read_guard_page_setting). The estimate used to count any non-empty value, including ones the runtime ignores. - MambaHybridCacheManagerV2._build_cache_config no longer passes the unchanged cache tiers back into replace(). - MambaState.reset_slots documents what the manager calls on every state, and a MambaReplayState protocol describes what it calls on a state that holds declared replay buffers: bind_replay_pool(), reset_replay_slots() and reset_slots(..., replay_slots=...). - A suspend no longer commits KDA pending drafts, so the commit chain has no production caller. Remove KDAReplayState.commit_pending_drafts and the SSM views only it read, commit_kda_pending_drafts, replay_kda_token_records, store_kda_replay_conv_window, the kda_mtp_commit_pending_drafts launcher with its stand-in inputs, and the REPLAY_ONLY variant of the KDA MTP verify kernel with its replay_only launcher argument and verify-kernel selection input. The remaining kernel variants trace the same code as before. Remove the tests that exercised only these, and the suspend tests' checks that nothing was committed; the conv-window copy that disaggregated seeding uses keeps its separate-replay-slot test. Signed-off-by: Xiwen Yu <[email protected]>
…ent) After the rebase onto main, which merged the final reuse-policy series and added the FP4 MLA hybrid layout: - The elastic hot-tier layout that the fixed-capacity test compares against now comes from main's ratio sizing, which breaks the 32 MiB tie between the two 4 KiB pool groups the other way. - getLayerGroupId() raises RuntimeError (a TLLM_CHECK) for a layer split by buffer reuse policies. - The FP4 MLA hybrid manager stubs describe their groups through buffer_grouping, which the hybrid manager's pool roles and disaggregated global layer IDs read, and declare the KDA replay roles through the manager's replay layouts instead of the removed KDAReplayState.disagg_ignored_roles(). - The suspended-request test checks that with the drafts' records the replay state stays in the recurrent-state slot and follows it. - The separate-replay-slot test of the v2 and two-CTA verify kernels lists only the kernel and output combinations that exist instead of skipping the others. Signed-off-by: Xiwen Yu <[email protected]>
…s (By Agent) clang-format and ruff-format reflow lines that the conflict resolution of the rebase onto main left too long or split: the nanobind KVCacheManagerConfig arguments, the KDA verify kernels' replay-slot cache accesses, the verify-kernel selection and the experimental Kimi K3 KDA module. No functional change. Signed-off-by: Xiwen Yu <[email protected]>
… Agent) test_v2_hybrid_fused_replay_promotion_matches_unfused_path, added with the one-launch GDN replay update, builds a Qwen3.5 V2 manager, which now keeps its replay bookkeeping in PRIVATE rows, and called update_mamba_states() without replay slots, which that manager rejects. The test now hands mamba_metadata.replay_state_indices with slots other than the state slots and checks the bookkeeping at those rows. Signed-off-by: Xiwen Yu <[email protected]>
Signed-off-by: Xiwen Yu <[email protected]>
LifeCycleRegistry numbered lifecycles in buffer registration order, so the first GDN layer's PRIVATE replay buffers took lifecycle 1 and pushed the attention group of a Qwen4Exp/Qwen3.5 manager to 2. The Qwen3.8 Flash Next modeling_v2 target certifies KV addressing over pools 0 and 1 only and rejected the layout ([0, 2]). Register lifecycles in two passes: buffers on their layer's policy first, then buffers whose override differs from it, each in layer and buffer order. A group only an override creates is numbered after every layer group, so adding PRIVATE replay never renumbers existing groups. The C++ tests that hard-coded the PRIVATE SSM group of the reserved-SSM config as 2 (and the PRIVATE attention group as 3) follow the new order. A new config test checks that a config's groups keep their ids when buffer overrides are added, and a Python test checks that a V2 Qwen3.5/Qwen4Exp manager with PRIVATE replay keeps the recurrent and attention groups, and the KV pool mapping, of the manager without replay. Signed-off-by: Xiwen Yu <[email protected]>
…eds it (By Agent) The IndexMapper capacity (and the guard-page setting it depends on) was computed early in KVCacheManagerV2.__init__, before the point where test_manager_initializes_capacity_only_policy_to_false deliberately stops initialization with a mapping that has no pp_size. Compute both right before the GPU quota, whose max_tokens round-trip and the cache config are the first readers of the PRIVATE replay bound. Signed-off-by: Xiwen Yu <[email protected]>
…ent) main's GB300 work added gdn_cached_replay_cute, which _replay_verify runs over a bf16 recurrent pool. It addressed the history and its bookkeeping by the checkpoint slot, required contiguous history and read 16-byte work items, so with PRIVATE replay it would have asserted on the pool-strided history views, or read another request's history. Give it the Triton entry's replay contract: replay_indices (the checkpoint slots when not given) address the history and bookkeeping, the history slots may have any 16-byte aligned stride, the bookkeeping any element stride, and work items of the engine's width carry the replay slot in their fifth field. Rows sharing the checkpoint slot keep the previous addressing. The persistent variant (unused) rejects separate replay slots. Tests: the dispatch test runs with the history at replay slots of its own, the CuTe entry gets a bit-exact coupled vs separate replay slot test (in-kernel commit with and without work items, and the all-layer commit), and the work items the cell runs build are sized to the engine's width. Signed-off-by: Xiwen Yu <[email protected]>
Signed-off-by: Xiwen Yu <[email protected]>
…up (By Agent) Main added the SINK_REQUIRED_ONLY attention reuse policy. Add tests for how it combines with the PRIVATE SSM replay group and max_live_kv_caches: - The lifecycle registry numbers a SINK_REQUIRED_ONLY layer with the layer lifecycles, before the PRIVATE group that only the old_x overrides create. A buffer-level SINK_REQUIRED_ONLY override either joins an equal layer lifecycle or is numbered after the layer lifecycles, in buffer order. - Only the PRIVATE SSM group gets a fixed capacity. SINK_REQUIRED_ONLY lifecycles stay ratio-sized. - At runtime the sinks are claimed and the window is selected or refilled with fresh pages, as without SSM layers. Meanwhile the PRIVATE replay group is never claimed, takes one fixed slot per living cache, keeps its slot across suspend and resume, and enforces the living-cache bound. Signed-off-by: Xiwen Yu <[email protected]>
Signed-off-by: Xiwen Yu <[email protected]>
…ide private replay (By Agent) Main now lets MambaHybridCacheManagerV2 hold mixed-precision KV, also with MTP. With MTP the hybrid managers keep their replay state in PRIVATE buffers, which split each recurrent layer across two layer groups, and the deprecated layer_grouping then raises. The mixed-precision disaggregated layer ids read a group's layers from _layer_ids_by_group instead, which lists a split layer once per group, as the transfer extractor does. The mixed-precision page-table key resolves the low and high groups with get_buffer_group_id, the lookup the page-table fill already uses. Test: a Mamba2 MTP replay manager with mixed-precision KV builds its mixed-precision page tables and names every layer group's layers for disaggregated transfer. Signed-off-by: Xiwen Yu <[email protected]>
…r V2 Add the region model that model and attention-backend code uses to declare its persistent memory: planes per model layer plus one life cycle (allocation unit, early-release window, hand-off to the prefix index). KVCacheManagerV2 lays the regions out on its existing slot (SSM) and span (attention) storage right after the base config is built, and keeps the ownership map of every storage layer it creates. A model layer covered by several regions keeps its id for the first one; the others are appended after the model layers, so per-model-layer tables are never indexed with them. Compacting zero-size layers renumbers the ownership map. No manager declares regions yet, so every built cache config is unchanged. Signed-off-by: Yueh-Ting Chen <[email protected]> (cherry picked from commit 718b967) Signed-off-by: Xiwen Yu <[email protected]>
A life cycle binds to a buffer, not to a layer. Instead of appending a storage layer for every further region on a model layer, lay_out_regions merges the planes of every region covering a layer into that layer's one V2 layer config: the layer takes the first covering region's reuse policy and each buffer of a region with another policy overrides it, so V2 places the buffer in its own life cycle's layer group while the layer keeps its id. The layout rejects what one layer config cannot hold: a role stored by two regions on one layer, regions on one layer with different allocation units, and token-block regions on one layer with different windows (the window is a layer property). RegionLayout records ownership per buffer, (layer id, role) -> region, and answers which region owns a buffer, which layers and roles a region stores, and, given the V2 runtime, the layer groups of a region via get_buffer_group_id. Every storage id is a model layer id, so the appended-storage helpers (StorageOwner, num_model_layers, is_model_layer, model_layer_of) and the per-region layer_config go away, and compacting zero-size layers only renumbers the buffer owners. No manager declares regions yet, so every built cache config is unchanged. Signed-off-by: Xiwen Yu <[email protected]>
…their groups (By Agent) KVCacheManagerV2 now collects its providers' regions in _declare_regions() once the per-layer views exist and before it costs the memory budget, so a manager can size its pools from the declarations; _lay_out_regions() lays the declared regions out with the cache config. Regions declare how their planes move between disaggregated workers (RegionTransfer: mapper kinds, resharding layouts, and roles the receiving worker rebuilds instead of transferring). The base disaggregation hooks add them to get_disagg_role_mapper_kinds(), get_disagg_role_layouts() and get_disagg_ignored_roles(). get_region_group_ids(region) resolves a region to the V2 layer groups of its buffers through get_buffer_group_id. A manager without regions builds the same cache config and answers its layer-based API exactly as with the region hooks bypassed; a GPU test checks this for a variable-window attention manager with and without block reuse. Signed-off-by: Xiwen Yu <[email protected]>
…e regions (By Agent) MambaHybridCacheManagerV2 provides the regions of its local recurrent layers: - recurrent_state (per request, snapshotted at declared points -> REQUIRED): SSM and convolution state plus the planes a model adds through _get_recurrent_buffer_configs (Qwen4Exp's PLE state); - replay_state (per request, never handed off -> PRIVATE): the model's replay buffers, on the same recurrent layers. When the kernels address the replay buffers by the recurrent-state slot, they are planes of recurrent_state instead. The layout puts both on the layers' one SSM config, so each layer keeps its id and its replay buffers land in their own layer group. What was special-cased from the replay layouts is now derived from the declarations: - max_live_kv_caches is set when a request-private slot region exists; - the replay group id is the replay_state region's layer group (get_region_group_ids); - per-state-slot bytes are the REQUIRED per-request planes, and the fixed replay intercept the PRIVATE ones; - the replay roles are the regions' rebuilt roles, so the hybrid manager no longer adds them to get_disagg_ignored_roles itself; - the typed views registered for binding are the per-request regions' buffers. _build_cache_config no longer builds the SSM layer configs. A recurrent buffer with its own reuse policy is rejected; such a buffer is a region of its own. MambaReplayState declares its replay buffers (replay_layout) and whether its kernels address them by the recurrent-state slot (replay_shares_state_slot); the manager's replay hooks default to them. Mamba2's ReplayHistory implements both, so the Nemotron manager drops its replay-layout override. The built cache config, pool groups, page tables, class cost estimates, disaggregated page table and state views of every Nemotron, Qwen3.5, Qwen4Exp, Kimi K3 and Glm5Next variant are unchanged. Signed-off-by: Xiwen Yu <[email protected]>
GDNReplayState declares its replay buffers through the MambaReplayState interface the hybrid manager builds its regions from: replay_layout() (renamed from pool_layout()) and replay_shares_state_slot. The Triton history has replay slots of its own and forms the replay_state region; the FlashInfer ring buffers are addressed by the recurrent-state index, so they are planes of the recurrent_state region. Qwen35HybridCacheManager and Qwen4ExpHybridCacheManager therefore drop their replay-layout and reuse-policy overrides, and gdn_replay_layout() and gdn_replay_reuse_policy() go away. Qwen4Exp's PLE state stays a set of recurrent_state planes through _get_recurrent_buffer_configs. The built cache config, pool groups, page tables, class cost estimates, disaggregated page table and state views of every Qwen3.5 and Qwen4Exp variant (no speculation, Triton, FlashInfer ring, PLE, disaggregated) are unchanged. Signed-off-by: Xiwen Yu <[email protected]>
KDAReplayState says where its replay buffers live (replay_shares_state_slot): in a replay_state region of their own, or, with the drafts' records, as planes of the recurrent_state region, because the experimental Kimi K3 engine's k3_kda_verify and k3_kda_attn kernels address the records' replay caches by the recurrent-state slot. KimiK3HybridCacheManager and Glm5NextCacheManager therefore drop their replay-layout and reuse-policy overrides. With every replay state declaring itself, MambaHybridCacheManagerV2 reads the replay layout from the model's MambaReplayState and builds its regions from it; the _get_replay_layout() and _replay_reuse_policy() hooks go away. Tests check that every replay state declares its buffers and placement and that the draft-record and coupled Mamba2 variants put their replay planes in the recurrent-state region. The built cache config, pool groups, page tables, class cost estimates, disaggregated page table and state views of every Kimi K3 (replay, draft records, BF16 KV, FP4 MLA) and Glm5Next variant, and of the other hybrid managers, are unchanged. Signed-off-by: Xiwen Yu <[email protected]>
Describe the region model as this branch implements it: the vocabulary, how a region maps onto KV cache manager V2 storage with life cycles bound to buffers rather than layers, what one layer config can hold, per-buffer ownership and the region lookups, the manager hooks and when they run, the linear-attention regions of each hybrid manager and mode, what the hybrid manager derives from them, backward compatibility for managers without regions, what is not covered yet (attention regions, which need per-buffer windows; class-level cost estimates; executor-wide gates), the rules for shared code, and how to show that a migration changes nothing. Link it from AGENTS.md next to the attention and MoE guides. Signed-off-by: Xiwen Yu <[email protected]>
…ost test (By Agent) The hybrid manager sizes a recurrent-state slot from its declared regions, which __init__ declares before costing. The GLM indexer cost test builds its manager with object.__new__, so it now declares the regions itself, as the Mamba manager tests' stubs do. Signed-off-by: Xiwen Yu <[email protected]>
…egions (By Agent) Attention regions are to follow, so keep the declarations they need from the original region model instead of dropping them: RegionLayer.bytes_per_token, Region.resumes_at_block_boundaries and Region.positioned_by_history. They default to 0 / False, and the manager does not read them yet, which the docstrings and the developer guide say. A test checks the defaults and that setting them leaves the layout unchanged. Signed-off-by: Xiwen Yu <[email protected]>
Signed-off-by: Xiwen Yu <[email protected]>
…s (By Agent) Main's NVIDIA#21409 builds the replay work items with the single-launch Triton kernel for every batch of up to 256 decodes, keeps that kernel from specializing on the alignment of the decode slice of state_indices, and sends strided accepted-count or buffer-index tensors to the ATen builder (its kernel indexes them without strides). Re-expressed on top of the private replay slots: - The kernel also reads replay_indices, the decode slice of the private replay slots, which starts at the same context offset; it is now kept out of the alignment specialization too, so a mixed step does not compile a new variant while serving. - Managers that keep the replay metadata in the KV cache pool hand out strided views of its per-slot rows. This branch's kernel reads both tensors through their strides, so the contiguity gate only sent private replay (including the GDN all-layer commit, which used the fused builder before the merge) to the ATen builder; the gate is now the batch size. - Main's compile-once test allocated work items 4 wide; they are REPLAY_WORK_ITEM_WIDTH (5) wide here. Tests: the compile-once test also runs private replay (separate replay slots at the context offset, strided metadata rows); strided bookkeeping now dispatches to the fused builder and still matches the ATen one; a new test checks through _prepare_replay_work_items, with and without the all-layer commit, that private replay builds in one launch and its work items equal the coupled layout's bit for bit apart from the replay slot column. Signed-off-by: Xiwen Yu <[email protected]>
…rd (By Agent) Release-Check's bandit scan (B105, hardcoded_password_string) flags AllocationUnit.TOKEN_BLOCK = "token_block" because the name contains "TOKEN". It is an enum value, so suppress it with the repository's usual `# nosec B105` comment. Signed-off-by: Xiwen Yu <[email protected]>
|
/bot run |
|
PR_Github #85443 [ run ] triggered by Bot. Commit: |
- MixedMambaHybridCacheManager serves GDN layers too: give it gdn_fused_verify (False; it never receives the flag) and gdn_replay_partitioned, which the GDN mixer calls on every speculative decode. cached_replay.py points at the managers that define it. - Qwen3-Next and Qwen4Exp rebuild the GDN metadata through one helper, gdn_metadata_for_batch: a rebuilt instance is prepared for the batch and replaces attn_metadata.mamba_metadata, so the decoder layers and the replay region's acceptance update read the same prepared instance. - Kimi K3's FP4 MLA estimate counts the HP rings of the GEN preemption headroom, like the runtime's resident capacity, and keeps attention_page_bytes per sequence. - Tests: GDN-serving managers' replay partition, the metadata rebuild with and without a Mamba cache manager, the warmup split's tail tokens, and the headroom case of the FP4 MLA estimate. Signed-off-by: Xiwen Yu <[email protected]>
|
/bot run |
|
PR_Github #85443 [ run ] completed with state
|
|
/bot run |
|
PR_Github #85605 [ run ] triggered by Bot. Commit: |
Wanli-Jiang
left a comment
There was a problem hiding this comment.
LGTM. the description still says the V1 managers name ReplayMamba2Metadata too; at the head none of them names a class, and the models name their own (REGIONS_DEVELOPER_GUIDE.md says the same). Could we drop that sentence?
|
Automatically added "ci: full pre-merge approved" because this PR has satisfied the required GitHub review approvals. Unresolved review conversations and other required checks remain independent merge requirements. |
|
@Wanli-Jiang Thanks! Dropped it: the description now says a model or a V2 manager names the metadata class and the V1 managers name none (they build the model's class). I also refreshed the other stale parts (GDN metadata split, in-forward snapshots now also on Qwen4Exp, the Mixed manager's GDN members, test results). |
|
PR_Github #85605 [ run ] completed with state
|
|
/bot run |
|
PR_Github #85668 [ run ] triggered by Bot. Commit: |
|
PR_Github #85668 [ run ] completed with state |
test_k3_kda_metadata.py (NVIDIA#21996) and two later changes on main crossed: - test_inforward_split imported InforwardSnapshotEntry from the shared Mamba cache manager package, which NVIDIA#22121 moved to modules/fla/inforward_snapshot.py; it fails in the l0_cpu stages. - test_prepare fakes Mamba2Metadata.prepare, and KimiK3MambaMetadata.prepare now also reads query_start_loc_long; the fake sets it too. The same change as NVIDIA#22570, so this branch passes CI before that PR lands. Signed-off-by: Xiwen Yu <[email protected]>
Conflicts with NVIDIA#22121: the hybrid manager is main's; the FP4 MLA policy implements its attention-layout operations on the layout object, and KimiK3HybridCacheManager lists Fp4MlaLayoutHooks in its bases, which the test of the model managers' bases allows like the in-forward snapshot mixin. Signed-off-by: Qi Zhang (qizh) <[email protected]>
…i K3 engine probes (By Agent) The engine probes of the Kimi K3 targets (common and dep16) checked the in-forward snapshot API on MambaHybridCacheManagerV2 and the split hook in Mamba2Metadata.prepare. NVIDIA#22121 moved both to the GDN family: the manager API to InforwardSnapshotHost and the hook call to GDNMambaMetadata.prepare, and InforwardSnapshotEntry to modules/fla/inforward_snapshot.py. The probes now check them there; the K3 step metadata's split behaviour is unchanged. Signed-off-by: Xiwen Yu <[email protected]>
Pick up main's fix of the Qwen3.8-Flash-Next FP8 tests that imported names moved by NVIDIA#22121 (NVIDIA#22580), and main's waive of the stage-KV cubin hash test (nvbugs/7114472). Signed-off-by: Xiwen Yu <[email protected]>
… K3 engine probes (By Agent) The engine probes of the Kimi K3 targets (common and dep16) checked the in-forward snapshot API on MambaHybridCacheManagerV2 and the split hook in Mamba2Metadata.prepare. NVIDIA#22121 moved both to the GDN family: the manager API to InforwardSnapshotHost and the hook call to GDNMambaMetadata.prepare, and InforwardSnapshotEntry to modules/fla/inforward_snapshot.py. The probes now check them there; the K3 step metadata's split behaviour is unchanged. The same change as in NVIDIA#22570. Signed-off-by: Xiwen Yu <[email protected]>
Description
Follow-up to #21324 (merged).
#21324 keeps the speculative-decoding replay state of hybrid models in KV cache regions. There, KDA (Kimi K3, GLM5Next) already owns its replay state through
KDAReplayRegion, while Mamba2 and GDN replay are still managed centrally:MambaHybridCacheManagerV2declares theirreplay_stateregion and owns the replay slots,Mamba2Metadatacarries replay slots and GDN replay work items, andmamba_cache_manager/common.pydefines the replay-state protocol and the bookkeeping kernel.This PR moves that code into the model families, so the generic runtime no longer knows about replay state. Each family gets its own provider, parallel to
KDAReplayRegion. The families' copies are similar by design, so that each family can change its own copy without touching the others, as Kimi K3 and GLM5Next already do with KDA. Regions, slot counts and kernels are unchanged; no behaviour change is intended.Per-family providers
Mamba2ReplayRegion(modules/mamba/replay_region.py)replay_state, REQUEST / PRIVATE,ceil(IndexMapper capacity / max_util_for_resume)slotsGDNReplayRegion(modules/fla/replay_region.py)GDNReplayRegionshared_buffers())KDAReplayRegion(unchanged)A provider declares its region, binds the allocated planes, owns the requests' replay slots (refreshed after allocation, kept across suspension, reset for new slots), records acceptance at those slots, and estimates its fixed pool for the cost estimate (with the GEN slot preemption headroom). The model managers connect it through the generic hooks of
KVCacheManagerV2/MambaHybridCacheManagerV2(_region_providers,_get_recurrent_buffer_configs,_setup_model_state,_setup_state_indices,_reset_context_mamba_slots,_update_model_state,_estimate_fixed_region_bytes,get_disagg_ignored_roles,free_resources,shutdown), the way the KDA managers connectKDAReplayRegion.Replay metadata and kernels
Mamba2Metadatano longer carries replay slots or replay work items.ReplayMamba2Metadata(modules/mamba/replay_metadata.py) adds them for Mamba2 andGDNMambaMetadata(modules/fla/gdn_metadata.py) for GDN; both build them with the work-item builders (REPLAY_WORK_*, the one-launch builder) and the replay-slot buffer ofmodules/mamba/replay_metadata.py.mamba_metadata_cls. The class used is the model's, else the manager's, elseMamba2Metadata(resolve_mamba_metadata_cls, used byAttentionMetadata._prepare_mamba_metadataand the layer-wise benchmark runner).gdn_metadata_for_batch, which prepares the rebuilt instance, so the GDN layers and the replay region's acceptance update read the same one.modules/fla/replay_promotion.py.common.pydropsMambaReplayState,ReplayLayoutandMambaAcceptanceBatch.replay_indices;MambaHybridCacheManagerV2drops the replay pool estimate andgdn_fused_verify/gdn_replay_partitioned, which the managers serving GDN layers define: the GDN V2 managers and both V1 managers (MixedMambaHybridCacheManagerkeeps the unfused verify).Other family-only features
The shared classes also carried features that only one family uses. They move into that family the same way:
Fp4MlaV2CacheLayoutPolicy)_configure_attention_cache_layout,_estimate_attention_cache_cost; the base keeps forwarding layout operations to the installed policymax_draft_len + 1scratch tokens per request)_append_layers,_bind_appended_layers; the base rejectslayer_specs, and its estimate takes the scratch asdraft_scratch_tokensInforwardSnapshotsand theInforwardSnapshotHostmixin (modules/fla/inforward_snapshot.py), used byQwen35HybridCacheManagerandQwen4ExpHybridCacheManager(opt-in, with its PLE state)GDNMambaMetadata(modules/fla/gdn_metadata.py)mamba_metadata_cls), so the V1 managers, which serve both families and name none, build it too.get_kv_cache_manager_clsinstead of getting a manager without the FP4 layout; no other family is an MLA model (GLM5Next is NoPE).mamba_cache_manager_v2.pyhas 1901 lines instead of main's 2545, andmamba2_metadata.py456 instead of 908.Guard
tests/unittest/_torch/pyexecutor/kv_cache/test_replay_decoupling.py(cpu_only; runs inl0_cpu.ymlthroughunittest/_torch/pyexecutor) parses the generic modules (kv_cache_manager_v2.py,regions.py,mamba_cache_manager_v2.py,mamba_cache_manager/common.py,mamba2_metadata.py) and fails if they name replay state or import a family's replay code; the three shared Mamba modules must also name no GDN, KDA, in-forward-snapshot or FP4/MLA state and import no family package.REGIONS_DEVELOPER_GUIDE.mddescribes the replay regions of the model families.Test Coverage
tests/unittest/_torch/pyexecutor/kv_cache/test_replay_decoupling.py(new)tests/unittest/_torch/pyexecutor/kv_cache/test_mamba_model_managers.py: the provider contract per family (fixed pool size, refresh of moved slots without resetting live history, stable index buffer for CUDA graphs, release, context reset, acceptance), ring mode without a region, disaggregated context servers without a provider, estimate vs declared pool, metadata class resolutiontests/unittest/_torch/pyexecutor/kv_cache/test_mamba_cache_manager.py: suspend/resume and steady-state index upload of the private replay slots per family, shared-slot mode, fixed-pool estimate vs GPU quotatests/unittest/_torch/modules/mamba/test_gdn_metadata.py(new): GDN metadata preparation, the in-forward split, the metadata rebuilt for a batch capacitytests/unittest/_torch/modules/mamba/test_mamba2_metadata.py,test_gdn_*,test_replay_selective_state_update.py, KDA and Qwen4Exp SSM tests: replay metadata and kernelsCI: pipeline #70725 at edf7bce (main merged) passed every single-GPU stage (150,085 tests, 0 failed); the multi-GPU stages waited for the
ci: full pre-merge approvedlabel.Local run on B200 (sm_100) at edf7bce, then the suites the review fixes touch at a80f1ea:
_torch/pyexecutor/kv_cache/test_host_tier_bound_to_gpu_numa_nodefails because the container blocks the NUMA syscall, as on main_torch/modules/mamba/_torch/modules/kimi_kda/,test_kimi_k3_mla.py,test_kimi_k3_config_routing.pytest_qwen4_exp_support.py, PLE,modeling_v2/models/qwen4_exp/.../ssm)test_py_executor.py,test_runtime_hooks.py, DSparkkv_cache_manager_v2_tests/attention/sparse/glm_kpool/test_kimi_k3_gen_dep[1]command on a dummy-weight Kimi K3 config)test_gdn_metadata.py,_torch/modules/mamba/, Qwen4Exp, decoder runners, Qwen3.5-VL🤖 Generated with Claude Code
Dev Engineer Review
CI status: Not established on the current head. Earlier pipeline comments report:
#69616failed.#69756failed, although its PR job reported success.#69875failed.#69926,#70046, and#70151were unstable. Later comments cite resource maintenance that reduced test coverage.#69980was aborted. A newer pipeline force-killed one run.ci: full pre-merge approvedlabel.Local test results (author-reported, not CI): 10 passed in
test_replay_decoupling.py, 422 passed intest_mamba_cache_manager.py, and 284 passed intest_mamba_model_managers.py. The author also reports 1,521 passed and 3 skipped undermodules/mamba/. Other suites are listed in the PR description but were not verified. These results are not independently confirmed.Review findings: No current review findings were supplied. Review severity counts are not available.
Behavior to verify: The PR moves Mamba2 and GDN replay-state ownership into family-specific providers. The author states that replay regions, slot counts, and kernels are unchanged. The supplied diff does not establish this equivalence.
Material risks:
MambaReplayStateandReplayLayoutare removed frommamba_cache_manager/common.py, along with their export-list entries.REPLAY_STATE_REGIONandInforwardSnapshotEntryare removed from__all__inmamba_cache_manager_v2.py.InforwardSnapshotEntryis also removed from themamba_cache_managerpackage exports. Confirm that no importers remain.MambaHybridCacheManagerV2.__init__drops the explicitgdn_fused_verifyparameter. Callers that still pass it reach**kwargs. Confirm that no caller passes it.GDNReplayState.updateandReplayHistory.updategain optionalreplay_slots.resolve_mamba_metadata_clsgains optionalkv_cache_manager.Qwen35HybridCacheManager.__init__gainsgdn_fused_verify.promote_conv_and_advance_replay_triton.get_kv_cache_manager_clsnow accepts onlykimi_linear. Other hybrid model types raiseValueError. Previously they returnedMambaHybridCacheManagerV2. Confirm that no supported model depends on the old path.Mamba2Metadata. Confirm that each family resolves to the intended class.Mamba2Metadatano longer builds replay work items or replay slots.ReplayMamba2MetadataandGDNMambaMetadataown that logic. Confirm that every replay path uses a replay-capable class.KimiK3MambaMetadataadds a static replay-slot buffer and aDeviceCopyBuffer. The manager must return exactly one index per batch request. Confirm this under graph capture and replay.test_replay_decoupling.pychecks imports and identifiers only. It does not check runtime behavior.QA Engineer Review
Changed test files:
tests/unittest/_torch/pyexecutor/kv_cache/test_replay_decoupling.py(new): CPU-only AST checks. Rejects replay identifiers other thancontext_replay_tokensin five shared modules. Rejects imports of family replay code.tests/unittest/_torch/pyexecutor/kv_cache/test_mamba_cache_manager.py: Covers Mamba2 and GDN replay-region providers, the fused promotion helper, the C++ hybrid path, fixed-pool estimates, and replay-index uploads.tests/unittest/_torch/pyexecutor/kv_cache/test_mamba_model_managers.py: Covers the replay-provider contract, metadata-class precedence, slot refresh and reset, KDA replay ownership, acceptance update paths, and Kimi K3 FP4 MLA routing.tests/unittest/_torch/pyexecutor/kv_cache/test_hybrid_unified_draft_kv.pyandtest_dflash_unified_kv_gate.py: UseKimiK3HybridCacheManagerin place of test-only subclasses.tests/unittest/_torch/modules/mamba/test_mamba2_metadata.py: Checks that generic metadata builds no replay data and thatReplayMamba2Metadatadoes.tests/unittest/_torch/modules/mamba/test_gdn_metadata.py(new): CUDA-only checks ofGDNMambaMetadata.prepare, including snapshot splitting and warmup.tests/unittest/_torch/modules/mamba/test_gdn_prefill_graph.py,test_gdn_conv_channel_last.py,test_gdn_direct_launch.py,test_gdn_inforward_snapshot.py, andtest_gdn_mixed_decode_routing.py: Switch toGDNMambaMetadataor the FLA snapshot-entry import.tests/unittest/_torch/modules/mamba/test_gdn_replay_recurrent.py,test_replay_selective_state_update.py, andmodeling_v2/.../test_modeling_v2_fused_recurrent_gated_delta_rule_cached_replay_update.py: Import-path updates toreplay_metadata.tests/unittest/_torch/speculative/hw_agnostic/test_dspark_model_engine_runtime.py: Mock updated for the newresolve_mamba_metadata_clscall shape.tests/unittest/_torch/modeling/test_modeling_minicpmv4_6.pyandtests/unittest/_torch/modules/fla/test_flashinfer_chunk_cu_seqlens_cache.py: Metadata-class and docstring updates.Test IDs, selectors, and test-db entries: Not established. Membership in
test-db/(CI) orqa/(manual QA) lists was not checked. No test-list files appear in the supplied change summary.Per-file QA perspective:
test_replay_decoupling.py: Confirms the layering rule. Re-run after any new replay-named identifier.test_mamba_cache_manager.pyandtest_mamba_model_managers.py: Verify fixed-pool byte estimates and slot reuse under shared-slot and private-region setups.test_mamba2_metadata.py: Verify thatMamba2Metadataproduces no replay slots and thatReplayMamba2Metadatadoes.test_dspark_model_engine_runtime.py: Verify that the mock matches the new call shape.interface.py: Metadata falls back to the cache manager'smamba_metadata_cls. Verify the fallback order.glm_kpool/cache_manager.py: Only a no-op override and@overridedecorators were removed. No behavior change is observed.qwen3_next.py,qwen4_exp.py, andmodeling_qwen3_5.py: Metadata refresh preserves an existing GDN metadata class. Verify that replacement metadata keeps the expected type.mamba_cache_manager_v2.py: Removes replay-state regions, replay exports, andgdn_fused_verify. Verify that the remaining recurrent-state and attention paths still work.legacy.py: Replay-enabled promotion uses the new replay helper. Non-replay promotion uses the standard kernel. Verify both paths._util.py: Onlykimi_linearis accepted for FP4 MLA hybrid models. Verify that other hybrid models fail with the expectedValueError.Coverage verdict: Needs follow-up. Unit tests cover the new providers, the metadata split, and the promotion path. CI on the current head is not established, and test-db listing is not established.