spark_model/model/
types.rs

1// SPDX-License-Identifier: AGPL-3.0-only
2
3#![allow(unused_imports, dead_code)]
4
5use parking_lot::Mutex;
6use std::collections::HashMap;
7use std::sync::Arc;
8
9use anyhow::{Result, bail};
10use atlas_core::config::{LayerType, ModelConfig};
11use spark_runtime::buffers::BufferArena;
12use spark_runtime::gpu::{DevicePtr, GpuBackend, GraphHandle, KernelHandle};
13use spark_runtime::kv_cache::PagedKvCache;
14
15use super::ssm_pool::SsmStatePool;
16use super::ssm_snapshot::SsmSnapshotPool;
17use crate::layer::{
18    AttnMetadataDev, ForwardContext, GdnPrefillBuffers, LayerState, SsmLayerState, TransformerLayer,
19};
20use crate::layers::ops;
21use crate::speculative::DraftProposer;
22use crate::traits::{ChunkedPrefillPageMetadata, Model, SequenceState};
23use crate::weight_map::{DenseWeight, Fp8DenseWeight, MtpWeights, QuantizedWeight};
24
25/// Architecture-agnostic transformer model.
26///
27/// Composes `Vec<Box<dyn TransformerLayer>>` into a full forward pass.
28/// Adding a new model only requires implementing [`TransformerLayer`]
29/// for each layer type — the model loop stays unchanged.
30#[allow(dead_code)]
31/// Rows in the drafter catch-up hidden ring (see `mtp_catchup_ring`):
32/// 512 covers the gate's 256-token serial re-probe interval with 2x margin.
33pub(super) const MTP_CATCHUP_RING_ROWS: usize = 512;
34
35pub struct TransformerModel {
36    pub(super) config: ModelConfig,
37    /// Which GEMM implementation each projection takes, resolved from the
38    /// environment when this model was built. Owned here and borrowed by every
39    /// `ForwardContext` this model creates, so the choice cannot outlive the
40    /// model — the property nine `OnceLock` statics could not have.
41    pub(super) dispatch: crate::layers::ops::GemmDispatch,
42    /// Weight re-encodings derived on demand and memoized for this model.
43    /// Dropped with the model, so no entry can outlive the allocation it
44    /// describes.
45    pub(super) derived: crate::layers::ops::DerivedWeights,
46    /// The weight ledger this model was built from.
47    ///
48    /// Held for TEARDOWN, not for lookup: the layers already copied the
49    /// pointers they need out of it during construction. It is the only
50    /// structure that knows every weight allocation, and it used to be dropped
51    /// at the end of `startup()` — leaving that memory live with nothing able
52    /// to free it. `None` once released.
53    pub(super) weight_store: Option<spark_runtime::weights::WeightStore>,
54    /// Non-GEMM kernel-path levers, resolved at model construction.
55    pub(super) levers: crate::layers::ops::ModelLevers,
56    /// Diagnostic counters and one-shot dump latches for this model. Sibling
57    /// to `levers`: what the kernels did, rather than what they do.
58    pub(super) stats: crate::layers::ops::ModelStats,
59    pub(super) embed_tokens: DenseWeight,
60    /// Fused n-gram input embedding (LongCat family), when the architecture
61    /// has one. `Mutex` because the forward path is `&self` while the row
62    /// cache mutates on lookup; the lock is taken once per embed, which is
63    /// nothing beside a transformer forward.
64    pub(super) ngram_embed: Option<std::sync::Mutex<crate::layers::ngram_embed::NgramEmbedding>>,
65    pub(super) final_norm: DenseWeight,
66    pub(super) lm_head_weight: DenseWeight,
67    pub(super) lm_head_nvfp4: Option<QuantizedWeight>,
68    /// TRANSPOSED `[K/2, ldb]` twin of `lm_head_nvfp4` + its PADDED row stride.
69    ///
70    /// The pad is load-bearing: the tile GEMM reads B with 16-byte `cp.async`,
71    /// which needs a 16-byte-aligned source, and row r sits at `r * stride`.
72    /// This checkpoint's vocab is 248077 — ODD — so an unpadded stride misaligns
73    /// 15 of every 16 k-rows and faults with CUDA 716. Padded to 248192.
74    ///
75    /// ADDITIVE: never replaces or aliases `lm_head_nvfp4`, so every existing
76    /// holder (including the `draft_lm_head_nvfp4` copy at `impl_a1.rs:157`)
77    /// keeps a valid row-major pointer. Built once, immutable, never freed —
78    /// so each per-`padded_n` CUDA graph binds one (kernel, tensor) pair.
79    /// `None` under `ATLAS_NO_LMHEAD_TGEMM=1`.
80    pub(super) lm_head_nvfp4_t: Option<(QuantizedWeight, u32)>,
81    /// Runtime FP8 E4M3 LM head (per-row scales), decoded via `w8a16_gemv`.
82    /// `Some` only when `--lm-head-dtype fp8` was requested; mutually exclusive
83    /// with `lm_head_nvfp4` (that stays `None` on the FP8 path). Additive: when
84    /// `None`, the NVFP4/BF16 LM-head dispatch is byte-identical to before.
85    pub(super) lm_head_fp8: Option<Fp8DenseWeight>,
86    pub(super) layers: Vec<Box<dyn TransformerLayer>>,
87    pub(super) buffers: BufferArena,
88    /// Startup-static LoRA adapter (pool + per-layer pairs + M2 pointer
89    /// tables). `None` = no adapter. Installed post-construction via
90    /// `set_lora_weights`, which also copies the per-layer pairs into the
91    /// layer structs; kept here as the owner of the pool/tables and for
92    /// status introspection.
93    pub(super) lora: Option<crate::lora::LoraWeights>,
94    /// True when runtime adapter rotation is ARMED: `ATLAS_LORA_ROTATE=1`, or
95    /// `$ATLAS_LORA_PEER` set. Armed ⇒ decode runs eager (no CUDA-graph
96    /// capture) so a `set_active_lora` re-point is immediately live
97    /// (eager-on-rotate). `false` (single startup adapter, no rotation env)
98    /// keeps the decode-graph path byte-identical to today.
99    pub(super) lora_rotatable: bool,
100    pub(super) kv_cache: Mutex<PagedKvCache>,
101    pub(super) gpu: Box<dyn GpuBackend>,
102    /// TQ+ InnerQ calibration driver, when `TURBO_INNERQ` is set. Owned here
103    /// rather than parked in a static: it writes `__device__` globals in THIS
104    /// model's modules, so it must not outlive the model. Reached from the
105    /// scheduler through `Model::poll_innerq`.
106    #[cfg(feature = "cuda")]
107    pub(super) innerq: Option<crate::layers::qwen3_attention::InnerQDriver>,
108    pub(super) rms_norm_kernel: KernelHandle,
109    pub(super) dense_gemv_kernel: KernelHandle,
110    /// FP32-output variant of dense_gemv_bf16. Used by the LM head when
111    /// `use_fp32_logits` is true, so the FP32 accumulator is preserved across
112    /// the BF16-storage rounding boundary that flips greedy argmax tiebreaks
113    /// on Gemma-4-31B (top-1 vs top-2 = 0.125 logit gap = exact BF16 step at
114    /// value 16-32 → BF16 store snaps the wrong way and starts a stop-word
115    /// loop). Loaded once at model init.
116    pub(super) dense_gemv_fp32out_kernel: KernelHandle,
117    pub(super) w4a16_gemv_kernel: KernelHandle,
118    pub(super) w4a16_gemv_logits_kernel: KernelHandle, // FP32 output for LM head
119    /// Tile GEMM over the TRANSPOSED lm_head twin. 0 when absent.
120    pub(super) w4a16_gemm_t_kernel: KernelHandle,
121    /// LOSSLESS BF16-MMA tile GEMM over the same twin. Preferred for lm_head:
122    /// `w4a16_gemm_t` downcasts activations BF16->FP8 E4M3, and lm_head is the
123    /// layer where a near-tie argmax flip changes the emitted token. Memory
124    /// records exactly that failure mode (stop/end-of-turn mis-ranking on DEEP
125    /// agentic trajectories) for sub-bf16 lm_heads. Costs ~1% of step.
126    /// 0 when absent. Kill switch: ATLAS_NO_LMHEAD_LOSSLESS=1.
127    pub(super) w4a16_gemm_t_bf16_kernel: KernelHandle,
128    pub(super) w4a16_gemm_kernel: KernelHandle,
129    pub(super) w4a16_gemv_batch2_kernel: KernelHandle,
130    /// Narrow `w4a16_gemv_batch{M}` family (M=4..8) for the K=3..8 verify
131    /// lm_head (one weight read for all rows; nsys 2026-07-18: the M64-tile
132    /// `w4a16_gemm` at M=4 cost 19.3 ms/verify-step on the 248320-row lm_head
133    /// — 94% tile padding). Individual tiers are 0-handles when the target
134    /// lacks them (dispatch falls back).
135    pub(super) w4a16_batchm: crate::layers::w4a16_gemv_tiers::W4a16BatchmTiers,
136    pub(super) w4a16_gemv_batch16_kernel: KernelHandle,
137    /// FP8 E4M3 LUT GEMV (M=1) for the FP8 LM head. Only used when
138    /// `lm_head_fp8.is_some()`; loaded unconditionally (cheap handle) so the
139    /// dispatch in `lm_head` / batched-decode / verify can reference it.
140    pub(super) dense_gemv_fp8w_kernel: KernelHandle,
141    /// FP8-weight dual-GEMV (batch=2): reads the FP8 weight once for both K=2
142    /// verify tokens. Bit-identical to two `dense_gemv_fp8w` calls; halves the
143    /// FP8 weight bandwidth for the lm_head on the MTP verify path.
144    pub(super) dense_gemv_fp8w_batch2_kernel: KernelHandle,
145    pub(super) dense_gemm_kernel: KernelHandle,
146    /// Batched BF16 GEMV (M rows, one weight pass). Used for the BF16 lm_head
147    /// at decode: reads the ~617 MB vocab weight once with coalesced uint4
148    /// loads, vs the scalar dense_gemm_bf16 (16x16 FFMA, ~89 GB/s). 0 = absent.
149    pub(super) dense_gemv_batchm_kernel: KernelHandle,
150    pub(super) argmax_kernel: KernelHandle,
151    /// Batched argmax (one block per row). 0 when the kernel set lacks it.
152    pub(super) argmax_batch_kernel: KernelHandle,
153    pub(super) argmax_logits_kernel: KernelHandle, // FP32 argmax for logits
154    pub(super) batched_embed_kernel: KernelHandle,
155    pub(super) fill_slots_kernel: KernelHandle,
156    /// Cached CUDA graph for single-sequence decode (layer loop + norm + LM head).
157    /// CUDA graph cache for n=1 decode, keyed by `seq.slot_idx`. The captured
158    /// graph has SSM h_state/conv_state pointers baked in as kernel arguments,
159    /// so a graph captured for slot S can ONLY be replayed for slot S — replay
160    /// for any other slot reads/writes the wrong sequence's recurrent state
161    /// and produces gibberish for both sequences. With concurrent users we may
162    /// alternate between slots in n=1 decode (e.g. via the per-seq fresh-decode
163    /// fix in scheduler::step_decode_only), so we keep one graph per slot.
164    pub(super) decode_graph: Mutex<std::collections::HashMap<usize, GraphHandle>>,
165    /// Cached CUDA graphs for batched decode, keyed by the per-row SSM pool
166    /// slot VECTOR (`trait_impl/decode_graph_key.rs`) — the only per-sequence
167    /// addresses a capture bakes. The old `padded_n` key was sound only while
168    /// the batch was exactly slots `[0..n)` with `n == padded_n`; the MTP
169    /// Phase-A bootstrap passes a slot SUBSET of the active set and would
170    /// replay another subset's baked GDN pointers.
171    /// Value = `(graph, last_use_tick)`; the `u64` alongside the map is the
172    /// monotonically increasing tick. At `BATCH_DECODE_GRAPH_CAP` entries the
173    /// least-recently-used graph is destroyed and replaced.
174    pub(super) batch_decode_graphs: Mutex<(HashMap<Vec<u32>, (GraphHandle, u64)>, u64)>,
175    /// Pre-allocated SSM state pool for stable GPU addresses across graph replays.
176    /// `Arc` so each `SequenceState` can hold a `SlotGuard` that releases its
177    /// claimed slot on drop — guaranteeing the slot returns to the free list on
178    /// EVERY sequence-exit path (normal finish, abort, error, swap-out failure,
179    /// panic/unwind), not just the explicit `free_sequence`/`compact_sequence`
180    /// sites. See `SsmStatePool::claim_guarded` / `SlotGuard`.
181    pub(super) ssm_pool: Arc<SsmStatePool>,
182    /// SSM state snapshot pool for Marconi prefix caching.
183    pub(super) ssm_snapshots: SsmSnapshotPool,
184    /// Optional SSM snapshot spill tier (`ATLAS_SSM_TIER`). `None` (default)
185    /// keeps the drop-only reclaim path byte-identical; `Some` moves an evicted
186    /// snapshot's bytes to the tier (keeping its index entry findable) so a warm
187    /// turn faults it back instead of recomputing. Threaded into
188    /// [`SsmSnapshotPool::reclaim_from_cache`] at every reclaim call site.
189    pub(super) ssm_tier_store: Option<Arc<dyn super::ssm_tier::SnapshotBlobStore>>,
190    /// Fixed max blocks per sequence (max_seq_len / block_size + 1).
191    /// Used as constant stride in attention metadata for CUDA graph compatibility.
192    pub(super) max_blocks_per_seq: u32,
193    /// Permanent KV cache block for padding sequences in batched decode.
194    pub(super) dummy_kv_block: u32,
195    /// Profile mode: skip graphs, sync+time each layer. Set ATLAS_PROFILE=1.
196    pub(super) profile: bool,
197    /// One-shot profile flag for the next prefill request only. Set
198    /// ATLAS_PROFILE_FIRST=1 to capture per-step timing on the first prefill
199    /// after startup without disabling CUDA graphs for subsequent decodes.
200    /// Consumed (atomically swapped to false) by `prefill_chunk` / `prefill`.
201    pub(super) profile_first_pending: std::sync::atomic::AtomicBool,
202    /// When true, decode() skips CUDA graph capture/replay. Set during
203    /// per-sequence batch decode to prevent SSM state pointer baking.
204    pub(super) suppress_graphs: std::sync::atomic::AtomicBool,
205    /// MTP draft proposer (built from mtp_weights at init).
206    pub(super) proposer: Option<Arc<dyn DraftProposer>>,
207    /// Dedicated buffer for saving hidden state before MTP head runs.
208    /// Size: hidden_size * 4 bytes (one FP32 vector). MTP overwrites shared
209    /// buffers (norm_output etc.), so the target hidden must be saved here first.
210    pub(super) mtp_hidden_save: DevicePtr,
211    /// Batched-verify hidden stash: `[8, hidden_size]` BF16 — one RAW-hidden
212    /// row per batched-verify sequence (n ≤ 8 envelope). Every drafter
213    /// `forward_one` writes its hidden into `buffers.hidden_states()`
214    /// (mtp_multi.rs), so seq 0's propose clobbers seq 1..n's verify hidden
215    /// rows; the batched verdict path copies each sequence's accepted-row
216    /// hidden here FIRST (`stash_verify_hidden_rows`), then feeds the drafter
217    /// from the stash (`save_hidden_for_mtp_from_stash`). NULL without MTP.
218    pub(super) verify_hidden_stash: DevicePtr,
219    /// ATLAS_MTP_CATCHUP: circular per-position final-hidden ring captured
220    /// during serial-decode stretches (BF16 rows, slot = position % ring
221    /// len). Feeds the drafter catch-up on the next propose. NULL when the
222    /// feature is off or no proposer exists.
223    pub(super) mtp_catchup_ring: DevicePtr,
224    /// (first_position, count) of the contiguous position range currently
225    /// resident in the ring; a non-contiguous capture resets the range.
226    pub(super) mtp_catchup_meta: parking_lot::Mutex<(usize, usize)>,
227    /// ATLAS_MTP_DRAFTER_PREFILL: per-position final-layer hidden capture for
228    /// the whole prompt, `[max_seq_len, hidden_size]` BF16 (~335 MB at 32k /
229    /// h=5120). NULL unless the env is set AND an MTP proposer is built.
230    /// Filled contiguously by the prefill chunk epilogues; consumed once by
231    /// the drafter-prefill pass on the first propose() of a sequence.
232    pub(super) mtp_prefill_hidden: DevicePtr,
233    /// Row capacity of `mtp_prefill_hidden` (== max_seq_len at alloc; 0 when
234    /// the feature is off). SSOT for the capture bounds check.
235    pub(super) mtp_prefill_capacity: usize,
236    /// Rows of `mtp_prefill_hidden` captured contiguously from position 0 for
237    /// the CURRENT sequence. Reset to 0 on `alloc_sequence`; a chunk whose
238    /// start does not extend the contiguous range (prefix-cache reuse, warm
239    /// restore) leaves it stale-short, which safely disables drafter-prefill
240    /// for that sequence (coverage check at the propose site).
241    pub(super) mtp_prefill_capture_len: std::sync::atomic::AtomicUsize,
242    /// Monotonic generation of the single-slot capture above. Bumped every
243    /// time a chunk-0 prefill (re)starts the capture; the restarting
244    /// sequence is stamped with the new value (`SequenceState::
245    /// mtp_capture_gen`). Appends and the drafter-prefill consume require
246    /// `stamp == current generation`, so at C>=2 a sequence whose capture
247    /// was overwritten by ANOTHER sequence's prefill skips the drafter
248    /// prefill instead of pairing its tokens with foreign hiddens. The
249    /// current value IS the latest capture's generation (single atomic,
250    /// SSOT). 0 = no capture ever started (matches the fresh-seq stamp 0,
251    /// which is harmless: `captured >= prompt_len >= 2` fails at len 0).
252    pub(super) mtp_prefill_capture_gen: std::sync::atomic::AtomicU64,
253    /// Ticket dispenser for `mtp_store_range` ownership (`SequenceState::
254    /// mtp_store_gen`), drawn once per `alloc_sequence`.
255    ///
256    /// ★ SEPARATE FROM `mtp_prefill_capture_gen`, and it must stay separate.
257    /// Drawing the store ticket from the capture counter advances it on every
258    /// admission, and `owns_capture` (`trait_impl/speculative.rs`) requires the
259    /// sequence's captured generation to still EQUAL the current one — so any
260    /// sequence admitted between a capture and its propose silently disabled
261    /// the other sequence's drafter prefill. Measured: C=1 unaffected (no
262    /// interleaved admission), C=2 TPOT 62 -> 79 ms and 30.8 -> 23.5 tok/s,
263    /// reproduced twice. One counter, two meanings, was the whole bug.
264    pub(super) mtp_store_gen_seq: std::sync::atomic::AtomicU64,
265    /// ATLAS_MTP_CARRY_DRAFTER: the previous turn's drafter KV, held so the
266    /// next turn of the same session can adopt it instead of rebuilding
267    /// (1136 ms at 12k rows) or — as today — silently going without. Single
268    /// slot: the carry is force-disabled outside single-sequence dispatch
269    /// (`mtp_carry::carry_armed_with`), and one slot makes block ownership
270    /// unambiguous (blocks are owned here XOR by a live sequence). This used to
271    /// say "MTP is gated `active.len() == 1` on every spec path" — that is
272    /// false, the dispatch cap defaults to 32. `None` when the feature is off
273    /// or nothing has been carried.
274    pub(super) mtp_carry: parking_lot::Mutex<Option<super::mtp_carry::CarriedDrafter>>,
275    /// Absolute position interval of `mtp_prefill_hidden` rows, WITH the
276    /// sequence generation that wrote them. Only maintained when
277    /// ATLAS_MTP_CARRY_DRAFTER is on.
278    ///
279    /// ★ THE STAMP IS THE GUARD; the `alloc_sequence` reset is not. This doc
280    /// used to claim the interval was "per-sequence by construction" because
281    /// `alloc_sequence` resets it — and that was false, in two orderings. The
282    /// reset happens when a sequence is ADMITTED, but the writer
283    /// (`drafter_prefill`) had no ownership check at all, so a sequence whose
284    /// last chunk landed after another had been admitted merged its write into
285    /// the newcomer's interval and then read the newcomer's rows. Reset still
286    /// happens, as defence in depth; `gen` is what makes the claim true.
287    pub(super) mtp_store_range: parking_lot::Mutex<super::mtp_carry::StoreRange>,
288    /// DFlash 5-layer hidden-state stack. Allocated only when a
289    /// `BlockDiffusionDraftHead` proposer is built. Layout:
290    /// `[5 × hidden_size × bf16]` shallow-to-deep at the layer indices
291    /// declared by `dflash_capture_layers`. Holds the most-recently-decoded
292    /// token's intermediate hiddens; the drafter consumes them via its `fc`
293    /// projection on the next propose() call. None for non-DFlash runs.
294    pub(super) dflash_hidden_save: Option<DevicePtr>,
295    /// Layer indices to capture for DFlash. Empty when DFlash is disabled.
296    /// Sourced from drafter's `dflash_config.target_layer_ids` at model build.
297    pub(super) dflash_capture_layers: Vec<usize>,
298    /// Row capacity of `dflash_hidden_save` (the K-row EAGLE capture buffer).
299    /// `try_dflash_capture_all` must never write past this many rows. Single
300    /// source of truth for the buffer's KMAX; 0 when DFlash is disabled.
301    pub(super) dflash_hidden_save_rows: usize,
302    /// Rows per per-sequence capture BAND in `dflash_hidden_save` (= γ+1).
303    /// Sequence `i` of a batched K=γ verify owns rows
304    /// `[i * dflash_kgamma, i * dflash_kgamma + k)`; single-sequence paths
305    /// use band 0. This is the stride the scheduler passes to `commit_ctx`
306    /// as `scratch_row`.
307    pub(super) dflash_kgamma: usize,
308    /// Cached CUDA graphs for K=2 verification, **keyed by `seq.slot_idx`**.
309    /// Same rationale as `decode_graph`: the captured graph has SSM
310    /// h_state/conv_state pointers baked in as kernel arguments, so replay for
311    /// a different slot writes to the wrong sequence's recurrent state. With
312    /// concurrent users alternating through MTP verify, a single
313    /// `Option<GraphHandle>` would corrupt both slots' SSM state.
314    pub(super) verify2_graph: Mutex<std::collections::HashMap<usize, GraphHandle>>,
315    /// Cached CUDA graphs for K=3 verification, keyed by `seq.slot_idx`.
316    pub(super) verify3_graph: Mutex<std::collections::HashMap<usize, GraphHandle>>,
317    /// Cached CUDA graphs for K=4 verification, keyed by `seq.slot_idx`.
318    pub(super) verify4_graph: Mutex<std::collections::HashMap<usize, GraphHandle>>,
319    /// Cached CUDA graphs for the BATCHED K-row verify (verify_e), keyed by
320    /// the batch's ssm-pool slot VECTOR (+ the per-seq row count K + a
321    /// wy-tables-present sentinel). Slot-vector keying is what a per-slot
322    /// key cannot give at n>1: the captured graph bakes every sequence's
323    /// h_state/conv_state/intermediate pointers, so it may only replay for
324    /// the exact same slot assignment in the same batch order (K is in the
325    /// key because a graph also bakes the R = n*K launch dimensions).
326    /// Attention metadata/block tables/embeds live at fixed scratch
327    /// addresses refreshed pre-replay (decode_a2 pattern).
328    /// Value = `(graph, last_use_tick)`; the `u64` alongside the map is the
329    /// monotonically increasing tick. At `VERIFY_BATCHED_GRAPH_CAP` entries
330    /// the least-recently-used graph is destroyed and replaced (slot vectors
331    /// churn with request turnover — the old insert-only map went
332    /// permanently eager after 32 distinct vectors on long serves).
333    pub(super) verify_batched_graphs:
334        Mutex<(std::collections::HashMap<Vec<u32>, (GraphHandle, u64)>, u64)>,
335    /// Batched-verify WY pointer-table staging: `num_ssm_layers` slices of
336    /// `crate::layer::VERIFY_WY_LAYER_STRIDE_BYTES` ([h|Hi0|Hi1|Hi2] × 4
337    /// u64 entries each) at a FIXED device address, refreshed pre-graph every
338    /// batched verify step (`upload_verify_wy_tables`). Enables the
339    /// single-launch table-form `gdn_decode_wy4` in the batched GDN arm.
340    /// NULL without an MTP proposer (path self-gates).
341    pub(super) verify_wy_tables: DevicePtr,
342    /// Encoded key of the bytes CURRENTLY staged in `verify_wy_tables`, or
343    /// `None` when nothing has been staged (the buffer is memset to zero at
344    /// allocation, which no key describes).
345    ///
346    /// `upload_verify_wy_tables` ran a 48 KB host build + a 48 KB H2D on
347    /// EVERY n>=2 verify step. The staged bytes are a pure function of
348    /// `(k, ssm-slot vector in batch order, ghost (slot, depth) pairs)` —
349    /// see `verify_wy_cache_key` for the enumeration and the proof — so a
350    /// step whose key matches what is already on the device may skip both.
351    /// Kill switch `ATLAS_NO_VERIFY_WY_CACHE` (PRESENCE) restores the
352    /// unconditional re-stage.
353    pub(super) verify_wy_cache: Mutex<Option<Vec<u64>>>,
354    /// Cached CUDA graphs for DFlash K=γ verification, keyed by
355    /// `(seq.slot_idx, K)`. K is `tokens.len()` (γ+1 typically). One graph
356    /// per (slot, K) — different γ values coexist via the K dimension.
357    pub(super) verify_kgamma_graph: Mutex<std::collections::HashMap<(usize, usize), GraphHandle>>,
358    /// Cached CUDA graphs for the DFlash decode+verify fused pass, keyed by
359    /// `(seq.slot_idx, M)` where M = tokens.len() = 1 + num_drafts.
360    /// Replaces the separate `decode_graph` (M=1) + `verify{k}_graph` (M=k)
361    /// on the DFlash path with a single M-row weight sweep.
362    pub(super) fused_graph: Mutex<std::collections::HashMap<(usize, usize), GraphHandle>>,
363    /// Prefix cache for KV block reuse across requests.
364    pub(super) prefix_cache: Box<dyn spark_runtime::prefix_cache::PrefixCache>,
365    /// Secondary CUDA stream for pipelining checkpoint D2D with MTP propose.
366    pub(super) secondary_stream: u64,
367    /// CUDA event for GPU-side inter-stream synchronization (avoids CPU-blocking sync).
368    pub(super) secondary_event: u64,
369    /// CUDA event ordering SSM-snapshot SAVES (on the default stream) before a
370    /// later warm Marconi RESTORE (on the prefill stream). Marconi saves
371    /// (`decode_marconi_checkpoint`, `finish_leaf_snapshot`, prefill-time
372    /// `prefill_save_snapshot`) record this event after their D2D copies; a
373    /// warm restore in `prefill_b_prefix_lookup` waits on it before reading the
374    /// snapshot region. Without this cross-stream edge, under concurrent
375    /// batched traffic the restore (prefill stream) can read a snapshot slot
376    /// whose save D2D (default stream) has not yet completed — restoring stale
377    /// / torn SSM recurrent state and diverging the warm decode from the cold
378    /// reference (the prefix-cache × hybrid-SSM warm-restore corruption).
379    pub(super) snapshot_event: u64,
380    /// Communication backend for expert parallelism (EP) all-reduce.
381    /// None for single-GPU (no distributed communication needed).
382    pub(super) comm: Option<std::sync::Arc<dyn spark_comm::CommBackend>>,
383    /// Small GPU buffer for EP token broadcast (4 bytes).
384    pub(super) ep_cmd_buf: DevicePtr,
385    /// EP wire-protocol version. When true, the seq_id-preamble protocol
386    /// extension from atlas#99 is active — every command broadcast is
387    /// preceded by a `seq_id` broadcast so the worker can dispatch
388    /// slot-bound work into the right `SequenceState` slot. When false,
389    /// the legacy single-sequence protocol is used. Set at construction
390    /// from `ATLAS_EP_PROTOCOL` env var; both ranks must agree.
391    pub(super) ep_protocol_v2: bool,
392    /// Self-speculative decoding mode: draft via layer-skipping (no MTP weights needed).
393    pub(super) self_speculative: bool,
394    /// Last token index passed to save_hidden_for_mtp (for EP broadcast to rank 1).
395    pub(super) last_mtp_hidden_idx: std::sync::atomic::AtomicUsize,
396    /// Optional vision encoder for VL models (Qwen3-VL).
397    pub(super) vision_encoder: Option<crate::layers::VisionEncoder>,
398    /// Number of patches encoded by the last prepare_vision_embed() call.
399    /// 0 means no vision embeddings pending.
400    pub(super) vision_embed_patches: Mutex<usize>,
401    /// Per-ITEM `(t_len, grid_h_post_merge, grid_w_post_merge)` from the most
402    /// recent prepare_vision_embed() call. Used by MRoPE prefill to assign
403    /// correct (t, h, w) position IDs to each vision pad token. Empty when no
404    /// vision input is pending.
405    ///
406    /// `t_len` is the number of TEMPORAL GROUPS the item spans: 1 for a still
407    /// image, `frames / temporal_patch_size` for a video. It is per item and
408    /// not per encoder row on purpose — a video feeds `t_len` rows to the ViT
409    /// but occupies ONE contiguous pad run, and the position builder has to
410    /// treat that run as a single item whose T advances rather than as
411    /// `t_len` unrelated images (which would restart T and mis-advance the
412    /// running position for everything after it).
413    pub(super) vision_image_grids: Mutex<Vec<(usize, usize, usize)>>,
414    /// Co-dispatched batched-ViT slice base for the NEXT prefill_chunk. When a
415    /// tick batches >=2 image requests into one buf_out, each request's chunk-0
416    /// splice/MRoPE must read its OWN slice: `vision_row_base` = first buf_out
417    /// row, `vision_grid_base` = first vision_image_grids index, and
418    /// `vision_owned_images` bounds the grid scan. All 0 ⇒ legacy (read from
419    /// row 0 / grid 0). Set right before prefill_chunk, reset to 0 right after.
420    pub(super) vision_row_base: Mutex<usize>,
421    pub(super) vision_grid_base: Mutex<usize>,
422    pub(super) vision_owned_images: Mutex<usize>,
423    /// Page-locked host staging for batched metadata H2D transfers.
424    /// Allocated once at init via cuMemAllocHost, freed in Drop.
425    ///
426    /// Uses UnsafeCell (not Mutex) because TransformerModel is only accessed
427    /// from the scheduler thread after construction. The Model trait requires
428    /// Send+Sync for the move to the scheduler thread, but the model is never
429    /// accessed from multiple threads simultaneously. A Mutex here caused a
430    /// 500x EP=2 decode regression (50 tok/s → 0.1 tok/s) due to contention
431    /// with the NCCL all-reduce path.
432    pub(super) pinned_staging: std::cell::UnsafeCell<PinnedMetaStaging>,
433    /// Save SSM snapshots every N blocks during chunked prefill.
434    /// 0 = disabled (leaf-only). When > 0, intermediate checkpoints are saved
435    /// at block boundaries, enabling partial prefix SSM restore.
436    pub(super) ssm_checkpoint_interval: usize,
437    /// Kernel handle for fused SSM state normalization (prevents state explosion
438    /// during long chunked prefill — the SSM forgetting bug).
439    pub(super) ssm_state_norm_kernel: KernelHandle,
440    /// FP16 h-state twin of the above (`ATLAS_SSM_H_FP16`). Selected from the
441    /// sequence's own `SsmLayerState::h_is_f16`, so the dispatch reads the
442    /// invariant rather than assuming it.
443    pub(super) ssm_state_norm_f16_kernel: KernelHandle,
444    /// GPU buffer for ssm_state_clamp_norm_fused's pointer table `[num_ssm_layers]`.
445    pub(super) ssm_norm_ptrs_buf: DevicePtr,
446    /// One-shot FP32 -> FP16 h-state converter (`ATLAS_SSM_H_FP16`).
447    pub(super) ssm_h_f32_to_f16_kernel: KernelHandle,
448    /// Its widening inverse. Used ONLY by the stage-3 f16-SIZED pool
449    /// (`--ssm-h-dtype f16-pool`) on the BATCHED prefill path, whose GDN
450    /// kernels take a device pointer TABLE and so cannot be wrapped inside
451    /// the layer the way the single-stream ladder is. Zero otherwise.
452    pub(super) ssm_h_f16_to_f32_kernel: KernelHandle,
453    /// Staging buffer for it, one layer wide (`h_bytes / 2`). The conversion is
454    /// a narrowing compaction and CANNOT be done in place: thread `2i`'s write
455    /// lands inside thread `i`'s read with nothing ordering them. Allocated
456    /// lazily on first use, so a serve without the flag pays nothing.
457    pub(super) ssm_h_f16_scratch: std::sync::OnceLock<DevicePtr>,
458
459    /// SOLID Incr-4: dedicated persistent GPU buffer for the batched-decode MoE
460    /// per-row fold map `[max_batch_size]` i32 (`< 0` = base skip, `>= 0` = fold
461    /// the active adapter). Allocated ONCE at init (fixed device address),
462    /// refreshed per decode step via copy_h2d_async — graph-capture-safe exactly
463    /// like the GDN buffers, and now DISTINCT from the old +160 metadata gap so
464    /// seq_slot@+128 reclaims its full +128..+256 range (concurrent-LoRA decode
465    /// cap 8 → 32). Always allocated (cheap, max_batch_size·4 B); never touched
466    /// when self.lora is None (upload_moe_row_adapter returns DevicePtr(0)).
467    pub(super) moe_row_adapter_buf: DevicePtr,
468
469    // ── Two-phase SSM prefill buffers ──
470    // These hold GDN inputs/outputs for the full sequence, allowing the GDN
471    // recurrence to run in a single kernel launch while GEMM projections are
472    // processed in smaller chunks (memory-bounded).
473    //
474    // Allocated at model init for max_seq_len tokens. Reused across layers
475    // (only one layer runs at a time) and across sequences.
476    /// Packed QKV for two-phase SSM prefill: [max_seq_len, conv_dim] BF16.
477    /// Layout per token: [Q(key_dim) | K(key_dim) | V(value_dim)].
478    pub(super) gdn_buf_qkv: DevicePtr,
479    /// Interleaved gate/beta for two-phase SSM prefill: [max_seq_len, 2*num_v_heads] FP32.
480    /// Layout per token: [gate(nv) | beta(nv)].
481    pub(super) gdn_buf_gate_beta: DevicePtr,
482    /// Full-sequence GDN output: [max_seq_len, value_dim] BF16
483    pub(super) gdn_buf_out: DevicePtr,
484    /// Full-sequence Z gate (for gated RMS norm in phase 3): [max_seq_len, value_dim] BF16
485    pub(super) gdn_buf_z: DevicePtr,
486    /// Max sequence length these buffers were allocated for.
487    pub(super) gdn_buf_max_len: usize,
488
489    /// Logit softcapping kernel: logits = cap * tanh(logits / cap).
490    /// KernelHandle(0) = disabled (no softcapping for this model).
491    pub(super) logit_softcap_kernel: KernelHandle,
492    /// FP32 variant of logit softcap. KernelHandle(0) when not loaded.
493    /// Used when `use_fp32_logits` is true.
494    pub(super) logit_softcap_fp32_kernel: KernelHandle,
495    /// Whether the single-token decode LM head produces FP32 logits (rather
496    /// than BF16). The FP32 logits path required an FP32 residual stream as a
497    /// precondition; with the residual stream now always BF16, this is always
498    /// false and the BF16 logits path is always taken.
499    pub(super) use_fp32_logits: bool,
500    /// FP32 logits scratch [vocab_size × 4 bytes]. NULL when `use_fp32_logits`
501    /// is false (no allocation).
502    pub(super) logits_fp32_buf: DevicePtr,
503    /// Embedding scale kernel: embeddings *= sqrt(hidden_size).
504    /// KernelHandle(0) = disabled (no scaling for this model).
505    pub(super) embed_scale_kernel: KernelHandle,
506    /// Feature-2 token overlay: per-adapter-slot embed/lm_head row-override
507    /// tables. `None` ⇒ feature OFF ⇒ every overlay forward hook early-returns
508    /// (byte-identical to a no-overlay build). Built in `set_lora_weights`
509    /// (Stage 2) from the resident pool's Stage-1 raw uploads.
510    pub(super) overlays: Option<crate::lora::TokenOverlaySet>,
511    /// Feature-2 token overlay kernels, resolved once at construction via
512    /// `try_kernel` (null-on-miss ⇒ overlay silently unused on an older image).
513    pub(super) overlay_kernels: crate::layers::ops::token_overlay::OverlayKernels,
514    /// Feature-2 per-forward overlay route: the current request's `adapter_slot`,
515    /// stamped at each `Model::{prefill,decode,...}` entry (the scheduler drives
516    /// the model serially on one thread, so a plain atomic is sufficient). The
517    /// overlay hooks resolve it through `routed_prefill_slot` so a request that
518    /// selects a NON-active pool adapter gets THAT adapter's overlay, not the
519    /// pool's active one. `i32::MIN` marks a mixed-adapter decode batch (per-token
520    /// `seq_slot` routing deferred to SOLID Incr-4) ⇒ the hooks skip.
521    pub(super) overlay_route_slot: std::sync::atomic::AtomicI32,
522    /// Feature-1 per-decode MoE route, stamped from the decode batch's adapter
523    /// slots at each `Model::{decode,decode_batch,mixed_forward}` entry (the
524    /// decode/verify `ForwardContext`s read it instead of a hardcoded `Fold`).
525    /// A pure-base decode batch resolves to `Skip` so base requests decode
526    /// normally even while an adapter is resident; any adapter-using row makes
527    /// the batch `Fold`/`Refuse`, which `reject_decode_lora` turns into a loud
528    /// bail (the decode-fold is SOLID Incr-4). Encoded 0=Skip 1=Fold 2=Refuse.
529    pub(super) decode_moe_route: std::sync::atomic::AtomicI32,
530}
531
532/// Pinned host memory staging buffer with reusable metadata Vecs.
533pub(crate) struct PinnedMetaStaging {
534    /// Page-locked host buffer (cuMemAllocHost).
535    pub(super) ptr: *mut u8,
536    /// Size in bytes.
537    pub(super) bytes: usize,
538    /// Reusable `Vec<u32>` for positions (avoids per-chunk heap allocation).
539    pub(super) positions: Vec<u32>,
540    pub(super) positions_h: Vec<u32>,
541    pub(super) positions_w: Vec<u32>,
542    /// Reusable `Vec<i64>` for slot mappings (avoids per-chunk heap allocation).
543    pub(super) slots: Vec<i64>,
544}
545
546impl PinnedMetaStaging {
547    /// The ONLY way to write this buffer: a bounds-checked cursor. See
548    /// [`crate::model::pinned_pack`] for why the rule lives there and not in
549    /// each of the five call sites that pack it.
550    ///
551    /// `dest_bytes` is how much room the DEVICE destination has, and it is
552    /// required rather than defaulted because it is the bound that was missing.
553    /// `bytes` here equals `sizes.scratch` exactly (`impl_a1.rs` allocates
554    /// `scratch.max(64 KiB)` and `sizes.rs` already floors scratch at 64 KiB),
555    /// but every one of these packs is uploaded to `scratch().offset(k)` for
556    /// some non-zero `k`. So a pack that fits the HOST staging buffer can still
557    /// run `k` bytes off the end of the DEVICE allocation, and checking only
558    /// `cursor <= stg.bytes` — which is all the old code did — never sees it.
559    /// The packer's capacity is the smaller of the two ends.
560    ///
561    /// Takes `&self` rather than `&mut self` on purpose — the bytes it writes
562    /// are the separate `cuMemAllocHost` region `ptr` refers to, not this
563    /// struct, so a shared borrow is enough and callers can still read the
564    /// reusable source `Vec`s alongside it.
565    pub(crate) fn packer_for(
566        &self,
567        dest_bytes: usize,
568    ) -> crate::model::pinned_pack::PinnedPacker<'_> {
569        // SAFETY: `ptr`/`bytes` are the `alloc_host_pinned` region installed in
570        // `impl_a1.rs` and released in `drop.rs`; it is live for the model's
571        // lifetime, zeroed at allocation (the trait's contract), and only ever
572        // touched from the single scheduler thread — the same invariant that
573        // `unsafe impl Sync for TransformerModel` above rests on. The capacity
574        // handed over is `min(host room, device room)`, never more than the
575        // allocation.
576        unsafe {
577            crate::model::pinned_pack::PinnedPacker::new(self.ptr, self.bytes.min(dest_bytes))
578        }
579    }
580}
581
582// SAFETY: TransformerModel is constructed on the main thread, then moved to
583// the scheduler thread via Box<dyn Model>. After the move, ALL access
584// (prefill, decode, batch_decode) happens on the single scheduler thread.
585// The Model trait requires Send+Sync for the cross-thread move, but the
586// Model is moved to the scheduler thread and accessed exclusively from there.
587// UnsafeCell<PinnedMetaStaging> is not inherently Sync, but single-thread
588// access is enforced at runtime by the scheduler architecture.
589// The raw pointer in PinnedMetaStaging points to cuMemAllocHost memory which
590// is process-global and valid from any thread.
591unsafe impl Send for TransformerModel {}
592// SAFETY: Model methods are only called from the scheduler thread. No concurrent &self access.
593unsafe impl Sync for TransformerModel {}
594
595/// Release every pool this model owns, newest first.
596///
597/// Construction order is buffers → kv cache → ssm pools → derived, so release
598/// runs the reverse. `Teardown` is used rather than a hand-rolled sequence
599/// because it attempts every resource even after one fails: a half-torn-down
600/// GPU is worse than a reported error.
601///
602/// NOT released here: the weights. `build_model` takes `store: &WeightStore`
603/// and the layers only copy pointers out of it, so this model does not own
604/// them — the host that retained the store releases it after this returns.
605impl TransformerModel {
606    /// Hand the model the ledger of its own weights, for teardown.
607    pub fn adopt_weight_store(&mut self, store: spark_runtime::weights::WeightStore) {
608        self.weight_store = Some(store);
609    }
610
611    pub(super) fn release_pools(&mut self) -> anyhow::Result<()> {
612        use atlas_core::scope::ModelResource;
613
614        let gpu: &dyn GpuBackend = self.gpu.as_ref();
615        let mut first_error: Option<anyhow::Error> = None;
616        let mut attempt = |label: &'static str, r: anyhow::Result<()>| {
617            if let Err(e) = r
618                && first_error.is_none()
619            {
620                first_error = Some(e.context(label));
621            }
622        };
623
624        attempt("derived weights", self.derived.release(gpu));
625        attempt("ssm snapshots", self.ssm_snapshots.release(gpu));
626        // The pool is Arc'd because slots are handed out to sequences. A live
627        // clone here means something still holds a slot, which is a drain bug,
628        // not a teardown one — so it is reported rather than forced.
629        match std::sync::Arc::get_mut(&mut self.ssm_pool) {
630            Some(pool) => attempt("ssm state pool", pool.release(gpu)),
631            None => attempt(
632                "ssm state pool",
633                Err(anyhow::anyhow!(
634                    "{} handle(s) still hold the SSM pool — a sequence was not \
635                     released before teardown",
636                    std::sync::Arc::strong_count(&self.ssm_pool) - 1
637                )),
638            ),
639        }
640        attempt("kv cache", self.kv_cache.lock().release(gpu));
641        attempt("buffer arena", self.buffers.release(gpu));
642        // Weights LAST: the layers hold pointers into them, so they must not be
643        // freed until everything that reads them is gone.
644        if let Some(mut store) = self.weight_store.take() {
645            attempt("weight store", store.release(gpu));
646        }
647        // LAST: whatever the owners above did not cover. Chiefly the loaders'
648        // fused weights, which live in layer structs and belong to no pool.
649        // Every pointer freed above has already left the ledger, so this
650        // cannot double-free — it only ever sees what was missed.
651        let swept = gpu.sweep_unreleased();
652        if swept > 0 {
653            tracing::warn!(
654                "teardown swept {swept} allocation(s) that no ModelResource \
655                 released — they are reclaimed, but each one is memory whose \
656                 owner is unaccounted for"
657            );
658        }
659
660        match first_error {
661            Some(e) => Err(e),
662            None => Ok(()),
663        }
664    }
665}