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