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        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_loaders::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_loaders::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 (mmap_arc, _) = (mc.mmap(), ());
1585        let mmap_bytes: &[u8] = &mmap_arc[..];
1586        let data_off = content.tensor_data_offset as usize;
1587
1588        // Extract a raw byte slice for a tensor.
1589        let get_tensor_bytes = |name: &str| -> fuel_ir::error::Result<(
1590            &[u8],
1591            fuel_loaders::quantized::GgmlDType,
1592            Vec<usize>,
1593        )> {
1594            let info = content
1595                .tensor_infos
1596                .get(name)
1597                .ok_or_else(|| content.missing_tensor_error(name))?;
1598            let elems = info.shape.elem_count();
1599            let block_size = info.ggml_dtype.block_size();
1600            let bytes_len = elems / block_size * info.ggml_dtype.type_size();
1601            let start = data_off + info.offset as usize;
1602            Ok((
1603                &mmap_bytes[start..start + bytes_len],
1604                info.ggml_dtype,
1605                info.shape.dims().to_vec(),
1606            ))
1607        };
1608
1609        // Load an F32 vector (for biases, norms, embedding). Dequantizes
1610        // if necessary.
1611        let load_f32 = |name: &str| -> fuel_ir::error::Result<Vec<f32>> {
1612            let (bytes, dt, _dims) = get_tensor_bytes(name)?;
1613            dequant_gguf_bytes_to_f32(bytes, dt, name)
1614        };
1615
1616        // Load a weight matrix as WeightStorage. For Q4_0 bytes, keep
1617        // them quantized; for other dtypes, dequantize to F32.
1618        // `out_features × in_features` is the GGUF/llama.cpp convention.
1619        let load_weight = |name: &str,
1620                           out_features: usize,
1621                           in_features: usize|
1622         -> fuel_ir::error::Result<WeightStorage> {
1623            let (bytes, dt, dims) = get_tensor_bytes(name)?;
1624            // GGUF stores weights as [out, in] — matches our Q4_0 block layout.
1625            let expected_elems = out_features * in_features;
1626            let actual_elems: usize = dims.iter().product();
1627            if actual_elems != expected_elems {
1628                fuel_ir::bail!(
1629                    "gguf: tensor {name:?} has {actual_elems} elements, expected {expected_elems} for [{out_features}, {in_features}]",
1630                );
1631            }
1632            // Debug fallback: FUEL_FORCE_F32=1 dequantizes every weight
1633            // at load time to isolate Q4_0-path bugs from model-structure
1634            // bugs. Useful for validating the PhiModel/loader against a
1635            // known-good computation path.
1636            let force_f32 = std::env::var("FUEL_FORCE_F32").is_ok();
1637            match dt {
1638                fuel_loaders::quantized::GgmlDType::Q4_0 if !force_f32 => Ok(WeightStorage::Q4_0 {
1639                    words: bytes_to_u32_arc(bytes),
1640                    bytes_len: bytes.len(),
1641                    in_features,
1642                    out_features,
1643                }),
1644                _ => {
1645                    // Dequantized data is in GGUF's native [out, in]
1646                    // row-major layout. Our standard F32/BF16 matmul
1647                    // expects [in, out], so transpose before storing.
1648                    // (Q4_0 keeps its native layout because qmatmul
1649                    // reads blocks as [N, K/32] directly.)
1650                    let f32_out_in = dequant_gguf_bytes_to_f32(bytes, dt, name)?;
1651                    let mut f32_in_out = vec![0.0_f32; out_features * in_features];
1652                    for o in 0..out_features {
1653                        for i in 0..in_features {
1654                            f32_in_out[i * out_features + o] = f32_out_in[o * in_features + i];
1655                        }
1656                    }
1657                    Ok(WeightStorage::F32(Arc::from(f32_in_out)))
1658                }
1659            }
1660        };
1661
1662        let token_embedding = load_f32("token_embd.weight")?;
1663        if token_embedding.len() != cfg.vocab_size * cfg.dim {
1664            fuel_ir::bail!(
1665                "gguf token_embd: {} elems, expected {}×{}",
1666                token_embedding.len(),
1667                cfg.vocab_size,
1668                cfg.dim,
1669            );
1670        }
1671
1672        let mut layers: Vec<PhiLayerWeights> = Vec::with_capacity(cfg.n_layers);
1673        let kv_dim = cfg.n_heads * cfg.head_dim;
1674
1675        for i in 0..cfg.n_layers {
1676            let prefix = format!("blk.{i}");
1677
1678            // Phi-2 GGUF packs Q/K/V into a single attn_qkv tensor of
1679            // shape [3*dim, dim]. We keep it PACKED as a single
1680            // WeightStorage and let the forward pass do one big matmul
1681            // + slice after (matching Candle's eager approach). This
1682            // avoids any hazards around byte-level Q/K/V splits on the
1683            // weight side.
1684            let attn_qkv_weight =
1685                load_weight(&format!("{prefix}.attn_qkv.weight"), 3 * cfg.dim, cfg.dim)?;
1686            let qkv_bias_vec = load_f32(&format!("{prefix}.attn_qkv.bias"))?;
1687            if qkv_bias_vec.len() != 3 * cfg.dim {
1688                fuel_ir::bail!(
1689                    "gguf attn_qkv.bias: {} elems, expected {}",
1690                    qkv_bias_vec.len(),
1691                    3 * cfg.dim
1692                );
1693            }
1694            let qkv_bias: Arc<[f32]> = Arc::from(qkv_bias_vec);
1695            let _ = kv_dim; // Phi-2 has no GQA; kv_dim == dim
1696
1697            let attn_dense =
1698                load_weight(&format!("{prefix}.attn_output.weight"), cfg.dim, cfg.dim)?;
1699            let attn_dense_bias = Arc::from(load_f32(&format!("{prefix}.attn_output.bias"))?);
1700
1701            let mlp_fc1 = load_weight(&format!("{prefix}.ffn_up.weight"), cfg.ffn_dim, cfg.dim)?;
1702            let mlp_fc1_bias = Arc::from(load_f32(&format!("{prefix}.ffn_up.bias"))?);
1703            let mlp_fc2 = load_weight(&format!("{prefix}.ffn_down.weight"), cfg.dim, cfg.ffn_dim)?;
1704            let mlp_fc2_bias = Arc::from(load_f32(&format!("{prefix}.ffn_down.bias"))?);
1705
1706            let norm_gain = Arc::from(load_f32(&format!("{prefix}.attn_norm.weight"))?);
1707            let norm_bias = Arc::from(load_f32(&format!("{prefix}.attn_norm.bias"))?);
1708
1709            layers.push(PhiLayerWeights {
1710                attn_qkv: PhiQkv::Packed {
1711                    qkv: attn_qkv_weight,
1712                    qkv_bias,
1713                },
1714                attn_dense,
1715                attn_dense_bias,
1716                mlp_fc1,
1717                mlp_fc1_bias,
1718                mlp_fc2,
1719                mlp_fc2_bias,
1720                norm_gain,
1721                norm_bias,
1722            });
1723        }
1724
1725        let final_norm_gain = Arc::from(load_f32("output_norm.weight")?);
1726        let final_norm_bias = Arc::from(load_f32("output_norm.bias")?);
1727
1728        // Output projection. In GGUF: `output.weight` has shape [vocab, dim].
1729        let output = load_weight("output.weight", cfg.vocab_size, cfg.dim)?;
1730        let output_bias = load_f32("output.bias").ok().map(Arc::from);
1731
1732        Ok(PhiWeights {
1733            instance: fuel_tensor::decode_shape::ModelInstanceId::next(),
1734            token_embedding: Arc::from(token_embedding),
1735            layers,
1736            final_norm_gain,
1737            final_norm_bias,
1738            output,
1739            output_bias,
1740        })
1741    }
1742}
1743
1744/// Dequantize a raw byte slice from GGUF (of the given GGML dtype) into
1745/// a flat `Vec<f32>`. Used by the lazy GGUF loader for non-Q4_0 tensors
1746/// (biases, norms, embeddings, and weight matrices of any dtype that
1747/// lacks a fused on-device dequant path).
1748fn dequant_gguf_bytes_to_f32(
1749    bytes: &[u8],
1750    dt: fuel_loaders::quantized::GgmlDType,
1751    name: &str,
1752) -> fuel_ir::error::Result<Vec<f32>> {
1753    use fuel_loaders::quantized::GgmlDType;
1754    use half::{bf16, f16};
1755    match dt {
1756        GgmlDType::F32 => {
1757            if !bytes.len().is_multiple_of(4) {
1758                fuel_ir::bail!(
1759                    "gguf {name}: F32 byte count {} not multiple of 4",
1760                    bytes.len()
1761                );
1762            }
1763            Ok(bytes
1764                .as_chunks::<4>()
1765                .0
1766                .iter()
1767                .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
1768                .collect())
1769        }
1770        GgmlDType::F16 => {
1771            if !bytes.len().is_multiple_of(2) {
1772                fuel_ir::bail!(
1773                    "gguf {name}: F16 byte count {} not multiple of 2",
1774                    bytes.len()
1775                );
1776            }
1777            Ok(bytes
1778                .as_chunks::<2>()
1779                .0
1780                .iter()
1781                .map(|c| f16::from_le_bytes([c[0], c[1]]).to_f32())
1782                .collect())
1783        }
1784        GgmlDType::BF16 => {
1785            if !bytes.len().is_multiple_of(2) {
1786                fuel_ir::bail!(
1787                    "gguf {name}: BF16 byte count {} not multiple of 2",
1788                    bytes.len()
1789                );
1790            }
1791            Ok(bytes
1792                .as_chunks::<2>()
1793                .0
1794                .iter()
1795                .map(|c| bf16::from_le_bytes([c[0], c[1]]).to_f32())
1796                .collect())
1797        }
1798        GgmlDType::Q4_0 => {
1799            // Should rarely be requested this way (prefer keeping Q4_0
1800            // quantized), but support it for biases or other oddities.
1801            Ok(cpu_dequant_q4_0_bytes(bytes))
1802        }
1803        GgmlDType::Q8_0 => Ok(cpu_dequant_q8_0_bytes(bytes)),
1804        // k-quants: dequant via the reference-CPU GgmlType trait impls.
1805        GgmlDType::Q6K => Ok(cpu_dequant_via_trait::<fuel_quantized::BlockQ6K>(bytes)),
1806        GgmlDType::Q5K => Ok(cpu_dequant_via_trait::<fuel_quantized::BlockQ5K>(bytes)),
1807        GgmlDType::Q4K => Ok(cpu_dequant_via_trait::<fuel_quantized::BlockQ4K>(bytes)),
1808        GgmlDType::Q3K => Ok(cpu_dequant_via_trait::<fuel_quantized::BlockQ3K>(bytes)),
1809        GgmlDType::Q2K => Ok(cpu_dequant_via_trait::<fuel_quantized::BlockQ2K>(bytes)),
1810        other => fuel_ir::bail!(
1811            "gguf {name}: dequant-to-f32 for dtype {other:?} not implemented in lazy loader"
1812        ),
1813    }
1814}
1815
1816/// Dequantize an arbitrary k-quant block stream to F32 via the
1817/// reference `GgmlType::to_float` trait. Callers give the concrete
1818/// block type `T` (e.g. `BlockQ6K`); the function reinterprets the
1819/// byte slice as `&[T]` and calls the impl. Used for dtypes that
1820/// don't have a fused on-device dequant kernel (yet).
1821fn cpu_dequant_via_trait<T: fuel_quantized::GgmlType>(bytes: &[u8]) -> Vec<f32> {
1822    let block_bytes = std::mem::size_of::<T>();
1823    assert!(
1824        bytes.len().is_multiple_of(block_bytes),
1825        "cpu_dequant_via_trait: bytes {} not multiple of block_bytes {}",
1826        bytes.len(),
1827        block_bytes
1828    );
1829    let n_blocks = bytes.len() / block_bytes;
1830    // `bytes` is a sub-slice at a GGUF tensor offset inside the mmap, so the
1831    // mmap's own alignment says nothing about THIS slice's: a tensor can start
1832    // at any 1-byte offset the file format allows. `blocks_from_bytes_cow`
1833    // borrows when the address happens to be aligned for `T` and copies into
1834    // an aligned `Vec<T>` when it is not, so neither case is undefined
1835    // behaviour. (This site used to cast unconditionally on the strength of
1836    // "the mmap is 8-byte aligned".)
1837    let blocks = fuel_quantized::blocks_from_bytes_cow::<T>(bytes);
1838    debug_assert_eq!(blocks.len(), n_blocks);
1839    let mut out = vec![0.0_f32; n_blocks * T::BLCK_SIZE];
1840    T::to_float(&blocks, &mut out);
1841    out
1842}
1843
1844/// Reinterpret a byte slice as a u32 `Arc` by reading little-endian
1845/// u32 words. Input length must be a multiple of 4. This performs one
1846/// copy at load time — all subsequent uses are cheap Arc clones.
1847fn bytes_to_u32_arc(bytes: &[u8]) -> Arc<[u32]> {
1848    assert_eq!(
1849        bytes.len() % 4,
1850        0,
1851        "bytes_to_u32_arc: len must be multiple of 4"
1852    );
1853    let words: Vec<u32> = bytes
1854        .as_chunks::<4>()
1855        .0
1856        .iter()
1857        .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]]))
1858        .collect();
1859    Arc::from(words)
1860}
1861
1862fn cpu_dequant_q4_0_bytes(bytes: &[u8]) -> Vec<f32> {
1863    use half::f16;
1864    let bpb = 18usize;
1865    let epb = 32usize;
1866    let n_blocks = bytes.len() / bpb;
1867    let mut out = vec![0.0_f32; n_blocks * epb];
1868    for b in 0..n_blocks {
1869        let off = b * bpb;
1870        let d = f16::from_le_bytes([bytes[off], bytes[off + 1]]).to_f32();
1871        let base = b * epb;
1872        for kk in 0..16 {
1873            let packed = bytes[off + 2 + kk];
1874            let lo = (packed & 0x0F) as i32 - 8;
1875            let hi = ((packed >> 4) & 0x0F) as i32 - 8;
1876            out[base + kk] = lo as f32 * d;
1877            out[base + 16 + kk] = hi as f32 * d;
1878        }
1879    }
1880    out
1881}
1882
1883fn cpu_dequant_q8_0_bytes(bytes: &[u8]) -> Vec<f32> {
1884    use half::f16;
1885    let bpb = 34usize;
1886    let epb = 32usize;
1887    let n_blocks = bytes.len() / bpb;
1888    let mut out = vec![0.0_f32; n_blocks * epb];
1889    for b in 0..n_blocks {
1890        let off = b * bpb;
1891        let d = f16::from_le_bytes([bytes[off], bytes[off + 1]]).to_f32();
1892        let base = b * epb;
1893        for kk in 0..32 {
1894            let q = bytes[off + 2 + kk] as i8 as i32;
1895            out[base + kk] = q as f32 * d;
1896        }
1897    }
1898    out
1899}
1900
1901/// Apply rotary embeddings to only the first `rotary_dim` entries of
1902/// the last dimension; pass the remaining `head_dim - rotary_dim` entries
1903/// through unchanged. Used by Phi-2 and Phi-3 which rotate only a
1904/// fraction of each head's feature dim.
1905///
1906/// Input shape: `[..., head_dim]`. Output shape: same.
1907fn partial_rope(
1908    x: &Tensor,
1909    cos: &Tensor,
1910    sin: &Tensor,
1911    rotary_dim: usize,
1912    head_dim: usize,
1913) -> Tensor {
1914    if rotary_dim == head_dim {
1915        return x.rope_with_tables(cos, sin).unwrap();
1916    }
1917    let rank = x.shape().dims().len();
1918    let last = rank - 1;
1919    let x_rot = x.slice(last, 0, rotary_dim).unwrap();
1920    let x_pass = x.slice(last, rotary_dim, head_dim - rotary_dim).unwrap();
1921    let x_rot_rotated = x_rot.rope_with_tables(cos, sin).unwrap();
1922    x_rot_rotated.concat(&x_pass, last).unwrap()
1923}
1924
1925#[cfg(test)]
1926impl PhiConfig {
1927    /// The hand-rolled parser this type used before the `serde` split, kept
1928    /// verbatim and test-only as the differential's oracle.
1929    pub(crate) fn from_hf_json_str_legacy(json: &str) -> fuel_ir::error::Result<Self> {
1930        let v: serde_json::Value = serde_json::from_str(json)
1931            .map_err(|e| fuel_ir::error::Error::Msg(format!("parsing config.json: {e}")))?;
1932
1933        let get_usize = |key: &str| -> fuel_ir::error::Result<usize> {
1934            v.get(key)
1935                .and_then(|x| x.as_u64())
1936                .map(|x| x as usize)
1937                .ok_or_else(|| {
1938                    fuel_ir::error::Error::Msg(format!(
1939                        "config.json: missing/invalid field {key:?}"
1940                    ))
1941                })
1942        };
1943        let get_f64 = |key: &str| -> Option<f64> { v.get(key).and_then(|x| x.as_f64()) };
1944
1945        let vocab_size = get_usize("vocab_size")?;
1946        let dim = get_usize("hidden_size")?;
1947        let n_layers = get_usize("num_hidden_layers")?;
1948        let n_heads = get_usize("num_attention_heads")?;
1949        let ffn_dim = get_usize("intermediate_size")?;
1950        let head_dim = v
1951            .get("head_dim")
1952            .and_then(|x| x.as_u64())
1953            .map(|x| x as usize)
1954            .unwrap_or(dim / n_heads);
1955        let layer_norm_eps = get_f64("layer_norm_eps").unwrap_or(1e-5);
1956        let rope_base = get_f64("rope_theta").unwrap_or(10_000.0);
1957        let partial_rotary_factor = get_f64("partial_rotary_factor").unwrap_or(0.4);
1958        let rotary_dim = (partial_rotary_factor * head_dim as f64).round() as usize;
1959        if !rotary_dim.is_multiple_of(2) {
1960            fuel_ir::bail!(
1961                "PhiConfig: rotary_dim {rotary_dim} must be even (partial_rotary_factor={partial_rotary_factor}, head_dim={head_dim})"
1962            );
1963        }
1964        let tie_word_embeddings = v
1965            .get("tie_word_embeddings")
1966            .and_then(|x| x.as_bool())
1967            .unwrap_or(false);
1968
1969        Ok(PhiConfig {
1970            vocab_size,
1971            dim,
1972            n_layers,
1973            n_heads,
1974            head_dim,
1975            ffn_dim,
1976            layer_norm_eps,
1977            rope_base,
1978            partial_rotary_factor,
1979            rotary_dim,
1980            tie_word_embeddings,
1981        })
1982    }
1983}
1984#[cfg(test)]
1985mod phi_config_tests {
1986    use super::PhiConfig;
1987
1988    /// ⚠️ THIS CONFIG HAD NO TEST FIXTURES AT ALL BEFORE THIS CORPUS.
1989    ///
1990    /// Its only caller was `PhiModel::from_hub`, which reads `config.json`
1991    /// over the network — so the parser had never been exercised by anything
1992    /// runnable offline. Seventh config in the increment and the most extreme
1993    /// coverage case: not a collapsed axis, not a partially-covered rule, but
1994    /// an EMPTY corpus. **All 4 fixtures are ADDED; none is pre-existing.**
1995    ///
1996    /// | behaviour                          | pre-existing fixture? |
1997    /// |------------------------------------|-----------------------|
1998    /// | anything at all                    | NO — there were none  |
1999    const DIFFERENTIAL_CORPUS: &[(&str, &str)] = &[
2000        (
2001            "ADDED: phi-2 shaped, explicit head_dim equal to the quotient",
2002            r#"{
2003                "vocab_size": 51200, "hidden_size": 2560, "num_hidden_layers": 32,
2004                "num_attention_heads": 32, "intermediate_size": 10240,
2005                "head_dim": 80, "layer_norm_eps": 1e-5, "rope_theta": 10000.0,
2006                "partial_rotary_factor": 0.4
2007            }"#,
2008        ),
2009        (
2010            "ADDED: minimal — every optional absent, head_dim derived",
2011            r#"{
2012                "vocab_size": 51200, "hidden_size": 1024, "num_hidden_layers": 16,
2013                "num_attention_heads": 16, "intermediate_size": 4096
2014            }"#,
2015        ),
2016        (
2017            "ADDED: explicit head_dim 96 != 2560/32 = 80, and rotary_dim CHAINS off it",
2018            r#"{
2019                "vocab_size": 51200, "hidden_size": 2560, "num_hidden_layers": 32,
2020                "num_attention_heads": 32, "intermediate_size": 10240,
2021                "head_dim": 96, "partial_rotary_factor": 0.4
2022            }"#,
2023        ),
2024        (
2025            "ADDED: odd rotary_dim — both paths must REJECT (0.5 * 10 = 5)",
2026            r#"{
2027                "vocab_size": 100, "hidden_size": 40, "num_hidden_layers": 2,
2028                "num_attention_heads": 4, "intermediate_size": 80,
2029                "partial_rotary_factor": 0.5
2030            }"#,
2031        ),
2032    ];
2033
2034    #[test]
2035    fn serde_path_agrees_with_the_legacy_parser_on_every_fixture() {
2036        assert_eq!(DIFFERENTIAL_CORPUS.len(), 4, "corpus shrank");
2037        for (name, json) in DIFFERENTIAL_CORPUS {
2038            let new = PhiConfig::from_hf_json_str(json);
2039            let old = PhiConfig::from_hf_json_str_legacy(json);
2040            match (new, old) {
2041                (Ok(a), Ok(b)) => assert_eq!(a, b, "differential mismatch on {name}"),
2042                (Err(_), Err(_)) => {}
2043                (Ok(_), Err(e)) => panic!("{name}: serde accepted, legacy rejected: {e}"),
2044                (Err(e), Ok(_)) => panic!("{name}: serde rejected, legacy accepted: {e}"),
2045            }
2046        }
2047    }
2048
2049    #[test]
2050    fn rotary_dim_chains_off_the_resolved_head_dim() {
2051        // The ordering constraint, made falsifiable. With head_dim explicit at
2052        // 96, rotary_dim must be round(0.4 * 96) = 38. If the chain read the
2053        // QUOTIENT instead (2560/32 = 80) it would be round(0.4 * 80) = 32.
2054        // Both are even, so the evenness check cannot tell them apart — only
2055        // this assertion can.
2056        let cfg = PhiConfig::from_hf_json_str(DIFFERENTIAL_CORPUS[2].1).unwrap();
2057        assert_eq!(cfg.head_dim, 96, "explicit head_dim must survive");
2058        assert_eq!(
2059            cfg.rotary_dim, 38,
2060            "rotary_dim must chain off the RESOLVED head_dim"
2061        );
2062        assert_ne!(
2063            cfg.rotary_dim, 32,
2064            "32 is what reading the raw quotient would give"
2065        );
2066    }
2067
2068    #[test]
2069    fn odd_rotary_dim_is_rejected_by_both_paths() {
2070        let json = DIFFERENTIAL_CORPUS[3].1;
2071        assert!(
2072            PhiConfig::from_hf_json_str(json).is_err(),
2073            "0.5 * 10 = 5 is odd"
2074        );
2075        assert!(
2076            PhiConfig::from_hf_json_str_legacy(json).is_err(),
2077            "legacy must agree"
2078        );
2079    }
2080}
2081
2082#[cfg(test)]
2083mod phi_kv_context_tests {
2084    use super::*;
2085    use fuel_tensor::{inference_context::InferenceContext, inference_context::KvCache};
2086
2087    // Parity with the retired Phi `_gpu_on` family
2088    // (`forward_with_cache_gpu_on` prefill + decode logits;
2089    // `generate_streaming_gpu_on` greedy token sequences) was
2090    // confirmed by `phi_forward_with_kv_context_matches_legacy_gpu_on`
2091    // and `phi_generate_with_kv_context_matches_legacy_generate`
2092    // immediately before retirement (commit 03df5c49); those tests
2093    // retired together with the legacy methods they referenced.
2094
2095    /// Build tiny Phi-2-shaped weights (Split QKV + biases everywhere,
2096    /// partial RoPE) for kv-context forward tests.
2097    fn make_tiny_phi(cfg: &PhiConfig, seed: u32) -> PhiWeights {
2098        let mut s: u32 = seed;
2099        let mut next = || -> f32 {
2100            s = s.wrapping_mul(1103515245).wrapping_add(12345);
2101            ((s >> 16) as u16 as f32 / 65535.0 - 0.5) * 0.1
2102        };
2103        let mut vec_of = |n: usize| -> Arc<[f32]> {
2104            let v: Vec<f32> = (0..n).map(|_| next()).collect();
2105            Arc::from(v)
2106        };
2107        let d = cfg.dim;
2108        let kv_dim = cfg.n_heads * cfg.head_dim;
2109        PhiWeights {
2110            instance: fuel_tensor::decode_shape::ModelInstanceId::next(),
2111            token_embedding: vec_of(cfg.vocab_size * d),
2112            layers: (0..cfg.n_layers)
2113                .map(|_| PhiLayerWeights {
2114                    attn_qkv: PhiQkv::Split {
2115                        q: vec_of(d * d).into(),
2116                        q_bias: vec_of(d),
2117                        k: vec_of(d * kv_dim).into(),
2118                        k_bias: vec_of(kv_dim),
2119                        v: vec_of(d * kv_dim).into(),
2120                        v_bias: vec_of(kv_dim),
2121                    },
2122                    attn_dense: vec_of(d * d).into(),
2123                    attn_dense_bias: vec_of(d),
2124                    mlp_fc1: vec_of(d * cfg.ffn_dim).into(),
2125                    mlp_fc1_bias: vec_of(cfg.ffn_dim),
2126                    mlp_fc2: vec_of(cfg.ffn_dim * d).into(),
2127                    mlp_fc2_bias: vec_of(d),
2128                    norm_gain: Arc::from(vec![1.0_f32; d]),
2129                    norm_bias: vec_of(d),
2130                })
2131                .collect(),
2132            final_norm_gain: Arc::from(vec![1.0_f32; d]),
2133            final_norm_bias: vec_of(d),
2134            output: vec_of(d * cfg.vocab_size).into(),
2135            output_bias: Some(vec_of(cfg.vocab_size)),
2136        }
2137    }
2138
2139    fn tiny_cfg() -> PhiConfig {
2140        PhiConfig {
2141            vocab_size: 16,
2142            dim: 8,
2143            n_layers: 2,
2144            n_heads: 2,
2145            head_dim: 4,
2146            ffn_dim: 16,
2147            layer_norm_eps: 1e-5,
2148            rope_base: 10000.0,
2149            partial_rotary_factor: 0.5,
2150            rotary_dim: 2,
2151            tie_word_embeddings: false,
2152        }
2153    }
2154
2155    /// KV-cache self-consistency on the new path: a monolithic prefill
2156    /// over N tokens must produce the same last-position logits as a
2157    /// shorter prefill followed by single-token decode steps through
2158    /// the same positions. Catches cache-position bugs without
2159    /// referencing the legacy path (survives its retirement).
2160    #[test]
2161    fn phi_kv_context_decode_consistent_with_monolithic_prefill() {
2162        let cfg = tiny_cfg();
2163        let model = PhiModel {
2164            config: cfg.clone(),
2165            weights: make_tiny_phi(&cfg, 7777),
2166        };
2167        let tokens = [1_u32, 5, 9, 12];
2168        let device = Device::cpu();
2169
2170        // Path A: monolithic prefill over all 4 tokens.
2171        let mut cache_a = KvCache::with_capacity(
2172            cfg.n_layers,
2173            cfg.n_heads,
2174            cfg.head_dim,
2175            tokens.len(),
2176            DType::F32,
2177            &device,
2178        )
2179        .expect("cache_a");
2180        let mut ctx_a = InferenceContext::new(device.clone());
2181        let expected = model
2182            .forward_with_kv_context(&tokens, &mut cache_a, &mut ctx_a)
2183            .expect("monolithic prefill");
2184
2185        // Path B: prefill 3, decode 1.
2186        let mut cache_b = KvCache::with_capacity(
2187            cfg.n_layers,
2188            cfg.n_heads,
2189            cfg.head_dim,
2190            tokens.len(),
2191            DType::F32,
2192            &device,
2193        )
2194        .expect("cache_b");
2195        let mut ctx_b = InferenceContext::new(device.clone());
2196        model
2197            .forward_with_kv_context(&tokens[..3], &mut cache_b, &mut ctx_b)
2198            .expect("prefill B");
2199        let actual = model
2200            .forward_with_kv_context(&tokens[3..], &mut cache_b, &mut ctx_b)
2201            .expect("decode B");
2202
2203        assert_eq!(actual.len(), expected.len());
2204        // Same O(ε) gemm accumulation-order band as the LLaMA
2205        // kv-context parity tests.
2206        for (i, (a, b)) in actual.iter().zip(expected.iter()).enumerate() {
2207            let diff = (a - b).abs();
2208            let rel = diff / a.abs().max(b.abs()).max(1e-6);
2209            assert!(
2210                diff < 5e-3 || rel < 1e-2,
2211                "logit[{i}]: chunked={a}, monolithic={b}, diff={diff}",
2212            );
2213        }
2214        assert_eq!(cache_a.cached_len, cache_b.cached_len);
2215    }
2216
2217    /// Greedy generation through the Phi kv-context path: correct
2218    /// shape (prompt preserved, max_new appended, tokens in vocab)
2219    /// and fully deterministic across runs.
2220    #[test]
2221    fn phi_generate_with_kv_context_greedy_is_deterministic() {
2222        let cfg = tiny_cfg();
2223        let model = PhiModel {
2224            config: cfg.clone(),
2225            weights: make_tiny_phi(&cfg, 7777),
2226        };
2227        let prompt = [1_u32, 5, 9];
2228        let max_new = 8;
2229        let device = Device::cpu();
2230
2231        let mut streamed = Vec::new();
2232        let run_a = model
2233            .generate_streaming_with_kv_context(
2234                &prompt,
2235                max_new,
2236                SamplingStrategy::Greedy,
2237                None,
2238                &device,
2239                DType::F32,
2240                |t| streamed.push(t),
2241            )
2242            .expect("run a");
2243        let run_b = model
2244            .generate_with_kv_context(
2245                &prompt,
2246                max_new,
2247                SamplingStrategy::Greedy,
2248                None,
2249                &device,
2250                DType::F32,
2251            )
2252            .expect("run b");
2253
2254        assert_eq!(run_a, run_b, "greedy generation must be deterministic");
2255        assert_eq!(run_a.len(), prompt.len() + max_new);
2256        assert_eq!(&run_a[..prompt.len()], &prompt);
2257        assert_eq!(
2258            streamed,
2259            &run_a[prompt.len()..],
2260            "callback sees exactly the new tokens"
2261        );
2262        for &t in &run_a {
2263            assert!((t as usize) < cfg.vocab_size, "token {t} out of vocab");
2264        }
2265    }
2266
2267    /// `forward_with_kv_context` build-time validation: with_dims
2268    /// caches (no pre-allocated buffers) and capacity overflows are
2269    /// rejected with typed errors, not panics.
2270    #[test]
2271    fn phi_forward_with_kv_context_rejects_invalid_cache() {
2272        let cfg = tiny_cfg();
2273        let model = PhiModel {
2274            config: cfg.clone(),
2275            weights: make_tiny_phi(&cfg, 7777),
2276        };
2277        let device = Device::cpu();
2278        let mut ctx = InferenceContext::new(device.clone());
2279
2280        // with_dims cache → typed error.
2281        let mut dims_cache = KvCache::with_dims(cfg.n_layers, cfg.n_heads, cfg.head_dim);
2282        let err = model
2283            .forward_with_kv_context(&[1, 2], &mut dims_cache, &mut ctx)
2284            .expect_err("with_dims cache must be rejected");
2285        assert!(format!("{err}").contains("with_capacity"));
2286
2287        // Capacity overflow → typed error.
2288        let mut small_cache = KvCache::with_capacity(
2289            cfg.n_layers,
2290            cfg.n_heads,
2291            cfg.head_dim,
2292            2,
2293            DType::F32,
2294            &device,
2295        )
2296        .expect("small cache");
2297        model
2298            .forward_with_kv_context(&[1, 2], &mut small_cache, &mut ctx)
2299            .expect("fits exactly");
2300        let err = model
2301            .forward_with_kv_context(&[3], &mut small_cache, &mut ctx)
2302            .expect_err("overflow must be rejected");
2303        assert!(format!("{err}").contains("max_seq_len"));
2304    }
2305
2306    /// Phase D · D4 correctness gate (the Phi mirror of the LlamaModel D1
2307    /// `forward_with_kv_context_decode_matches_non_cached_forward`).
2308    ///
2309    /// PhiModel has no non-cached `forward` reference, so — like the
2310    /// existing `phi_kv_context_decode_consistent_with_monolithic_prefill`
2311    /// — this compares the input-independent decode graph (write_slice_dyn
2312    /// at a symbolic offset + full-capacity attention + fixed-capacity
2313    /// mask) against a monolithic prefill over the same token history. A
2314    /// prefill (seq>1) + a seq==1 decode step exercise BOTH the multi-row
2315    /// and single-row shapes of the transformed `apply_layer_with_kv_writes`.
2316    /// Within the existing O(ε) gemm accumulation-order band the two paths
2317    /// must agree — masked positions contribute exactly 0, so the extra
2318    /// masked compute over `max_seq_len` (vs the live `total_seq`) is a
2319    /// no-op numerically.
2320    ///
2321    /// Born-red shape: if the write offset were baked concretely (breaking
2322    /// the symbolic path) or the fixed-capacity mask failed to null the
2323    /// stale tail, the decode logits would diverge from the monolithic
2324    /// prefill and this fails.
2325    #[test]
2326    fn phi_decode_matches_non_cached_forward() {
2327        let cfg = tiny_cfg(); // partial RoPE (rotary_dim=2, head_dim=4)
2328        let model = PhiModel {
2329            config: cfg.clone(),
2330            weights: make_tiny_phi(&cfg, 7777),
2331        };
2332
2333        let prompt = [1_u32, 5, 9];
2334        let next_token = 12_u32;
2335        let full = [prompt[0], prompt[1], prompt[2], next_token];
2336        let device = Device::cpu();
2337
2338        // Reference: monolithic prefill over all 4 tokens.
2339        let mut cache_ref = KvCache::with_capacity(
2340            cfg.n_layers,
2341            cfg.n_heads,
2342            cfg.head_dim,
2343            full.len(),
2344            DType::F32,
2345            &device,
2346        )
2347        .expect("with_capacity ref");
2348        let mut ctx_ref = InferenceContext::new(device.clone());
2349        let expected = model
2350            .forward_with_kv_context(&full, &mut cache_ref, &mut ctx_ref)
2351            .expect("monolithic prefill");
2352
2353        // Input-independent path: prefill(3) then decode(1) through the
2354        // transformed apply_layer_with_kv_writes.
2355        let mut cache = KvCache::with_capacity(
2356            cfg.n_layers,
2357            cfg.n_heads,
2358            cfg.head_dim,
2359            full.len(),
2360            DType::F32,
2361            &device,
2362        )
2363        .expect("with_capacity");
2364        let mut ctx = InferenceContext::new(device);
2365        let _prefill = model
2366            .forward_with_kv_context(&prompt, &mut cache, &mut ctx)
2367            .expect("prefill");
2368        assert_eq!(cache.cached_len, prompt.len());
2369        let actual = model
2370            .forward_with_kv_context(&[next_token], &mut cache, &mut ctx)
2371            .expect("decode");
2372        assert_eq!(cache.cached_len, full.len());
2373        assert_eq!(actual.len(), expected.len());
2374
2375        // Same O(ε) gemm accumulation-order band as the other Phi kv-context
2376        // parity tests.
2377        for (i, (a, b)) in actual.iter().zip(expected.iter()).enumerate() {
2378            let diff = (a - b).abs();
2379            let rel = diff / a.abs().max(b.abs()).max(1e-6);
2380            assert!(
2381                diff < 5e-3 || rel < 1e-2,
2382                "logit[{i}]: input-independent={a}, monolithic={b}, diff={diff}",
2383            );
2384        }
2385    }
2386
2387    /// Phase D · D4 born-red gate for plan-once persistent decode (the Phi
2388    /// mirror of the LlamaModel
2389    /// `forward_with_kv_context_persistent_plan_once_matches_d1`).
2390    ///
2391    /// Drive [`PhiModel::forward_with_kv_context_persistent`] for ≥3 decode
2392    /// tokens (after a prefill) holding ONE `DecodeSession`, in lockstep
2393    /// against the D1 [`PhiModel::forward_with_kv_context`] rebuild path
2394    /// (a SECOND identical model + cache + ctx fed the identical token each
2395    /// step). Assert the three plan-once invariants:
2396    ///   (a) `optimize_calls_thread_local()` bumps **exactly once** across
2397    ///       all the decode tokens — the first persistent decode token
2398    ///       builds + optimizes the held session; tokens 2..N skip optimize
2399    ///       (reuse via the D2a prebuilt seam);
2400    ///   (b) each persistent token's logits are **exactly `==`** the D1
2401    ///       cached path on the same prefix — same plan → same kernels →
2402    ///       bit-exact (NOT epsilon);
2403    ///   (c) the held graph's node `len()` is **stable from token 2 onward**
2404    ///       (no per-token node growth).
2405    #[test]
2406    fn phi_persistent_plan_once_matches_d1() {
2407        let cfg = tiny_cfg(); // partial RoPE + parallel block + biases
2408        // Two byte-identical models (same seed): one drives the D2
2409        // persistent path, one the D1 rebuild path.
2410        let model_d2 = PhiModel {
2411            config: cfg.clone(),
2412            weights: make_tiny_phi(&cfg, 7777),
2413        };
2414        let model_d1 = PhiModel {
2415            config: cfg.clone(),
2416            weights: make_tiny_phi(&cfg, 7777),
2417        };
2418
2419        let prompt = [1_u32, 5, 9];
2420        let decode_tokens = [12_u32, 3, 7, 2]; // ≥3 decode tokens
2421        let max_seq_len = prompt.len() + decode_tokens.len();
2422
2423        // --- D1 (rebuild) reference FIRST, in its own pass, so its
2424        // per-token re-plans don't pollute the optimize-count window we
2425        // measure around the D2 loop. ---
2426        let dev1 = Device::cpu();
2427        let mut cache1 = KvCache::with_capacity(
2428            cfg.n_layers,
2429            cfg.n_heads,
2430            cfg.head_dim,
2431            max_seq_len,
2432            DType::F32,
2433            &dev1,
2434        )
2435        .expect("with_capacity d1");
2436        let mut ctx1 = InferenceContext::new(dev1);
2437        let _ = model_d1
2438            .forward_with_kv_context(&prompt, &mut cache1, &mut ctx1)
2439            .expect("d1 prefill");
2440        let mut d1_expected: Vec<Vec<f32>> = Vec::with_capacity(decode_tokens.len());
2441        for &tok in &decode_tokens {
2442            d1_expected.push(
2443                model_d1
2444                    .forward_with_kv_context(&[tok], &mut cache1, &mut ctx1)
2445                    .expect("d1 decode"),
2446            );
2447        }
2448
2449        // --- D2 (persistent) session state ---
2450        let dev2 = Device::cpu();
2451        let mut cache2 = KvCache::with_capacity(
2452            cfg.n_layers,
2453            cfg.n_heads,
2454            cfg.head_dim,
2455            max_seq_len,
2456            DType::F32,
2457            &dev2,
2458        )
2459        .expect("with_capacity d2");
2460        let mut ctx2 = InferenceContext::new(dev2);
2461        let mut session: Option<fuel_tensor::inference_context::DecodeSession> = None;
2462
2463        // Prefill (seq>1 → falls back to the rebuild path; NO session).
2464        let _ = model_d2
2465            .forward_with_kv_context_persistent(&prompt, &mut cache2, &mut ctx2, &mut session)
2466            .expect("d2 prefill");
2467        assert!(
2468            session.is_none(),
2469            "prefill (seq>1) must NOT build the held session"
2470        );
2471
2472        // Decode ≥3 tokens through the persistent path ONLY. Snapshot the
2473        // thread-local optimize count just before the loop (isolated from
2474        // other suite threads' concurrent optimizes).
2475        let opt_before = fuel_tensor::pipelined_bridge::optimize_calls_thread_local();
2476        let mut len_at_token2: Option<usize> = None;
2477
2478        for (i, &tok) in decode_tokens.iter().enumerate() {
2479            let d2 = model_d2
2480                .forward_with_kv_context_persistent(&[tok], &mut cache2, &mut ctx2, &mut session)
2481                .expect("d2 decode");
2482
2483            // (b) bit-exact vs. the D1 cached path (same plan → same kernels).
2484            assert_eq!(
2485                d2, d1_expected[i],
2486                "persistent decode token {i} must be byte-identical to the D1 cached path",
2487            );
2488
2489            let sess = session
2490                .as_ref()
2491                .expect("session built on first decode token");
2492            let graph_len = sess.graph_node_count();
2493            if i == 1 {
2494                len_at_token2 = Some(graph_len);
2495            } else if i >= 2 {
2496                // (c) node count stable from token 2 onward.
2497                assert_eq!(
2498                    Some(graph_len),
2499                    len_at_token2,
2500                    "held graph must NOT grow from token 2 onward (token {i})",
2501                );
2502            }
2503        }
2504
2505        // (a) optimize bumped EXACTLY ONCE across all decode tokens.
2506        let opt_after = fuel_tensor::pipelined_bridge::optimize_calls_thread_local();
2507        assert_eq!(
2508            opt_after - opt_before,
2509            1,
2510            "persistent decode must optimize EXACTLY ONCE across {} decode tokens \
2511             (the first builds the session; the rest skip optimize): {opt_before} -> {opt_after}",
2512            decode_tokens.len(),
2513        );
2514
2515        assert_eq!(cache2.cached_len, max_seq_len);
2516        assert_eq!(cache1.cached_len, max_seq_len);
2517    }
2518
2519    /// Phase D · D4 generate-loop integration (the Phi mirror of the
2520    /// LlamaModel `generate_loop_persistent_byte_exact_and_plans_once`).
2521    ///
2522    /// The plain PhiModel decode generate loops
2523    /// (`generate_streaming_with_kv_context` / `generate_with_kv_context`)
2524    /// now hold ONE plan-once `DecodeSession` and route every step through
2525    /// [`PhiModel::forward_with_kv_context_persistent`]. This is the
2526    /// end-to-end guard that the plan-once path is USED in production Phi
2527    /// generation and stays bit-exact vs the D1 rebuild path.
2528    ///
2529    /// Drives an explicit persistent generate loop (mirroring the wired
2530    /// production loop) against a SEPARATE D1 reference loop over the same
2531    /// inputs, asserting:
2532    ///   (a) the generated token sequence is **byte-identical** over N≥4
2533    ///       greedy tokens (greedy diverges on ANY logit drift — a strong
2534    ///       end-to-end guard);
2535    ///   (b) each step's **logits** are **exactly `==`** the D1 cached path;
2536    ///   (c) `optimize_calls_thread_local()` bumps **exactly 2** across
2537    ///       prefill + N decode (1 prefill fallback + 1 decode-session
2538    ///       build) regardless of N — plan-once at the loop level.
2539    /// GAP-029 increment 2b — is `attended_len_sym` actually UNREFERENCED?
2540    ///
2541    /// The shared-driver de-duplication rests on a claim made only in comments:
2542    /// Phi's session carries `attended_len_sym = SymId(1)` "for API parity but
2543    /// never referenced/bound", and Llama's own doc says its attended-length
2544    /// binding "is unreferenced on today's f32 decode graph (no flash arm)". If
2545    /// both are true, Phi adopting Llama's shared `per_token_sym_env` (which
2546    /// binds both symbols) is a no-op and one driver can serve both.
2547    ///
2548    /// **The byte-exact persistent tests CANNOT settle this.** If the symbol
2549    /// were referenced but bound to its usual value, byte-exactness passes and
2550    /// says nothing about referencedness — the comment and the passing test are
2551    /// the same evidence, and neither discriminates.
2552    ///
2553    /// The discriminating instrument is a **negative control on the binding**:
2554    /// bind the symbol to a deliberately WRONG value and look at the output.
2555    ///   - output changes  ⇒ referenced ⇒ the no-op claim is FALSE
2556    ///   - output identical ⇒ genuinely unreferenced (positive evidence, not a
2557    ///     comment's word)
2558    ///
2559    /// **A wrong-binding test that sees no change is vacuous on its own**, since
2560    /// "the perturbation never reached the graph" produces the identical result.
2561    /// So each arm below is paired with a positive control that perturbs
2562    /// `cached_len_sym` — a symbol the KV write demonstrably DOES reference —
2563    /// and requires the output to change. Only then does "unchanged" mean
2564    /// unreferenced rather than "the instrument is blind".
2565    ///
2566    /// Scope of the claim, per Llama's own qualifier: **F32, CPU, today's decode
2567    /// graph, no flash arm.** A bf16/f16 CUDA decode that offers the flash arm
2568    /// would reference `attended_len` and must re-run this control.
2569    #[test]
2570    fn phi_attended_len_sym_is_unreferenced_negative_control() {
2571        let cfg = tiny_cfg();
2572        let model = PhiModel {
2573            config: cfg.clone(),
2574            weights: make_tiny_phi(&cfg, 7777),
2575        };
2576        let prompt = [1_u32, 5, 9];
2577        let max_seq_len = prompt.len() + 4;
2578
2579        let dev = Device::cpu();
2580        let mut cache = KvCache::with_capacity(
2581            cfg.n_layers,
2582            cfg.n_heads,
2583            cfg.head_dim,
2584            max_seq_len,
2585            DType::F32,
2586            &dev,
2587        )
2588        .expect("with_capacity");
2589        let mut ctx = InferenceContext::new(dev.clone());
2590        let mut session: Option<fuel_tensor::inference_context::DecodeSession> = None;
2591
2592        // Prefill, then ONE decode token to BUILD the held session.
2593        let _ = model
2594            .forward_with_kv_context_persistent(&prompt, &mut cache, &mut ctx, &mut session)
2595            .expect("prefill");
2596        let _ = model
2597            .forward_with_kv_context_persistent(&[12], &mut cache, &mut ctx, &mut session)
2598            .expect("build decode session");
2599        let s = session.as_ref().expect("session built");
2600
2601        // Realize the SAME next token three times, varying ONLY the SymEnv.
2602        // `realize_token` takes &self and clones `base_cache` internally, so the
2603        // three calls cannot pollute each other.
2604        let cached_len = cache.cached_len;
2605        let next = [3_u32];
2606        let mk_data = || {
2607            model
2608                .build_token_rope_mask_arcs(&dev, cached_len, &next, s.max_seq_len())
2609                .expect("token data")
2610        };
2611
2612        let mut env_ok = fuel_ir::SymEnv::new();
2613        env_ok
2614            .bind(s.cached_len_sym(), cached_len)
2615            .expect("bind cached_len");
2616        let baseline = s.realize_token(&dev, mk_data(), &env_ok).expect("baseline");
2617
2618        // --- the measurement: attended_len bound to a WRONG value ---
2619        let mut env_bad_attended = fuel_ir::SymEnv::new();
2620        env_bad_attended
2621            .bind(s.cached_len_sym(), cached_len)
2622            .expect("bind cached_len");
2623        env_bad_attended
2624            .bind(s.attended_len_sym(), cached_len + 4242)
2625            .expect("bind attended_len (wrong on purpose)");
2626        let perturbed_attended = s
2627            .realize_token(&dev, mk_data(), &env_bad_attended)
2628            .expect("realize with wrong attended_len");
2629
2630        // --- control A: perturb the DATA, which must always move the output ---
2631        // Proves `realize_token` is live and sensitive at all; without it,
2632        // "nothing changed" could mean the realize returns a cached or constant
2633        // result and every verdict below would be vacuous.
2634        let other = [6_u32];
2635        let data_other = model
2636            .build_token_rope_mask_arcs(&dev, cached_len, &other, s.max_seq_len())
2637            .expect("token data (different token)");
2638        let mut env_ok2 = fuel_ir::SymEnv::new();
2639        env_ok2
2640            .bind(s.cached_len_sym(), cached_len)
2641            .expect("bind cached_len");
2642        let perturbed_data = s
2643            .realize_token(&dev, data_other, &env_ok2)
2644            .expect("realize with different token");
2645        assert_ne!(
2646            perturbed_data, baseline,
2647            "control A FAILED: a DIFFERENT input token produced identical \
2648             logits, so realize_token is not responding to its inputs and no \
2649             verdict from this test means anything",
2650        );
2651
2652        // --- control B: is the SymEnv consulted AT ALL on this path? ---
2653        let with_off = s.offset_node().is_some();
2654        let mut env_bad_cached = fuel_ir::SymEnv::new();
2655        env_bad_cached
2656            .bind(s.cached_len_sym(), cached_len + 1)
2657            .expect("bind cached_len (wrong on purpose)");
2658        let perturbed_cached = s
2659            .realize_token(&dev, mk_data(), &env_bad_cached)
2660            .expect("realize with wrong cached_len");
2661
2662        // See the Llama twin for the full reasoning: on the device-offset path
2663        // the KV write offset rides a device-resident BUFFER, so cached_len_sym
2664        // is expected inert; on the SymEnv path it drives the write and MUST
2665        // move the output. Asserting the direction that matches the path keeps
2666        // this a control rather than a coin flip.
2667        if with_off {
2668            assert_eq!(
2669                perturbed_cached, baseline,
2670                "on the device-offset path the KV offset rides the offset \
2671                 BUFFER, so a wrong cached_len_sym should be inert — it moved \
2672                 the output, meaning the symbol IS load-bearing here",
2673            );
2674        } else {
2675            assert_ne!(
2676                perturbed_cached, baseline,
2677                "on the SymEnv path the KV offset rides cached_len_sym, so a \
2678                 wrong binding MUST move the output; it did not, so this test \
2679                 cannot detect referencedness and its verdict is vacuous",
2680            );
2681        }
2682
2683        assert_eq!(
2684            perturbed_attended, baseline,
2685            "attended_len_sym IS referenced by Phi's decode graph — the \
2686             'carried for API parity but never referenced' comment at \
2687             lazy.rs:12088 is FALSE, and sharing per_token_sym_env between \
2688             Llama and Phi is NOT the no-op the GAP-029 2b design assumes",
2689        );
2690
2691        // MEASURED 2026-08-12: Phi runs the **SymEnv path** on CPU
2692        // (`offset_node().is_none()`), so control B above took the `assert_ne`
2693        // branch and PASSED — a wrong `cached_len_sym` does move Phi's output.
2694        // The SymEnv is therefore demonstrably LIVE here, which is what makes
2695        // the `attended_len` verdict non-vacuous: it is inert while a sibling
2696        // symbol in the same env is load-bearing.
2697        //
2698        // So for Phi this is positive evidence, not a comment's word:
2699        // `attended_len_sym` is genuinely unreferenced, and adopting the shared
2700        // `per_token_sym_env` (which binds it) is a real no-op.
2701        eprintln!(
2702            "[gap-029 2b control] phi: offset_node.is_some()={with_off} \
2703             ({} path; SymEnv live={})",
2704            if with_off { "device-offset" } else { "SymEnv" },
2705            !with_off,
2706        );
2707    }
2708
2709    /// It ALSO drives the real production wrapper `generate_with_kv_context`
2710    /// and asserts the returned token sequence matches the reference.
2711    #[test]
2712    fn phi_generate_loop_persistent_byte_exact_and_plans_once() {
2713        let cfg = tiny_cfg();
2714        let model = PhiModel {
2715            config: cfg.clone(),
2716            weights: make_tiny_phi(&cfg, 7777),
2717        };
2718
2719        let prompt = [1_u32, 5, 9];
2720        let max_new = 5; // N ≥ 4 greedy decode tokens
2721        let max_seq_len = prompt.len() + max_new;
2722        let strategy = SamplingStrategy::Greedy;
2723
2724        // ---- D1 (rebuild) REFERENCE loop FIRST, in its own pass. Greedy
2725        // sampling open-coded with `sample_logits` so it is bit-identical to
2726        // the persistent loop's sampling. ----
2727        let dev1 = Device::cpu();
2728        let mut cache1 = KvCache::with_capacity(
2729            cfg.n_layers,
2730            cfg.n_heads,
2731            cfg.head_dim,
2732            max_seq_len,
2733            DType::F32,
2734            &dev1,
2735        )
2736        .expect("with_capacity d1");
2737        let mut ctx1 = InferenceContext::new(dev1);
2738        let mut rng1: u64 = 0;
2739        let mut ref_tokens: Vec<u32> = prompt.to_vec();
2740        let mut ref_step_logits: Vec<Vec<f32>> = Vec::with_capacity(max_new);
2741        let mut last1 = model
2742            .forward_with_kv_context(&prompt, &mut cache1, &mut ctx1)
2743            .expect("d1 prefill");
2744        for _ in 0..max_new {
2745            let next = sample_logits(&last1, strategy, &mut rng1);
2746            ref_tokens.push(next);
2747            last1 = model
2748                .forward_with_kv_context(&[next], &mut cache1, &mut ctx1)
2749                .expect("d1 decode");
2750            ref_step_logits.push(last1.clone());
2751        }
2752
2753        // ---- D2 (persistent) generate loop — mirrors the wired production
2754        // loop. Snapshot the thread-local optimize count around the WHOLE
2755        // loop (prefill + decode). ----
2756        let opt_before = fuel_tensor::pipelined_bridge::optimize_calls_thread_local();
2757
2758        let dev2 = Device::cpu();
2759        let mut cache2 = KvCache::with_capacity(
2760            cfg.n_layers,
2761            cfg.n_heads,
2762            cfg.head_dim,
2763            max_seq_len,
2764            DType::F32,
2765            &dev2,
2766        )
2767        .expect("with_capacity d2");
2768        let mut ctx2 = InferenceContext::new(dev2);
2769        let mut rng2: u64 = 0;
2770        let mut session: Option<fuel_tensor::inference_context::DecodeSession> = None;
2771        let mut d2_tokens: Vec<u32> = prompt.to_vec();
2772        let mut d2_step_logits: Vec<Vec<f32>> = Vec::with_capacity(max_new);
2773        let mut last2 = model
2774            .forward_with_kv_context_persistent(&prompt, &mut cache2, &mut ctx2, &mut session)
2775            .expect("d2 prefill");
2776        assert!(
2777            session.is_none(),
2778            "prefill (seq>1) must NOT build the held session"
2779        );
2780        for _ in 0..max_new {
2781            let next = sample_logits(&last2, strategy, &mut rng2);
2782            d2_tokens.push(next);
2783            last2 = model
2784                .forward_with_kv_context_persistent(&[next], &mut cache2, &mut ctx2, &mut session)
2785                .expect("d2 decode");
2786            d2_step_logits.push(last2.clone());
2787        }
2788
2789        let opt_after = fuel_tensor::pipelined_bridge::optimize_calls_thread_local();
2790
2791        // (a) Byte-identical token sequence over N greedy tokens.
2792        assert_eq!(
2793            d2_tokens, ref_tokens,
2794            "persistent generate loop must produce the byte-identical token sequence \
2795             as the D1 rebuild path over {max_new} greedy tokens",
2796        );
2797
2798        // (b) Each step's logits exactly == the D1 cached path (bit-exact).
2799        assert_eq!(d2_step_logits.len(), ref_step_logits.len());
2800        for (i, (d2, d1)) in d2_step_logits
2801            .iter()
2802            .zip(ref_step_logits.iter())
2803            .enumerate()
2804        {
2805            assert_eq!(
2806                d2, d1,
2807                "persistent decode step {i} logits must be byte-identical to the D1 cached path",
2808            );
2809        }
2810
2811        // (c) optimize bumped exactly twice (1 prefill fallback + 1
2812        // decode-session build) regardless of N.
2813        assert_eq!(
2814            opt_after - opt_before,
2815            2,
2816            "persistent generate must optimize EXACTLY twice (1 prefill fallback + 1 \
2817             decode-session build) regardless of N={max_new} decode tokens: \
2818             {opt_before} -> {opt_after}",
2819        );
2820
2821        assert!(session.is_some(), "held session survives the decode loop");
2822        assert_eq!(cache2.cached_len, max_seq_len);
2823        assert_eq!(cache1.cached_len, max_seq_len);
2824
2825        // ---- Drive the REAL production wrapper and confirm the wiring. ----
2826        let via_wrapper = model
2827            .generate_with_kv_context(&prompt, max_new, strategy, None, &Device::cpu(), DType::F32)
2828            .expect("generate_with_kv_context");
2829        assert_eq!(
2830            via_wrapper, ref_tokens,
2831            "generate_with_kv_context (wired to the persistent path) must produce the \
2832             byte-identical token sequence as the D1 reference",
2833        );
2834    }
2835
2836    /// Board item 86 (OverMind self-fork / Lightbulb KV-cache handoff design,
2837    /// `ROADMAP.md` "Research track: forked-agent KV-cache mechanics") — the
2838    /// one real gap Lightbulb's prototype found: does `KvCache::write_bytes`
2839    /// (host-supplied KV bytes, no Arc replacement) land where a HELD,
2840    /// already-built `DecodeSession` reads from, with no rebind and no
2841    /// rebuild? Confirms three things together, since any one alone would be
2842    /// a weaker, possibly-vacuous claim:
2843    ///
2844    /// 1. `alloc_id`/`device_location` are unchanged by the write (the
2845    ///    structural precondition for reuse — `write_bytes` takes `&self`, so
2846    ///    this is actually compile-time guaranteed; checked here anyway as a
2847    ///    regression guard).
2848    /// 2. `optimize_calls_thread_local` does NOT bump across the write (no
2849    ///    rebuild was triggered — a bump here would mean the write silently
2850    ///    forced the expensive D1 fallback despite `write_bytes` promising
2851    ///    otherwise).
2852    /// 3. The NEXT decode step's logits actually reflect the overwritten
2853    ///    value — the discriminating half. A primitive that satisfies (1) and
2854    ///    (2) but is a silent no-op (writes somewhere the plan never reads)
2855    ///    would pass both and still not deliver what Lightbulb needs; only
2856    ///    comparing against an un-overwritten reference run catches that.
2857    #[test]
2858    fn phi_persistent_plan_reads_a_write_bytes_overwrite_without_rebuilding() {
2859        let cfg = tiny_cfg();
2860        let model = PhiModel {
2861            config: cfg.clone(),
2862            weights: make_tiny_phi(&cfg, 7777),
2863        };
2864        let prompt = [1_u32, 5, 9];
2865        let decode_steps_before_overwrite = 2;
2866        let max_seq_len = prompt.len() + decode_steps_before_overwrite + 1;
2867        let strategy = SamplingStrategy::Greedy;
2868
2869        // Drive the persistent loop through `decode_steps_before_overwrite`
2870        // tokens, returning (cache, ctx, session, tokens, rng) so the caller
2871        // can either overwrite the cache or not before the final step.
2872        let run_to_overwrite_point = || {
2873            let device = Device::cpu();
2874            let mut cache = KvCache::with_capacity(
2875                cfg.n_layers,
2876                cfg.n_heads,
2877                cfg.head_dim,
2878                max_seq_len,
2879                DType::F32,
2880                &device,
2881            )
2882            .expect("with_capacity");
2883            let mut ctx = InferenceContext::new(device);
2884            let mut rng: u64 = 0;
2885            let mut session: Option<fuel_tensor::inference_context::DecodeSession> = None;
2886            let mut tokens: Vec<u32> = prompt.to_vec();
2887            let mut last = model
2888                .forward_with_kv_context_persistent(&prompt, &mut cache, &mut ctx, &mut session)
2889                .expect("prefill");
2890            for _ in 0..decode_steps_before_overwrite {
2891                let next = sample_logits(&last, strategy, &mut rng);
2892                tokens.push(next);
2893                last = model
2894                    .forward_with_kv_context_persistent(&[next], &mut cache, &mut ctx, &mut session)
2895                    .expect("decode (pre-overwrite)");
2896            }
2897            (cache, ctx, session, tokens, rng)
2898        };
2899
2900        // ---- Reference run: no overwrite, decode one more token normally. ----
2901        let (mut ref_cache, mut ref_ctx, mut ref_session, ref_tokens, _ref_rng) =
2902            run_to_overwrite_point();
2903        assert!(
2904            ref_session.is_some(),
2905            "the held DecodeSession must exist by now (built on the first decode token)",
2906        );
2907        let ref_next_logits = model
2908            .forward_with_kv_context_persistent(
2909                &[*ref_tokens.last().unwrap()],
2910                &mut ref_cache,
2911                &mut ref_ctx,
2912                &mut ref_session,
2913            )
2914            .expect("reference decode (no overwrite)");
2915
2916        // ---- Overwrite run: same setup, but write_bytes clobbers layer 0's
2917        // K at position 0 (the first prompt token — always inside the causal
2918        // window of every later token) just before the final decode step. ----
2919        let (mut ow_cache, mut ow_ctx, mut ow_session, ow_tokens, _ow_rng) =
2920            run_to_overwrite_point();
2921        assert_eq!(
2922            ow_tokens, ref_tokens,
2923            "both runs must reach an identical token stream before the overwrite \
2924             (same model, same seed, same prompt) — divergence must come ONLY from the write",
2925        );
2926
2927        let alloc_before = ow_cache.alloc_id();
2928        let loc_before = ow_cache.device_location();
2929        let opt_before_write = fuel_tensor::pipelined_bridge::optimize_calls_thread_local();
2930
2931        // A distinctive, non-zero payload — n=1 position, n_kv_heads*head_dim
2932        // f32 values, head-major (`[1, n_kv_heads, 1, head_dim]`).
2933        let payload: Vec<f32> = (0..(cfg.n_heads * cfg.head_dim))
2934            .map(|i| 9000.0 + i as f32)
2935            .collect();
2936        let payload_bytes: Vec<u8> = payload.iter().flat_map(|f| f.to_le_bytes()).collect();
2937        ow_cache
2938            .write_bytes(0, KvSlot::K, 0, 1, &payload_bytes, &Device::cpu())
2939            .expect("write_bytes");
2940
2941        assert_eq!(
2942            ow_cache.alloc_id(),
2943            alloc_before,
2944            "write_bytes must not re-mint alloc_id",
2945        );
2946        assert_eq!(
2947            ow_cache.device_location(),
2948            loc_before,
2949            "write_bytes must not clear device_location",
2950        );
2951
2952        // `write_bytes` realizes its OWN small throwaway Const->WriteSlice
2953        // graph (same shape as `DeviceKvPool::write_block_bytes`), which
2954        // costs exactly one `optimize_graph` call for that tiny graph — a
2955        // real, expected, cheap cost, not the thing under test. Measure the
2956        // DECODE STEP's own delta separately: THAT must be zero, or the write
2957        // forced the expensive held-plan rebuild.
2958        let opt_after_write = fuel_tensor::pipelined_bridge::optimize_calls_thread_local();
2959        assert_eq!(
2960            opt_after_write - opt_before_write,
2961            1,
2962            "write_bytes's own one-off realize should cost exactly one optimize call \
2963             for its throwaway graph (same shape as DeviceKvPool::write_block_bytes) — \
2964             a different count means this assumption needs re-checking",
2965        );
2966
2967        let ow_next_logits = model
2968            .forward_with_kv_context_persistent(
2969                &[*ow_tokens.last().unwrap()],
2970                &mut ow_cache,
2971                &mut ow_ctx,
2972                &mut ow_session,
2973            )
2974            .expect("overwrite-run decode (post-overwrite)");
2975
2976        let opt_after_decode = fuel_tensor::pipelined_bridge::optimize_calls_thread_local();
2977        assert_eq!(
2978            opt_after_decode, opt_after_write,
2979            "the decode step AFTER write_bytes must not trigger a plan rebuild — \
2980             optimize_calls_thread_local must be unchanged across it specifically \
2981             (write_bytes's own one-off optimize, measured above, is expected and excluded)",
2982        );
2983
2984        // THE DISCRIMINATING ASSERTION: the overwrite must actually have been
2985        // read. Equal logits here would mean write_bytes is a well-behaved
2986        // no-op that satisfies every OTHER assertion in this test while
2987        // delivering nothing Lightbulb's handoff design actually needs.
2988        assert_ne!(
2989            ow_next_logits, ref_next_logits,
2990            "the decode step after write_bytes must differ from the un-overwritten \
2991             reference — otherwise the held plan never read the write at all",
2992        );
2993    }
2994
2995    /// **WHICH Phi decode nodes land on the host?** — diagnostic for the
2996    /// capture rejection (`cross-device Op::Copy ... target Cpu`).
2997    ///
2998    /// Capture records CUDA operations issued to a stream. Host code is not a
2999    /// CUDA operation, so it cannot be recorded — and a cross-device `Copy` is
3000    /// the SYMPTOM of host compute sitting mid-graph, not the cause. This says
3001    /// which node(s) actually caused it, which decides the fix: a load-bearing
3002    /// host op means capture genuinely cannot apply; an accidentally-placed one
3003    /// means the fix is placement, and capture then works for free.
3004    ///
3005    /// Reports rather than asserts. The one thing it DOES assert is that
3006    /// placement was computed (`has_placements`) — an all-`None` dump would
3007    /// read as "nothing is on CUDA", a wrong answer wearing a null answer's
3008    /// clothes.
3009    #[test]
3010    #[cfg(feature = "cuda")]
3011    #[ignore = "requires a live CUDA device"]
3012    fn phi_decode_node_placement_report_cuda() {
3013        use std::collections::BTreeMap;
3014
3015        let cfg = tiny_cfg();
3016        let dev: Device = match fuel_cuda_backend::CudaDevice::new(0) {
3017            Ok(d) => d.into(),
3018            Err(e) => {
3019                return fuel_test_support::hardware::skip(
3020                    fuel_test_support::hardware::Hardware::Cuda,
3021                    fuel_test_support::hardware::Missing::device(format!(
3022                        "CudaDevice::new(0): {e:?}"
3023                    )),
3024                );
3025            }
3026        };
3027        let model = PhiModel {
3028            config: cfg.clone(),
3029            weights: make_tiny_phi(&cfg, 7),
3030        };
3031        let prompt = [1_u32, 2, 3];
3032        let max_seq_len = prompt.len() + 4;
3033
3034        let mut cache = KvCache::with_capacity(
3035            cfg.n_layers,
3036            cfg.n_heads,
3037            cfg.head_dim,
3038            max_seq_len,
3039            DType::F32,
3040            &dev,
3041        )
3042        .expect("with_capacity");
3043        let mut ctx = InferenceContext::new(dev.clone());
3044        let mut sess: Option<fuel_tensor::inference_context::DecodeSession> = None;
3045        model
3046            .forward_with_kv_context_persistent(&prompt, &mut cache, &mut ctx, &mut sess)
3047            .expect("prefill");
3048        model
3049            .forward_with_kv_context_persistent(&[4], &mut cache, &mut ctx, &mut sess)
3050            .expect("first decode token builds the held plan");
3051        let s = sess.as_ref().expect("held session");
3052
3053        let opt = s.optimized();
3054        assert!(
3055            opt.has_placements(),
3056            "placement NOT COMPUTED — every lookup would be None and the report below would describe a missing instrument, not the graph",
3057        );
3058
3059        let g = s.graph().read().expect("graph lock");
3060        let mut by_op: BTreeMap<String, BTreeMap<String, usize>> = BTreeMap::new();
3061        let mut host_nodes: Vec<String> = Vec::new();
3062        for i in 0..g.len() {
3063            let id = fuel_graph::NodeId(i);
3064            let op_name = match &g.node(id).op {
3065                fuel_graph::Op::Fused(fid, _) => format!("Fused({fid:?})"),
3066                other => format!("{other:?}")
3067                    .split(' ')
3068                    .next()
3069                    .unwrap_or("?")
3070                    .to_string(),
3071            };
3072            let place = match opt.placement_of(id) {
3073                Some(d) => format!("{d:?}"),
3074                None => "None".to_string(),
3075            };
3076            if place.starts_with("Cpu") {
3077                host_nodes.push(format!("#{i} {op_name}"));
3078            }
3079            *by_op.entry(op_name).or_default().entry(place).or_insert(0) += 1;
3080        }
3081
3082        println!(
3083            "
3084=== Phi decode plan: node placement (CUDA) ==="
3085        );
3086        println!("total nodes: {}", g.len());
3087        for (op, places) in &by_op {
3088            let r: Vec<String> = places.iter().map(|(d, n)| format!("{d}x{n}")).collect();
3089            println!("  {op:<34} {}", r.join("  "));
3090        }
3091        println!(
3092            "
3093--- HOST-PLACED NODES ({}) ---",
3094            host_nodes.len()
3095        );
3096        for h in &host_nodes {
3097            println!("    {h}");
3098        }
3099        println!(
3100            "--- END ---
3101"
3102        );
3103    }
3104
3105    /// **GPU gate for Phi's CapturedRun decode** — the mirror of
3106    /// `forward_with_kv_context_captured_matches_persistent` (Llama).
3107    ///
3108    /// Phi's capture shipped default-on verified only by `cargo check`, and its
3109    /// captured entry is `#[cfg(feature = "cuda")]` — so every CPU test in this
3110    /// crate passes with it arbitrarily broken. This closes that.
3111    ///
3112    /// **The specific failure it guards is silent.** Phi uses PARTIAL rotary:
3113    /// its RoPE tables are sized for `rotary_dim`, not `head_dim`. The replay
3114    /// path serialises those tables to raw bytes and H2Ds them into fixed
3115    /// capture buffers, so a wrong-but-well-formed table would write the WRONG
3116    /// VALUES into the RIGHT BUFFERS — correct shapes, no error, fluent wrong
3117    /// tokens. Byte-exactness against the persistent path is the only thing
3118    /// that catches it.
3119    ///
3120    /// Drives >= 4 decode tokens so all four driver branches run: token 1
3121    /// builds the held `DecodeSession`; token 2 builds the
3122    /// `CapturedDecodeSession` and returns its logits from an empty-`updates`
3123    /// warm replay; tokens 3-4 are pure `cuGraphLaunch` replays fed by freshly
3124    /// serialised per-token bytes — which is where a partial-rotary mistake
3125    /// would surface and nowhere earlier.
3126    ///
3127    /// Bit-exact, not epsilon: same plan, same kernels, same bytes.
3128    #[test]
3129    #[cfg(feature = "cuda")]
3130    #[ignore = "requires a live CUDA device"]
3131    fn phi_forward_with_kv_context_captured_matches_persistent() {
3132        let cfg = tiny_cfg();
3133
3134        let cuda = match fuel_cuda_backend::CudaDevice::new(0) {
3135            Ok(d) => d,
3136            Err(e) => {
3137                return fuel_test_support::hardware::skip(
3138                    fuel_test_support::hardware::Hardware::Cuda,
3139                    fuel_test_support::hardware::Missing::device(format!(
3140                        "CudaDevice::new(0): {e:?}"
3141                    )),
3142                );
3143            }
3144        };
3145        let dev: Device = cuda.into();
3146
3147        let prompt = [1_u32, 2, 3];
3148        let decode_tokens = [4_u32, 5, 6, 7]; // >= 4 so every branch runs
3149        let max_seq_len = prompt.len() + decode_tokens.len();
3150
3151        // Two models with byte-identical weights (same seed): one drives the
3152        // reference persistent path, one the captured path under test.
3153        let model_ref = PhiModel {
3154            config: cfg.clone(),
3155            weights: make_tiny_phi(&cfg, 7),
3156        };
3157        let model_cap = PhiModel {
3158            config: cfg.clone(),
3159            weights: make_tiny_phi(&cfg, 7),
3160        };
3161
3162        // --- Reference: forward_with_kv_context_persistent ---
3163        let mut cache_ref = KvCache::with_capacity(
3164            cfg.n_layers,
3165            cfg.n_heads,
3166            cfg.head_dim,
3167            max_seq_len,
3168            DType::F32,
3169            &dev,
3170        )
3171        .expect("with_capacity ref");
3172        let mut ctx_ref = InferenceContext::new(dev.clone());
3173        let mut sess_ref: Option<fuel_tensor::inference_context::DecodeSession> = None;
3174        model_ref
3175            .forward_with_kv_context_persistent(
3176                &prompt,
3177                &mut cache_ref,
3178                &mut ctx_ref,
3179                &mut sess_ref,
3180            )
3181            .expect("ref prefill");
3182        let mut ref_logits: Vec<Vec<f32>> = Vec::with_capacity(decode_tokens.len());
3183        for &tok in &decode_tokens {
3184            ref_logits.push(
3185                model_ref
3186                    .forward_with_kv_context_persistent(
3187                        &[tok],
3188                        &mut cache_ref,
3189                        &mut ctx_ref,
3190                        &mut sess_ref,
3191                    )
3192                    .expect("ref decode"),
3193            );
3194        }
3195
3196        // --- Under test: forward_with_kv_context_captured ---
3197        let mut cache_cap = KvCache::with_capacity(
3198            cfg.n_layers,
3199            cfg.n_heads,
3200            cfg.head_dim,
3201            max_seq_len,
3202            DType::F32,
3203            &dev,
3204        )
3205        .expect("with_capacity captured");
3206        let mut ctx_cap = InferenceContext::new(dev.clone());
3207        let mut sess_cap: Option<fuel_tensor::inference_context::DecodeSession> = None;
3208        let mut captured: Option<fuel_dispatch::pipelined::CapturedDecodeSession> = None;
3209        model_cap
3210            .forward_with_kv_context_captured(
3211                &prompt,
3212                &mut cache_cap,
3213                &mut ctx_cap,
3214                &mut sess_cap,
3215                &mut captured,
3216            )
3217            .expect("captured prefill");
3218        assert!(
3219            captured.is_none(),
3220            "prefill (seq != 1) must NOT build a capture"
3221        );
3222
3223        for (i, &tok) in decode_tokens.iter().enumerate() {
3224            let got = model_cap
3225                .forward_with_kv_context_captured(
3226                    &[tok],
3227                    &mut cache_cap,
3228                    &mut ctx_cap,
3229                    &mut sess_cap,
3230                    &mut captured,
3231                )
3232                .expect("captured decode");
3233
3234            assert_eq!(
3235                got, ref_logits[i],
3236                "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.",
3237            );
3238
3239            if i == 0 {
3240                assert!(sess_cap.is_some(), "token 1 builds the held session");
3241                assert!(captured.is_none(), "token 1 must NOT build the capture yet");
3242            }
3243        }
3244
3245        // Both caches advanced identically — the fallback path must bump the
3246        // cache exactly as the captured path would.
3247        assert_eq!(cache_cap.cached_len, max_seq_len);
3248        assert_eq!(cache_ref.cached_len, max_seq_len);
3249
3250        // --- Report whether capture actually formed (state, not verdict) ---
3251        //
3252        // Byte-exactness above is the CLAIM and is asserted unconditionally.
3253        // Whether the capture forms is a property of the model's GRAPH, and
3254        // Phi's is currently NOT capturable: its decode plan carries 3 fused
3255        // `LayerNormLastDim` and 4 fused `ROPE` nodes with no CUDA binding, so
3256        // they land on the host and force the cross-device `Op::Copy` that
3257        // `capture_decode` rejects (measured — see
3258        // `phi_decode_node_placement_report_cuda`). Llama captures because its
3259        // rope runs DECOMPOSED on CUDA instead of as a fused node.
3260        //
3261        // So this asserts the INVARIANT that holds either way — capture is an
3262        // optimization, and declining it must never change the answer — and
3263        // reports which branch ran. If a future registration puts LayerNorm and
3264        // ROPE on CUDA, capture will start forming and this test keeps passing
3265        // while the line below changes: a state report, not a frozen
3266        // expectation.
3267        if captured.is_some() {
3268            println!("Phi capture FORMED — the decode graph is fully CUDA-resident");
3269        } else {
3270            println!(
3271                "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."
3272            );
3273        }
3274    }
3275}
3276
3277// GAP-347 PR 4 (bail! consolidation): before/after test for this consumer
3278// crate family. `fuel_ir::bail!` is now `fuel_ir::bail!` re-exported
3279// (the fuel-core-local `macro_rules!` duplicate was deleted), which can
3280// change `$crate::Error` resolution silently across a macro-path swap.
3281// This proves the error text/variant this crate actually relies on
3282// (src/lib.rs's `fuel_ir::bail!`) is unchanged.
3283#[cfg(test)]
3284mod bail_consolidation_tests {
3285    fn always_bails() -> fuel_ir::error::Result<()> {
3286        fuel_ir::bail!("deliberate failure for the fuel-core dissolution bail! consolidation test");
3287        #[allow(unreachable_code)]
3288        Ok(())
3289    }
3290
3291    #[test]
3292    fn fuel_core_bail_still_produces_a_typed_err_with_the_message() {
3293        let err = always_bails().expect_err("bail! must produce an Err, never panic");
3294        assert!(err.to_string().contains("deliberate failure"));
3295    }
3296}