Skip to main content

fuel_model_phi/
lib.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! The Phi-family lazy-graph decoder (`PhiConfig`/`PhiWeights`/`PhiModel`).
3//!
4//! Extracted from `fuel-core/src/lazy.rs` (fuel-core dissolution, per
5//! `docs/architecture/02-layers.md`'s ratified `fuel-model-phi`† — one architecture per
6//! crate). `fuel-core` keeps no shim for this type (see `fuel-model-llama`'s doc comment for
7//! why: `fuel-model-phi` depends on `fuel-core`, so a re-export back would be a build cycle).
8//! Every real consumer was repointed to `fuel_model_phi::` directly.
9//!
10//! ⚠️ Same stepping-stone status as `fuel-model-llama`, including the same generic-utility
11//! exclusion: this crate does not own `WeightStorage`, `load_tensor_as_f32`,
12//! `load_transposed_matrix*`, or `apply_affine_rms_norm`, all textually near `PhiModel` in
13//! the original file but used by dozens of unrelated models and left in `fuel-core`.
14
15use fuel_ir::shape::Shape;
16use fuel_tensor::{DType, Device};
17use fuel_tensor::{
18    inference_context::InferenceContext, inference_context::KvCache, inference_context::KvSlot,
19};
20use fuel_tensor::{
21    lazy::SamplingStrategy, lazy::Tensor, lazy::TokenDataHost, lazy::WeightStorage,
22    lazy::build_decode_causal_mask, lazy::load_tensor_as_f32,
23    lazy::load_transposed_matrix_preserve_dtype, lazy::refresh_decode_session, lazy::sample_logits,
24};
25#[cfg(feature = "cuda")]
26use fuel_tensor::{lazy::TokenDataBytes, lazy::captured_output_to_f32};
27use serde::Deserialize;
28use std::sync::Arc;
29
30impl fuel_tensor::persistent_decode::PersistentDecodeModel for PhiModel {
31    fn decode_n_layers(&self) -> usize {
32        self.config.n_layers
33    }
34
35    /// **Measured: Phi takes the SymEnv path on CPU/F32** (`offset: None`), so
36    /// there is no device-offset operand and its builder takes no dtype/offset
37    /// arguments. `rope_inv_freq` is ignored: Phi has no LLaMA-3-style RoPE
38    /// scaling override, and accepting-then-dropping it here is what lets one
39    /// driver serve both without the driver knowing which model it has.
40    fn build_decode_token_data(
41        &self,
42        device: &Device,
43        cached_len: usize,
44        tokens: &[u32],
45        session: &fuel_tensor::inference_context::DecodeSession,
46        _cache: &KvCache,
47        _rope_inv_freq: Option<&[f64]>,
48    ) -> fuel_ir::error::Result<fuel_tensor::inference_context::DecodeTokenData> {
49        self.build_token_rope_mask_arcs(device, cached_len, tokens, session.max_seq_len())
50    }
51}
52// ---- Phi-2 model assembly ---------------------------------------------------
53//
54// Phi-2 (microsoft/phi-2, 2.7B params) differs from LLaMA in four
55// meaningful ways, each of which exercises a different code path:
56//
57//   1. Norm: LayerNorm with gain + bias (not RMSNorm with gain only)
58//   2. MLP: standard fc1 → GELU → fc2 (not SwiGLU's gate ⊗ up → down)
59//   3. Residual structure: parallel attention + MLP — both branches
60//      consume the same pre-block-norm input and are summed with x:
61//        h' = x + attn(LN(x)) + mlp(LN(x))
62//      compared to LLaMA's sequential:
63//        h1 = x + attn(LN1(x))
64//        h2 = h1 + mlp(LN2(h1))
65//   4. Partial RoPE: only the first `rotary_dim` entries of each head
66//      get rotated (rotary_dim=32 for head_dim=80 in Phi-2). The rest
67//      pass through unchanged. We slice → rope → concat.
68//
69// Phi-2 also has biases on Q/K/V/dense and on fc1/fc2, plus a bias on
70// the LayerNorm. Every one of those is a real `broadcast_add` in the
71// graph, which exercises the lazy broadcast path we built for the
72// stride-aware binary work.
73
74/// Phi-2 model hyperparameters. Field semantics match the LLaMA config
75/// where they overlap; the `layer_norm_eps`, `partial_rotary_factor`,
76/// and `rotary_dim` fields are Phi-specific.
77#[derive(Debug, Clone, PartialEq)]
78pub struct PhiConfig {
79    pub vocab_size: usize,
80    pub dim: usize, // hidden_size
81    pub n_layers: usize,
82    pub n_heads: usize,
83    pub head_dim: usize,
84    pub ffn_dim: usize, // intermediate_size
85    pub layer_norm_eps: f64,
86    pub rope_base: f64,
87    pub partial_rotary_factor: f64,
88    /// Number of dims at the start of head_dim that get rotated.
89    /// `rotary_dim = (partial_rotary_factor * head_dim).round() as usize`.
90    /// Must be even for the half-split RoPE layout.
91    pub rotary_dim: usize,
92    pub tie_word_embeddings: bool,
93}
94
95fn default_phi_layer_norm_eps() -> f64 {
96    1e-5
97}
98fn default_phi_rope_base() -> f64 {
99    10_000.0
100}
101fn default_partial_rotary_factor() -> f64 {
102    0.4
103}
104
105/// A Phi `config.json` under HuggingFace's field names.
106///
107/// ⚠️ THIS IS THE ONE CONFIG WHOSE RESOLUTION IS A CHAIN RATHER THAN A MAP,
108/// which is why it was converted last: the shape had to be settled by the
109/// other six before the constraint could be honoured rather than discovered.
110///
111/// ```text
112///   head_dim   <- "head_dim" if present, else dim / n_heads
113///   rotary_dim <- round(partial_rotary_factor * head_dim)     depends on ^
114///   then rotary_dim must be even
115/// ```
116///
117/// `rotary_dim` is derived from the RESOLVED `head_dim`, not from the raw
118/// field, so `resolve` computes `head_dim` into a binding first and uses that
119/// binding. Writing the two as sibling entries in a struct literal would
120/// happen to work — Rust evaluates fields in source order — but it would
121/// encode the ordering as an accident of layout rather than as a dependency,
122/// and a later field reshuffle would silently change the result.
123#[derive(Debug, Clone, Deserialize)]
124pub(crate) struct PhiConfigRaw {
125    vocab_size: usize,
126    hidden_size: usize,
127    num_hidden_layers: usize,
128    num_attention_heads: usize,
129    intermediate_size: usize,
130    #[serde(default)]
131    head_dim: Option<usize>,
132    #[serde(default = "default_phi_layer_norm_eps")]
133    layer_norm_eps: f64,
134    #[serde(default = "default_phi_rope_base", rename = "rope_theta")]
135    rope_base: f64,
136    #[serde(default = "default_partial_rotary_factor")]
137    partial_rotary_factor: f64,
138    #[serde(default)]
139    tie_word_embeddings: bool,
140}
141
142impl PhiConfigRaw {
143    fn from_json_str(json: &str) -> fuel_ir::error::Result<Self> {
144        serde_json::from_str(json)
145            .map_err(|e| fuel_ir::error::Error::Msg(format!("parsing config.json: {e}")))
146    }
147
148    fn resolve(self) -> fuel_ir::error::Result<PhiConfig> {
149        // ORDERED, not a flat map: rotary_dim reads the resolved head_dim.
150        let head_dim = fuel_loaders::hf_config::head_dim(
151            self.head_dim,
152            self.hidden_size,
153            self.num_attention_heads,
154        )?;
155        let rotary_dim = (self.partial_rotary_factor * head_dim as f64).round() as usize;
156        if !rotary_dim.is_multiple_of(2) {
157            fuel_ir::bail!(
158                "PhiConfig: rotary_dim {rotary_dim} must be even (partial_rotary_factor={}, head_dim={head_dim})",
159                self.partial_rotary_factor
160            );
161        }
162        Ok(PhiConfig {
163            vocab_size: self.vocab_size,
164            dim: self.hidden_size,
165            n_layers: self.num_hidden_layers,
166            n_heads: self.num_attention_heads,
167            head_dim,
168            ffn_dim: self.intermediate_size,
169            layer_norm_eps: self.layer_norm_eps,
170            rope_base: self.rope_base,
171            partial_rotary_factor: self.partial_rotary_factor,
172            rotary_dim,
173            tie_word_embeddings: self.tie_word_embeddings,
174        })
175    }
176}
177
178impl PhiConfig {
179    ///
180    /// `PhiConfigRaw` is the wire shape; `PhiConfigRaw::resolve` applies
181    /// the CHAINED derivation and the evenness check.
182    pub fn from_hf_json_str(json: &str) -> fuel_ir::error::Result<Self> {
183        PhiConfigRaw::from_json_str(json)?.resolve()
184    }
185}
186
187/// How Q/K/V projections are stored for a Phi layer.
188///
189/// - `Split`: separate Q, K, V weights + biases (matches HF safetensors
190///   layout — `q_proj.weight`, `k_proj.weight`, `v_proj.weight`).
191/// - `Packed`: single `[3*dim, dim]` weight + `[3*dim]` bias (matches
192///   llama.cpp GGUF layout — `attn_qkv.weight`). The forward pass does
193///   one big matmul producing `[*, 3*dim]`, then slices that output
194///   into Q, K, V. Critically, the slice happens on the OUTPUT side
195///   rather than up-front on the weights — this matches Candle's
196///   `qkv.reshape(3, n_head, head_dim).i((.., .., 0..3))` exactly and
197///   avoids any potential byte-split-order hazards on the weight side.
198#[derive(Debug, Clone)]
199pub enum PhiQkv {
200    Split {
201        q: WeightStorage,
202        q_bias: Arc<[f32]>,
203        k: WeightStorage,
204        k_bias: Arc<[f32]>,
205        v: WeightStorage,
206        v_bias: Arc<[f32]>,
207    },
208    Packed {
209        /// `[3*dim, dim]` weight (GGUF layout).
210        qkv: WeightStorage,
211        /// `[3*dim]` bias, Q first then K then V (standard Candle convention).
212        qkv_bias: Arc<[f32]>,
213    },
214}
215
216/// Per-layer Phi-2 weights. Every projection has a bias (unlike LLaMA).
217#[derive(Debug, Clone)]
218pub struct PhiLayerWeights {
219    pub attn_qkv: PhiQkv,
220    /// Output projection (called "dense" in Phi-2, not "o_proj").
221    pub attn_dense: WeightStorage,
222    pub attn_dense_bias: Arc<[f32]>,
223    pub mlp_fc1: WeightStorage, // [dim, ffn_dim]
224    pub mlp_fc1_bias: Arc<[f32]>,
225    pub mlp_fc2: WeightStorage, // [ffn_dim, dim]
226    pub mlp_fc2_bias: Arc<[f32]>,
227    /// Pre-block LayerNorm (single norm for Phi-2's parallel attn+MLP).
228    pub norm_gain: Arc<[f32]>,
229    pub norm_bias: Arc<[f32]>,
230}
231
232#[derive(Debug, Clone)]
233pub struct PhiWeights {
234    /// See `LlamaWeights::instance`.
235    pub instance: fuel_tensor::decode_shape::ModelInstanceId,
236    pub token_embedding: Arc<[f32]>, // [vocab_size, dim]
237    pub layers: Vec<PhiLayerWeights>,
238    pub final_norm_gain: Arc<[f32]>,
239    pub final_norm_bias: Arc<[f32]>,
240    pub output: WeightStorage, // [dim, vocab_size]
241    pub output_bias: Option<Arc<[f32]>>,
242}
243
244#[derive(Debug, Clone)]
245pub struct PhiModel {
246    pub config: PhiConfig,
247    pub weights: PhiWeights,
248}
249
250impl PhiModel {
251    /// See `LlamaModel::decode_shape_key`.
252    pub fn decode_shape_key(&self) -> u64 {
253        let mut h = fuel_tensor::decode_shape::ShapeKeyHasher::new();
254        h.mix_str("phi")
255            .mix_instance(self.weights.instance)
256            .mix_u64(self.config.n_layers as u64)
257            .mix_u64(self.config.n_heads as u64)
258            .mix_u64(self.config.head_dim as u64)
259            .mix_u64(self.config.dim as u64)
260            .mix_u64(self.config.vocab_size as u64);
261        h.finish()
262    }
263
264    // ===== Phase 7.6 step 9c E.3.3/E.3.4 — KvCache + InferenceContext =====
265    //
266    // The pipelined-executor forward/generate family, mirroring
267    // `LlamaModel::forward_with_kv_context`. Pre-allocated KV buffers
268    // (`KvCache::with_capacity`) + `Op::WriteSlice` in-graph mutation;
269    // runs on CPU, CUDA, and Vulkan via binding-table dispatch. Phi-2
270    // has no GQA, so the cache's `n_kv_heads` slot carries `n_heads`.
271
272    /// Variant of [`Self::apply_layer_with_cache`] that uses
273    /// pre-allocated KV-cache buffers + `Op::WriteSlice`. The K/V
274    /// caches are bound via `k_cache_const` / `v_cache_const` (Const
275    /// placeholders the caller has wired into [`InferenceContext`]).
276    ///
277    /// **Phase D · D4 (input-independent decode graph — the Phi mirror
278    /// of the LlamaModel D1/D2b transform):** the KV write lands at the
279    /// runtime offset `cached_len` via `write_slice_dyn`
280    /// (`DynScalar::Sym(cached_len_sym)`, resolved through the per-pass
281    /// `SymEnv` at realize), and attention reads the **full fixed-capacity**
282    /// buffers `[batch, n_heads, max_seq_len, head_dim]` with a fixed
283    /// `[1, 1, seq, max_seq_len]` causal `mask` (`k > cached_len + q` masks
284    /// future positions AND the zero-init stale tail). Nothing in the
285    /// graph's *shape* or *structure* depends on `cached_len`, so the
286    /// decode-step graph is byte-identical across tokens — the prerequisite
287    /// for plan-once persistent decode. Numerically identical to the prior
288    /// `slice(0..total_seq)` form (masked positions contribute 0).
289    ///
290    /// Phi specifics preserved from the sliced form: parallel attention +
291    /// MLP over a SHARED pre-block LayerNorm, bias on every projection,
292    /// partial RoPE (only the first `rotary_dim` head entries rotate),
293    /// no GQA (`kv_dim == n_heads * head_dim`), and the parallel residual
294    /// `x + attn_out + mlp_out`. The `mask` is hoisted to ONE shared Const
295    /// built in the forward (was one Const per layer) — byte-exact (it
296    /// depends only on `cached_len` / `seq` / `max_seq_len`), and it cuts
297    /// the per-token data-Const re-bind on the persistent path to 1.
298    fn apply_layer_with_kv_writes(
299        &self,
300        x: &Tensor,
301        layer: &PhiLayerWeights,
302        k_cache_const: &Tensor,
303        v_cache_const: &Tensor,
304        cached_len_sym: fuel_ir::SymId,
305        rope_cos: &Tensor,
306        rope_sin: &Tensor,
307        mask: &Tensor,
308    ) -> fuel_ir::error::Result<Tensor> {
309        let cfg = &self.config;
310        let x_shape = x.shape();
311        let dims = x_shape.dims();
312        let batch = dims[0];
313        let seq = dims[1];
314        let kv_dim = cfg.n_heads * cfg.head_dim; // no GQA in Phi-2
315
316        // Shared pre-block LayerNorm.
317        let x_norm = x.layer_norm_affine(
318            Arc::clone(&layer.norm_gain),
319            Arc::clone(&layer.norm_bias),
320            cfg.layer_norm_eps,
321        )?;
322
323        // Q/K/V projections with bias — identical to apply_layer_with_cache.
324        let (q, k, v) = match &layer.attn_qkv {
325            PhiQkv::Split {
326                q,
327                q_bias,
328                k,
329                k_bias,
330                v,
331                v_bias,
332            } => {
333                let q_out =
334                    q.apply_linear_with_bias(&x_norm, cfg.dim, cfg.dim, Arc::clone(q_bias))?;
335                let k_out =
336                    k.apply_linear_with_bias(&x_norm, cfg.dim, kv_dim, Arc::clone(k_bias))?;
337                let v_out =
338                    v.apply_linear_with_bias(&x_norm, cfg.dim, kv_dim, Arc::clone(v_bias))?;
339                (q_out, k_out, v_out)
340            }
341            PhiQkv::Packed { qkv, qkv_bias } => {
342                let combined = qkv.apply_linear_with_bias(
343                    &x_norm,
344                    cfg.dim,
345                    3 * cfg.dim,
346                    Arc::clone(qkv_bias),
347                )?;
348                let last = combined.rank() - 1;
349                let q_out = combined.slice(last, 0, cfg.dim)?;
350                let k_out = combined.slice(last, cfg.dim, cfg.dim)?;
351                let v_out = combined.slice(last, 2 * cfg.dim, cfg.dim)?;
352                (q_out, k_out, v_out)
353            }
354        };
355
356        // Split heads → [batch, n_heads, seq, head_dim].
357        let q_h = q
358            .reshape(Shape::from_dims(&[batch, seq, cfg.n_heads, cfg.head_dim]))?
359            .permute([0, 2, 1, 3_usize])?;
360        let k_h = k
361            .reshape(Shape::from_dims(&[batch, seq, cfg.n_heads, cfg.head_dim]))?
362            .permute([0, 2, 1, 3_usize])?;
363        let v_h = v
364            .reshape(Shape::from_dims(&[batch, seq, cfg.n_heads, cfg.head_dim]))?
365            .permute([0, 2, 1, 3_usize])?;
366
367        // Partial RoPE on Q and K (first `rotary_dim` entries rotate).
368        let q_r = partial_rope(&q_h, rope_cos, rope_sin, cfg.rotary_dim, cfg.head_dim);
369        let k_r = partial_rope(&k_h, rope_cos, rope_sin, cfg.rotary_dim, cfg.head_dim);
370
371        // Write fresh K/V into the pre-allocated cache buffers via
372        // Op::WriteSlice at the RUNTIME offset `cached_len`. On axis 2
373        // the start is dynamic (`cached_len_sym`, resolved at realize)
374        // and the slab width is `seq`. The returned tensor's Storage Arc
375        // IS the cache const's Arc — post-write reference to the same
376        // buffer (the executor adopts dest's Arc as the kernel output,
377        // mutating in place). Keeping the offset symbolic makes the write
378        // node structurally identical across tokens.
379        let write_ranges = vec![
380            (0, batch),
381            (0, cfg.n_heads),
382            (0, seq), // axis-2 start is dynamic; width = seq
383            (0, cfg.head_dim),
384        ];
385        let dyn_off = fuel_ir::DynScalar::Sym(cached_len_sym);
386        let full_k = k_cache_const.write_slice_dyn(&k_r, write_ranges.clone(), 2, dyn_off)?;
387        let full_v = v_cache_const.write_slice_dyn(&v_h, write_ranges, 2, dyn_off)?;
388
389        // Attend over the FULL fixed-capacity buffers (no slice to
390        // `total_seq`) so the attention shape is `max_seq_len` every
391        // token. The fixed-capacity causal mask (built once in the
392        // forward, shared across layers) excludes future positions AND
393        // the stale/unwritten tail.
394        let k_t = full_k.transpose()?;
395        let scale = 1.0_f64 / (cfg.head_dim as f64).sqrt();
396        let scores = q_r.matmul(&k_t)?;
397        let scores_scaled = Tensor::from_graph_tensor(scores.graph_tensor().mul_scalar(scale));
398        let scores_masked = scores_scaled.broadcast_add(mask)?;
399        let attn = scores_masked.softmax_last_dim()?;
400        let attn_v = attn.matmul(&full_v)?;
401
402        // Merge heads: [batch, n_heads, seq, head_dim] → [batch, seq, dim].
403        let merged = attn_v
404            .permute([0, 2, 1, 3_usize])?
405            .reshape(Shape::from_dims(&[batch, seq, cfg.dim]))?;
406        let attn_out = layer.attn_dense.apply_linear_with_bias(
407            &merged,
408            cfg.dim,
409            cfg.dim,
410            Arc::clone(&layer.attn_dense_bias),
411        )?;
412
413        // MLP branch (shares x_norm with the attention branch).
414        let fc1_out = layer.mlp_fc1.apply_linear_with_bias(
415            &x_norm,
416            cfg.dim,
417            cfg.ffn_dim,
418            Arc::clone(&layer.mlp_fc1_bias),
419        )?;
420        let gelu_out = fc1_out.gelu_tanh();
421        let mlp_out = layer.mlp_fc2.apply_linear_with_bias(
422            &gelu_out,
423            cfg.ffn_dim,
424            cfg.dim,
425            Arc::clone(&layer.mlp_fc2_bias),
426        )?;
427
428        // Parallel residual: x + attn_out + mlp_out.
429        x.add(&attn_out)?.add(&mlp_out)
430    }
431
432    /// Forward pass using pre-allocated KV-cache buffers and
433    /// `Op::WriteSlice`; returns last-position logits. Mirrors
434    /// `LlamaModel::forward_with_kv_context` — see its docs for the
435    /// architectural notes. The cache must have been constructed via
436    /// [`KvCache::with_capacity`] with `n_kv_heads == n_heads` (Phi-2
437    /// has no GQA).
438    pub fn forward_with_kv_context(
439        &self,
440        tokens: &[u32],
441        cache: &mut KvCache,
442        ctx: &mut InferenceContext,
443    ) -> fuel_ir::error::Result<Vec<f32>> {
444        let cfg = &self.config;
445        let weights = &self.weights;
446        let seq = tokens.len();
447        let batch = 1;
448        let cached_len = cache.cached_len;
449
450        if seq == 0 {
451            return Err(fuel_ir::Error::Msg(
452                "PhiModel::forward_with_kv_context: zero tokens".to_string(),
453            )
454            .bt());
455        }
456        if cache.n_layers() != cfg.n_layers {
457            return Err(fuel_ir::Error::Msg(format!(
458                "PhiModel::forward_with_kv_context: cache n_layers {} != model n_layers {}",
459                cache.n_layers(),
460                cfg.n_layers,
461            ))
462            .bt());
463        }
464        let max_seq_len = cache.max_seq_len.ok_or_else(|| {
465            fuel_ir::Error::Msg(
466                "PhiModel::forward_with_kv_context: cache was constructed via with_dims \
467                 (no pre-allocated buffers); call KvCache::with_capacity(...) for the \
468                 WriteSlice path"
469                    .to_string(),
470            )
471            .bt()
472        })?;
473        if cached_len + seq > max_seq_len {
474            return Err(fuel_ir::Error::Msg(format!(
475                "PhiModel::forward_with_kv_context: cached_len ({cached_len}) + seq \
476                 ({seq}) > max_seq_len ({max_seq_len})",
477            ))
478            .bt());
479        }
480        let cache_dtype = cache.dtype.unwrap_or(DType::F32);
481        if cache.n_kv_heads != cfg.n_heads || cache.head_dim != cfg.head_dim {
482            return Err(fuel_ir::Error::Msg(format!(
483                "PhiModel::forward_with_kv_context: cache shape (n_kv_heads={}, \
484                 head_dim={}) disagrees with model config (n_heads={}, head_dim={})",
485                cache.n_kv_heads, cache.head_dim, cfg.n_heads, cfg.head_dim,
486            ))
487            .bt());
488        }
489
490        // Embed lookup + reshape to [batch, seq, dim].
491        let embed = Tensor::from_f32(
492            weights.token_embedding.clone(),
493            Shape::from_dims(&[cfg.vocab_size, cfg.dim]),
494            &Device::cpu(),
495        )?;
496        let token_ids = embed.const_u32_like(tokens.to_vec(), Shape::from_dims(&[seq]))?;
497        let mut h = embed
498            .index_select(0, &token_ids)?
499            .reshape(Shape::from_dims(&[batch, seq, cfg.dim]))?;
500
501        // RoPE tables are sized for `rotary_dim`, not the full
502        // head_dim — partial RoPE rotates only the first `rotary_dim`
503        // entries.
504        let (rope_cos, rope_sin) =
505            h.rope_tables_const(cfg.rope_base, cached_len, seq, cfg.rotary_dim);
506
507        // Phase D · D4: the per-token KV-write offset (`cached_len`) is a
508        // runtime symbol bound through the per-pass `SymEnv` at realize,
509        // not baked into the graph. One symbol shared across all layers
510        // (they all append at the same offset); a fixed id keeps the
511        // decode-step graph structurally identical across tokens.
512        let cached_len_sym = fuel_ir::SymId(0);
513
514        // Phase D · D4: the causal mask is hoisted to ONE shared Const
515        // (was one Const per layer) — byte-identical across layers (it
516        // depends only on `cached_len` / `seq` / `max_seq_len`).
517        let mask_data = build_decode_causal_mask(cached_len, seq, max_seq_len);
518        let mask = h.const_f32_like(mask_data, Shape::from_dims(&[1, 1, seq, max_seq_len]))?;
519
520        // Per-layer: bind the cache K + V Arcs to fresh Const NodeIds,
521        // dispatch through the WriteSlice variant, clean up the
522        // per-step bindings after realize.
523        let cache_shape = Shape::from_dims(&[batch, cfg.n_heads, max_seq_len, cfg.head_dim]);
524        let mut bound_node_ids: Vec<fuel_graph::NodeId> = Vec::with_capacity(2 * cfg.n_layers);
525        for (li, layer_weights) in weights.layers.iter().enumerate() {
526            let k_arc = cache.slot_storage(li, KvSlot::K).ok_or_else(|| {
527                fuel_ir::Error::Msg(format!(
528                    "PhiModel::forward_with_kv_context: cache layer {li} has no K slot \
529                     (with_capacity should have populated all layers)",
530                ))
531                .bt()
532            })?;
533            let v_arc = cache.slot_storage(li, KvSlot::V).ok_or_else(|| {
534                fuel_ir::Error::Msg(format!(
535                    "PhiModel::forward_with_kv_context: cache layer {li} has no V slot",
536                ))
537                .bt()
538            })?;
539            let k_cache_node = h.const_placeholder_like(cache_shape.clone(), cache_dtype);
540            let v_cache_node = h.const_placeholder_like(cache_shape.clone(), cache_dtype);
541            let k_id = k_cache_node.graph_tensor().id();
542            let v_id = v_cache_node.graph_tensor().id();
543            ctx.insert(k_id, k_arc);
544            ctx.insert(v_id, v_arc);
545            bound_node_ids.push(k_id);
546            bound_node_ids.push(v_id);
547
548            h = self.apply_layer_with_kv_writes(
549                &h,
550                layer_weights,
551                &k_cache_node,
552                &v_cache_node,
553                cached_len_sym,
554                &rope_cos,
555                &rope_sin,
556                &mask,
557            )?;
558        }
559
560        // Final LayerNorm, output projection (+ optional bias).
561        let h_norm = h.layer_norm_affine(
562            Arc::clone(&weights.final_norm_gain),
563            Arc::clone(&weights.final_norm_bias),
564            cfg.layer_norm_eps,
565        )?;
566        let logits_no_bias = weights
567            .output
568            .apply_linear(&h_norm, cfg.dim, cfg.vocab_size)?;
569        let logits = match &weights.output_bias {
570            Some(b) => {
571                let b_t =
572                    h_norm.const_f32_like(Arc::clone(b), Shape::from_dims(&[cfg.vocab_size]))?;
573                logits_no_bias.broadcast_add(&b_t)?
574            }
575            None => logits_no_bias,
576        };
577
578        let last_pos = seq - 1;
579        let last_logits = logits
580            .slice(1, last_pos, 1)?
581            .reshape(Shape::from_dims(&[cfg.vocab_size]))?;
582
583        // Realize through InferenceContext. The WriteSlice nodes mutate
584        // the cache buffers in place at the runtime offset `cached_len`,
585        // supplied for this pass via the `SymEnv`; downstream attention
586        // reads the post-write full-capacity buffers.
587        let mut sym_env = fuel_ir::SymEnv::new();
588        sym_env.bind(cached_len_sym, cached_len)?;
589        let logits_vec = ctx.realize_one_as_with_env::<f32>(
590            last_logits.graph_tensor().graph(),
591            last_logits.graph_tensor().id(),
592            &sym_env,
593        )?;
594
595        // Clean up per-step bindings so they don't accumulate across
596        // decode steps (each step gets a fresh graph; the previous
597        // step's NodeIds are dead).
598        for id in bound_node_ids {
599            ctx.remove(id);
600        }
601
602        // Bump cache state.
603        cache.cached_len += seq;
604        for li in 0..cfg.n_layers {
605            cache.bump_version(li, KvSlot::K);
606            cache.bump_version(li, KvSlot::V);
607        }
608
609        Ok(logits_vec)
610    }
611
612    /// Phase D · D4 — plan-once persistent decode (the Phi mirror of
613    /// `LlamaModel::forward_with_kv_context_persistent`). Sibling of
614    /// [`Self::forward_with_kv_context`] that HOLDS the optimized
615    /// decode-step graph in `session` and, on every token after the
616    /// first, re-realizes the SAME graph with the D2a prebuilt seam —
617    /// **skipping the `prepare` D2H-splice + the `optimize_graph`
618    /// placement DP**. The per-token re-plan win comes from not
619    /// re-planning. See the LlamaModel sibling for the full control-flow
620    /// contract; the Phi version differs only in the model body it
621    /// builds (parallel attn+MLP, LayerNorm, partial RoPE, projection
622    /// biases, optional output bias).
623    ///
624    /// Byte-identical to the D1 cached path ([`Self::forward_with_kv_context`])
625    /// on the same prefix (same plan → same kernels). Bumps
626    /// `cache.cached_len` + per-slot versions exactly as the D1 path does.
627    pub fn forward_with_kv_context_persistent(
628        &self,
629        tokens: &[u32],
630        cache: &mut KvCache,
631        ctx: &mut InferenceContext,
632        session: &mut Option<fuel_tensor::inference_context::DecodeSession>,
633    ) -> fuel_ir::error::Result<Vec<f32>> {
634        let cfg = &self.config;
635        let seq = tokens.len();
636        let max_seq_len = cache.max_seq_len;
637        let cache_dtype = cache.dtype.unwrap_or(DType::F32);
638
639        // A non-`seq==1` step (prefill / spec-decode verification) is
640        // shape-distinct from the held decode graph — drop any session and
641        // fall back to the D1 rebuild path (the session rebuilds on the
642        // next decode token).
643        if seq != 1 {
644            self.drop_decode_session(session, ctx);
645            return self.forward_with_kv_context(tokens, cache, ctx);
646        }
647
648        // seq == 1. If a session exists but its validity keys no longer
649        // match the live cache/model (max_seq_len / n_layers / dtype), it
650        // is stale — drop it so we rebuild fresh below. A key differing ONLY
651        // in the KV allocation gets a guarded re-bind first (GAP-028). No
652        // capture exists on this path, hence the no-op reader retirement.
653        refresh_decode_session(
654            session,
655            ctx,
656            seq,
657            max_seq_len,
658            cache_dtype,
659            cfg.n_layers,
660            self.decode_shape_key(),
661            cache,
662            || {},
663            |s, c| self.drop_decode_session(s, c),
664        );
665
666        match session.as_ref() {
667            None => {
668                // First decode token (or post-invalidation): build +
669                // optimize the held graph ONCE.
670                self.build_and_realize_first_decode_token(tokens, cache, ctx, session)
671            }
672            Some(_) => {
673                // Subsequent decode token: re-bind data + skip optimize.
674                let res = self.rebind_and_realize_prebuilt(tokens, cache, &*ctx, &*session);
675                match res {
676                    Ok(logits) => Ok(logits),
677                    Err(fuel_ir::error::Error::TopologyChanged { .. }) => {
678                        self.drop_decode_session(session, ctx);
679                        self.forward_with_kv_context(tokens, cache, ctx)
680                    }
681                    Err(e) => Err(e),
682                }
683            }
684        }
685    }
686
687    /// Build the held Phi decode-step graph with STABLE re-bindable data
688    /// Consts, optimize it ONCE via the capturing prebuild, populate
689    /// `session`, and return the first token's logits. Only called for
690    /// the first `seq == 1` decode token when there is no valid session.
691    fn build_and_realize_first_decode_token(
692        &self,
693        tokens: &[u32],
694        cache: &mut KvCache,
695        ctx: &mut InferenceContext,
696        session: &mut Option<fuel_tensor::inference_context::DecodeSession>,
697    ) -> fuel_ir::error::Result<Vec<f32>> {
698        let cfg = &self.config;
699        let weights = &self.weights;
700        let seq = tokens.len();
701        let batch = 1;
702        let cached_len = cache.cached_len;
703        let max_seq_len = cache.max_seq_len.ok_or_else(|| {
704            fuel_ir::Error::Msg(
705                "PhiModel::forward_with_kv_context_persistent: cache built via with_dims \
706                 (no pre-allocated buffers); use KvCache::with_capacity"
707                    .to_string(),
708            )
709            .bt()
710        })?;
711        if cache.n_layers() != cfg.n_layers {
712            return Err(fuel_ir::Error::Msg(format!(
713                "PhiModel::forward_with_kv_context_persistent: cache n_layers {} != model {}",
714                cache.n_layers(),
715                cfg.n_layers,
716            ))
717            .bt());
718        }
719        if cached_len + seq > max_seq_len {
720            return Err(fuel_ir::Error::Msg(format!(
721                "PhiModel::forward_with_kv_context_persistent: cached_len ({cached_len}) + \
722                 seq ({seq}) > max_seq_len ({max_seq_len})",
723            ))
724            .bt());
725        }
726        let cache_dtype = cache.dtype.unwrap_or(DType::F32);
727
728        // Embed lookup + reshape to [batch, seq, dim]. Token-ids is a
729        // STABLE re-bindable placeholder Const (bytes bound via ctx).
730        let embed = Tensor::from_f32(
731            weights.token_embedding.clone(),
732            Shape::from_dims(&[cfg.vocab_size, cfg.dim]),
733            &Device::cpu(),
734        )?;
735        let token_ids = embed.const_placeholder_like(Shape::from_dims(&[seq]), DType::U32);
736        let token_ids_node = token_ids.graph_tensor().id();
737        let mut h = embed
738            .index_select(0, &token_ids)?
739            .reshape(Shape::from_dims(&[batch, seq, cfg.dim]))?;
740
741        // RoPE cos/sin: STABLE re-bindable placeholder Consts. Phi's
742        // tables are sized for `rotary_dim` (partial RoPE), NOT head_dim.
743        let rope_shape = Shape::from_dims(&[seq, cfg.rotary_dim]);
744        let rope_cos = h.const_placeholder_like(rope_shape.clone(), DType::F32);
745        let rope_sin = h.const_placeholder_like(rope_shape, DType::F32);
746        let rope_cos_node = rope_cos.graph_tensor().id();
747        let rope_sin_node = rope_sin.graph_tensor().id();
748
749        // Mask: STABLE re-bindable placeholder Const (hoisted; shared).
750        let mask =
751            h.const_placeholder_like(Shape::from_dims(&[1, 1, seq, max_seq_len]), DType::F32);
752        let mask_node = mask.graph_tensor().id();
753
754        let cached_len_sym = fuel_ir::SymId(0);
755        // No GQA in Phi-2: the KV cache carries `n_heads`.
756        let cache_shape = Shape::from_dims(&[batch, cfg.n_heads, max_seq_len, cfg.head_dim]);
757
758        // Per-layer KV placeholder Consts (STABLE). The Arcs are bound
759        // ONCE here and mutate in place via Op::WriteSlice each token.
760        let mut kv_nodes: Vec<(fuel_graph::NodeId, fuel_graph::NodeId)> =
761            Vec::with_capacity(cfg.n_layers);
762        for (li, layer_weights) in weights.layers.iter().enumerate() {
763            let k_arc = cache.slot_storage(li, KvSlot::K).ok_or_else(|| {
764                fuel_ir::Error::Msg(format!(
765                    "PhiModel::forward_with_kv_context_persistent: cache layer {li} has no K slot",
766                ))
767                .bt()
768            })?;
769            let v_arc = cache.slot_storage(li, KvSlot::V).ok_or_else(|| {
770                fuel_ir::Error::Msg(format!(
771                    "PhiModel::forward_with_kv_context_persistent: cache layer {li} has no V slot",
772                ))
773                .bt()
774            })?;
775            let k_cache_node = h.const_placeholder_like(cache_shape.clone(), cache_dtype);
776            let v_cache_node = h.const_placeholder_like(cache_shape.clone(), cache_dtype);
777            let k_id = k_cache_node.graph_tensor().id();
778            let v_id = v_cache_node.graph_tensor().id();
779            ctx.insert(k_id, k_arc);
780            ctx.insert(v_id, v_arc);
781            kv_nodes.push((k_id, v_id));
782
783            h = self.apply_layer_with_kv_writes(
784                &h,
785                layer_weights,
786                &k_cache_node,
787                &v_cache_node,
788                cached_len_sym,
789                &rope_cos,
790                &rope_sin,
791                &mask,
792            )?;
793        }
794
795        // Final LayerNorm, output projection (+ optional output bias).
796        let h_norm = h.layer_norm_affine(
797            Arc::clone(&weights.final_norm_gain),
798            Arc::clone(&weights.final_norm_bias),
799            cfg.layer_norm_eps,
800        )?;
801        let logits_no_bias = weights
802            .output
803            .apply_linear(&h_norm, cfg.dim, cfg.vocab_size)?;
804        let logits = match &weights.output_bias {
805            Some(b) => {
806                let b_t =
807                    h_norm.const_f32_like(Arc::clone(b), Shape::from_dims(&[cfg.vocab_size]))?;
808                logits_no_bias.broadcast_add(&b_t)?
809            }
810            None => logits_no_bias,
811        };
812        let last_pos = seq - 1;
813        let logits_root = logits
814            .slice(1, last_pos, 1)?
815            .reshape(Shape::from_dims(&[cfg.vocab_size]))?;
816        let logits_node = logits_root.graph_tensor().id();
817        let graph = logits_root.graph_tensor().graph().clone();
818
819        // Bind the per-token DATA into ctx (token-ids / RoPE / mask) as
820        // device-resident Arcs so the FIRST realize's const-cache walk
821        // resolves them (they are placeholders, not in graph.storage_map).
822        // KV Arcs were already inserted above. The optimize + realize then
823        // runs ONCE, capturing the reusable artifacts + the full realized
824        // cache (weights + KV + data) for the held session.
825        let data =
826            self.build_token_rope_mask_arcs(ctx.device(), cached_len, tokens, max_seq_len)?;
827        ctx.insert(token_ids_node, Arc::clone(&data.token_ids));
828        ctx.insert(rope_cos_node, Arc::clone(&data.rope_cos));
829        ctx.insert(rope_sin_node, Arc::clone(&data.rope_sin));
830        ctx.insert(mask_node, Arc::clone(&data.mask));
831
832        let mut sym_env = fuel_ir::SymEnv::new();
833        sym_env.bind(cached_len_sym, cached_len)?;
834
835        let (effective_target, optimized, base_cache, logits_vec) =
836            ctx.prebuild_optimized_capturing_as_with_env::<f32>(&graph, logits_node, &sym_env)?;
837
838        // The held session now owns the graph + base_cache; drop the
839        // transient ctx bindings.
840        ctx.remove(token_ids_node);
841        ctx.remove(rope_cos_node);
842        ctx.remove(rope_sin_node);
843        ctx.remove(mask_node);
844        for (k, v) in &kv_nodes {
845            ctx.remove(*k);
846            ctx.remove(*v);
847        }
848
849        *session = Some(fuel_tensor::inference_context::DecodeSession::new(
850            graph,
851            optimized,
852            effective_target,
853            logits_node,
854            token_ids_node,
855            rope_cos_node,
856            rope_sin_node,
857            mask_node,
858            kv_nodes,
859            // Phi decode stays on the SymEnv `Op::WriteSlice` path (no
860            // device-offset / CapturedRun yet — sequenced behind Llama).
861            None,
862            cached_len_sym,
863            // PhiModel decode does not offer the CUDA flash-decode arm yet
864            // (only LlamaModel is wired), so this attended-length symbol is
865            // carried for API parity but never referenced/bound in Phi's
866            // per-token env — a placeholder distinct from `cached_len_sym`.
867            fuel_ir::SymId(1),
868            base_cache,
869            seq,
870            max_seq_len,
871            cfg.n_layers,
872            cache_dtype,
873            self.decode_shape_key(),
874            // Which ALLOCATION's KV Arcs are baked into `base_cache`, and
875            // where they live — both read from the one source (GAP-028).
876            cache,
877        ));
878
879        // Bump cache state (identical to the D1 path).
880        cache.cached_len += seq;
881        for li in 0..cfg.n_layers {
882            cache.bump_version(li, KvSlot::K);
883            cache.bump_version(li, KvSlot::V);
884        }
885        Ok(logits_vec)
886    }
887
888    /// Re-bind the per-token data Consts (token-ids / RoPE / mask) into
889    /// device Arcs, bind the `SymEnv`, and realize via the D2a prebuilt
890    /// seam (SKIPPING optimize) over the held session's base cache. The
891    /// KV Arcs are stable (mutated in place by WriteSlice) — not touched
892    /// here. Called for every decode token after the first.
893    fn rebind_and_realize_prebuilt(
894        &self,
895        tokens: &[u32],
896        cache: &mut KvCache,
897        ctx: &InferenceContext,
898        session: &Option<fuel_tensor::inference_context::DecodeSession>,
899    ) -> fuel_ir::error::Result<Vec<f32>> {
900        // GAP-029 2b: forwards to the shared driver. Phi previously built its
901        // own `SymEnv` binding ONLY `cached_len_sym`; the shared
902        // `per_token_sym_env` also binds `attended_len_sym`. That extra binding
903        // is a measured no-op for Phi — negative-controlled in
904        // `phi_attended_len_sym_is_unreferenced_negative_control`, on the SymEnv
905        // path where a wrong `cached_len_sym` DOES move the logits, so the env
906        // is provably live while this symbol is inert.
907        fuel_tensor::persistent_decode::rebind_and_realize_prebuilt(
908            self, tokens, cache, ctx, session, None,
909        )
910    }
911
912    /// Recompute the per-token host bytes (token-ids / RoPE cos+sin sized
913    /// for `rotary_dim` / mask) and build device-resident Arcs from them
914    /// (the SAME upload path `KvCache::with_capacity` uses). The bytes
915    /// change per token; the NodeId stays stable (re-bound via a
916    /// `base_cache` overwrite, not a fresh graph).
917    /// Phi's per-token decode data as HOST buffers — the single source of
918    /// truth shared by [`Self::build_token_rope_mask_arcs`] (which uploads it)
919    /// and [`Self::build_token_rope_mask_bytes`] (which serialises it for
920    /// capture replay).
921    ///
922    /// Extracted rather than duplicated deliberately. If the upload path and
923    /// the replay path computed this data separately they could drift, and the
924    /// failure would be silent: replay would H2D the *wrong bytes* into the
925    /// right buffers and produce confident garbage. One computation, two
926    /// consumers, drift unrepresentable.
927    ///
928    /// **Phi-specific:** RoPE tables are sized for `rotary_dim`, not `head_dim`
929    /// — Phi uses PARTIAL rotary embedding. Getting that wrong here is exactly
930    /// the silent-wrong-bytes failure above, since the shapes would still match.
931    fn compute_token_rope_mask_host_data(
932        &self,
933        cached_len: usize,
934        tokens: &[u32],
935        max_seq_len: usize,
936    ) -> fuel_ir::error::Result<TokenDataHost> {
937        let cfg = &self.config;
938        let seq = tokens.len();
939        // Phi's RoPE tables are sized for `rotary_dim` (partial RoPE).
940        let (cos_data, sin_data) =
941            fuel_graph::build_rope_tables(cfg.rope_base, cached_len, seq, cfg.rotary_dim);
942        Ok(TokenDataHost {
943            token_ids: fuel_ir::HostBuffer::U32(tokens.to_vec()),
944            rope_cos: fuel_ir::HostBuffer::F32(cos_data),
945            rope_sin: fuel_ir::HostBuffer::F32(sin_data),
946            mask: fuel_ir::HostBuffer::F32(build_decode_causal_mask(cached_len, seq, max_seq_len)),
947            // Phi decode stays on the SymEnv `Op::WriteSlice` path — the KV
948            // write offset rides `cached_len_sym`, so there is no device-offset
949            // operand to rebind. Capture handles this: the offset entry is
950            // conditional on `offset_node().is_some()`.
951            offset: None,
952        })
953    }
954
955    fn build_token_rope_mask_arcs(
956        &self,
957        device: &Device,
958        cached_len: usize,
959        tokens: &[u32],
960        max_seq_len: usize,
961    ) -> fuel_ir::error::Result<fuel_tensor::inference_context::DecodeTokenData> {
962        let host = self.compute_token_rope_mask_host_data(cached_len, tokens, max_seq_len)?;
963        let upload = fuel_tensor::pipelined_bridge::upload_host_buffer_to_device;
964        Ok(fuel_tensor::inference_context::DecodeTokenData {
965            token_ids: upload(device, host.token_ids)?,
966            rope_cos: upload(device, host.rope_cos)?,
967            rope_sin: upload(device, host.rope_sin)?,
968            mask: upload(device, host.mask)?,
969            offset: None,
970        })
971    }
972
973    /// The same per-token data as raw host bytes, for
974    /// [`fuel_dispatch::pipelined::CapturedDecodeSession::replay_token`]'s
975    /// in-place H2D overwrite of the fixed capture buffers. Shares
976    /// [`Self::compute_token_rope_mask_host_data`] with the Arc path, so the
977    /// captured and uncaptured routes cannot disagree about what a token's
978    /// data is.
979    #[cfg(feature = "cuda")]
980    fn build_token_rope_mask_bytes(
981        &self,
982        cached_len: usize,
983        tokens: &[u32],
984        max_seq_len: usize,
985    ) -> fuel_ir::error::Result<TokenDataBytes> {
986        let host = self.compute_token_rope_mask_host_data(cached_len, tokens, max_seq_len)?;
987        Ok(TokenDataBytes {
988            token_ids: fuel_tensor::pipelined_bridge::host_buffer_to_bytes(&host.token_ids),
989            rope_cos: fuel_tensor::pipelined_bridge::host_buffer_to_bytes(&host.rope_cos),
990            rope_sin: fuel_tensor::pipelined_bridge::host_buffer_to_bytes(&host.rope_sin),
991            mask: fuel_tensor::pipelined_bridge::host_buffer_to_bytes(&host.mask),
992            offset: None,
993        })
994    }
995
996    /// CapturedRun decode for Phi — the sibling of
997    /// [`LlamaModel::forward_with_kv_context_captured`], same four cases:
998    ///
999    /// 1. `seq != 1` — not a decode step; drop session + capture, fall back to
1000    ///    the rebuild path.
1001    /// 1b. stale held pair — retire BOTH (see below), leaving case 2 to rebuild.
1002    /// 2. first decode token — build the held session; `captured` stays `None`.
1003    /// 3. second decode token — build this token's data as fresh FIXED-address
1004    ///    Arcs, merge over `session.base_cache()`, and capture once targeting
1005    ///    `logits_node()` (NOT `effective_target`: `capture_decode` rejects the
1006    ///    D2H `Op::Copy` splice as non-single-device-CUDA-capturable, so the
1007    ///    D2H happens here, after replay). The warm pass inside `capture()`
1008    ///    already computed this token, so its logits come from an empty-updates
1009    ///    `replay_token(&[])`.
1010    /// 4. third token onward — recompute the per-token data as raw bytes and
1011    ///    replay with one `cuGraphLaunch`.
1012    ///
1013    /// **Phi is on the SymEnv path** (`offset: None`), so there is no
1014    /// device-offset operand to rebind — the KV write offset rides
1015    /// `cached_len_sym`. The offset entries below are conditional for exactly
1016    /// that reason and are simply absent for Phi today.
1017    ///
1018    /// Staleness retires the capture WITH the session via the shared
1019    /// [`invalidate_decode_pair_if_stale`]: a recorded CUDA graph outliving its
1020    /// session would replay against fixed device addresses that no longer
1021    /// describe the live cache — wrong logits at full speed. Sharing the helper
1022    /// with `LlamaModel` rather than copying it means the two models cannot
1023    /// drift on what "stale" means.
1024    #[cfg(feature = "cuda")]
1025    pub fn forward_with_kv_context_captured(
1026        &self,
1027        tokens: &[u32],
1028        cache: &mut KvCache,
1029        ctx: &mut InferenceContext,
1030        session: &mut Option<fuel_tensor::inference_context::DecodeSession>,
1031        captured: &mut Option<fuel_dispatch::pipelined::CapturedDecodeSession>,
1032    ) -> fuel_ir::error::Result<Vec<f32>> {
1033        let cfg = &self.config;
1034        let seq = tokens.len();
1035
1036        // ---- 1. Non-decode step: drop state, fall back. ----
1037        if seq != 1 {
1038            *captured = None;
1039            self.drop_decode_session(session, ctx);
1040            return self.forward_with_kv_context(tokens, cache, ctx);
1041        }
1042
1043        // ---- 1b. Staleness: retire capture-then-session together. ----
1044        fuel_tensor::lazy::invalidate_decode_pair_if_stale(
1045            session,
1046            captured,
1047            ctx,
1048            seq,
1049            cache.max_seq_len,
1050            cache.dtype.unwrap_or(DType::F32),
1051            cfg.n_layers,
1052            self.decode_shape_key(),
1053            cache,
1054            |s, ctx| self.drop_decode_session(s, ctx),
1055        );
1056
1057        // ---- 2. First decode token: build the held session. ----
1058        if session.is_none() {
1059            *captured = None;
1060            return self.build_and_realize_first_decode_token(tokens, cache, ctx, session);
1061        }
1062
1063        let cached_len = cache.cached_len;
1064
1065        // ---- 3. Second decode token: build the capture. ----
1066        if captured.is_none() {
1067            let device = ctx.device().clone();
1068            let s = session.as_ref().expect("session is Some (checked above)");
1069
1070            let data =
1071                self.build_token_rope_mask_arcs(&device, cached_len, tokens, s.max_seq_len())?;
1072
1073            let mut merged_cache: fuel_dispatch::pipelined::StorageCache = s.base_cache().clone();
1074            merged_cache.insert(s.token_ids_node(), Arc::clone(&data.token_ids));
1075            merged_cache.insert(s.rope_cos_node(), Arc::clone(&data.rope_cos));
1076            merged_cache.insert(s.rope_sin_node(), Arc::clone(&data.rope_sin));
1077            merged_cache.insert(s.mask_node(), Arc::clone(&data.mask));
1078            let per_token_node_ids: Vec<fuel_graph::NodeId> = vec![
1079                s.token_ids_node(),
1080                s.rope_cos_node(),
1081                s.rope_sin_node(),
1082                s.mask_node(),
1083            ];
1084
1085            let sym_env = s.per_token_sym_env(cached_len)?;
1086            // CAPTURE IS AN OPTIMIZATION: IT MUST DEGRADE, NEVER FAIL.
1087            //
1088            // `capture_decode` rejects any graph it cannot record — most
1089            // commonly a CROSS-DEVICE `Op::Copy`, which appears whenever any
1090            // node in the decode graph lands on the host. That is a property of
1091            // the model's graph, not an error in this call: PhiModel hits it
1092            // today, and the paged decode graph hits it because `Op::PagedAttn`
1093            // is host-placed for want of a CUDA kernel.
1094            //
1095            // Propagating it would turn "this graph cannot be captured" into
1096            // "generation fails" — which is what happened when capture was
1097            // first defaulted on for Phi, and is exactly the wrong trade for an
1098            // optimization. Fall back to the ordinary persistent rebind instead
1099            // and return a correct token.
1100            //
1101            // Safe by inspection: `capture()` runs BEFORE any `cache` mutation
1102            // below, so nothing is half-applied and the fallback recomputes the
1103            // token cleanly. A genuine compute error is not masked — the
1104            // fallback re-runs the same work through the persistent path and
1105            // surfaces it there.
1106            //
1107            // Retried per token rather than remembered, deliberately: the check
1108            // is a cheap graph scan on an already-built plan, it only costs
1109            // anything on models that cannot capture (which get no benefit
1110            // either way), and it self-corrects if a future registration makes
1111            // the graph capturable mid-run.
1112            let cd_session = match fuel_dispatch::pipelined::CapturedDecodeSession::capture(
1113                s.graph().clone(),
1114                s.logits_node(),
1115                merged_cache,
1116                &per_token_node_ids,
1117                sym_env,
1118            ) {
1119                Ok(cd) => cd,
1120                Err(_) => {
1121                    let res = self.rebind_and_realize_prebuilt(tokens, cache, &*ctx, &*session);
1122                    return res;
1123                }
1124            };
1125
1126            // The warm pass inside `capture()` already computed THIS token.
1127            let output = cd_session.replay_token(&[])?;
1128            let logits = captured_output_to_f32(&output)?;
1129            *captured = Some(cd_session);
1130
1131            cache.cached_len += seq;
1132            for li in 0..cfg.n_layers {
1133                cache.bump_version(li, KvSlot::K);
1134                cache.bump_version(li, KvSlot::V);
1135            }
1136            return Ok(logits);
1137        }
1138
1139        // ---- 4. Third token onward: pure replay. ----
1140        let cap = captured.as_ref().expect("captured is Some (checked above)");
1141        let s = session
1142            .as_ref()
1143            .expect("session is Some whenever captured is Some");
1144
1145        let bytes = self.build_token_rope_mask_bytes(cached_len, tokens, s.max_seq_len())?;
1146        let updates: Vec<(fuel_graph::NodeId, &[u8])> = vec![
1147            (s.token_ids_node(), bytes.token_ids.as_slice()),
1148            (s.rope_cos_node(), bytes.rope_cos.as_slice()),
1149            (s.rope_sin_node(), bytes.rope_sin.as_slice()),
1150            (s.mask_node(), bytes.mask.as_slice()),
1151        ];
1152
1153        let output = cap.replay_token(&updates)?;
1154        let logits = captured_output_to_f32(&output)?;
1155
1156        cache.cached_len += seq;
1157        for li in 0..cfg.n_layers {
1158            cache.bump_version(li, KvSlot::K);
1159            cache.bump_version(li, KvSlot::V);
1160        }
1161        Ok(logits)
1162    }
1163
1164    /// Drop a held decode session, removing any leftover persistent
1165    /// data-Const / KV bindings from `ctx` (defensive). No-op if `None`.
1166    fn drop_decode_session(
1167        &self,
1168        session: &mut Option<fuel_tensor::inference_context::DecodeSession>,
1169        ctx: &mut InferenceContext,
1170    ) {
1171        if let Some(s) = session.take() {
1172            ctx.remove(s.token_ids_node());
1173            ctx.remove(s.rope_cos_node());
1174            ctx.remove(s.rope_sin_node());
1175            ctx.remove(s.mask_node());
1176            for (k, v) in s.kv_nodes() {
1177                ctx.remove(*k);
1178                ctx.remove(*v);
1179            }
1180        }
1181    }
1182
1183    /// Streaming generation through [`Self::forward_with_kv_context`].
1184    /// Allocates a pre-allocated [`KvCache`] of capacity
1185    /// `prompt_tokens.len() + max_new_tokens` on `device`, then loops
1186    /// prefill + decode, calling `on_token` for each generated token.
1187    /// Mirrors `LlamaModel::generate_streaming_with_kv_context`.
1188    pub fn generate_streaming_with_kv_context(
1189        &self,
1190        prompt_tokens: &[u32],
1191        max_new_tokens: usize,
1192        strategy: SamplingStrategy,
1193        eos_id: Option<u32>,
1194        device: &Device,
1195        dtype: DType,
1196        mut on_token: impl FnMut(u32),
1197    ) -> fuel_ir::error::Result<Vec<u32>> {
1198        let cfg = &self.config;
1199        if prompt_tokens.is_empty() {
1200            return Err(fuel_ir::Error::Msg(
1201                "PhiModel::generate_streaming_with_kv_context: prompt is empty".to_string(),
1202            )
1203            .bt());
1204        }
1205        let mut tokens: Vec<u32> = prompt_tokens.to_vec();
1206        let mut rng_state: u64 = match strategy {
1207            SamplingStrategy::Temperature { seed, .. } => seed,
1208            _ => 0,
1209        };
1210
1211        let max_seq_len = prompt_tokens.len() + max_new_tokens;
1212        let mut cache = KvCache::with_capacity(
1213            cfg.n_layers,
1214            cfg.n_heads,
1215            cfg.head_dim,
1216            max_seq_len,
1217            dtype,
1218            device,
1219        )?;
1220        let mut ctx = InferenceContext::new(device.clone());
1221
1222        // Phase D · D4: hold ONE plan-once decode session across the whole
1223        // generation (the Phi mirror of the LlamaModel D2c wiring). Prefill
1224        // (seq>1) routes through the persistent entry, which falls back to
1225        // the D1 rebuild path WITHOUT building the session; each per-token
1226        // decode step (seq==1) builds the held graph on the FIRST token
1227        // (optimize once) and reuses it — skipping optimize — thereafter.
1228        // The session is loop-internal; the public signature is unchanged.
1229        let mut session: Option<fuel_tensor::inference_context::DecodeSession> = None;
1230
1231        // CUDA-graph capture is ON BY DEFAULT here, matching
1232        // `LlamaModel::generate_streaming_with_kv_context`. Measured on Llama:
1233        // 4.28x at k=1 in release, byte-exact, replay cost build-profile-
1234        // invariant. Phi shares the decode substrate (`DecodeSession`, the
1235        // capture/replay machinery, the staleness predicate), so the same win
1236        // applies; the ratio itself has not been separately measured for Phi.
1237        //
1238        // Phi stays on the SymEnv path (`offset: None`) — the KV write offset
1239        // rides `cached_len_sym` rather than a device-offset operand — which
1240        // capture handles, since the offset entry is conditional.
1241        #[cfg(feature = "cuda")]
1242        let mut captured: Option<fuel_dispatch::pipelined::CapturedDecodeSession> = None;
1243
1244        // Prefill: one forward pass over the full prompt. Always the persistent
1245        // entry — `seq != 1`, so the captured path would immediately fall back.
1246        let mut last_logits = self.forward_with_kv_context_persistent(
1247            prompt_tokens,
1248            &mut cache,
1249            &mut ctx,
1250            &mut session,
1251        )?;
1252
1253        // Decode loop.
1254        for _ in 0..max_new_tokens {
1255            let next = sample_logits(&last_logits, strategy, &mut rng_state)?;
1256            tokens.push(next);
1257            on_token(next);
1258            if let Some(eos) = eos_id
1259                && next == eos
1260            {
1261                break;
1262            }
1263            #[cfg(feature = "cuda")]
1264            {
1265                last_logits = self.forward_with_kv_context_captured(
1266                    &[next],
1267                    &mut cache,
1268                    &mut ctx,
1269                    &mut session,
1270                    &mut captured,
1271                )?;
1272            }
1273            #[cfg(not(feature = "cuda"))]
1274            {
1275                last_logits = self.forward_with_kv_context_persistent(
1276                    &[next],
1277                    &mut cache,
1278                    &mut ctx,
1279                    &mut session,
1280                )?;
1281            }
1282        }
1283        Ok(tokens)
1284    }
1285
1286    /// Non-streaming convenience wrapper around
1287    /// [`Self::generate_streaming_with_kv_context`].
1288    pub fn generate_with_kv_context(
1289        &self,
1290        prompt_tokens: &[u32],
1291        max_new_tokens: usize,
1292        strategy: SamplingStrategy,
1293        eos_id: Option<u32>,
1294        device: &Device,
1295        dtype: DType,
1296    ) -> fuel_ir::error::Result<Vec<u32>> {
1297        self.generate_streaming_with_kv_context(
1298            prompt_tokens,
1299            max_new_tokens,
1300            strategy,
1301            eos_id,
1302            device,
1303            dtype,
1304            |_| {},
1305        )
1306    }
1307
1308    /// Load weights from a HuggingFace Hub repo (e.g. "microsoft/phi-2").
1309    pub fn from_hub(repo_id: &str) -> fuel_ir::error::Result<Self> {
1310        let api = hf_hub::api::sync::Api::new()
1311            .map_err(|e| fuel_ir::error::Error::Msg(format!("hf-hub api init: {e}")))?;
1312        let repo = api.model(repo_id.to_string());
1313
1314        let config_path = repo
1315            .get("config.json")
1316            .map_err(|e| fuel_ir::error::Error::Msg(format!("hf-hub config.json: {e}")))?;
1317        let config_str = std::fs::read_to_string(&config_path)?;
1318        let config = PhiConfig::from_hf_json_str(&config_str)?;
1319
1320        let weight_paths: Vec<std::path::PathBuf> = match repo.get("model.safetensors.index.json") {
1321            Ok(index_path) => {
1322                let index_str = std::fs::read_to_string(&index_path)?;
1323                let index: serde_json::Value = serde_json::from_str(&index_str)
1324                    .map_err(|e| fuel_ir::error::Error::Msg(format!("parsing index: {e}")))?;
1325                let weight_map = index
1326                    .get("weight_map")
1327                    .and_then(|x| x.as_object())
1328                    .ok_or_else(|| {
1329                        fuel_ir::error::Error::Msg("index.json: missing weight_map".into())
1330                    })?;
1331                let mut unique = std::collections::HashSet::new();
1332                for v in weight_map.values() {
1333                    if let Some(s) = v.as_str() {
1334                        unique.insert(s.to_string());
1335                    }
1336                }
1337                let mut paths: Vec<std::path::PathBuf> = Vec::new();
1338                for shard_name in unique {
1339                    let p = repo.get(&shard_name).map_err(|e| {
1340                        fuel_ir::error::Error::Msg(format!("hf-hub {shard_name}: {e}"))
1341                    })?;
1342                    paths.push(p);
1343                }
1344                paths
1345            }
1346            Err(_) => {
1347                let p = repo.get("model.safetensors").map_err(|e| {
1348                    fuel_ir::error::Error::Msg(format!("hf-hub model.safetensors: {e}"))
1349                })?;
1350                vec![p]
1351            }
1352        };
1353
1354        let st = unsafe { fuel_formats::safetensors::MmapedSafetensors::multi(&weight_paths) }?;
1355        let weights = PhiWeights::load_from_mmapped(&st, &config)?;
1356        Ok(PhiModel { config, weights })
1357    }
1358
1359    /// Load a Phi-2 model from a GGUF file (e.g. one of TheBloke's
1360    /// quantized Phi-2 releases). Q4_0 tensors stay quantized on-device;
1361    /// other dtypes dequantize to F32 at load time. Config is derived
1362    /// from the GGUF metadata.
1363    pub fn from_gguf<P: AsRef<std::path::Path>>(path: P) -> fuel_ir::error::Result<Self> {
1364        use fuel_loaders::quantized::gguf_mmap::MmapedContent;
1365        let mc = MmapedContent::from_path(&path)?;
1366        let meta = mc.metadata();
1367        let get_u32 = |k: &str| -> fuel_ir::error::Result<u32> {
1368            meta.get(k)
1369                .ok_or_else(|| fuel_ir::error::Error::Msg(format!("gguf metadata: missing {k:?}")))?
1370                .to_u32()
1371                .map_err(|e| fuel_ir::error::Error::Msg(format!("gguf metadata {k:?}: {e:?}")))
1372        };
1373        let get_f32 = |k: &str| -> fuel_ir::error::Result<f32> {
1374            meta.get(k)
1375                .ok_or_else(|| fuel_ir::error::Error::Msg(format!("gguf metadata: missing {k:?}")))?
1376                .to_f32()
1377                .map_err(|e| fuel_ir::error::Error::Msg(format!("gguf metadata {k:?}: {e:?}")))
1378        };
1379        // Phi-2 metadata keys (llama.cpp convention).
1380        let dim = get_u32("phi2.embedding_length")? as usize;
1381        let n_layers = get_u32("phi2.block_count")? as usize;
1382        let n_heads = get_u32("phi2.attention.head_count")? as usize;
1383        let ffn_dim = get_u32("phi2.feed_forward_length")? as usize;
1384        let head_dim = dim / n_heads;
1385        let layer_norm_eps = get_f32("phi2.attention.layer_norm_epsilon").unwrap_or(1e-5) as f64;
1386        let rope_base = get_f32("phi2.rope.freq_base").unwrap_or(10_000.0) as f64;
1387        let rotary_dim = get_u32("phi2.rope.dimension_count").unwrap_or(32) as usize;
1388        let partial_rotary_factor = rotary_dim as f64 / head_dim as f64;
1389
1390        // Derive vocab_size from the token_embd shape (no explicit
1391        // metadata key for it in GGUF; llama.cpp infers from the
1392        // tokenizer array which needs a dedicated API). token_embd has
1393        // shape [vocab, dim].
1394        let vocab_size = mc
1395            .content()
1396            .tensor_infos
1397            .get("token_embd.weight")
1398            .ok_or_else(|| fuel_ir::error::Error::Msg("gguf: missing token_embd.weight".into()))?
1399            .shape
1400            .dims()[0];
1401
1402        let config = PhiConfig {
1403            vocab_size,
1404            dim,
1405            n_layers,
1406            n_heads,
1407            head_dim,
1408            ffn_dim,
1409            layer_norm_eps,
1410            rope_base,
1411            partial_rotary_factor,
1412            rotary_dim,
1413            tie_word_embeddings: false,
1414        };
1415
1416        // MmapedContent drops here; the load_from_gguf path re-opens.
1417        // In practice this is two mmaps in flight, both pointing at the
1418        // same file — cheap on modern OSes. If this becomes a hotspot,
1419        // refactor to hand the Arc<Mmap> through.
1420        drop(mc);
1421        let weights = PhiWeights::load_from_gguf(&path, &config)?;
1422        Ok(PhiModel { config, weights })
1423    }
1424}
1425
1426impl PhiWeights {
1427    pub fn load_from_mmapped(
1428        st: &fuel_formats::safetensors::MmapedSafetensors,
1429        cfg: &PhiConfig,
1430    ) -> fuel_ir::error::Result<Self> {
1431        let kv_dim = cfg.n_heads * cfg.head_dim;
1432        let token_embedding = load_tensor_as_f32(st, "model.embed_tokens.weight")?;
1433        if token_embedding.len() != cfg.vocab_size * cfg.dim {
1434            fuel_ir::bail!(
1435                "embed_tokens: {} elements, expected {}",
1436                token_embedding.len(),
1437                cfg.vocab_size * cfg.dim,
1438            );
1439        }
1440
1441        let mut layers: Vec<PhiLayerWeights> = Vec::with_capacity(cfg.n_layers);
1442        for i in 0..cfg.n_layers {
1443            // Phi-2 uses `dense` for the output projection (not `o_proj`)
1444            // and `fc1`/`fc2` for the MLP (not `gate_proj`/`up_proj`/`down_proj`).
1445            let attn_q = load_transposed_matrix_preserve_dtype(
1446                st,
1447                &format!("model.layers.{i}.self_attn.q_proj.weight"),
1448                cfg.dim,
1449                cfg.dim,
1450            )?;
1451            let attn_k = load_transposed_matrix_preserve_dtype(
1452                st,
1453                &format!("model.layers.{i}.self_attn.k_proj.weight"),
1454                kv_dim,
1455                cfg.dim,
1456            )?;
1457            let attn_v = load_transposed_matrix_preserve_dtype(
1458                st,
1459                &format!("model.layers.{i}.self_attn.v_proj.weight"),
1460                kv_dim,
1461                cfg.dim,
1462            )?;
1463            let attn_dense = load_transposed_matrix_preserve_dtype(
1464                st,
1465                &format!("model.layers.{i}.self_attn.dense.weight"),
1466                cfg.dim,
1467                cfg.dim,
1468            )?;
1469            let mlp_fc1 = load_transposed_matrix_preserve_dtype(
1470                st,
1471                &format!("model.layers.{i}.mlp.fc1.weight"),
1472                cfg.ffn_dim,
1473                cfg.dim,
1474            )?;
1475            let mlp_fc2 = load_transposed_matrix_preserve_dtype(
1476                st,
1477                &format!("model.layers.{i}.mlp.fc2.weight"),
1478                cfg.dim,
1479                cfg.ffn_dim,
1480            )?;
1481
1482            let attn_q_bias = Arc::from(load_tensor_as_f32(
1483                st,
1484                &format!("model.layers.{i}.self_attn.q_proj.bias"),
1485            )?);
1486            let attn_k_bias = Arc::from(load_tensor_as_f32(
1487                st,
1488                &format!("model.layers.{i}.self_attn.k_proj.bias"),
1489            )?);
1490            let attn_v_bias = Arc::from(load_tensor_as_f32(
1491                st,
1492                &format!("model.layers.{i}.self_attn.v_proj.bias"),
1493            )?);
1494            let attn_dense_bias = Arc::from(load_tensor_as_f32(
1495                st,
1496                &format!("model.layers.{i}.self_attn.dense.bias"),
1497            )?);
1498            let mlp_fc1_bias = Arc::from(load_tensor_as_f32(
1499                st,
1500                &format!("model.layers.{i}.mlp.fc1.bias"),
1501            )?);
1502            let mlp_fc2_bias = Arc::from(load_tensor_as_f32(
1503                st,
1504                &format!("model.layers.{i}.mlp.fc2.bias"),
1505            )?);
1506
1507            // Phi-2's pre-block LayerNorm is `input_layernorm.{weight,bias}`.
1508            let norm_gain = Arc::from(load_tensor_as_f32(
1509                st,
1510                &format!("model.layers.{i}.input_layernorm.weight"),
1511            )?);
1512            let norm_bias = Arc::from(load_tensor_as_f32(
1513                st,
1514                &format!("model.layers.{i}.input_layernorm.bias"),
1515            )?);
1516
1517            layers.push(PhiLayerWeights {
1518                attn_qkv: PhiQkv::Split {
1519                    q: attn_q,
1520                    q_bias: attn_q_bias,
1521                    k: attn_k,
1522                    k_bias: attn_k_bias,
1523                    v: attn_v,
1524                    v_bias: attn_v_bias,
1525                },
1526                attn_dense,
1527                attn_dense_bias,
1528                mlp_fc1,
1529                mlp_fc1_bias,
1530                mlp_fc2,
1531                mlp_fc2_bias,
1532                norm_gain,
1533                norm_bias,
1534            });
1535        }
1536
1537        let final_norm_gain = Arc::from(load_tensor_as_f32(st, "model.final_layernorm.weight")?);
1538        let final_norm_bias = Arc::from(load_tensor_as_f32(st, "model.final_layernorm.bias")?);
1539
1540        let output: WeightStorage = if cfg.tie_word_embeddings {
1541            // Tied: transpose embed_tokens.
1542            let mut transposed = vec![0.0_f32; cfg.dim * cfg.vocab_size];
1543            for i in 0..cfg.vocab_size {
1544                for j in 0..cfg.dim {
1545                    transposed[j * cfg.vocab_size + i] = token_embedding[i * cfg.dim + j];
1546                }
1547            }
1548            WeightStorage::F32(Arc::from(transposed))
1549        } else {
1550            load_transposed_matrix_preserve_dtype(st, "lm_head.weight", cfg.vocab_size, cfg.dim)?
1551        };
1552        let output_bias = load_tensor_as_f32(st, "lm_head.bias").ok().map(Arc::from);
1553
1554        Ok(PhiWeights {
1555            instance: fuel_tensor::decode_shape::ModelInstanceId::next(),
1556            token_embedding: Arc::from(token_embedding),
1557            layers,
1558            final_norm_gain,
1559            final_norm_bias,
1560            output,
1561            output_bias,
1562        })
1563    }
1564
1565    /// Load Phi-2 weights from a GGUF file. Q4_0 tensors stay quantized
1566    /// (go into `WeightStorage::Q4_0`); other GGML dtypes are dequantized
1567    /// to F32 at load time and stored as `WeightStorage::F32` (or
1568    /// `Arc<[f32]>` for biases, norms, embedding).
1569    ///
1570    /// GGUF key layout for Phi-2:
1571    ///   token_embd.weight / output.weight / output_norm.{weight,bias}
1572    ///   blk.{i}.attn_qkv.{weight,bias}           (packed 3*dim × dim)
1573    ///   blk.{i}.attn_output.{weight,bias}
1574    ///   blk.{i}.ffn_up.{weight,bias}
1575    ///   blk.{i}.ffn_down.{weight,bias}
1576    ///   blk.{i}.attn_norm.{weight,bias}
1577    pub fn load_from_gguf<P: AsRef<std::path::Path>>(
1578        path: P,
1579        cfg: &PhiConfig,
1580    ) -> fuel_ir::error::Result<Self> {
1581        use fuel_loaders::quantized::gguf_mmap::MmapedContent;
1582        let mc = MmapedContent::from_path(path)?;
1583        let content = mc.content();
1584        let data_off = content.tensor_data_offset as usize;
1585
1586        // Extract a raw byte slice for a tensor.
1587        let get_tensor_bytes = |name: &str| -> fuel_ir::error::Result<(
1588            &[u8],
1589            fuel_loaders::quantized::GgmlDType,
1590            Vec<usize>,
1591        )> {
1592            let info = content
1593                .tensor_infos
1594                .get(name)
1595                .ok_or_else(|| content.missing_tensor_error(name))?;
1596            let elems = info.shape.elem_count();
1597            let block_size = info.ggml_dtype.block_size();
1598            let bytes_len = elems / block_size * info.ggml_dtype.type_size();
1599            let start = data_off + info.offset as usize;
1600            Ok((
1601                mc.bytes_at(start, bytes_len)?,
1602                info.ggml_dtype,
1603                info.shape.dims().to_vec(),
1604            ))
1605        };
1606
1607        // Load an F32 vector (for biases, norms, embedding). Dequantizes
1608        // if necessary.
1609        let load_f32 = |name: &str| -> fuel_ir::error::Result<Vec<f32>> {
1610            let (bytes, dt, _dims) = get_tensor_bytes(name)?;
1611            dequant_gguf_bytes_to_f32(bytes, dt, name)
1612        };
1613
1614        // Load a weight matrix as WeightStorage. For Q4_0 bytes, keep
1615        // them quantized; for other dtypes, dequantize to F32.
1616        // `out_features × in_features` is the GGUF/llama.cpp convention.
1617        let load_weight = |name: &str,
1618                           out_features: usize,
1619                           in_features: usize|
1620         -> fuel_ir::error::Result<WeightStorage> {
1621            let (bytes, dt, dims) = get_tensor_bytes(name)?;
1622            // GGUF stores weights as [out, in] — matches our Q4_0 block layout.
1623            let expected_elems = out_features * in_features;
1624            let actual_elems: usize = dims.iter().product();
1625            if actual_elems != expected_elems {
1626                fuel_ir::bail!(
1627                    "gguf: tensor {name:?} has {actual_elems} elements, expected {expected_elems} for [{out_features}, {in_features}]",
1628                );
1629            }
1630            // Debug fallback: FUEL_FORCE_F32=1 dequantizes every weight
1631            // at load time to isolate Q4_0-path bugs from model-structure
1632            // bugs. Useful for validating the PhiModel/loader against a
1633            // known-good computation path.
1634            let force_f32 = std::env::var("FUEL_FORCE_F32").is_ok();
1635            match dt {
1636                fuel_loaders::quantized::GgmlDType::Q4_0 if !force_f32 => Ok(WeightStorage::Q4_0 {
1637                    words: bytes_to_u32_arc(bytes),
1638                    bytes_len: bytes.len(),
1639                    in_features,
1640                    out_features,
1641                }),
1642                _ => {
1643                    // Dequantized data is in GGUF's native [out, in]
1644                    // row-major layout. Our standard F32/BF16 matmul
1645                    // expects [in, out], so transpose before storing.
1646                    // (Q4_0 keeps its native layout because qmatmul
1647                    // reads blocks as [N, K/32] directly.)
1648                    let f32_out_in = dequant_gguf_bytes_to_f32(bytes, dt, name)?;
1649                    let mut f32_in_out = vec![0.0_f32; out_features * in_features];
1650                    for o in 0..out_features {
1651                        for i in 0..in_features {
1652                            f32_in_out[i * out_features + o] = f32_out_in[o * in_features + i];
1653                        }
1654                    }
1655                    Ok(WeightStorage::F32(Arc::from(f32_in_out)))
1656                }
1657            }
1658        };
1659
1660        let token_embedding = load_f32("token_embd.weight")?;
1661        if token_embedding.len() != cfg.vocab_size * cfg.dim {
1662            fuel_ir::bail!(
1663                "gguf token_embd: {} elems, expected {}×{}",
1664                token_embedding.len(),
1665                cfg.vocab_size,
1666                cfg.dim,
1667            );
1668        }
1669
1670        let mut layers: Vec<PhiLayerWeights> = Vec::with_capacity(cfg.n_layers);
1671        let kv_dim = cfg.n_heads * cfg.head_dim;
1672
1673        for i in 0..cfg.n_layers {
1674            let prefix = format!("blk.{i}");
1675
1676            // Phi-2 GGUF packs Q/K/V into a single attn_qkv tensor of
1677            // shape [3*dim, dim]. We keep it PACKED as a single
1678            // WeightStorage and let the forward pass do one big matmul
1679            // + slice after (matching Candle's eager approach). This
1680            // avoids any hazards around byte-level Q/K/V splits on the
1681            // weight side.
1682            let attn_qkv_weight =
1683                load_weight(&format!("{prefix}.attn_qkv.weight"), 3 * cfg.dim, cfg.dim)?;
1684            let qkv_bias_vec = load_f32(&format!("{prefix}.attn_qkv.bias"))?;
1685            if qkv_bias_vec.len() != 3 * cfg.dim {
1686                fuel_ir::bail!(
1687                    "gguf attn_qkv.bias: {} elems, expected {}",
1688                    qkv_bias_vec.len(),
1689                    3 * cfg.dim
1690                );
1691            }
1692            let qkv_bias: Arc<[f32]> = Arc::from(qkv_bias_vec);
1693            let _ = kv_dim; // Phi-2 has no GQA; kv_dim == dim
1694
1695            let attn_dense =
1696                load_weight(&format!("{prefix}.attn_output.weight"), cfg.dim, cfg.dim)?;
1697            let attn_dense_bias = Arc::from(load_f32(&format!("{prefix}.attn_output.bias"))?);
1698
1699            let mlp_fc1 = load_weight(&format!("{prefix}.ffn_up.weight"), cfg.ffn_dim, cfg.dim)?;
1700            let mlp_fc1_bias = Arc::from(load_f32(&format!("{prefix}.ffn_up.bias"))?);
1701            let mlp_fc2 = load_weight(&format!("{prefix}.ffn_down.weight"), cfg.dim, cfg.ffn_dim)?;
1702            let mlp_fc2_bias = Arc::from(load_f32(&format!("{prefix}.ffn_down.bias"))?);
1703
1704            let norm_gain = Arc::from(load_f32(&format!("{prefix}.attn_norm.weight"))?);
1705            let norm_bias = Arc::from(load_f32(&format!("{prefix}.attn_norm.bias"))?);
1706
1707            layers.push(PhiLayerWeights {
1708                attn_qkv: PhiQkv::Packed {
1709                    qkv: attn_qkv_weight,
1710                    qkv_bias,
1711                },
1712                attn_dense,
1713                attn_dense_bias,
1714                mlp_fc1,
1715                mlp_fc1_bias,
1716                mlp_fc2,
1717                mlp_fc2_bias,
1718                norm_gain,
1719                norm_bias,
1720            });
1721        }
1722
1723        let final_norm_gain = Arc::from(load_f32("output_norm.weight")?);
1724        let final_norm_bias = Arc::from(load_f32("output_norm.bias")?);
1725
1726        // Output projection. In GGUF: `output.weight` has shape [vocab, dim].
1727        let output = load_weight("output.weight", cfg.vocab_size, cfg.dim)?;
1728        let output_bias = load_f32("output.bias").ok().map(Arc::from);
1729
1730        Ok(PhiWeights {
1731            instance: fuel_tensor::decode_shape::ModelInstanceId::next(),
1732            token_embedding: Arc::from(token_embedding),
1733            layers,
1734            final_norm_gain,
1735            final_norm_bias,
1736            output,
1737            output_bias,
1738        })
1739    }
1740}
1741
1742/// Dequantize a raw byte slice from GGUF (of the given GGML dtype) into
1743/// a flat `Vec<f32>`. Used by the lazy GGUF loader for non-Q4_0 tensors
1744/// (biases, norms, embeddings, and weight matrices of any dtype that
1745/// lacks a fused on-device dequant path).
1746fn dequant_gguf_bytes_to_f32(
1747    bytes: &[u8],
1748    dt: fuel_loaders::quantized::GgmlDType,
1749    name: &str,
1750) -> fuel_ir::error::Result<Vec<f32>> {
1751    use fuel_loaders::quantized::GgmlDType;
1752    use half::{bf16, f16};
1753    match dt {
1754        GgmlDType::F32 => {
1755            if !bytes.len().is_multiple_of(4) {
1756                fuel_ir::bail!(
1757                    "gguf {name}: F32 byte count {} not multiple of 4",
1758                    bytes.len()
1759                );
1760            }
1761            Ok(bytes
1762                .as_chunks::<4>()
1763                .0
1764                .iter()
1765                .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
1766                .collect())
1767        }
1768        GgmlDType::F16 => {
1769            if !bytes.len().is_multiple_of(2) {
1770                fuel_ir::bail!(
1771                    "gguf {name}: F16 byte count {} not multiple of 2",
1772                    bytes.len()
1773                );
1774            }
1775            Ok(bytes
1776                .as_chunks::<2>()
1777                .0
1778                .iter()
1779                .map(|c| f16::from_le_bytes([c[0], c[1]]).to_f32())
1780                .collect())
1781        }
1782        GgmlDType::BF16 => {
1783            if !bytes.len().is_multiple_of(2) {
1784                fuel_ir::bail!(
1785                    "gguf {name}: BF16 byte count {} not multiple of 2",
1786                    bytes.len()
1787                );
1788            }
1789            Ok(bytes
1790                .as_chunks::<2>()
1791                .0
1792                .iter()
1793                .map(|c| bf16::from_le_bytes([c[0], c[1]]).to_f32())
1794                .collect())
1795        }
1796        GgmlDType::Q4_0 => {
1797            // Should rarely be requested this way (prefer keeping Q4_0
1798            // quantized), but support it for biases or other oddities.
1799            Ok(cpu_dequant_q4_0_bytes(bytes))
1800        }
1801        GgmlDType::Q8_0 => Ok(cpu_dequant_q8_0_bytes(bytes)),
1802        // k-quants: dequant via the reference-CPU GgmlType trait impls.
1803        GgmlDType::Q6K => Ok(cpu_dequant_via_trait::<fuel_quantized::BlockQ6K>(bytes)),
1804        GgmlDType::Q5K => Ok(cpu_dequant_via_trait::<fuel_quantized::BlockQ5K>(bytes)),
1805        GgmlDType::Q4K => Ok(cpu_dequant_via_trait::<fuel_quantized::BlockQ4K>(bytes)),
1806        GgmlDType::Q3K => Ok(cpu_dequant_via_trait::<fuel_quantized::BlockQ3K>(bytes)),
1807        GgmlDType::Q2K => Ok(cpu_dequant_via_trait::<fuel_quantized::BlockQ2K>(bytes)),
1808        other => fuel_ir::bail!(
1809            "gguf {name}: dequant-to-f32 for dtype {other:?} not implemented in lazy loader"
1810        ),
1811    }
1812}
1813
1814/// Dequantize an arbitrary k-quant block stream to F32 via the
1815/// reference `GgmlType::to_float` trait. Callers give the concrete
1816/// block type `T` (e.g. `BlockQ6K`); the function reinterprets the
1817/// byte slice as `&[T]` and calls the impl. Used for dtypes that
1818/// don't have a fused on-device dequant kernel (yet).
1819fn cpu_dequant_via_trait<T: fuel_quantized::GgmlType>(bytes: &[u8]) -> Vec<f32> {
1820    let block_bytes = std::mem::size_of::<T>();
1821    assert!(
1822        bytes.len().is_multiple_of(block_bytes),
1823        "cpu_dequant_via_trait: bytes {} not multiple of block_bytes {}",
1824        bytes.len(),
1825        block_bytes
1826    );
1827    let n_blocks = bytes.len() / block_bytes;
1828    // `bytes` is a sub-slice at a GGUF tensor offset inside the mmap, so the
1829    // mmap's own alignment says nothing about THIS slice's: a tensor can start
1830    // at any 1-byte offset the file format allows. `blocks_from_bytes_cow`
1831    // borrows when the address happens to be aligned for `T` and copies into
1832    // an aligned `Vec<T>` when it is not, so neither case is undefined
1833    // behaviour. (This site used to cast unconditionally on the strength of
1834    // "the mmap is 8-byte aligned".)
1835    let blocks = fuel_quantized::blocks_from_bytes_cow::<T>(bytes);
1836    debug_assert_eq!(blocks.len(), n_blocks);
1837    let mut out = vec![0.0_f32; n_blocks * T::BLCK_SIZE];
1838    T::to_float(&blocks, &mut out);
1839    out
1840}
1841
1842/// Reinterpret a byte slice as a u32 `Arc` by reading little-endian
1843/// u32 words. Input length must be a multiple of 4. This performs one
1844/// copy at load time — all subsequent uses are cheap Arc clones.
1845fn bytes_to_u32_arc(bytes: &[u8]) -> Arc<[u32]> {
1846    assert_eq!(
1847        bytes.len() % 4,
1848        0,
1849        "bytes_to_u32_arc: len must be multiple of 4"
1850    );
1851    let words: Vec<u32> = bytes
1852        .as_chunks::<4>()
1853        .0
1854        .iter()
1855        .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]]))
1856        .collect();
1857    Arc::from(words)
1858}
1859
1860fn cpu_dequant_q4_0_bytes(bytes: &[u8]) -> Vec<f32> {
1861    use half::f16;
1862    let bpb = 18usize;
1863    let epb = 32usize;
1864    let n_blocks = bytes.len() / bpb;
1865    let mut out = vec![0.0_f32; n_blocks * epb];
1866    for b in 0..n_blocks {
1867        let off = b * bpb;
1868        let d = f16::from_le_bytes([bytes[off], bytes[off + 1]]).to_f32();
1869        let base = b * epb;
1870        for kk in 0..16 {
1871            let packed = bytes[off + 2 + kk];
1872            let lo = (packed & 0x0F) as i32 - 8;
1873            let hi = ((packed >> 4) & 0x0F) as i32 - 8;
1874            out[base + kk] = lo as f32 * d;
1875            out[base + 16 + kk] = hi as f32 * d;
1876        }
1877    }
1878    out
1879}
1880
1881fn cpu_dequant_q8_0_bytes(bytes: &[u8]) -> Vec<f32> {
1882    use half::f16;
1883    let bpb = 34usize;
1884    let epb = 32usize;
1885    let n_blocks = bytes.len() / bpb;
1886    let mut out = vec![0.0_f32; n_blocks * epb];
1887    for b in 0..n_blocks {
1888        let off = b * bpb;
1889        let d = f16::from_le_bytes([bytes[off], bytes[off + 1]]).to_f32();
1890        let base = b * epb;
1891        for kk in 0..32 {
1892            let q = bytes[off + 2 + kk] as i8 as i32;
1893            out[base + kk] = q as f32 * d;
1894        }
1895    }
1896    out
1897}
1898
1899/// Apply rotary embeddings to only the first `rotary_dim` entries of
1900/// the last dimension; pass the remaining `head_dim - rotary_dim` entries
1901/// through unchanged. Used by Phi-2 and Phi-3 which rotate only a
1902/// fraction of each head's feature dim.
1903///
1904/// Input shape: `[..., head_dim]`. Output shape: same.
1905fn partial_rope(
1906    x: &Tensor,
1907    cos: &Tensor,
1908    sin: &Tensor,
1909    rotary_dim: usize,
1910    head_dim: usize,
1911) -> Tensor {
1912    if rotary_dim == head_dim {
1913        return x.rope_with_tables(cos, sin).unwrap();
1914    }
1915    let rank = x.shape().dims().len();
1916    let last = rank - 1;
1917    let x_rot = x.slice(last, 0, rotary_dim).unwrap();
1918    let x_pass = x.slice(last, rotary_dim, head_dim - rotary_dim).unwrap();
1919    let x_rot_rotated = x_rot.rope_with_tables(cos, sin).unwrap();
1920    x_rot_rotated.concat(&x_pass, last).unwrap()
1921}
1922
1923#[cfg(test)]
1924impl PhiConfig {
1925    /// The hand-rolled parser this type used before the `serde` split, kept
1926    /// verbatim and test-only as the differential's oracle.
1927    pub(crate) fn from_hf_json_str_legacy(json: &str) -> fuel_ir::error::Result<Self> {
1928        let v: serde_json::Value = serde_json::from_str(json)
1929            .map_err(|e| fuel_ir::error::Error::Msg(format!("parsing config.json: {e}")))?;
1930
1931        let get_usize = |key: &str| -> fuel_ir::error::Result<usize> {
1932            v.get(key)
1933                .and_then(|x| x.as_u64())
1934                .map(|x| x as usize)
1935                .ok_or_else(|| {
1936                    fuel_ir::error::Error::Msg(format!(
1937                        "config.json: missing/invalid field {key:?}"
1938                    ))
1939                })
1940        };
1941        let get_f64 = |key: &str| -> Option<f64> { v.get(key).and_then(|x| x.as_f64()) };
1942
1943        let vocab_size = get_usize("vocab_size")?;
1944        let dim = get_usize("hidden_size")?;
1945        let n_layers = get_usize("num_hidden_layers")?;
1946        let n_heads = get_usize("num_attention_heads")?;
1947        let ffn_dim = get_usize("intermediate_size")?;
1948        let head_dim = v
1949            .get("head_dim")
1950            .and_then(|x| x.as_u64())
1951            .map(|x| x as usize)
1952            .unwrap_or(dim / n_heads);
1953        let layer_norm_eps = get_f64("layer_norm_eps").unwrap_or(1e-5);
1954        let rope_base = get_f64("rope_theta").unwrap_or(10_000.0);
1955        let partial_rotary_factor = get_f64("partial_rotary_factor").unwrap_or(0.4);
1956        let rotary_dim = (partial_rotary_factor * head_dim as f64).round() as usize;
1957        if !rotary_dim.is_multiple_of(2) {
1958            fuel_ir::bail!(
1959                "PhiConfig: rotary_dim {rotary_dim} must be even (partial_rotary_factor={partial_rotary_factor}, head_dim={head_dim})"
1960            );
1961        }
1962        let tie_word_embeddings = v
1963            .get("tie_word_embeddings")
1964            .and_then(|x| x.as_bool())
1965            .unwrap_or(false);
1966
1967        Ok(PhiConfig {
1968            vocab_size,
1969            dim,
1970            n_layers,
1971            n_heads,
1972            head_dim,
1973            ffn_dim,
1974            layer_norm_eps,
1975            rope_base,
1976            partial_rotary_factor,
1977            rotary_dim,
1978            tie_word_embeddings,
1979        })
1980    }
1981}
1982#[cfg(test)]
1983mod phi_config_tests {
1984    use super::PhiConfig;
1985
1986    /// ⚠️ THIS CONFIG HAD NO TEST FIXTURES AT ALL BEFORE THIS CORPUS.
1987    ///
1988    /// Its only caller was `PhiModel::from_hub`, which reads `config.json`
1989    /// over the network — so the parser had never been exercised by anything
1990    /// runnable offline. Seventh config in the increment and the most extreme
1991    /// coverage case: not a collapsed axis, not a partially-covered rule, but
1992    /// an EMPTY corpus. **All 4 fixtures are ADDED; none is pre-existing.**
1993    ///
1994    /// | behaviour                          | pre-existing fixture? |
1995    /// |------------------------------------|-----------------------|
1996    /// | anything at all                    | NO — there were none  |
1997    const DIFFERENTIAL_CORPUS: &[(&str, &str)] = &[
1998        (
1999            "ADDED: phi-2 shaped, explicit head_dim equal to the quotient",
2000            r#"{
2001                "vocab_size": 51200, "hidden_size": 2560, "num_hidden_layers": 32,
2002                "num_attention_heads": 32, "intermediate_size": 10240,
2003                "head_dim": 80, "layer_norm_eps": 1e-5, "rope_theta": 10000.0,
2004                "partial_rotary_factor": 0.4
2005            }"#,
2006        ),
2007        (
2008            "ADDED: minimal — every optional absent, head_dim derived",
2009            r#"{
2010                "vocab_size": 51200, "hidden_size": 1024, "num_hidden_layers": 16,
2011                "num_attention_heads": 16, "intermediate_size": 4096
2012            }"#,
2013        ),
2014        (
2015            "ADDED: explicit head_dim 96 != 2560/32 = 80, and rotary_dim CHAINS off it",
2016            r#"{
2017                "vocab_size": 51200, "hidden_size": 2560, "num_hidden_layers": 32,
2018                "num_attention_heads": 32, "intermediate_size": 10240,
2019                "head_dim": 96, "partial_rotary_factor": 0.4
2020            }"#,
2021        ),
2022        (
2023            "ADDED: odd rotary_dim — both paths must REJECT (0.5 * 10 = 5)",
2024            r#"{
2025                "vocab_size": 100, "hidden_size": 40, "num_hidden_layers": 2,
2026                "num_attention_heads": 4, "intermediate_size": 80,
2027                "partial_rotary_factor": 0.5
2028            }"#,
2029        ),
2030    ];
2031
2032    #[test]
2033    fn serde_path_agrees_with_the_legacy_parser_on_every_fixture() {
2034        assert_eq!(DIFFERENTIAL_CORPUS.len(), 4, "corpus shrank");
2035        for (name, json) in DIFFERENTIAL_CORPUS {
2036            let new = PhiConfig::from_hf_json_str(json);
2037            let old = PhiConfig::from_hf_json_str_legacy(json);
2038            match (new, old) {
2039                (Ok(a), Ok(b)) => assert_eq!(a, b, "differential mismatch on {name}"),
2040                (Err(_), Err(_)) => {}
2041                (Ok(_), Err(e)) => panic!("{name}: serde accepted, legacy rejected: {e}"),
2042                (Err(e), Ok(_)) => panic!("{name}: serde rejected, legacy accepted: {e}"),
2043            }
2044        }
2045    }
2046
2047    #[test]
2048    fn rotary_dim_chains_off_the_resolved_head_dim() {
2049        // The ordering constraint, made falsifiable. With head_dim explicit at
2050        // 96, rotary_dim must be round(0.4 * 96) = 38. If the chain read the
2051        // QUOTIENT instead (2560/32 = 80) it would be round(0.4 * 80) = 32.
2052        // Both are even, so the evenness check cannot tell them apart — only
2053        // this assertion can.
2054        let cfg = PhiConfig::from_hf_json_str(DIFFERENTIAL_CORPUS[2].1).unwrap();
2055        assert_eq!(cfg.head_dim, 96, "explicit head_dim must survive");
2056        assert_eq!(
2057            cfg.rotary_dim, 38,
2058            "rotary_dim must chain off the RESOLVED head_dim"
2059        );
2060        assert_ne!(
2061            cfg.rotary_dim, 32,
2062            "32 is what reading the raw quotient would give"
2063        );
2064    }
2065
2066    #[test]
2067    fn odd_rotary_dim_is_rejected_by_both_paths() {
2068        let json = DIFFERENTIAL_CORPUS[3].1;
2069        assert!(
2070            PhiConfig::from_hf_json_str(json).is_err(),
2071            "0.5 * 10 = 5 is odd"
2072        );
2073        assert!(
2074            PhiConfig::from_hf_json_str_legacy(json).is_err(),
2075            "legacy must agree"
2076        );
2077    }
2078}
2079
2080#[cfg(test)]
2081mod phi_kv_context_tests {
2082    use super::*;
2083    use fuel_tensor::{inference_context::InferenceContext, inference_context::KvCache};
2084
2085    // Parity with the retired Phi `_gpu_on` family
2086    // (`forward_with_cache_gpu_on` prefill + decode logits;
2087    // `generate_streaming_gpu_on` greedy token sequences) was
2088    // confirmed by `phi_forward_with_kv_context_matches_legacy_gpu_on`
2089    // and `phi_generate_with_kv_context_matches_legacy_generate`
2090    // immediately before retirement (commit 03df5c49); those tests
2091    // retired together with the legacy methods they referenced.
2092
2093    /// Build tiny Phi-2-shaped weights (Split QKV + biases everywhere,
2094    /// partial RoPE) for kv-context forward tests.
2095    fn make_tiny_phi(cfg: &PhiConfig, seed: u32) -> PhiWeights {
2096        let mut s: u32 = seed;
2097        let mut next = || -> f32 {
2098            s = s.wrapping_mul(1103515245).wrapping_add(12345);
2099            ((s >> 16) as u16 as f32 / 65535.0 - 0.5) * 0.1
2100        };
2101        let mut vec_of = |n: usize| -> Arc<[f32]> {
2102            let v: Vec<f32> = (0..n).map(|_| next()).collect();
2103            Arc::from(v)
2104        };
2105        let d = cfg.dim;
2106        let kv_dim = cfg.n_heads * cfg.head_dim;
2107        PhiWeights {
2108            instance: fuel_tensor::decode_shape::ModelInstanceId::next(),
2109            token_embedding: vec_of(cfg.vocab_size * d),
2110            layers: (0..cfg.n_layers)
2111                .map(|_| PhiLayerWeights {
2112                    attn_qkv: PhiQkv::Split {
2113                        q: vec_of(d * d).into(),
2114                        q_bias: vec_of(d),
2115                        k: vec_of(d * kv_dim).into(),
2116                        k_bias: vec_of(kv_dim),
2117                        v: vec_of(d * kv_dim).into(),
2118                        v_bias: vec_of(kv_dim),
2119                    },
2120                    attn_dense: vec_of(d * d).into(),
2121                    attn_dense_bias: vec_of(d),
2122                    mlp_fc1: vec_of(d * cfg.ffn_dim).into(),
2123                    mlp_fc1_bias: vec_of(cfg.ffn_dim),
2124                    mlp_fc2: vec_of(cfg.ffn_dim * d).into(),
2125                    mlp_fc2_bias: vec_of(d),
2126                    norm_gain: Arc::from(vec![1.0_f32; d]),
2127                    norm_bias: vec_of(d),
2128                })
2129                .collect(),
2130            final_norm_gain: Arc::from(vec![1.0_f32; d]),
2131            final_norm_bias: vec_of(d),
2132            output: vec_of(d * cfg.vocab_size).into(),
2133            output_bias: Some(vec_of(cfg.vocab_size)),
2134        }
2135    }
2136
2137    fn tiny_cfg() -> PhiConfig {
2138        PhiConfig {
2139            vocab_size: 16,
2140            dim: 8,
2141            n_layers: 2,
2142            n_heads: 2,
2143            head_dim: 4,
2144            ffn_dim: 16,
2145            layer_norm_eps: 1e-5,
2146            rope_base: 10000.0,
2147            partial_rotary_factor: 0.5,
2148            rotary_dim: 2,
2149            tie_word_embeddings: false,
2150        }
2151    }
2152
2153    /// KV-cache self-consistency on the new path: a monolithic prefill
2154    /// over N tokens must produce the same last-position logits as a
2155    /// shorter prefill followed by single-token decode steps through
2156    /// the same positions. Catches cache-position bugs without
2157    /// referencing the legacy path (survives its retirement).
2158    #[test]
2159    fn phi_kv_context_decode_consistent_with_monolithic_prefill() {
2160        let cfg = tiny_cfg();
2161        let model = PhiModel {
2162            config: cfg.clone(),
2163            weights: make_tiny_phi(&cfg, 7777),
2164        };
2165        let tokens = [1_u32, 5, 9, 12];
2166        let device = Device::cpu();
2167
2168        // Path A: monolithic prefill over all 4 tokens.
2169        let mut cache_a = KvCache::with_capacity(
2170            cfg.n_layers,
2171            cfg.n_heads,
2172            cfg.head_dim,
2173            tokens.len(),
2174            DType::F32,
2175            &device,
2176        )
2177        .expect("cache_a");
2178        let mut ctx_a = InferenceContext::new(device.clone());
2179        let expected = model
2180            .forward_with_kv_context(&tokens, &mut cache_a, &mut ctx_a)
2181            .expect("monolithic prefill");
2182
2183        // Path B: prefill 3, decode 1.
2184        let mut cache_b = KvCache::with_capacity(
2185            cfg.n_layers,
2186            cfg.n_heads,
2187            cfg.head_dim,
2188            tokens.len(),
2189            DType::F32,
2190            &device,
2191        )
2192        .expect("cache_b");
2193        let mut ctx_b = InferenceContext::new(device.clone());
2194        model
2195            .forward_with_kv_context(&tokens[..3], &mut cache_b, &mut ctx_b)
2196            .expect("prefill B");
2197        let actual = model
2198            .forward_with_kv_context(&tokens[3..], &mut cache_b, &mut ctx_b)
2199            .expect("decode B");
2200
2201        assert_eq!(actual.len(), expected.len());
2202        // Same O(ε) gemm accumulation-order band as the LLaMA
2203        // kv-context parity tests.
2204        for (i, (a, b)) in actual.iter().zip(expected.iter()).enumerate() {
2205            let diff = (a - b).abs();
2206            let rel = diff / a.abs().max(b.abs()).max(1e-6);
2207            assert!(
2208                diff < 5e-3 || rel < 1e-2,
2209                "logit[{i}]: chunked={a}, monolithic={b}, diff={diff}",
2210            );
2211        }
2212        assert_eq!(cache_a.cached_len, cache_b.cached_len);
2213    }
2214
2215    /// Greedy generation through the Phi kv-context path: correct
2216    /// shape (prompt preserved, max_new appended, tokens in vocab)
2217    /// and fully deterministic across runs.
2218    #[test]
2219    fn phi_generate_with_kv_context_greedy_is_deterministic() {
2220        let cfg = tiny_cfg();
2221        let model = PhiModel {
2222            config: cfg.clone(),
2223            weights: make_tiny_phi(&cfg, 7777),
2224        };
2225        let prompt = [1_u32, 5, 9];
2226        let max_new = 8;
2227        let device = Device::cpu();
2228
2229        let mut streamed = Vec::new();
2230        let run_a = model
2231            .generate_streaming_with_kv_context(
2232                &prompt,
2233                max_new,
2234                SamplingStrategy::Greedy,
2235                None,
2236                &device,
2237                DType::F32,
2238                |t| streamed.push(t),
2239            )
2240            .expect("run a");
2241        let run_b = model
2242            .generate_with_kv_context(
2243                &prompt,
2244                max_new,
2245                SamplingStrategy::Greedy,
2246                None,
2247                &device,
2248                DType::F32,
2249            )
2250            .expect("run b");
2251
2252        assert_eq!(run_a, run_b, "greedy generation must be deterministic");
2253        assert_eq!(run_a.len(), prompt.len() + max_new);
2254        assert_eq!(&run_a[..prompt.len()], &prompt);
2255        assert_eq!(
2256            streamed,
2257            &run_a[prompt.len()..],
2258            "callback sees exactly the new tokens"
2259        );
2260        for &t in &run_a {
2261            assert!((t as usize) < cfg.vocab_size, "token {t} out of vocab");
2262        }
2263    }
2264
2265    /// `forward_with_kv_context` build-time validation: with_dims
2266    /// caches (no pre-allocated buffers) and capacity overflows are
2267    /// rejected with typed errors, not panics.
2268    #[test]
2269    fn phi_forward_with_kv_context_rejects_invalid_cache() {
2270        let cfg = tiny_cfg();
2271        let model = PhiModel {
2272            config: cfg.clone(),
2273            weights: make_tiny_phi(&cfg, 7777),
2274        };
2275        let device = Device::cpu();
2276        let mut ctx = InferenceContext::new(device.clone());
2277
2278        // with_dims cache → typed error.
2279        let mut dims_cache = KvCache::with_dims(cfg.n_layers, cfg.n_heads, cfg.head_dim);
2280        let err = model
2281            .forward_with_kv_context(&[1, 2], &mut dims_cache, &mut ctx)
2282            .expect_err("with_dims cache must be rejected");
2283        assert!(format!("{err}").contains("with_capacity"));
2284
2285        // Capacity overflow → typed error.
2286        let mut small_cache = KvCache::with_capacity(
2287            cfg.n_layers,
2288            cfg.n_heads,
2289            cfg.head_dim,
2290            2,
2291            DType::F32,
2292            &device,
2293        )
2294        .expect("small cache");
2295        model
2296            .forward_with_kv_context(&[1, 2], &mut small_cache, &mut ctx)
2297            .expect("fits exactly");
2298        let err = model
2299            .forward_with_kv_context(&[3], &mut small_cache, &mut ctx)
2300            .expect_err("overflow must be rejected");
2301        assert!(format!("{err}").contains("max_seq_len"));
2302    }
2303
2304    /// Phase D · D4 correctness gate (the Phi mirror of the LlamaModel D1
2305    /// `forward_with_kv_context_decode_matches_non_cached_forward`).
2306    ///
2307    /// PhiModel has no non-cached `forward` reference, so — like the
2308    /// existing `phi_kv_context_decode_consistent_with_monolithic_prefill`
2309    /// — this compares the input-independent decode graph (write_slice_dyn
2310    /// at a symbolic offset + full-capacity attention + fixed-capacity
2311    /// mask) against a monolithic prefill over the same token history. A
2312    /// prefill (seq>1) + a seq==1 decode step exercise BOTH the multi-row
2313    /// and single-row shapes of the transformed `apply_layer_with_kv_writes`.
2314    /// Within the existing O(ε) gemm accumulation-order band the two paths
2315    /// must agree — masked positions contribute exactly 0, so the extra
2316    /// masked compute over `max_seq_len` (vs the live `total_seq`) is a
2317    /// no-op numerically.
2318    ///
2319    /// Born-red shape: if the write offset were baked concretely (breaking
2320    /// the symbolic path) or the fixed-capacity mask failed to null the
2321    /// stale tail, the decode logits would diverge from the monolithic
2322    /// prefill and this fails.
2323    #[test]
2324    fn phi_decode_matches_non_cached_forward() {
2325        let cfg = tiny_cfg(); // partial RoPE (rotary_dim=2, head_dim=4)
2326        let model = PhiModel {
2327            config: cfg.clone(),
2328            weights: make_tiny_phi(&cfg, 7777),
2329        };
2330
2331        let prompt = [1_u32, 5, 9];
2332        let next_token = 12_u32;
2333        let full = [prompt[0], prompt[1], prompt[2], next_token];
2334        let device = Device::cpu();
2335
2336        // Reference: monolithic prefill over all 4 tokens.
2337        let mut cache_ref = KvCache::with_capacity(
2338            cfg.n_layers,
2339            cfg.n_heads,
2340            cfg.head_dim,
2341            full.len(),
2342            DType::F32,
2343            &device,
2344        )
2345        .expect("with_capacity ref");
2346        let mut ctx_ref = InferenceContext::new(device.clone());
2347        let expected = model
2348            .forward_with_kv_context(&full, &mut cache_ref, &mut ctx_ref)
2349            .expect("monolithic prefill");
2350
2351        // Input-independent path: prefill(3) then decode(1) through the
2352        // transformed apply_layer_with_kv_writes.
2353        let mut cache = KvCache::with_capacity(
2354            cfg.n_layers,
2355            cfg.n_heads,
2356            cfg.head_dim,
2357            full.len(),
2358            DType::F32,
2359            &device,
2360        )
2361        .expect("with_capacity");
2362        let mut ctx = InferenceContext::new(device);
2363        let _prefill = model
2364            .forward_with_kv_context(&prompt, &mut cache, &mut ctx)
2365            .expect("prefill");
2366        assert_eq!(cache.cached_len, prompt.len());
2367        let actual = model
2368            .forward_with_kv_context(&[next_token], &mut cache, &mut ctx)
2369            .expect("decode");
2370        assert_eq!(cache.cached_len, full.len());
2371        assert_eq!(actual.len(), expected.len());
2372
2373        // Same O(ε) gemm accumulation-order band as the other Phi kv-context
2374        // parity tests.
2375        for (i, (a, b)) in actual.iter().zip(expected.iter()).enumerate() {
2376            let diff = (a - b).abs();
2377            let rel = diff / a.abs().max(b.abs()).max(1e-6);
2378            assert!(
2379                diff < 5e-3 || rel < 1e-2,
2380                "logit[{i}]: input-independent={a}, monolithic={b}, diff={diff}",
2381            );
2382        }
2383    }
2384
2385    /// Phase D · D4 born-red gate for plan-once persistent decode (the Phi
2386    /// mirror of the LlamaModel
2387    /// `forward_with_kv_context_persistent_plan_once_matches_d1`).
2388    ///
2389    /// Drive [`PhiModel::forward_with_kv_context_persistent`] for ≥3 decode
2390    /// tokens (after a prefill) holding ONE `DecodeSession`, in lockstep
2391    /// against the D1 [`PhiModel::forward_with_kv_context`] rebuild path
2392    /// (a SECOND identical model + cache + ctx fed the identical token each
2393    /// step). Assert the three plan-once invariants:
2394    ///   (a) `optimize_calls_thread_local()` bumps **exactly once** across
2395    ///       all the decode tokens — the first persistent decode token
2396    ///       builds + optimizes the held session; tokens 2..N skip optimize
2397    ///       (reuse via the D2a prebuilt seam);
2398    ///   (b) each persistent token's logits are **exactly `==`** the D1
2399    ///       cached path on the same prefix — same plan → same kernels →
2400    ///       bit-exact (NOT epsilon);
2401    ///   (c) the held graph's node `len()` is **stable from token 2 onward**
2402    ///       (no per-token node growth).
2403    #[test]
2404    fn phi_persistent_plan_once_matches_d1() {
2405        let cfg = tiny_cfg(); // partial RoPE + parallel block + biases
2406        // Two byte-identical models (same seed): one drives the D2
2407        // persistent path, one the D1 rebuild path.
2408        let model_d2 = PhiModel {
2409            config: cfg.clone(),
2410            weights: make_tiny_phi(&cfg, 7777),
2411        };
2412        let model_d1 = PhiModel {
2413            config: cfg.clone(),
2414            weights: make_tiny_phi(&cfg, 7777),
2415        };
2416
2417        let prompt = [1_u32, 5, 9];
2418        let decode_tokens = [12_u32, 3, 7, 2]; // ≥3 decode tokens
2419        let max_seq_len = prompt.len() + decode_tokens.len();
2420
2421        // --- D1 (rebuild) reference FIRST, in its own pass, so its
2422        // per-token re-plans don't pollute the optimize-count window we
2423        // measure around the D2 loop. ---
2424        let dev1 = Device::cpu();
2425        let mut cache1 = KvCache::with_capacity(
2426            cfg.n_layers,
2427            cfg.n_heads,
2428            cfg.head_dim,
2429            max_seq_len,
2430            DType::F32,
2431            &dev1,
2432        )
2433        .expect("with_capacity d1");
2434        let mut ctx1 = InferenceContext::new(dev1);
2435        let _ = model_d1
2436            .forward_with_kv_context(&prompt, &mut cache1, &mut ctx1)
2437            .expect("d1 prefill");
2438        let mut d1_expected: Vec<Vec<f32>> = Vec::with_capacity(decode_tokens.len());
2439        for &tok in &decode_tokens {
2440            d1_expected.push(
2441                model_d1
2442                    .forward_with_kv_context(&[tok], &mut cache1, &mut ctx1)
2443                    .expect("d1 decode"),
2444            );
2445        }
2446
2447        // --- D2 (persistent) session state ---
2448        let dev2 = Device::cpu();
2449        let mut cache2 = KvCache::with_capacity(
2450            cfg.n_layers,
2451            cfg.n_heads,
2452            cfg.head_dim,
2453            max_seq_len,
2454            DType::F32,
2455            &dev2,
2456        )
2457        .expect("with_capacity d2");
2458        let mut ctx2 = InferenceContext::new(dev2);
2459        let mut session: Option<fuel_tensor::inference_context::DecodeSession> = None;
2460
2461        // Prefill (seq>1 → falls back to the rebuild path; NO session).
2462        let _ = model_d2
2463            .forward_with_kv_context_persistent(&prompt, &mut cache2, &mut ctx2, &mut session)
2464            .expect("d2 prefill");
2465        assert!(
2466            session.is_none(),
2467            "prefill (seq>1) must NOT build the held session"
2468        );
2469
2470        // Decode ≥3 tokens through the persistent path ONLY. Snapshot the
2471        // thread-local optimize count just before the loop (isolated from
2472        // other suite threads' concurrent optimizes).
2473        let opt_before = fuel_tensor::pipelined_bridge::optimize_calls_thread_local();
2474        let mut len_at_token2: Option<usize> = None;
2475
2476        for (i, &tok) in decode_tokens.iter().enumerate() {
2477            let d2 = model_d2
2478                .forward_with_kv_context_persistent(&[tok], &mut cache2, &mut ctx2, &mut session)
2479                .expect("d2 decode");
2480
2481            // (b) bit-exact vs. the D1 cached path (same plan → same kernels).
2482            assert_eq!(
2483                d2, d1_expected[i],
2484                "persistent decode token {i} must be byte-identical to the D1 cached path",
2485            );
2486
2487            let sess = session
2488                .as_ref()
2489                .expect("session built on first decode token");
2490            let graph_len = sess.graph_node_count();
2491            if i == 1 {
2492                len_at_token2 = Some(graph_len);
2493            } else if i >= 2 {
2494                // (c) node count stable from token 2 onward.
2495                assert_eq!(
2496                    Some(graph_len),
2497                    len_at_token2,
2498                    "held graph must NOT grow from token 2 onward (token {i})",
2499                );
2500            }
2501        }
2502
2503        // (a) optimize bumped EXACTLY ONCE across all decode tokens.
2504        let opt_after = fuel_tensor::pipelined_bridge::optimize_calls_thread_local();
2505        assert_eq!(
2506            opt_after - opt_before,
2507            1,
2508            "persistent decode must optimize EXACTLY ONCE across {} decode tokens \
2509             (the first builds the session; the rest skip optimize): {opt_before} -> {opt_after}",
2510            decode_tokens.len(),
2511        );
2512
2513        assert_eq!(cache2.cached_len, max_seq_len);
2514        assert_eq!(cache1.cached_len, max_seq_len);
2515    }
2516
2517    /// Phase D · D4 generate-loop integration (the Phi mirror of the
2518    /// LlamaModel `generate_loop_persistent_byte_exact_and_plans_once`).
2519    ///
2520    /// The plain PhiModel decode generate loops
2521    /// (`generate_streaming_with_kv_context` / `generate_with_kv_context`)
2522    /// now hold ONE plan-once `DecodeSession` and route every step through
2523    /// [`PhiModel::forward_with_kv_context_persistent`]. This is the
2524    /// end-to-end guard that the plan-once path is USED in production Phi
2525    /// generation and stays bit-exact vs the D1 rebuild path.
2526    ///
2527    /// Drives an explicit persistent generate loop (mirroring the wired
2528    /// production loop) against a SEPARATE D1 reference loop over the same
2529    /// inputs, asserting:
2530    ///   (a) the generated token sequence is **byte-identical** over N≥4
2531    ///       greedy tokens (greedy diverges on ANY logit drift — a strong
2532    ///       end-to-end guard);
2533    ///   (b) each step's **logits** are **exactly `==`** the D1 cached path;
2534    ///   (c) `optimize_calls_thread_local()` bumps **exactly 2** across
2535    ///       prefill + N decode (1 prefill fallback + 1 decode-session
2536    ///       build) regardless of N — plan-once at the loop level.
2537    /// GAP-029 increment 2b — is `attended_len_sym` actually UNREFERENCED?
2538    ///
2539    /// The shared-driver de-duplication rests on a claim made only in comments:
2540    /// Phi's session carries `attended_len_sym = SymId(1)` "for API parity but
2541    /// never referenced/bound", and Llama's own doc says its attended-length
2542    /// binding "is unreferenced on today's f32 decode graph (no flash arm)". If
2543    /// both are true, Phi adopting Llama's shared `per_token_sym_env` (which
2544    /// binds both symbols) is a no-op and one driver can serve both.
2545    ///
2546    /// **The byte-exact persistent tests CANNOT settle this.** If the symbol
2547    /// were referenced but bound to its usual value, byte-exactness passes and
2548    /// says nothing about referencedness — the comment and the passing test are
2549    /// the same evidence, and neither discriminates.
2550    ///
2551    /// The discriminating instrument is a **negative control on the binding**:
2552    /// bind the symbol to a deliberately WRONG value and look at the output.
2553    ///   - output changes  ⇒ referenced ⇒ the no-op claim is FALSE
2554    ///   - output identical ⇒ genuinely unreferenced (positive evidence, not a
2555    ///     comment's word)
2556    ///
2557    /// **A wrong-binding test that sees no change is vacuous on its own**, since
2558    /// "the perturbation never reached the graph" produces the identical result.
2559    /// So each arm below is paired with a positive control that perturbs
2560    /// `cached_len_sym` — a symbol the KV write demonstrably DOES reference —
2561    /// and requires the output to change. Only then does "unchanged" mean
2562    /// unreferenced rather than "the instrument is blind".
2563    ///
2564    /// Scope of the claim, per Llama's own qualifier: **F32, CPU, today's decode
2565    /// graph, no flash arm.** A bf16/f16 CUDA decode that offers the flash arm
2566    /// would reference `attended_len` and must re-run this control.
2567    #[test]
2568    fn phi_attended_len_sym_is_unreferenced_negative_control() {
2569        let cfg = tiny_cfg();
2570        let model = PhiModel {
2571            config: cfg.clone(),
2572            weights: make_tiny_phi(&cfg, 7777),
2573        };
2574        let prompt = [1_u32, 5, 9];
2575        let max_seq_len = prompt.len() + 4;
2576
2577        let dev = Device::cpu();
2578        let mut cache = KvCache::with_capacity(
2579            cfg.n_layers,
2580            cfg.n_heads,
2581            cfg.head_dim,
2582            max_seq_len,
2583            DType::F32,
2584            &dev,
2585        )
2586        .expect("with_capacity");
2587        let mut ctx = InferenceContext::new(dev.clone());
2588        let mut session: Option<fuel_tensor::inference_context::DecodeSession> = None;
2589
2590        // Prefill, then ONE decode token to BUILD the held session.
2591        let _ = model
2592            .forward_with_kv_context_persistent(&prompt, &mut cache, &mut ctx, &mut session)
2593            .expect("prefill");
2594        let _ = model
2595            .forward_with_kv_context_persistent(&[12], &mut cache, &mut ctx, &mut session)
2596            .expect("build decode session");
2597        let s = session.as_ref().expect("session built");
2598
2599        // Realize the SAME next token three times, varying ONLY the SymEnv.
2600        // `realize_token` takes &self and clones `base_cache` internally, so the
2601        // three calls cannot pollute each other.
2602        let cached_len = cache.cached_len;
2603        let next = [3_u32];
2604        let mk_data = || {
2605            model
2606                .build_token_rope_mask_arcs(&dev, cached_len, &next, s.max_seq_len())
2607                .expect("token data")
2608        };
2609
2610        let mut env_ok = fuel_ir::SymEnv::new();
2611        env_ok
2612            .bind(s.cached_len_sym(), cached_len)
2613            .expect("bind cached_len");
2614        let baseline = s.realize_token(&dev, mk_data(), &env_ok).expect("baseline");
2615
2616        // --- the measurement: attended_len bound to a WRONG value ---
2617        let mut env_bad_attended = fuel_ir::SymEnv::new();
2618        env_bad_attended
2619            .bind(s.cached_len_sym(), cached_len)
2620            .expect("bind cached_len");
2621        env_bad_attended
2622            .bind(s.attended_len_sym(), cached_len + 4242)
2623            .expect("bind attended_len (wrong on purpose)");
2624        let perturbed_attended = s
2625            .realize_token(&dev, mk_data(), &env_bad_attended)
2626            .expect("realize with wrong attended_len");
2627
2628        // --- control A: perturb the DATA, which must always move the output ---
2629        // Proves `realize_token` is live and sensitive at all; without it,
2630        // "nothing changed" could mean the realize returns a cached or constant
2631        // result and every verdict below would be vacuous.
2632        let other = [6_u32];
2633        let data_other = model
2634            .build_token_rope_mask_arcs(&dev, cached_len, &other, s.max_seq_len())
2635            .expect("token data (different token)");
2636        let mut env_ok2 = fuel_ir::SymEnv::new();
2637        env_ok2
2638            .bind(s.cached_len_sym(), cached_len)
2639            .expect("bind cached_len");
2640        let perturbed_data = s
2641            .realize_token(&dev, data_other, &env_ok2)
2642            .expect("realize with different token");
2643        assert_ne!(
2644            perturbed_data, baseline,
2645            "control A FAILED: a DIFFERENT input token produced identical \
2646             logits, so realize_token is not responding to its inputs and no \
2647             verdict from this test means anything",
2648        );
2649
2650        // --- control B: is the SymEnv consulted AT ALL on this path? ---
2651        let with_off = s.offset_node().is_some();
2652        let mut env_bad_cached = fuel_ir::SymEnv::new();
2653        env_bad_cached
2654            .bind(s.cached_len_sym(), cached_len + 1)
2655            .expect("bind cached_len (wrong on purpose)");
2656        let perturbed_cached = s
2657            .realize_token(&dev, mk_data(), &env_bad_cached)
2658            .expect("realize with wrong cached_len");
2659
2660        // See the Llama twin for the full reasoning: on the device-offset path
2661        // the KV write offset rides a device-resident BUFFER, so cached_len_sym
2662        // is expected inert; on the SymEnv path it drives the write and MUST
2663        // move the output. Asserting the direction that matches the path keeps
2664        // this a control rather than a coin flip.
2665        if with_off {
2666            assert_eq!(
2667                perturbed_cached, baseline,
2668                "on the device-offset path the KV offset rides the offset \
2669                 BUFFER, so a wrong cached_len_sym should be inert — it moved \
2670                 the output, meaning the symbol IS load-bearing here",
2671            );
2672        } else {
2673            assert_ne!(
2674                perturbed_cached, baseline,
2675                "on the SymEnv path the KV offset rides cached_len_sym, so a \
2676                 wrong binding MUST move the output; it did not, so this test \
2677                 cannot detect referencedness and its verdict is vacuous",
2678            );
2679        }
2680
2681        assert_eq!(
2682            perturbed_attended, baseline,
2683            "attended_len_sym IS referenced by Phi's decode graph — the \
2684             'carried for API parity but never referenced' comment at \
2685             lazy.rs:12088 is FALSE, and sharing per_token_sym_env between \
2686             Llama and Phi is NOT the no-op the GAP-029 2b design assumes",
2687        );
2688
2689        // MEASURED 2026-08-12: Phi runs the **SymEnv path** on CPU
2690        // (`offset_node().is_none()`), so control B above took the `assert_ne`
2691        // branch and PASSED — a wrong `cached_len_sym` does move Phi's output.
2692        // The SymEnv is therefore demonstrably LIVE here, which is what makes
2693        // the `attended_len` verdict non-vacuous: it is inert while a sibling
2694        // symbol in the same env is load-bearing.
2695        //
2696        // So for Phi this is positive evidence, not a comment's word:
2697        // `attended_len_sym` is genuinely unreferenced, and adopting the shared
2698        // `per_token_sym_env` (which binds it) is a real no-op.
2699        eprintln!(
2700            "[gap-029 2b control] phi: offset_node.is_some()={with_off} \
2701             ({} path; SymEnv live={})",
2702            if with_off { "device-offset" } else { "SymEnv" },
2703            !with_off,
2704        );
2705    }
2706
2707    /// It ALSO drives the real production wrapper `generate_with_kv_context`
2708    /// and asserts the returned token sequence matches the reference.
2709    #[test]
2710    fn phi_generate_loop_persistent_byte_exact_and_plans_once() {
2711        let cfg = tiny_cfg();
2712        let model = PhiModel {
2713            config: cfg.clone(),
2714            weights: make_tiny_phi(&cfg, 7777),
2715        };
2716
2717        let prompt = [1_u32, 5, 9];
2718        let max_new = 5; // N ≥ 4 greedy decode tokens
2719        let max_seq_len = prompt.len() + max_new;
2720        let strategy = SamplingStrategy::Greedy;
2721
2722        // ---- D1 (rebuild) REFERENCE loop FIRST, in its own pass. Greedy
2723        // sampling open-coded with `sample_logits` so it is bit-identical to
2724        // the persistent loop's sampling. ----
2725        let dev1 = Device::cpu();
2726        let mut cache1 = KvCache::with_capacity(
2727            cfg.n_layers,
2728            cfg.n_heads,
2729            cfg.head_dim,
2730            max_seq_len,
2731            DType::F32,
2732            &dev1,
2733        )
2734        .expect("with_capacity d1");
2735        let mut ctx1 = InferenceContext::new(dev1);
2736        let mut rng1: u64 = 0;
2737        let mut ref_tokens: Vec<u32> = prompt.to_vec();
2738        let mut ref_step_logits: Vec<Vec<f32>> = Vec::with_capacity(max_new);
2739        let mut last1 = model
2740            .forward_with_kv_context(&prompt, &mut cache1, &mut ctx1)
2741            .expect("d1 prefill");
2742        for _ in 0..max_new {
2743            let next = sample_logits(&last1, strategy, &mut rng1).unwrap();
2744            ref_tokens.push(next);
2745            last1 = model
2746                .forward_with_kv_context(&[next], &mut cache1, &mut ctx1)
2747                .expect("d1 decode");
2748            ref_step_logits.push(last1.clone());
2749        }
2750
2751        // ---- D2 (persistent) generate loop — mirrors the wired production
2752        // loop. Snapshot the thread-local optimize count around the WHOLE
2753        // loop (prefill + decode). ----
2754        let opt_before = fuel_tensor::pipelined_bridge::optimize_calls_thread_local();
2755
2756        let dev2 = Device::cpu();
2757        let mut cache2 = KvCache::with_capacity(
2758            cfg.n_layers,
2759            cfg.n_heads,
2760            cfg.head_dim,
2761            max_seq_len,
2762            DType::F32,
2763            &dev2,
2764        )
2765        .expect("with_capacity d2");
2766        let mut ctx2 = InferenceContext::new(dev2);
2767        let mut rng2: u64 = 0;
2768        let mut session: Option<fuel_tensor::inference_context::DecodeSession> = None;
2769        let mut d2_tokens: Vec<u32> = prompt.to_vec();
2770        let mut d2_step_logits: Vec<Vec<f32>> = Vec::with_capacity(max_new);
2771        let mut last2 = model
2772            .forward_with_kv_context_persistent(&prompt, &mut cache2, &mut ctx2, &mut session)
2773            .expect("d2 prefill");
2774        assert!(
2775            session.is_none(),
2776            "prefill (seq>1) must NOT build the held session"
2777        );
2778        for _ in 0..max_new {
2779            let next = sample_logits(&last2, strategy, &mut rng2).unwrap();
2780            d2_tokens.push(next);
2781            last2 = model
2782                .forward_with_kv_context_persistent(&[next], &mut cache2, &mut ctx2, &mut session)
2783                .expect("d2 decode");
2784            d2_step_logits.push(last2.clone());
2785        }
2786
2787        let opt_after = fuel_tensor::pipelined_bridge::optimize_calls_thread_local();
2788
2789        // (a) Byte-identical token sequence over N greedy tokens.
2790        assert_eq!(
2791            d2_tokens, ref_tokens,
2792            "persistent generate loop must produce the byte-identical token sequence \
2793             as the D1 rebuild path over {max_new} greedy tokens",
2794        );
2795
2796        // (b) Each step's logits exactly == the D1 cached path (bit-exact).
2797        assert_eq!(d2_step_logits.len(), ref_step_logits.len());
2798        for (i, (d2, d1)) in d2_step_logits
2799            .iter()
2800            .zip(ref_step_logits.iter())
2801            .enumerate()
2802        {
2803            assert_eq!(
2804                d2, d1,
2805                "persistent decode step {i} logits must be byte-identical to the D1 cached path",
2806            );
2807        }
2808
2809        // (c) optimize bumped exactly twice (1 prefill fallback + 1
2810        // decode-session build) regardless of N.
2811        assert_eq!(
2812            opt_after - opt_before,
2813            2,
2814            "persistent generate must optimize EXACTLY twice (1 prefill fallback + 1 \
2815             decode-session build) regardless of N={max_new} decode tokens: \
2816             {opt_before} -> {opt_after}",
2817        );
2818
2819        assert!(session.is_some(), "held session survives the decode loop");
2820        assert_eq!(cache2.cached_len, max_seq_len);
2821        assert_eq!(cache1.cached_len, max_seq_len);
2822
2823        // ---- Drive the REAL production wrapper and confirm the wiring. ----
2824        let via_wrapper = model
2825            .generate_with_kv_context(&prompt, max_new, strategy, None, &Device::cpu(), DType::F32)
2826            .expect("generate_with_kv_context");
2827        assert_eq!(
2828            via_wrapper, ref_tokens,
2829            "generate_with_kv_context (wired to the persistent path) must produce the \
2830             byte-identical token sequence as the D1 reference",
2831        );
2832    }
2833
2834    /// Board item 86 (OverMind self-fork / Lightbulb KV-cache handoff design,
2835    /// `ROADMAP.md` "Research track: forked-agent KV-cache mechanics") — the
2836    /// one real gap Lightbulb's prototype found: does `KvCache::write_bytes`
2837    /// (host-supplied KV bytes, no Arc replacement) land where a HELD,
2838    /// already-built `DecodeSession` reads from, with no rebind and no
2839    /// rebuild? Confirms three things together, since any one alone would be
2840    /// a weaker, possibly-vacuous claim:
2841    ///
2842    /// 1. `alloc_id`/`device_location` are unchanged by the write (the
2843    ///    structural precondition for reuse — `write_bytes` takes `&self`, so
2844    ///    this is actually compile-time guaranteed; checked here anyway as a
2845    ///    regression guard).
2846    /// 2. `optimize_calls_thread_local` does NOT bump across the write (no
2847    ///    rebuild was triggered — a bump here would mean the write silently
2848    ///    forced the expensive D1 fallback despite `write_bytes` promising
2849    ///    otherwise).
2850    /// 3. The NEXT decode step's logits actually reflect the overwritten
2851    ///    value — the discriminating half. A primitive that satisfies (1) and
2852    ///    (2) but is a silent no-op (writes somewhere the plan never reads)
2853    ///    would pass both and still not deliver what Lightbulb needs; only
2854    ///    comparing against an un-overwritten reference run catches that.
2855    #[test]
2856    fn phi_persistent_plan_reads_a_write_bytes_overwrite_without_rebuilding() {
2857        let cfg = tiny_cfg();
2858        let model = PhiModel {
2859            config: cfg.clone(),
2860            weights: make_tiny_phi(&cfg, 7777),
2861        };
2862        let prompt = [1_u32, 5, 9];
2863        let decode_steps_before_overwrite = 2;
2864        let max_seq_len = prompt.len() + decode_steps_before_overwrite + 1;
2865        let strategy = SamplingStrategy::Greedy;
2866
2867        // Drive the persistent loop through `decode_steps_before_overwrite`
2868        // tokens, returning (cache, ctx, session, tokens, rng) so the caller
2869        // can either overwrite the cache or not before the final step.
2870        let run_to_overwrite_point = || {
2871            let device = Device::cpu();
2872            let mut cache = KvCache::with_capacity(
2873                cfg.n_layers,
2874                cfg.n_heads,
2875                cfg.head_dim,
2876                max_seq_len,
2877                DType::F32,
2878                &device,
2879            )
2880            .expect("with_capacity");
2881            let mut ctx = InferenceContext::new(device);
2882            let mut rng: u64 = 0;
2883            let mut session: Option<fuel_tensor::inference_context::DecodeSession> = None;
2884            let mut tokens: Vec<u32> = prompt.to_vec();
2885            let mut last = model
2886                .forward_with_kv_context_persistent(&prompt, &mut cache, &mut ctx, &mut session)
2887                .expect("prefill");
2888            for _ in 0..decode_steps_before_overwrite {
2889                let next = sample_logits(&last, strategy, &mut rng).unwrap();
2890                tokens.push(next);
2891                last = model
2892                    .forward_with_kv_context_persistent(&[next], &mut cache, &mut ctx, &mut session)
2893                    .expect("decode (pre-overwrite)");
2894            }
2895            (cache, ctx, session, tokens, rng)
2896        };
2897
2898        // ---- Reference run: no overwrite, decode one more token normally. ----
2899        let (mut ref_cache, mut ref_ctx, mut ref_session, ref_tokens, _ref_rng) =
2900            run_to_overwrite_point();
2901        assert!(
2902            ref_session.is_some(),
2903            "the held DecodeSession must exist by now (built on the first decode token)",
2904        );
2905        let ref_next_logits = model
2906            .forward_with_kv_context_persistent(
2907                &[*ref_tokens.last().unwrap()],
2908                &mut ref_cache,
2909                &mut ref_ctx,
2910                &mut ref_session,
2911            )
2912            .expect("reference decode (no overwrite)");
2913
2914        // ---- Overwrite run: same setup, but write_bytes clobbers layer 0's
2915        // K at position 0 (the first prompt token — always inside the causal
2916        // window of every later token) just before the final decode step. ----
2917        let (mut ow_cache, mut ow_ctx, mut ow_session, ow_tokens, _ow_rng) =
2918            run_to_overwrite_point();
2919        assert_eq!(
2920            ow_tokens, ref_tokens,
2921            "both runs must reach an identical token stream before the overwrite \
2922             (same model, same seed, same prompt) — divergence must come ONLY from the write",
2923        );
2924
2925        let alloc_before = ow_cache.alloc_id();
2926        let loc_before = ow_cache.device_location();
2927        let opt_before_write = fuel_tensor::pipelined_bridge::optimize_calls_thread_local();
2928
2929        // A distinctive, non-zero payload — n=1 position, n_kv_heads*head_dim
2930        // f32 values, head-major (`[1, n_kv_heads, 1, head_dim]`).
2931        let payload: Vec<f32> = (0..(cfg.n_heads * cfg.head_dim))
2932            .map(|i| 9000.0 + i as f32)
2933            .collect();
2934        let payload_bytes: Vec<u8> = payload.iter().flat_map(|f| f.to_le_bytes()).collect();
2935        ow_cache
2936            .write_bytes(0, KvSlot::K, 0, 1, &payload_bytes, &Device::cpu())
2937            .expect("write_bytes");
2938
2939        assert_eq!(
2940            ow_cache.alloc_id(),
2941            alloc_before,
2942            "write_bytes must not re-mint alloc_id",
2943        );
2944        assert_eq!(
2945            ow_cache.device_location(),
2946            loc_before,
2947            "write_bytes must not clear device_location",
2948        );
2949
2950        // `write_bytes` realizes its OWN small throwaway Const->WriteSlice
2951        // graph (same shape as `DeviceKvPool::write_block_bytes`), which
2952        // costs exactly one `optimize_graph` call for that tiny graph — a
2953        // real, expected, cheap cost, not the thing under test. Measure the
2954        // DECODE STEP's own delta separately: THAT must be zero, or the write
2955        // forced the expensive held-plan rebuild.
2956        let opt_after_write = fuel_tensor::pipelined_bridge::optimize_calls_thread_local();
2957        assert_eq!(
2958            opt_after_write - opt_before_write,
2959            1,
2960            "write_bytes's own one-off realize should cost exactly one optimize call \
2961             for its throwaway graph (same shape as DeviceKvPool::write_block_bytes) — \
2962             a different count means this assumption needs re-checking",
2963        );
2964
2965        let ow_next_logits = model
2966            .forward_with_kv_context_persistent(
2967                &[*ow_tokens.last().unwrap()],
2968                &mut ow_cache,
2969                &mut ow_ctx,
2970                &mut ow_session,
2971            )
2972            .expect("overwrite-run decode (post-overwrite)");
2973
2974        let opt_after_decode = fuel_tensor::pipelined_bridge::optimize_calls_thread_local();
2975        assert_eq!(
2976            opt_after_decode, opt_after_write,
2977            "the decode step AFTER write_bytes must not trigger a plan rebuild — \
2978             optimize_calls_thread_local must be unchanged across it specifically \
2979             (write_bytes's own one-off optimize, measured above, is expected and excluded)",
2980        );
2981
2982        // THE DISCRIMINATING ASSERTION: the overwrite must actually have been
2983        // read. Equal logits here would mean write_bytes is a well-behaved
2984        // no-op that satisfies every OTHER assertion in this test while
2985        // delivering nothing Lightbulb's handoff design actually needs.
2986        assert_ne!(
2987            ow_next_logits, ref_next_logits,
2988            "the decode step after write_bytes must differ from the un-overwritten \
2989             reference — otherwise the held plan never read the write at all",
2990        );
2991    }
2992
2993    /// **WHICH Phi decode nodes land on the host?** — diagnostic for the
2994    /// capture rejection (`cross-device Op::Copy ... target Cpu`).
2995    ///
2996    /// Capture records CUDA operations issued to a stream. Host code is not a
2997    /// CUDA operation, so it cannot be recorded — and a cross-device `Copy` is
2998    /// the SYMPTOM of host compute sitting mid-graph, not the cause. This says
2999    /// which node(s) actually caused it, which decides the fix: a load-bearing
3000    /// host op means capture genuinely cannot apply; an accidentally-placed one
3001    /// means the fix is placement, and capture then works for free.
3002    ///
3003    /// Reports rather than asserts. The one thing it DOES assert is that
3004    /// placement was computed (`has_placements`) — an all-`None` dump would
3005    /// read as "nothing is on CUDA", a wrong answer wearing a null answer's
3006    /// clothes.
3007    #[test]
3008    #[cfg(feature = "cuda")]
3009    #[ignore = "requires a live CUDA device"]
3010    fn phi_decode_node_placement_report_cuda() {
3011        use std::collections::BTreeMap;
3012
3013        let cfg = tiny_cfg();
3014        let dev: Device = match fuel_cuda_backend::CudaDevice::new(0) {
3015            Ok(d) => d.into(),
3016            Err(e) => {
3017                return fuel_test_support::hardware::skip(
3018                    fuel_test_support::hardware::Hardware::Cuda,
3019                    fuel_test_support::hardware::Missing::device(format!(
3020                        "CudaDevice::new(0): {e:?}"
3021                    )),
3022                );
3023            }
3024        };
3025        let model = PhiModel {
3026            config: cfg.clone(),
3027            weights: make_tiny_phi(&cfg, 7),
3028        };
3029        let prompt = [1_u32, 2, 3];
3030        let max_seq_len = prompt.len() + 4;
3031
3032        let mut cache = KvCache::with_capacity(
3033            cfg.n_layers,
3034            cfg.n_heads,
3035            cfg.head_dim,
3036            max_seq_len,
3037            DType::F32,
3038            &dev,
3039        )
3040        .expect("with_capacity");
3041        let mut ctx = InferenceContext::new(dev.clone());
3042        let mut sess: Option<fuel_tensor::inference_context::DecodeSession> = None;
3043        model
3044            .forward_with_kv_context_persistent(&prompt, &mut cache, &mut ctx, &mut sess)
3045            .expect("prefill");
3046        model
3047            .forward_with_kv_context_persistent(&[4], &mut cache, &mut ctx, &mut sess)
3048            .expect("first decode token builds the held plan");
3049        let s = sess.as_ref().expect("held session");
3050
3051        let opt = s.optimized();
3052        assert!(
3053            opt.has_placements(),
3054            "placement NOT COMPUTED — every lookup would be None and the report below would describe a missing instrument, not the graph",
3055        );
3056
3057        let g = s.graph().read().expect("graph lock");
3058        let mut by_op: BTreeMap<String, BTreeMap<String, usize>> = BTreeMap::new();
3059        let mut host_nodes: Vec<String> = Vec::new();
3060        for i in 0..g.len() {
3061            let id = fuel_graph::NodeId(i);
3062            let op_name = match &g.node(id).op {
3063                fuel_graph::Op::Fused(fid, _) => format!("Fused({fid:?})"),
3064                other => format!("{other:?}")
3065                    .split(' ')
3066                    .next()
3067                    .unwrap_or("?")
3068                    .to_string(),
3069            };
3070            let place = match opt.placement_of(id) {
3071                Some(d) => format!("{d:?}"),
3072                None => "None".to_string(),
3073            };
3074            if place.starts_with("Cpu") {
3075                host_nodes.push(format!("#{i} {op_name}"));
3076            }
3077            *by_op.entry(op_name).or_default().entry(place).or_insert(0) += 1;
3078        }
3079
3080        println!(
3081            "
3082=== Phi decode plan: node placement (CUDA) ==="
3083        );
3084        println!("total nodes: {}", g.len());
3085        for (op, places) in &by_op {
3086            let r: Vec<String> = places.iter().map(|(d, n)| format!("{d}x{n}")).collect();
3087            println!("  {op:<34} {}", r.join("  "));
3088        }
3089        println!(
3090            "
3091--- HOST-PLACED NODES ({}) ---",
3092            host_nodes.len()
3093        );
3094        for h in &host_nodes {
3095            println!("    {h}");
3096        }
3097        println!(
3098            "--- END ---
3099"
3100        );
3101    }
3102
3103    /// **GPU gate for Phi's CapturedRun decode** — the mirror of
3104    /// `forward_with_kv_context_captured_matches_persistent` (Llama).
3105    ///
3106    /// Phi's capture shipped default-on verified only by `cargo check`, and its
3107    /// captured entry is `#[cfg(feature = "cuda")]` — so every CPU test in this
3108    /// crate passes with it arbitrarily broken. This closes that.
3109    ///
3110    /// **The specific failure it guards is silent.** Phi uses PARTIAL rotary:
3111    /// its RoPE tables are sized for `rotary_dim`, not `head_dim`. The replay
3112    /// path serialises those tables to raw bytes and H2Ds them into fixed
3113    /// capture buffers, so a wrong-but-well-formed table would write the WRONG
3114    /// VALUES into the RIGHT BUFFERS — correct shapes, no error, fluent wrong
3115    /// tokens. Byte-exactness against the persistent path is the only thing
3116    /// that catches it.
3117    ///
3118    /// Drives >= 4 decode tokens so all four driver branches run: token 1
3119    /// builds the held `DecodeSession`; token 2 builds the
3120    /// `CapturedDecodeSession` and returns its logits from an empty-`updates`
3121    /// warm replay; tokens 3-4 are pure `cuGraphLaunch` replays fed by freshly
3122    /// serialised per-token bytes — which is where a partial-rotary mistake
3123    /// would surface and nowhere earlier.
3124    ///
3125    /// Bit-exact, not epsilon: same plan, same kernels, same bytes.
3126    #[test]
3127    #[cfg(feature = "cuda")]
3128    #[ignore = "requires a live CUDA device"]
3129    fn phi_forward_with_kv_context_captured_matches_persistent() {
3130        let cfg = tiny_cfg();
3131
3132        let cuda = match fuel_cuda_backend::CudaDevice::new(0) {
3133            Ok(d) => d,
3134            Err(e) => {
3135                return fuel_test_support::hardware::skip(
3136                    fuel_test_support::hardware::Hardware::Cuda,
3137                    fuel_test_support::hardware::Missing::device(format!(
3138                        "CudaDevice::new(0): {e:?}"
3139                    )),
3140                );
3141            }
3142        };
3143        let dev: Device = cuda.into();
3144
3145        let prompt = [1_u32, 2, 3];
3146        let decode_tokens = [4_u32, 5, 6, 7]; // >= 4 so every branch runs
3147        let max_seq_len = prompt.len() + decode_tokens.len();
3148
3149        // Two models with byte-identical weights (same seed): one drives the
3150        // reference persistent path, one the captured path under test.
3151        let model_ref = PhiModel {
3152            config: cfg.clone(),
3153            weights: make_tiny_phi(&cfg, 7),
3154        };
3155        let model_cap = PhiModel {
3156            config: cfg.clone(),
3157            weights: make_tiny_phi(&cfg, 7),
3158        };
3159
3160        // --- Reference: forward_with_kv_context_persistent ---
3161        let mut cache_ref = KvCache::with_capacity(
3162            cfg.n_layers,
3163            cfg.n_heads,
3164            cfg.head_dim,
3165            max_seq_len,
3166            DType::F32,
3167            &dev,
3168        )
3169        .expect("with_capacity ref");
3170        let mut ctx_ref = InferenceContext::new(dev.clone());
3171        let mut sess_ref: Option<fuel_tensor::inference_context::DecodeSession> = None;
3172        model_ref
3173            .forward_with_kv_context_persistent(
3174                &prompt,
3175                &mut cache_ref,
3176                &mut ctx_ref,
3177                &mut sess_ref,
3178            )
3179            .expect("ref prefill");
3180        let mut ref_logits: Vec<Vec<f32>> = Vec::with_capacity(decode_tokens.len());
3181        for &tok in &decode_tokens {
3182            ref_logits.push(
3183                model_ref
3184                    .forward_with_kv_context_persistent(
3185                        &[tok],
3186                        &mut cache_ref,
3187                        &mut ctx_ref,
3188                        &mut sess_ref,
3189                    )
3190                    .expect("ref decode"),
3191            );
3192        }
3193
3194        // --- Under test: forward_with_kv_context_captured ---
3195        let mut cache_cap = KvCache::with_capacity(
3196            cfg.n_layers,
3197            cfg.n_heads,
3198            cfg.head_dim,
3199            max_seq_len,
3200            DType::F32,
3201            &dev,
3202        )
3203        .expect("with_capacity captured");
3204        let mut ctx_cap = InferenceContext::new(dev.clone());
3205        let mut sess_cap: Option<fuel_tensor::inference_context::DecodeSession> = None;
3206        let mut captured: Option<fuel_dispatch::pipelined::CapturedDecodeSession> = None;
3207        model_cap
3208            .forward_with_kv_context_captured(
3209                &prompt,
3210                &mut cache_cap,
3211                &mut ctx_cap,
3212                &mut sess_cap,
3213                &mut captured,
3214            )
3215            .expect("captured prefill");
3216        assert!(
3217            captured.is_none(),
3218            "prefill (seq != 1) must NOT build a capture"
3219        );
3220
3221        for (i, &tok) in decode_tokens.iter().enumerate() {
3222            let got = model_cap
3223                .forward_with_kv_context_captured(
3224                    &[tok],
3225                    &mut cache_cap,
3226                    &mut ctx_cap,
3227                    &mut sess_cap,
3228                    &mut captured,
3229                )
3230                .expect("captured decode");
3231
3232            assert_eq!(
3233                got, ref_logits[i],
3234                "Phi captured decode token {i} must be BYTE-IDENTICAL to the persistent path (same plan => same kernels). A mismatch here on tokens 3+ is the partial-rotary replay-bytes failure this test exists for.",
3235            );
3236
3237            if i == 0 {
3238                assert!(sess_cap.is_some(), "token 1 builds the held session");
3239                assert!(captured.is_none(), "token 1 must NOT build the capture yet");
3240            }
3241        }
3242
3243        // Both caches advanced identically — the fallback path must bump the
3244        // cache exactly as the captured path would.
3245        assert_eq!(cache_cap.cached_len, max_seq_len);
3246        assert_eq!(cache_ref.cached_len, max_seq_len);
3247
3248        // --- Report whether capture actually formed (state, not verdict) ---
3249        //
3250        // Byte-exactness above is the CLAIM and is asserted unconditionally.
3251        // Whether the capture forms is a property of the model's GRAPH, and
3252        // Phi's is currently NOT capturable: its decode plan carries 3 fused
3253        // `LayerNormLastDim` and 4 fused `ROPE` nodes with no CUDA binding, so
3254        // they land on the host and force the cross-device `Op::Copy` that
3255        // `capture_decode` rejects (measured — see
3256        // `phi_decode_node_placement_report_cuda`). Llama captures because its
3257        // rope runs DECOMPOSED on CUDA instead of as a fused node.
3258        //
3259        // So this asserts the INVARIANT that holds either way — capture is an
3260        // optimization, and declining it must never change the answer — and
3261        // reports which branch ran. If a future registration puts LayerNorm and
3262        // ROPE on CUDA, capture will start forming and this test keeps passing
3263        // while the line below changes: a state report, not a frozen
3264        // expectation.
3265        if captured.is_some() {
3266            println!("Phi capture FORMED — the decode graph is fully CUDA-resident");
3267        } else {
3268            println!(
3269                "Phi capture DECLINED (expected today) — host-placed fused LayerNormLastDim/ROPE force a cross-device Copy. Results were byte-identical via the persistent fallback, which is the property that matters: capture degrades, never fails."
3270            );
3271        }
3272    }
3273}
3274
3275// GAP-347 PR 4 (bail! consolidation): before/after test for this consumer
3276// crate family. `fuel_ir::bail!` is now `fuel_ir::bail!` re-exported
3277// (the fuel-core-local `macro_rules!` duplicate was deleted), which can
3278// change `$crate::Error` resolution silently across a macro-path swap.
3279// This proves the error text/variant this crate actually relies on
3280// (src/lib.rs's `fuel_ir::bail!`) is unchanged.
3281#[cfg(test)]
3282mod bail_consolidation_tests {
3283    fn always_bails() -> fuel_ir::error::Result<()> {
3284        fuel_ir::bail!("deliberate failure for the fuel-core dissolution bail! consolidation test");
3285        #[allow(unreachable_code)]
3286        Ok(())
3287    }
3288
3289    #[test]
3290    fn fuel_core_bail_still_produces_a_typed_err_with_the_message() {
3291        let err = always_bails().expect_err("bail! must produce an Err, never panic");
3292        assert!(err.to_string().contains("deliberate failure"));
3293    }
3294}