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