1use 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 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#[derive(Debug, Clone, PartialEq)]
78pub struct PhiConfig {
79 pub vocab_size: usize,
80 pub dim: usize, pub n_layers: usize,
82 pub n_heads: usize,
83 pub head_dim: usize,
84 pub ffn_dim: usize, pub layer_norm_eps: f64,
86 pub rope_base: f64,
87 pub partial_rotary_factor: f64,
88 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#[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 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 pub fn from_hf_json_str(json: &str) -> fuel_ir::error::Result<Self> {
183 PhiConfigRaw::from_json_str(json)?.resolve()
184 }
185}
186
187#[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 qkv: WeightStorage,
211 qkv_bias: Arc<[f32]>,
213 },
214}
215
216#[derive(Debug, Clone)]
218pub struct PhiLayerWeights {
219 pub attn_qkv: PhiQkv,
220 pub attn_dense: WeightStorage,
222 pub attn_dense_bias: Arc<[f32]>,
223 pub mlp_fc1: WeightStorage, pub mlp_fc1_bias: Arc<[f32]>,
225 pub mlp_fc2: WeightStorage, pub mlp_fc2_bias: Arc<[f32]>,
227 pub norm_gain: Arc<[f32]>,
229 pub norm_bias: Arc<[f32]>,
230}
231
232#[derive(Debug, Clone)]
233pub struct PhiWeights {
234 pub instance: fuel_tensor::decode_shape::ModelInstanceId,
236 pub token_embedding: Arc<[f32]>, pub layers: Vec<PhiLayerWeights>,
238 pub final_norm_gain: Arc<[f32]>,
239 pub final_norm_bias: Arc<[f32]>,
240 pub output: WeightStorage, 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 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 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; 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 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 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 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 let write_ranges = vec![
380 (0, batch),
381 (0, cfg.n_heads),
382 (0, seq), (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 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 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 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 x.add(&attn_out)?.add(&mlp_out)
430 }
431
432 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 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 let (rope_cos, rope_sin) =
505 h.rope_tables_const(cfg.rope_base, cached_len, seq, cfg.rotary_dim);
506
507 let cached_len_sym = fuel_ir::SymId(0);
513
514 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 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 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 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 for id in bound_node_ids {
599 ctx.remove(id);
600 }
601
602 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 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 if seq != 1 {
644 self.drop_decode_session(session, ctx);
645 return self.forward_with_kv_context(tokens, cache, ctx);
646 }
647
648 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 self.build_and_realize_first_decode_token(tokens, cache, ctx, session)
671 }
672 Some(_) => {
673 let res = self.rebind_and_realize_prebuilt(tokens, cache, &*ctx, &*session);
675 match res {
676 Ok(logits) => Ok(logits),
677 Err(fuel_ir::error::Error::TopologyChanged { .. }) => {
678 self.drop_decode_session(session, ctx);
679 self.forward_with_kv_context(tokens, cache, ctx)
680 }
681 Err(e) => Err(e),
682 }
683 }
684 }
685 }
686
687 fn build_and_realize_first_decode_token(
692 &self,
693 tokens: &[u32],
694 cache: &mut KvCache,
695 ctx: &mut InferenceContext,
696 session: &mut Option<fuel_tensor::inference_context::DecodeSession>,
697 ) -> fuel_ir::error::Result<Vec<f32>> {
698 let cfg = &self.config;
699 let weights = &self.weights;
700 let seq = tokens.len();
701 let batch = 1;
702 let cached_len = cache.cached_len;
703 let max_seq_len = cache.max_seq_len.ok_or_else(|| {
704 fuel_ir::Error::Msg(
705 "PhiModel::forward_with_kv_context_persistent: cache built via with_dims \
706 (no pre-allocated buffers); use KvCache::with_capacity"
707 .to_string(),
708 )
709 .bt()
710 })?;
711 if cache.n_layers() != cfg.n_layers {
712 return Err(fuel_ir::Error::Msg(format!(
713 "PhiModel::forward_with_kv_context_persistent: cache n_layers {} != model {}",
714 cache.n_layers(),
715 cfg.n_layers,
716 ))
717 .bt());
718 }
719 if cached_len + seq > max_seq_len {
720 return Err(fuel_ir::Error::Msg(format!(
721 "PhiModel::forward_with_kv_context_persistent: cached_len ({cached_len}) + \
722 seq ({seq}) > max_seq_len ({max_seq_len})",
723 ))
724 .bt());
725 }
726 let cache_dtype = cache.dtype.unwrap_or(DType::F32);
727
728 let embed = Tensor::from_f32(
731 weights.token_embedding.clone(),
732 Shape::from_dims(&[cfg.vocab_size, cfg.dim]),
733 &Device::cpu(),
734 )?;
735 let token_ids = embed.const_placeholder_like(Shape::from_dims(&[seq]), DType::U32);
736 let token_ids_node = token_ids.graph_tensor().id();
737 let mut h = embed
738 .index_select(0, &token_ids)?
739 .reshape(Shape::from_dims(&[batch, seq, cfg.dim]))?;
740
741 let rope_shape = Shape::from_dims(&[seq, cfg.rotary_dim]);
744 let rope_cos = h.const_placeholder_like(rope_shape.clone(), DType::F32);
745 let rope_sin = h.const_placeholder_like(rope_shape, DType::F32);
746 let rope_cos_node = rope_cos.graph_tensor().id();
747 let rope_sin_node = rope_sin.graph_tensor().id();
748
749 let mask =
751 h.const_placeholder_like(Shape::from_dims(&[1, 1, seq, max_seq_len]), DType::F32);
752 let mask_node = mask.graph_tensor().id();
753
754 let cached_len_sym = fuel_ir::SymId(0);
755 let cache_shape = Shape::from_dims(&[batch, cfg.n_heads, max_seq_len, cfg.head_dim]);
757
758 let mut kv_nodes: Vec<(fuel_graph::NodeId, fuel_graph::NodeId)> =
761 Vec::with_capacity(cfg.n_layers);
762 for (li, layer_weights) in weights.layers.iter().enumerate() {
763 let k_arc = cache.slot_storage(li, KvSlot::K).ok_or_else(|| {
764 fuel_ir::Error::Msg(format!(
765 "PhiModel::forward_with_kv_context_persistent: cache layer {li} has no K slot",
766 ))
767 .bt()
768 })?;
769 let v_arc = cache.slot_storage(li, KvSlot::V).ok_or_else(|| {
770 fuel_ir::Error::Msg(format!(
771 "PhiModel::forward_with_kv_context_persistent: cache layer {li} has no V slot",
772 ))
773 .bt()
774 })?;
775 let k_cache_node = h.const_placeholder_like(cache_shape.clone(), cache_dtype);
776 let v_cache_node = h.const_placeholder_like(cache_shape.clone(), cache_dtype);
777 let k_id = k_cache_node.graph_tensor().id();
778 let v_id = v_cache_node.graph_tensor().id();
779 ctx.insert(k_id, k_arc);
780 ctx.insert(v_id, v_arc);
781 kv_nodes.push((k_id, v_id));
782
783 h = self.apply_layer_with_kv_writes(
784 &h,
785 layer_weights,
786 &k_cache_node,
787 &v_cache_node,
788 cached_len_sym,
789 &rope_cos,
790 &rope_sin,
791 &mask,
792 )?;
793 }
794
795 let h_norm = h.layer_norm_affine(
797 Arc::clone(&weights.final_norm_gain),
798 Arc::clone(&weights.final_norm_bias),
799 cfg.layer_norm_eps,
800 )?;
801 let logits_no_bias = weights
802 .output
803 .apply_linear(&h_norm, cfg.dim, cfg.vocab_size)?;
804 let logits = match &weights.output_bias {
805 Some(b) => {
806 let b_t =
807 h_norm.const_f32_like(Arc::clone(b), Shape::from_dims(&[cfg.vocab_size]))?;
808 logits_no_bias.broadcast_add(&b_t)?
809 }
810 None => logits_no_bias,
811 };
812 let last_pos = seq - 1;
813 let logits_root = logits
814 .slice(1, last_pos, 1)?
815 .reshape(Shape::from_dims(&[cfg.vocab_size]))?;
816 let logits_node = logits_root.graph_tensor().id();
817 let graph = logits_root.graph_tensor().graph().clone();
818
819 let data =
826 self.build_token_rope_mask_arcs(ctx.device(), cached_len, tokens, max_seq_len)?;
827 ctx.insert(token_ids_node, Arc::clone(&data.token_ids));
828 ctx.insert(rope_cos_node, Arc::clone(&data.rope_cos));
829 ctx.insert(rope_sin_node, Arc::clone(&data.rope_sin));
830 ctx.insert(mask_node, Arc::clone(&data.mask));
831
832 let mut sym_env = fuel_ir::SymEnv::new();
833 sym_env.bind(cached_len_sym, cached_len)?;
834
835 let (effective_target, optimized, base_cache, logits_vec) =
836 ctx.prebuild_optimized_capturing_as_with_env::<f32>(&graph, logits_node, &sym_env)?;
837
838 ctx.remove(token_ids_node);
841 ctx.remove(rope_cos_node);
842 ctx.remove(rope_sin_node);
843 ctx.remove(mask_node);
844 for (k, v) in &kv_nodes {
845 ctx.remove(*k);
846 ctx.remove(*v);
847 }
848
849 *session = Some(fuel_tensor::inference_context::DecodeSession::new(
850 graph,
851 optimized,
852 effective_target,
853 logits_node,
854 token_ids_node,
855 rope_cos_node,
856 rope_sin_node,
857 mask_node,
858 kv_nodes,
859 None,
862 cached_len_sym,
863 fuel_ir::SymId(1),
868 base_cache,
869 seq,
870 max_seq_len,
871 cfg.n_layers,
872 cache_dtype,
873 self.decode_shape_key(),
874 cache,
877 ));
878
879 cache.cached_len += seq;
881 for li in 0..cfg.n_layers {
882 cache.bump_version(li, KvSlot::K);
883 cache.bump_version(li, KvSlot::V);
884 }
885 Ok(logits_vec)
886 }
887
888 fn rebind_and_realize_prebuilt(
894 &self,
895 tokens: &[u32],
896 cache: &mut KvCache,
897 ctx: &InferenceContext,
898 session: &Option<fuel_tensor::inference_context::DecodeSession>,
899 ) -> fuel_ir::error::Result<Vec<f32>> {
900 fuel_tensor::persistent_decode::rebind_and_realize_prebuilt(
908 self, tokens, cache, ctx, session, None,
909 )
910 }
911
912 fn compute_token_rope_mask_host_data(
932 &self,
933 cached_len: usize,
934 tokens: &[u32],
935 max_seq_len: usize,
936 ) -> fuel_ir::error::Result<TokenDataHost> {
937 let cfg = &self.config;
938 let seq = tokens.len();
939 let (cos_data, sin_data) =
941 fuel_graph::build_rope_tables(cfg.rope_base, cached_len, seq, cfg.rotary_dim);
942 Ok(TokenDataHost {
943 token_ids: fuel_ir::HostBuffer::U32(tokens.to_vec()),
944 rope_cos: fuel_ir::HostBuffer::F32(cos_data),
945 rope_sin: fuel_ir::HostBuffer::F32(sin_data),
946 mask: fuel_ir::HostBuffer::F32(build_decode_causal_mask(cached_len, seq, max_seq_len)),
947 offset: None,
952 })
953 }
954
955 fn build_token_rope_mask_arcs(
956 &self,
957 device: &Device,
958 cached_len: usize,
959 tokens: &[u32],
960 max_seq_len: usize,
961 ) -> fuel_ir::error::Result<fuel_tensor::inference_context::DecodeTokenData> {
962 let host = self.compute_token_rope_mask_host_data(cached_len, tokens, max_seq_len)?;
963 let upload = fuel_tensor::pipelined_bridge::upload_host_buffer_to_device;
964 Ok(fuel_tensor::inference_context::DecodeTokenData {
965 token_ids: upload(device, host.token_ids)?,
966 rope_cos: upload(device, host.rope_cos)?,
967 rope_sin: upload(device, host.rope_sin)?,
968 mask: upload(device, host.mask)?,
969 offset: None,
970 })
971 }
972
973 #[cfg(feature = "cuda")]
980 fn build_token_rope_mask_bytes(
981 &self,
982 cached_len: usize,
983 tokens: &[u32],
984 max_seq_len: usize,
985 ) -> fuel_ir::error::Result<TokenDataBytes> {
986 let host = self.compute_token_rope_mask_host_data(cached_len, tokens, max_seq_len)?;
987 Ok(TokenDataBytes {
988 token_ids: fuel_tensor::pipelined_bridge::host_buffer_to_bytes(&host.token_ids),
989 rope_cos: fuel_tensor::pipelined_bridge::host_buffer_to_bytes(&host.rope_cos),
990 rope_sin: fuel_tensor::pipelined_bridge::host_buffer_to_bytes(&host.rope_sin),
991 mask: fuel_tensor::pipelined_bridge::host_buffer_to_bytes(&host.mask),
992 offset: None,
993 })
994 }
995
996 #[cfg(feature = "cuda")]
1025 pub fn forward_with_kv_context_captured(
1026 &self,
1027 tokens: &[u32],
1028 cache: &mut KvCache,
1029 ctx: &mut InferenceContext,
1030 session: &mut Option<fuel_tensor::inference_context::DecodeSession>,
1031 captured: &mut Option<fuel_dispatch::pipelined::CapturedDecodeSession>,
1032 ) -> fuel_ir::error::Result<Vec<f32>> {
1033 let cfg = &self.config;
1034 let seq = tokens.len();
1035
1036 if seq != 1 {
1038 *captured = None;
1039 self.drop_decode_session(session, ctx);
1040 return self.forward_with_kv_context(tokens, cache, ctx);
1041 }
1042
1043 invalidate_decode_pair_if_stale(
1045 session,
1046 captured,
1047 ctx,
1048 seq,
1049 cache.max_seq_len,
1050 cache.dtype.unwrap_or(DType::F32),
1051 cfg.n_layers,
1052 self.decode_shape_key(),
1053 cache,
1054 |s, ctx| self.drop_decode_session(s, ctx),
1055 );
1056
1057 if session.is_none() {
1059 *captured = None;
1060 return self.build_and_realize_first_decode_token(tokens, cache, ctx, session);
1061 }
1062
1063 let cached_len = cache.cached_len;
1064
1065 if captured.is_none() {
1067 let device = ctx.device().clone();
1068 let s = session.as_ref().expect("session is Some (checked above)");
1069
1070 let data =
1071 self.build_token_rope_mask_arcs(&device, cached_len, tokens, s.max_seq_len())?;
1072
1073 let mut merged_cache: fuel_dispatch::pipelined::StorageCache = s.base_cache().clone();
1074 merged_cache.insert(s.token_ids_node(), Arc::clone(&data.token_ids));
1075 merged_cache.insert(s.rope_cos_node(), Arc::clone(&data.rope_cos));
1076 merged_cache.insert(s.rope_sin_node(), Arc::clone(&data.rope_sin));
1077 merged_cache.insert(s.mask_node(), Arc::clone(&data.mask));
1078 let per_token_node_ids: Vec<fuel_graph::NodeId> = vec![
1079 s.token_ids_node(),
1080 s.rope_cos_node(),
1081 s.rope_sin_node(),
1082 s.mask_node(),
1083 ];
1084
1085 let sym_env = s.per_token_sym_env(cached_len)?;
1086 let cd_session = match fuel_dispatch::pipelined::CapturedDecodeSession::capture(
1113 s.graph().clone(),
1114 s.logits_node(),
1115 merged_cache,
1116 &per_token_node_ids,
1117 sym_env,
1118 ) {
1119 Ok(cd) => cd,
1120 Err(_) => {
1121 let res = self.rebind_and_realize_prebuilt(tokens, cache, &*ctx, &*session);
1122 return res;
1123 }
1124 };
1125
1126 let output = cd_session.replay_token(&[])?;
1128 let logits = captured_output_to_f32(&output)?;
1129 *captured = Some(cd_session);
1130
1131 cache.cached_len += seq;
1132 for li in 0..cfg.n_layers {
1133 cache.bump_version(li, KvSlot::K);
1134 cache.bump_version(li, KvSlot::V);
1135 }
1136 return Ok(logits);
1137 }
1138
1139 let cap = captured.as_ref().expect("captured is Some (checked above)");
1141 let s = session
1142 .as_ref()
1143 .expect("session is Some whenever captured is Some");
1144
1145 let bytes = self.build_token_rope_mask_bytes(cached_len, tokens, s.max_seq_len())?;
1146 let updates: Vec<(fuel_graph::NodeId, &[u8])> = vec![
1147 (s.token_ids_node(), bytes.token_ids.as_slice()),
1148 (s.rope_cos_node(), bytes.rope_cos.as_slice()),
1149 (s.rope_sin_node(), bytes.rope_sin.as_slice()),
1150 (s.mask_node(), bytes.mask.as_slice()),
1151 ];
1152
1153 let output = cap.replay_token(&updates)?;
1154 let logits = captured_output_to_f32(&output)?;
1155
1156 cache.cached_len += seq;
1157 for li in 0..cfg.n_layers {
1158 cache.bump_version(li, KvSlot::K);
1159 cache.bump_version(li, KvSlot::V);
1160 }
1161 Ok(logits)
1162 }
1163
1164 fn drop_decode_session(
1167 &self,
1168 session: &mut Option<fuel_tensor::inference_context::DecodeSession>,
1169 ctx: &mut InferenceContext,
1170 ) {
1171 if let Some(s) = session.take() {
1172 ctx.remove(s.token_ids_node());
1173 ctx.remove(s.rope_cos_node());
1174 ctx.remove(s.rope_sin_node());
1175 ctx.remove(s.mask_node());
1176 for (k, v) in s.kv_nodes() {
1177 ctx.remove(*k);
1178 ctx.remove(*v);
1179 }
1180 }
1181 }
1182
1183 pub fn generate_streaming_with_kv_context(
1189 &self,
1190 prompt_tokens: &[u32],
1191 max_new_tokens: usize,
1192 strategy: SamplingStrategy,
1193 eos_id: Option<u32>,
1194 device: &Device,
1195 dtype: DType,
1196 mut on_token: impl FnMut(u32),
1197 ) -> fuel_ir::error::Result<Vec<u32>> {
1198 let cfg = &self.config;
1199 if prompt_tokens.is_empty() {
1200 return Err(fuel_ir::Error::Msg(
1201 "PhiModel::generate_streaming_with_kv_context: prompt is empty".to_string(),
1202 )
1203 .bt());
1204 }
1205 let mut tokens: Vec<u32> = prompt_tokens.to_vec();
1206 let mut rng_state: u64 = match strategy {
1207 SamplingStrategy::Temperature { seed, .. } => seed,
1208 _ => 0,
1209 };
1210
1211 let max_seq_len = prompt_tokens.len() + max_new_tokens;
1212 let mut cache = KvCache::with_capacity(
1213 cfg.n_layers,
1214 cfg.n_heads,
1215 cfg.head_dim,
1216 max_seq_len,
1217 dtype,
1218 device,
1219 )?;
1220 let mut ctx = InferenceContext::new(device.clone());
1221
1222 let mut session: Option<fuel_tensor::inference_context::DecodeSession> = None;
1230
1231 #[cfg(feature = "cuda")]
1242 let mut captured: Option<fuel_dispatch::pipelined::CapturedDecodeSession> = None;
1243
1244 let mut last_logits = self.forward_with_kv_context_persistent(
1247 prompt_tokens,
1248 &mut cache,
1249 &mut ctx,
1250 &mut session,
1251 )?;
1252
1253 for _ in 0..max_new_tokens {
1255 let next = sample_logits(&last_logits, strategy, &mut rng_state);
1256 tokens.push(next);
1257 on_token(next);
1258 if let Some(eos) = eos_id
1259 && next == eos
1260 {
1261 break;
1262 }
1263 #[cfg(feature = "cuda")]
1264 {
1265 last_logits = self.forward_with_kv_context_captured(
1266 &[next],
1267 &mut cache,
1268 &mut ctx,
1269 &mut session,
1270 &mut captured,
1271 )?;
1272 }
1273 #[cfg(not(feature = "cuda"))]
1274 {
1275 last_logits = self.forward_with_kv_context_persistent(
1276 &[next],
1277 &mut cache,
1278 &mut ctx,
1279 &mut session,
1280 )?;
1281 }
1282 }
1283 Ok(tokens)
1284 }
1285
1286 pub fn generate_with_kv_context(
1289 &self,
1290 prompt_tokens: &[u32],
1291 max_new_tokens: usize,
1292 strategy: SamplingStrategy,
1293 eos_id: Option<u32>,
1294 device: &Device,
1295 dtype: DType,
1296 ) -> fuel_ir::error::Result<Vec<u32>> {
1297 self.generate_streaming_with_kv_context(
1298 prompt_tokens,
1299 max_new_tokens,
1300 strategy,
1301 eos_id,
1302 device,
1303 dtype,
1304 |_| {},
1305 )
1306 }
1307
1308 pub fn from_hub(repo_id: &str) -> fuel_ir::error::Result<Self> {
1310 let api = hf_hub::api::sync::Api::new()
1311 .map_err(|e| fuel_ir::error::Error::Msg(format!("hf-hub api init: {e}")))?;
1312 let repo = api.model(repo_id.to_string());
1313
1314 let config_path = repo
1315 .get("config.json")
1316 .map_err(|e| fuel_ir::error::Error::Msg(format!("hf-hub config.json: {e}")))?;
1317 let config_str = std::fs::read_to_string(&config_path)?;
1318 let config = PhiConfig::from_hf_json_str(&config_str)?;
1319
1320 let weight_paths: Vec<std::path::PathBuf> = match repo.get("model.safetensors.index.json") {
1321 Ok(index_path) => {
1322 let index_str = std::fs::read_to_string(&index_path)?;
1323 let index: serde_json::Value = serde_json::from_str(&index_str)
1324 .map_err(|e| fuel_ir::error::Error::Msg(format!("parsing index: {e}")))?;
1325 let weight_map = index
1326 .get("weight_map")
1327 .and_then(|x| x.as_object())
1328 .ok_or_else(|| {
1329 fuel_ir::error::Error::Msg("index.json: missing weight_map".into())
1330 })?;
1331 let mut unique = std::collections::HashSet::new();
1332 for v in weight_map.values() {
1333 if let Some(s) = v.as_str() {
1334 unique.insert(s.to_string());
1335 }
1336 }
1337 let mut paths: Vec<std::path::PathBuf> = Vec::new();
1338 for shard_name in unique {
1339 let p = repo.get(&shard_name).map_err(|e| {
1340 fuel_ir::error::Error::Msg(format!("hf-hub {shard_name}: {e}"))
1341 })?;
1342 paths.push(p);
1343 }
1344 paths
1345 }
1346 Err(_) => {
1347 let p = repo.get("model.safetensors").map_err(|e| {
1348 fuel_ir::error::Error::Msg(format!("hf-hub model.safetensors: {e}"))
1349 })?;
1350 vec![p]
1351 }
1352 };
1353
1354 let st = unsafe { fuel_loaders::safetensors::MmapedSafetensors::multi(&weight_paths) }?;
1355 let weights = PhiWeights::load_from_mmapped(&st, &config)?;
1356 Ok(PhiModel { config, weights })
1357 }
1358
1359 pub fn from_gguf<P: AsRef<std::path::Path>>(path: P) -> fuel_ir::error::Result<Self> {
1364 use fuel_loaders::quantized::gguf_mmap::MmapedContent;
1365 let mc = MmapedContent::from_path(&path)?;
1366 let meta = mc.metadata();
1367 let get_u32 = |k: &str| -> fuel_ir::error::Result<u32> {
1368 meta.get(k)
1369 .ok_or_else(|| fuel_ir::error::Error::Msg(format!("gguf metadata: missing {k:?}")))?
1370 .to_u32()
1371 .map_err(|e| fuel_ir::error::Error::Msg(format!("gguf metadata {k:?}: {e:?}")))
1372 };
1373 let get_f32 = |k: &str| -> fuel_ir::error::Result<f32> {
1374 meta.get(k)
1375 .ok_or_else(|| fuel_ir::error::Error::Msg(format!("gguf metadata: missing {k:?}")))?
1376 .to_f32()
1377 .map_err(|e| fuel_ir::error::Error::Msg(format!("gguf metadata {k:?}: {e:?}")))
1378 };
1379 let dim = get_u32("phi2.embedding_length")? as usize;
1381 let n_layers = get_u32("phi2.block_count")? as usize;
1382 let n_heads = get_u32("phi2.attention.head_count")? as usize;
1383 let ffn_dim = get_u32("phi2.feed_forward_length")? as usize;
1384 let head_dim = dim / n_heads;
1385 let layer_norm_eps = get_f32("phi2.attention.layer_norm_epsilon").unwrap_or(1e-5) as f64;
1386 let rope_base = get_f32("phi2.rope.freq_base").unwrap_or(10_000.0) as f64;
1387 let rotary_dim = get_u32("phi2.rope.dimension_count").unwrap_or(32) as usize;
1388 let partial_rotary_factor = rotary_dim as f64 / head_dim as f64;
1389
1390 let vocab_size = mc
1395 .content()
1396 .tensor_infos
1397 .get("token_embd.weight")
1398 .ok_or_else(|| fuel_ir::error::Error::Msg("gguf: missing token_embd.weight".into()))?
1399 .shape
1400 .dims()[0];
1401
1402 let config = PhiConfig {
1403 vocab_size,
1404 dim,
1405 n_layers,
1406 n_heads,
1407 head_dim,
1408 ffn_dim,
1409 layer_norm_eps,
1410 rope_base,
1411 partial_rotary_factor,
1412 rotary_dim,
1413 tie_word_embeddings: false,
1414 };
1415
1416 drop(mc);
1421 let weights = PhiWeights::load_from_gguf(&path, &config)?;
1422 Ok(PhiModel { config, weights })
1423 }
1424}
1425
1426impl PhiWeights {
1427 pub fn load_from_mmapped(
1428 st: &fuel_loaders::safetensors::MmapedSafetensors,
1429 cfg: &PhiConfig,
1430 ) -> fuel_ir::error::Result<Self> {
1431 let kv_dim = cfg.n_heads * cfg.head_dim;
1432 let token_embedding = load_tensor_as_f32(st, "model.embed_tokens.weight")?;
1433 if token_embedding.len() != cfg.vocab_size * cfg.dim {
1434 fuel_ir::bail!(
1435 "embed_tokens: {} elements, expected {}",
1436 token_embedding.len(),
1437 cfg.vocab_size * cfg.dim,
1438 );
1439 }
1440
1441 let mut layers: Vec<PhiLayerWeights> = Vec::with_capacity(cfg.n_layers);
1442 for i in 0..cfg.n_layers {
1443 let attn_q = load_transposed_matrix_preserve_dtype(
1446 st,
1447 &format!("model.layers.{i}.self_attn.q_proj.weight"),
1448 cfg.dim,
1449 cfg.dim,
1450 )?;
1451 let attn_k = load_transposed_matrix_preserve_dtype(
1452 st,
1453 &format!("model.layers.{i}.self_attn.k_proj.weight"),
1454 kv_dim,
1455 cfg.dim,
1456 )?;
1457 let attn_v = load_transposed_matrix_preserve_dtype(
1458 st,
1459 &format!("model.layers.{i}.self_attn.v_proj.weight"),
1460 kv_dim,
1461 cfg.dim,
1462 )?;
1463 let attn_dense = load_transposed_matrix_preserve_dtype(
1464 st,
1465 &format!("model.layers.{i}.self_attn.dense.weight"),
1466 cfg.dim,
1467 cfg.dim,
1468 )?;
1469 let mlp_fc1 = load_transposed_matrix_preserve_dtype(
1470 st,
1471 &format!("model.layers.{i}.mlp.fc1.weight"),
1472 cfg.ffn_dim,
1473 cfg.dim,
1474 )?;
1475 let mlp_fc2 = load_transposed_matrix_preserve_dtype(
1476 st,
1477 &format!("model.layers.{i}.mlp.fc2.weight"),
1478 cfg.dim,
1479 cfg.ffn_dim,
1480 )?;
1481
1482 let attn_q_bias = Arc::from(load_tensor_as_f32(
1483 st,
1484 &format!("model.layers.{i}.self_attn.q_proj.bias"),
1485 )?);
1486 let attn_k_bias = Arc::from(load_tensor_as_f32(
1487 st,
1488 &format!("model.layers.{i}.self_attn.k_proj.bias"),
1489 )?);
1490 let attn_v_bias = Arc::from(load_tensor_as_f32(
1491 st,
1492 &format!("model.layers.{i}.self_attn.v_proj.bias"),
1493 )?);
1494 let attn_dense_bias = Arc::from(load_tensor_as_f32(
1495 st,
1496 &format!("model.layers.{i}.self_attn.dense.bias"),
1497 )?);
1498 let mlp_fc1_bias = Arc::from(load_tensor_as_f32(
1499 st,
1500 &format!("model.layers.{i}.mlp.fc1.bias"),
1501 )?);
1502 let mlp_fc2_bias = Arc::from(load_tensor_as_f32(
1503 st,
1504 &format!("model.layers.{i}.mlp.fc2.bias"),
1505 )?);
1506
1507 let norm_gain = Arc::from(load_tensor_as_f32(
1509 st,
1510 &format!("model.layers.{i}.input_layernorm.weight"),
1511 )?);
1512 let norm_bias = Arc::from(load_tensor_as_f32(
1513 st,
1514 &format!("model.layers.{i}.input_layernorm.bias"),
1515 )?);
1516
1517 layers.push(PhiLayerWeights {
1518 attn_qkv: PhiQkv::Split {
1519 q: attn_q,
1520 q_bias: attn_q_bias,
1521 k: attn_k,
1522 k_bias: attn_k_bias,
1523 v: attn_v,
1524 v_bias: attn_v_bias,
1525 },
1526 attn_dense,
1527 attn_dense_bias,
1528 mlp_fc1,
1529 mlp_fc1_bias,
1530 mlp_fc2,
1531 mlp_fc2_bias,
1532 norm_gain,
1533 norm_bias,
1534 });
1535 }
1536
1537 let final_norm_gain = Arc::from(load_tensor_as_f32(st, "model.final_layernorm.weight")?);
1538 let final_norm_bias = Arc::from(load_tensor_as_f32(st, "model.final_layernorm.bias")?);
1539
1540 let output: WeightStorage = if cfg.tie_word_embeddings {
1541 let mut transposed = vec![0.0_f32; cfg.dim * cfg.vocab_size];
1543 for i in 0..cfg.vocab_size {
1544 for j in 0..cfg.dim {
1545 transposed[j * cfg.vocab_size + i] = token_embedding[i * cfg.dim + j];
1546 }
1547 }
1548 WeightStorage::F32(Arc::from(transposed))
1549 } else {
1550 load_transposed_matrix_preserve_dtype(st, "lm_head.weight", cfg.vocab_size, cfg.dim)?
1551 };
1552 let output_bias = load_tensor_as_f32(st, "lm_head.bias").ok().map(Arc::from);
1553
1554 Ok(PhiWeights {
1555 instance: fuel_tensor::decode_shape::ModelInstanceId::next(),
1556 token_embedding: Arc::from(token_embedding),
1557 layers,
1558 final_norm_gain,
1559 final_norm_bias,
1560 output,
1561 output_bias,
1562 })
1563 }
1564
1565 pub fn load_from_gguf<P: AsRef<std::path::Path>>(
1578 path: P,
1579 cfg: &PhiConfig,
1580 ) -> fuel_ir::error::Result<Self> {
1581 use fuel_loaders::quantized::gguf_mmap::MmapedContent;
1582 let mc = MmapedContent::from_path(path)?;
1583 let content = mc.content();
1584 let (mmap_arc, _) = (mc.mmap(), ());
1585 let mmap_bytes: &[u8] = &mmap_arc[..];
1586 let data_off = content.tensor_data_offset as usize;
1587
1588 let get_tensor_bytes = |name: &str| -> fuel_ir::error::Result<(
1590 &[u8],
1591 fuel_loaders::quantized::GgmlDType,
1592 Vec<usize>,
1593 )> {
1594 let info = content
1595 .tensor_infos
1596 .get(name)
1597 .ok_or_else(|| content.missing_tensor_error(name))?;
1598 let elems = info.shape.elem_count();
1599 let block_size = info.ggml_dtype.block_size();
1600 let bytes_len = elems / block_size * info.ggml_dtype.type_size();
1601 let start = data_off + info.offset as usize;
1602 Ok((
1603 &mmap_bytes[start..start + bytes_len],
1604 info.ggml_dtype,
1605 info.shape.dims().to_vec(),
1606 ))
1607 };
1608
1609 let load_f32 = |name: &str| -> fuel_ir::error::Result<Vec<f32>> {
1612 let (bytes, dt, _dims) = get_tensor_bytes(name)?;
1613 dequant_gguf_bytes_to_f32(bytes, dt, name)
1614 };
1615
1616 let load_weight = |name: &str,
1620 out_features: usize,
1621 in_features: usize|
1622 -> fuel_ir::error::Result<WeightStorage> {
1623 let (bytes, dt, dims) = get_tensor_bytes(name)?;
1624 let expected_elems = out_features * in_features;
1626 let actual_elems: usize = dims.iter().product();
1627 if actual_elems != expected_elems {
1628 fuel_ir::bail!(
1629 "gguf: tensor {name:?} has {actual_elems} elements, expected {expected_elems} for [{out_features}, {in_features}]",
1630 );
1631 }
1632 let force_f32 = std::env::var("FUEL_FORCE_F32").is_ok();
1637 match dt {
1638 fuel_loaders::quantized::GgmlDType::Q4_0 if !force_f32 => Ok(WeightStorage::Q4_0 {
1639 words: bytes_to_u32_arc(bytes),
1640 bytes_len: bytes.len(),
1641 in_features,
1642 out_features,
1643 }),
1644 _ => {
1645 let f32_out_in = dequant_gguf_bytes_to_f32(bytes, dt, name)?;
1651 let mut f32_in_out = vec![0.0_f32; out_features * in_features];
1652 for o in 0..out_features {
1653 for i in 0..in_features {
1654 f32_in_out[i * out_features + o] = f32_out_in[o * in_features + i];
1655 }
1656 }
1657 Ok(WeightStorage::F32(Arc::from(f32_in_out)))
1658 }
1659 }
1660 };
1661
1662 let token_embedding = load_f32("token_embd.weight")?;
1663 if token_embedding.len() != cfg.vocab_size * cfg.dim {
1664 fuel_ir::bail!(
1665 "gguf token_embd: {} elems, expected {}×{}",
1666 token_embedding.len(),
1667 cfg.vocab_size,
1668 cfg.dim,
1669 );
1670 }
1671
1672 let mut layers: Vec<PhiLayerWeights> = Vec::with_capacity(cfg.n_layers);
1673 let kv_dim = cfg.n_heads * cfg.head_dim;
1674
1675 for i in 0..cfg.n_layers {
1676 let prefix = format!("blk.{i}");
1677
1678 let attn_qkv_weight =
1685 load_weight(&format!("{prefix}.attn_qkv.weight"), 3 * cfg.dim, cfg.dim)?;
1686 let qkv_bias_vec = load_f32(&format!("{prefix}.attn_qkv.bias"))?;
1687 if qkv_bias_vec.len() != 3 * cfg.dim {
1688 fuel_ir::bail!(
1689 "gguf attn_qkv.bias: {} elems, expected {}",
1690 qkv_bias_vec.len(),
1691 3 * cfg.dim
1692 );
1693 }
1694 let qkv_bias: Arc<[f32]> = Arc::from(qkv_bias_vec);
1695 let _ = kv_dim; let attn_dense =
1698 load_weight(&format!("{prefix}.attn_output.weight"), cfg.dim, cfg.dim)?;
1699 let attn_dense_bias = Arc::from(load_f32(&format!("{prefix}.attn_output.bias"))?);
1700
1701 let mlp_fc1 = load_weight(&format!("{prefix}.ffn_up.weight"), cfg.ffn_dim, cfg.dim)?;
1702 let mlp_fc1_bias = Arc::from(load_f32(&format!("{prefix}.ffn_up.bias"))?);
1703 let mlp_fc2 = load_weight(&format!("{prefix}.ffn_down.weight"), cfg.dim, cfg.ffn_dim)?;
1704 let mlp_fc2_bias = Arc::from(load_f32(&format!("{prefix}.ffn_down.bias"))?);
1705
1706 let norm_gain = Arc::from(load_f32(&format!("{prefix}.attn_norm.weight"))?);
1707 let norm_bias = Arc::from(load_f32(&format!("{prefix}.attn_norm.bias"))?);
1708
1709 layers.push(PhiLayerWeights {
1710 attn_qkv: PhiQkv::Packed {
1711 qkv: attn_qkv_weight,
1712 qkv_bias,
1713 },
1714 attn_dense,
1715 attn_dense_bias,
1716 mlp_fc1,
1717 mlp_fc1_bias,
1718 mlp_fc2,
1719 mlp_fc2_bias,
1720 norm_gain,
1721 norm_bias,
1722 });
1723 }
1724
1725 let final_norm_gain = Arc::from(load_f32("output_norm.weight")?);
1726 let final_norm_bias = Arc::from(load_f32("output_norm.bias")?);
1727
1728 let output = load_weight("output.weight", cfg.vocab_size, cfg.dim)?;
1730 let output_bias = load_f32("output.bias").ok().map(Arc::from);
1731
1732 Ok(PhiWeights {
1733 instance: fuel_tensor::decode_shape::ModelInstanceId::next(),
1734 token_embedding: Arc::from(token_embedding),
1735 layers,
1736 final_norm_gain,
1737 final_norm_bias,
1738 output,
1739 output_bias,
1740 })
1741 }
1742}
1743
1744fn dequant_gguf_bytes_to_f32(
1749 bytes: &[u8],
1750 dt: fuel_loaders::quantized::GgmlDType,
1751 name: &str,
1752) -> fuel_ir::error::Result<Vec<f32>> {
1753 use fuel_loaders::quantized::GgmlDType;
1754 use half::{bf16, f16};
1755 match dt {
1756 GgmlDType::F32 => {
1757 if !bytes.len().is_multiple_of(4) {
1758 fuel_ir::bail!(
1759 "gguf {name}: F32 byte count {} not multiple of 4",
1760 bytes.len()
1761 );
1762 }
1763 Ok(bytes
1764 .as_chunks::<4>()
1765 .0
1766 .iter()
1767 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
1768 .collect())
1769 }
1770 GgmlDType::F16 => {
1771 if !bytes.len().is_multiple_of(2) {
1772 fuel_ir::bail!(
1773 "gguf {name}: F16 byte count {} not multiple of 2",
1774 bytes.len()
1775 );
1776 }
1777 Ok(bytes
1778 .as_chunks::<2>()
1779 .0
1780 .iter()
1781 .map(|c| f16::from_le_bytes([c[0], c[1]]).to_f32())
1782 .collect())
1783 }
1784 GgmlDType::BF16 => {
1785 if !bytes.len().is_multiple_of(2) {
1786 fuel_ir::bail!(
1787 "gguf {name}: BF16 byte count {} not multiple of 2",
1788 bytes.len()
1789 );
1790 }
1791 Ok(bytes
1792 .as_chunks::<2>()
1793 .0
1794 .iter()
1795 .map(|c| bf16::from_le_bytes([c[0], c[1]]).to_f32())
1796 .collect())
1797 }
1798 GgmlDType::Q4_0 => {
1799 Ok(cpu_dequant_q4_0_bytes(bytes))
1802 }
1803 GgmlDType::Q8_0 => Ok(cpu_dequant_q8_0_bytes(bytes)),
1804 GgmlDType::Q6K => Ok(cpu_dequant_via_trait::<fuel_quantized::BlockQ6K>(bytes)),
1806 GgmlDType::Q5K => Ok(cpu_dequant_via_trait::<fuel_quantized::BlockQ5K>(bytes)),
1807 GgmlDType::Q4K => Ok(cpu_dequant_via_trait::<fuel_quantized::BlockQ4K>(bytes)),
1808 GgmlDType::Q3K => Ok(cpu_dequant_via_trait::<fuel_quantized::BlockQ3K>(bytes)),
1809 GgmlDType::Q2K => Ok(cpu_dequant_via_trait::<fuel_quantized::BlockQ2K>(bytes)),
1810 other => fuel_ir::bail!(
1811 "gguf {name}: dequant-to-f32 for dtype {other:?} not implemented in lazy loader"
1812 ),
1813 }
1814}
1815
1816fn cpu_dequant_via_trait<T: fuel_quantized::GgmlType>(bytes: &[u8]) -> Vec<f32> {
1822 let block_bytes = std::mem::size_of::<T>();
1823 assert!(
1824 bytes.len().is_multiple_of(block_bytes),
1825 "cpu_dequant_via_trait: bytes {} not multiple of block_bytes {}",
1826 bytes.len(),
1827 block_bytes
1828 );
1829 let n_blocks = bytes.len() / block_bytes;
1830 let blocks = fuel_quantized::blocks_from_bytes_cow::<T>(bytes);
1838 debug_assert_eq!(blocks.len(), n_blocks);
1839 let mut out = vec![0.0_f32; n_blocks * T::BLCK_SIZE];
1840 T::to_float(&blocks, &mut out);
1841 out
1842}
1843
1844fn bytes_to_u32_arc(bytes: &[u8]) -> Arc<[u32]> {
1848 assert_eq!(
1849 bytes.len() % 4,
1850 0,
1851 "bytes_to_u32_arc: len must be multiple of 4"
1852 );
1853 let words: Vec<u32> = bytes
1854 .as_chunks::<4>()
1855 .0
1856 .iter()
1857 .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]]))
1858 .collect();
1859 Arc::from(words)
1860}
1861
1862fn cpu_dequant_q4_0_bytes(bytes: &[u8]) -> Vec<f32> {
1863 use half::f16;
1864 let bpb = 18usize;
1865 let epb = 32usize;
1866 let n_blocks = bytes.len() / bpb;
1867 let mut out = vec![0.0_f32; n_blocks * epb];
1868 for b in 0..n_blocks {
1869 let off = b * bpb;
1870 let d = f16::from_le_bytes([bytes[off], bytes[off + 1]]).to_f32();
1871 let base = b * epb;
1872 for kk in 0..16 {
1873 let packed = bytes[off + 2 + kk];
1874 let lo = (packed & 0x0F) as i32 - 8;
1875 let hi = ((packed >> 4) & 0x0F) as i32 - 8;
1876 out[base + kk] = lo as f32 * d;
1877 out[base + 16 + kk] = hi as f32 * d;
1878 }
1879 }
1880 out
1881}
1882
1883fn cpu_dequant_q8_0_bytes(bytes: &[u8]) -> Vec<f32> {
1884 use half::f16;
1885 let bpb = 34usize;
1886 let epb = 32usize;
1887 let n_blocks = bytes.len() / bpb;
1888 let mut out = vec![0.0_f32; n_blocks * epb];
1889 for b in 0..n_blocks {
1890 let off = b * bpb;
1891 let d = f16::from_le_bytes([bytes[off], bytes[off + 1]]).to_f32();
1892 let base = b * epb;
1893 for kk in 0..32 {
1894 let q = bytes[off + 2 + kk] as i8 as i32;
1895 out[base + kk] = q as f32 * d;
1896 }
1897 }
1898 out
1899}
1900
1901fn partial_rope(
1908 x: &Tensor,
1909 cos: &Tensor,
1910 sin: &Tensor,
1911 rotary_dim: usize,
1912 head_dim: usize,
1913) -> Tensor {
1914 if rotary_dim == head_dim {
1915 return x.rope_with_tables(cos, sin).unwrap();
1916 }
1917 let rank = x.shape().dims().len();
1918 let last = rank - 1;
1919 let x_rot = x.slice(last, 0, rotary_dim).unwrap();
1920 let x_pass = x.slice(last, rotary_dim, head_dim - rotary_dim).unwrap();
1921 let x_rot_rotated = x_rot.rope_with_tables(cos, sin).unwrap();
1922 x_rot_rotated.concat(&x_pass, last).unwrap()
1923}
1924
1925#[cfg(test)]
1926impl PhiConfig {
1927 pub(crate) fn from_hf_json_str_legacy(json: &str) -> fuel_ir::error::Result<Self> {
1930 let v: serde_json::Value = serde_json::from_str(json)
1931 .map_err(|e| fuel_ir::error::Error::Msg(format!("parsing config.json: {e}")))?;
1932
1933 let get_usize = |key: &str| -> fuel_ir::error::Result<usize> {
1934 v.get(key)
1935 .and_then(|x| x.as_u64())
1936 .map(|x| x as usize)
1937 .ok_or_else(|| {
1938 fuel_ir::error::Error::Msg(format!(
1939 "config.json: missing/invalid field {key:?}"
1940 ))
1941 })
1942 };
1943 let get_f64 = |key: &str| -> Option<f64> { v.get(key).and_then(|x| x.as_f64()) };
1944
1945 let vocab_size = get_usize("vocab_size")?;
1946 let dim = get_usize("hidden_size")?;
1947 let n_layers = get_usize("num_hidden_layers")?;
1948 let n_heads = get_usize("num_attention_heads")?;
1949 let ffn_dim = get_usize("intermediate_size")?;
1950 let head_dim = v
1951 .get("head_dim")
1952 .and_then(|x| x.as_u64())
1953 .map(|x| x as usize)
1954 .unwrap_or(dim / n_heads);
1955 let layer_norm_eps = get_f64("layer_norm_eps").unwrap_or(1e-5);
1956 let rope_base = get_f64("rope_theta").unwrap_or(10_000.0);
1957 let partial_rotary_factor = get_f64("partial_rotary_factor").unwrap_or(0.4);
1958 let rotary_dim = (partial_rotary_factor * head_dim as f64).round() as usize;
1959 if !rotary_dim.is_multiple_of(2) {
1960 fuel_ir::bail!(
1961 "PhiConfig: rotary_dim {rotary_dim} must be even (partial_rotary_factor={partial_rotary_factor}, head_dim={head_dim})"
1962 );
1963 }
1964 let tie_word_embeddings = v
1965 .get("tie_word_embeddings")
1966 .and_then(|x| x.as_bool())
1967 .unwrap_or(false);
1968
1969 Ok(PhiConfig {
1970 vocab_size,
1971 dim,
1972 n_layers,
1973 n_heads,
1974 head_dim,
1975 ffn_dim,
1976 layer_norm_eps,
1977 rope_base,
1978 partial_rotary_factor,
1979 rotary_dim,
1980 tie_word_embeddings,
1981 })
1982 }
1983}
1984#[cfg(test)]
1985mod phi_config_tests {
1986 use super::PhiConfig;
1987
1988 const DIFFERENTIAL_CORPUS: &[(&str, &str)] = &[
2000 (
2001 "ADDED: phi-2 shaped, explicit head_dim equal to the quotient",
2002 r#"{
2003 "vocab_size": 51200, "hidden_size": 2560, "num_hidden_layers": 32,
2004 "num_attention_heads": 32, "intermediate_size": 10240,
2005 "head_dim": 80, "layer_norm_eps": 1e-5, "rope_theta": 10000.0,
2006 "partial_rotary_factor": 0.4
2007 }"#,
2008 ),
2009 (
2010 "ADDED: minimal — every optional absent, head_dim derived",
2011 r#"{
2012 "vocab_size": 51200, "hidden_size": 1024, "num_hidden_layers": 16,
2013 "num_attention_heads": 16, "intermediate_size": 4096
2014 }"#,
2015 ),
2016 (
2017 "ADDED: explicit head_dim 96 != 2560/32 = 80, and rotary_dim CHAINS off it",
2018 r#"{
2019 "vocab_size": 51200, "hidden_size": 2560, "num_hidden_layers": 32,
2020 "num_attention_heads": 32, "intermediate_size": 10240,
2021 "head_dim": 96, "partial_rotary_factor": 0.4
2022 }"#,
2023 ),
2024 (
2025 "ADDED: odd rotary_dim — both paths must REJECT (0.5 * 10 = 5)",
2026 r#"{
2027 "vocab_size": 100, "hidden_size": 40, "num_hidden_layers": 2,
2028 "num_attention_heads": 4, "intermediate_size": 80,
2029 "partial_rotary_factor": 0.5
2030 }"#,
2031 ),
2032 ];
2033
2034 #[test]
2035 fn serde_path_agrees_with_the_legacy_parser_on_every_fixture() {
2036 assert_eq!(DIFFERENTIAL_CORPUS.len(), 4, "corpus shrank");
2037 for (name, json) in DIFFERENTIAL_CORPUS {
2038 let new = PhiConfig::from_hf_json_str(json);
2039 let old = PhiConfig::from_hf_json_str_legacy(json);
2040 match (new, old) {
2041 (Ok(a), Ok(b)) => assert_eq!(a, b, "differential mismatch on {name}"),
2042 (Err(_), Err(_)) => {}
2043 (Ok(_), Err(e)) => panic!("{name}: serde accepted, legacy rejected: {e}"),
2044 (Err(e), Ok(_)) => panic!("{name}: serde rejected, legacy accepted: {e}"),
2045 }
2046 }
2047 }
2048
2049 #[test]
2050 fn rotary_dim_chains_off_the_resolved_head_dim() {
2051 let cfg = PhiConfig::from_hf_json_str(DIFFERENTIAL_CORPUS[2].1).unwrap();
2057 assert_eq!(cfg.head_dim, 96, "explicit head_dim must survive");
2058 assert_eq!(
2059 cfg.rotary_dim, 38,
2060 "rotary_dim must chain off the RESOLVED head_dim"
2061 );
2062 assert_ne!(
2063 cfg.rotary_dim, 32,
2064 "32 is what reading the raw quotient would give"
2065 );
2066 }
2067
2068 #[test]
2069 fn odd_rotary_dim_is_rejected_by_both_paths() {
2070 let json = DIFFERENTIAL_CORPUS[3].1;
2071 assert!(
2072 PhiConfig::from_hf_json_str(json).is_err(),
2073 "0.5 * 10 = 5 is odd"
2074 );
2075 assert!(
2076 PhiConfig::from_hf_json_str_legacy(json).is_err(),
2077 "legacy must agree"
2078 );
2079 }
2080}
2081
2082#[cfg(test)]
2083mod phi_kv_context_tests {
2084 use super::*;
2085 use fuel_tensor::{inference_context::InferenceContext, inference_context::KvCache};
2086
2087 fn make_tiny_phi(cfg: &PhiConfig, seed: u32) -> PhiWeights {
2098 let mut s: u32 = seed;
2099 let mut next = || -> f32 {
2100 s = s.wrapping_mul(1103515245).wrapping_add(12345);
2101 ((s >> 16) as u16 as f32 / 65535.0 - 0.5) * 0.1
2102 };
2103 let mut vec_of = |n: usize| -> Arc<[f32]> {
2104 let v: Vec<f32> = (0..n).map(|_| next()).collect();
2105 Arc::from(v)
2106 };
2107 let d = cfg.dim;
2108 let kv_dim = cfg.n_heads * cfg.head_dim;
2109 PhiWeights {
2110 instance: fuel_tensor::decode_shape::ModelInstanceId::next(),
2111 token_embedding: vec_of(cfg.vocab_size * d),
2112 layers: (0..cfg.n_layers)
2113 .map(|_| PhiLayerWeights {
2114 attn_qkv: PhiQkv::Split {
2115 q: vec_of(d * d).into(),
2116 q_bias: vec_of(d),
2117 k: vec_of(d * kv_dim).into(),
2118 k_bias: vec_of(kv_dim),
2119 v: vec_of(d * kv_dim).into(),
2120 v_bias: vec_of(kv_dim),
2121 },
2122 attn_dense: vec_of(d * d).into(),
2123 attn_dense_bias: vec_of(d),
2124 mlp_fc1: vec_of(d * cfg.ffn_dim).into(),
2125 mlp_fc1_bias: vec_of(cfg.ffn_dim),
2126 mlp_fc2: vec_of(cfg.ffn_dim * d).into(),
2127 mlp_fc2_bias: vec_of(d),
2128 norm_gain: Arc::from(vec![1.0_f32; d]),
2129 norm_bias: vec_of(d),
2130 })
2131 .collect(),
2132 final_norm_gain: Arc::from(vec![1.0_f32; d]),
2133 final_norm_bias: vec_of(d),
2134 output: vec_of(d * cfg.vocab_size).into(),
2135 output_bias: Some(vec_of(cfg.vocab_size)),
2136 }
2137 }
2138
2139 fn tiny_cfg() -> PhiConfig {
2140 PhiConfig {
2141 vocab_size: 16,
2142 dim: 8,
2143 n_layers: 2,
2144 n_heads: 2,
2145 head_dim: 4,
2146 ffn_dim: 16,
2147 layer_norm_eps: 1e-5,
2148 rope_base: 10000.0,
2149 partial_rotary_factor: 0.5,
2150 rotary_dim: 2,
2151 tie_word_embeddings: false,
2152 }
2153 }
2154
2155 #[test]
2161 fn phi_kv_context_decode_consistent_with_monolithic_prefill() {
2162 let cfg = tiny_cfg();
2163 let model = PhiModel {
2164 config: cfg.clone(),
2165 weights: make_tiny_phi(&cfg, 7777),
2166 };
2167 let tokens = [1_u32, 5, 9, 12];
2168 let device = Device::cpu();
2169
2170 let mut cache_a = KvCache::with_capacity(
2172 cfg.n_layers,
2173 cfg.n_heads,
2174 cfg.head_dim,
2175 tokens.len(),
2176 DType::F32,
2177 &device,
2178 )
2179 .expect("cache_a");
2180 let mut ctx_a = InferenceContext::new(device.clone());
2181 let expected = model
2182 .forward_with_kv_context(&tokens, &mut cache_a, &mut ctx_a)
2183 .expect("monolithic prefill");
2184
2185 let mut cache_b = KvCache::with_capacity(
2187 cfg.n_layers,
2188 cfg.n_heads,
2189 cfg.head_dim,
2190 tokens.len(),
2191 DType::F32,
2192 &device,
2193 )
2194 .expect("cache_b");
2195 let mut ctx_b = InferenceContext::new(device.clone());
2196 model
2197 .forward_with_kv_context(&tokens[..3], &mut cache_b, &mut ctx_b)
2198 .expect("prefill B");
2199 let actual = model
2200 .forward_with_kv_context(&tokens[3..], &mut cache_b, &mut ctx_b)
2201 .expect("decode B");
2202
2203 assert_eq!(actual.len(), expected.len());
2204 for (i, (a, b)) in actual.iter().zip(expected.iter()).enumerate() {
2207 let diff = (a - b).abs();
2208 let rel = diff / a.abs().max(b.abs()).max(1e-6);
2209 assert!(
2210 diff < 5e-3 || rel < 1e-2,
2211 "logit[{i}]: chunked={a}, monolithic={b}, diff={diff}",
2212 );
2213 }
2214 assert_eq!(cache_a.cached_len, cache_b.cached_len);
2215 }
2216
2217 #[test]
2221 fn phi_generate_with_kv_context_greedy_is_deterministic() {
2222 let cfg = tiny_cfg();
2223 let model = PhiModel {
2224 config: cfg.clone(),
2225 weights: make_tiny_phi(&cfg, 7777),
2226 };
2227 let prompt = [1_u32, 5, 9];
2228 let max_new = 8;
2229 let device = Device::cpu();
2230
2231 let mut streamed = Vec::new();
2232 let run_a = model
2233 .generate_streaming_with_kv_context(
2234 &prompt,
2235 max_new,
2236 SamplingStrategy::Greedy,
2237 None,
2238 &device,
2239 DType::F32,
2240 |t| streamed.push(t),
2241 )
2242 .expect("run a");
2243 let run_b = model
2244 .generate_with_kv_context(
2245 &prompt,
2246 max_new,
2247 SamplingStrategy::Greedy,
2248 None,
2249 &device,
2250 DType::F32,
2251 )
2252 .expect("run b");
2253
2254 assert_eq!(run_a, run_b, "greedy generation must be deterministic");
2255 assert_eq!(run_a.len(), prompt.len() + max_new);
2256 assert_eq!(&run_a[..prompt.len()], &prompt);
2257 assert_eq!(
2258 streamed,
2259 &run_a[prompt.len()..],
2260 "callback sees exactly the new tokens"
2261 );
2262 for &t in &run_a {
2263 assert!((t as usize) < cfg.vocab_size, "token {t} out of vocab");
2264 }
2265 }
2266
2267 #[test]
2271 fn phi_forward_with_kv_context_rejects_invalid_cache() {
2272 let cfg = tiny_cfg();
2273 let model = PhiModel {
2274 config: cfg.clone(),
2275 weights: make_tiny_phi(&cfg, 7777),
2276 };
2277 let device = Device::cpu();
2278 let mut ctx = InferenceContext::new(device.clone());
2279
2280 let mut dims_cache = KvCache::with_dims(cfg.n_layers, cfg.n_heads, cfg.head_dim);
2282 let err = model
2283 .forward_with_kv_context(&[1, 2], &mut dims_cache, &mut ctx)
2284 .expect_err("with_dims cache must be rejected");
2285 assert!(format!("{err}").contains("with_capacity"));
2286
2287 let mut small_cache = KvCache::with_capacity(
2289 cfg.n_layers,
2290 cfg.n_heads,
2291 cfg.head_dim,
2292 2,
2293 DType::F32,
2294 &device,
2295 )
2296 .expect("small cache");
2297 model
2298 .forward_with_kv_context(&[1, 2], &mut small_cache, &mut ctx)
2299 .expect("fits exactly");
2300 let err = model
2301 .forward_with_kv_context(&[3], &mut small_cache, &mut ctx)
2302 .expect_err("overflow must be rejected");
2303 assert!(format!("{err}").contains("max_seq_len"));
2304 }
2305
2306 #[test]
2326 fn phi_decode_matches_non_cached_forward() {
2327 let cfg = tiny_cfg(); let model = PhiModel {
2329 config: cfg.clone(),
2330 weights: make_tiny_phi(&cfg, 7777),
2331 };
2332
2333 let prompt = [1_u32, 5, 9];
2334 let next_token = 12_u32;
2335 let full = [prompt[0], prompt[1], prompt[2], next_token];
2336 let device = Device::cpu();
2337
2338 let mut cache_ref = KvCache::with_capacity(
2340 cfg.n_layers,
2341 cfg.n_heads,
2342 cfg.head_dim,
2343 full.len(),
2344 DType::F32,
2345 &device,
2346 )
2347 .expect("with_capacity ref");
2348 let mut ctx_ref = InferenceContext::new(device.clone());
2349 let expected = model
2350 .forward_with_kv_context(&full, &mut cache_ref, &mut ctx_ref)
2351 .expect("monolithic prefill");
2352
2353 let mut cache = KvCache::with_capacity(
2356 cfg.n_layers,
2357 cfg.n_heads,
2358 cfg.head_dim,
2359 full.len(),
2360 DType::F32,
2361 &device,
2362 )
2363 .expect("with_capacity");
2364 let mut ctx = InferenceContext::new(device);
2365 let _prefill = model
2366 .forward_with_kv_context(&prompt, &mut cache, &mut ctx)
2367 .expect("prefill");
2368 assert_eq!(cache.cached_len, prompt.len());
2369 let actual = model
2370 .forward_with_kv_context(&[next_token], &mut cache, &mut ctx)
2371 .expect("decode");
2372 assert_eq!(cache.cached_len, full.len());
2373 assert_eq!(actual.len(), expected.len());
2374
2375 for (i, (a, b)) in actual.iter().zip(expected.iter()).enumerate() {
2378 let diff = (a - b).abs();
2379 let rel = diff / a.abs().max(b.abs()).max(1e-6);
2380 assert!(
2381 diff < 5e-3 || rel < 1e-2,
2382 "logit[{i}]: input-independent={a}, monolithic={b}, diff={diff}",
2383 );
2384 }
2385 }
2386
2387 #[test]
2406 fn phi_persistent_plan_once_matches_d1() {
2407 let cfg = tiny_cfg(); let model_d2 = PhiModel {
2411 config: cfg.clone(),
2412 weights: make_tiny_phi(&cfg, 7777),
2413 };
2414 let model_d1 = PhiModel {
2415 config: cfg.clone(),
2416 weights: make_tiny_phi(&cfg, 7777),
2417 };
2418
2419 let prompt = [1_u32, 5, 9];
2420 let decode_tokens = [12_u32, 3, 7, 2]; let max_seq_len = prompt.len() + decode_tokens.len();
2422
2423 let dev1 = Device::cpu();
2427 let mut cache1 = KvCache::with_capacity(
2428 cfg.n_layers,
2429 cfg.n_heads,
2430 cfg.head_dim,
2431 max_seq_len,
2432 DType::F32,
2433 &dev1,
2434 )
2435 .expect("with_capacity d1");
2436 let mut ctx1 = InferenceContext::new(dev1);
2437 let _ = model_d1
2438 .forward_with_kv_context(&prompt, &mut cache1, &mut ctx1)
2439 .expect("d1 prefill");
2440 let mut d1_expected: Vec<Vec<f32>> = Vec::with_capacity(decode_tokens.len());
2441 for &tok in &decode_tokens {
2442 d1_expected.push(
2443 model_d1
2444 .forward_with_kv_context(&[tok], &mut cache1, &mut ctx1)
2445 .expect("d1 decode"),
2446 );
2447 }
2448
2449 let dev2 = Device::cpu();
2451 let mut cache2 = KvCache::with_capacity(
2452 cfg.n_layers,
2453 cfg.n_heads,
2454 cfg.head_dim,
2455 max_seq_len,
2456 DType::F32,
2457 &dev2,
2458 )
2459 .expect("with_capacity d2");
2460 let mut ctx2 = InferenceContext::new(dev2);
2461 let mut session: Option<fuel_tensor::inference_context::DecodeSession> = None;
2462
2463 let _ = model_d2
2465 .forward_with_kv_context_persistent(&prompt, &mut cache2, &mut ctx2, &mut session)
2466 .expect("d2 prefill");
2467 assert!(
2468 session.is_none(),
2469 "prefill (seq>1) must NOT build the held session"
2470 );
2471
2472 let opt_before = fuel_tensor::pipelined_bridge::optimize_calls_thread_local();
2476 let mut len_at_token2: Option<usize> = None;
2477
2478 for (i, &tok) in decode_tokens.iter().enumerate() {
2479 let d2 = model_d2
2480 .forward_with_kv_context_persistent(&[tok], &mut cache2, &mut ctx2, &mut session)
2481 .expect("d2 decode");
2482
2483 assert_eq!(
2485 d2, d1_expected[i],
2486 "persistent decode token {i} must be byte-identical to the D1 cached path",
2487 );
2488
2489 let sess = session
2490 .as_ref()
2491 .expect("session built on first decode token");
2492 let graph_len = sess.graph_node_count();
2493 if i == 1 {
2494 len_at_token2 = Some(graph_len);
2495 } else if i >= 2 {
2496 assert_eq!(
2498 Some(graph_len),
2499 len_at_token2,
2500 "held graph must NOT grow from token 2 onward (token {i})",
2501 );
2502 }
2503 }
2504
2505 let opt_after = fuel_tensor::pipelined_bridge::optimize_calls_thread_local();
2507 assert_eq!(
2508 opt_after - opt_before,
2509 1,
2510 "persistent decode must optimize EXACTLY ONCE across {} decode tokens \
2511 (the first builds the session; the rest skip optimize): {opt_before} -> {opt_after}",
2512 decode_tokens.len(),
2513 );
2514
2515 assert_eq!(cache2.cached_len, max_seq_len);
2516 assert_eq!(cache1.cached_len, max_seq_len);
2517 }
2518
2519 #[test]
2570 fn phi_attended_len_sym_is_unreferenced_negative_control() {
2571 let cfg = tiny_cfg();
2572 let model = PhiModel {
2573 config: cfg.clone(),
2574 weights: make_tiny_phi(&cfg, 7777),
2575 };
2576 let prompt = [1_u32, 5, 9];
2577 let max_seq_len = prompt.len() + 4;
2578
2579 let dev = Device::cpu();
2580 let mut cache = KvCache::with_capacity(
2581 cfg.n_layers,
2582 cfg.n_heads,
2583 cfg.head_dim,
2584 max_seq_len,
2585 DType::F32,
2586 &dev,
2587 )
2588 .expect("with_capacity");
2589 let mut ctx = InferenceContext::new(dev.clone());
2590 let mut session: Option<fuel_tensor::inference_context::DecodeSession> = None;
2591
2592 let _ = model
2594 .forward_with_kv_context_persistent(&prompt, &mut cache, &mut ctx, &mut session)
2595 .expect("prefill");
2596 let _ = model
2597 .forward_with_kv_context_persistent(&[12], &mut cache, &mut ctx, &mut session)
2598 .expect("build decode session");
2599 let s = session.as_ref().expect("session built");
2600
2601 let cached_len = cache.cached_len;
2605 let next = [3_u32];
2606 let mk_data = || {
2607 model
2608 .build_token_rope_mask_arcs(&dev, cached_len, &next, s.max_seq_len())
2609 .expect("token data")
2610 };
2611
2612 let mut env_ok = fuel_ir::SymEnv::new();
2613 env_ok
2614 .bind(s.cached_len_sym(), cached_len)
2615 .expect("bind cached_len");
2616 let baseline = s.realize_token(&dev, mk_data(), &env_ok).expect("baseline");
2617
2618 let mut env_bad_attended = fuel_ir::SymEnv::new();
2620 env_bad_attended
2621 .bind(s.cached_len_sym(), cached_len)
2622 .expect("bind cached_len");
2623 env_bad_attended
2624 .bind(s.attended_len_sym(), cached_len + 4242)
2625 .expect("bind attended_len (wrong on purpose)");
2626 let perturbed_attended = s
2627 .realize_token(&dev, mk_data(), &env_bad_attended)
2628 .expect("realize with wrong attended_len");
2629
2630 let other = [6_u32];
2635 let data_other = model
2636 .build_token_rope_mask_arcs(&dev, cached_len, &other, s.max_seq_len())
2637 .expect("token data (different token)");
2638 let mut env_ok2 = fuel_ir::SymEnv::new();
2639 env_ok2
2640 .bind(s.cached_len_sym(), cached_len)
2641 .expect("bind cached_len");
2642 let perturbed_data = s
2643 .realize_token(&dev, data_other, &env_ok2)
2644 .expect("realize with different token");
2645 assert_ne!(
2646 perturbed_data, baseline,
2647 "control A FAILED: a DIFFERENT input token produced identical \
2648 logits, so realize_token is not responding to its inputs and no \
2649 verdict from this test means anything",
2650 );
2651
2652 let with_off = s.offset_node().is_some();
2654 let mut env_bad_cached = fuel_ir::SymEnv::new();
2655 env_bad_cached
2656 .bind(s.cached_len_sym(), cached_len + 1)
2657 .expect("bind cached_len (wrong on purpose)");
2658 let perturbed_cached = s
2659 .realize_token(&dev, mk_data(), &env_bad_cached)
2660 .expect("realize with wrong cached_len");
2661
2662 if with_off {
2668 assert_eq!(
2669 perturbed_cached, baseline,
2670 "on the device-offset path the KV offset rides the offset \
2671 BUFFER, so a wrong cached_len_sym should be inert — it moved \
2672 the output, meaning the symbol IS load-bearing here",
2673 );
2674 } else {
2675 assert_ne!(
2676 perturbed_cached, baseline,
2677 "on the SymEnv path the KV offset rides cached_len_sym, so a \
2678 wrong binding MUST move the output; it did not, so this test \
2679 cannot detect referencedness and its verdict is vacuous",
2680 );
2681 }
2682
2683 assert_eq!(
2684 perturbed_attended, baseline,
2685 "attended_len_sym IS referenced by Phi's decode graph — the \
2686 'carried for API parity but never referenced' comment at \
2687 lazy.rs:12088 is FALSE, and sharing per_token_sym_env between \
2688 Llama and Phi is NOT the no-op the GAP-029 2b design assumes",
2689 );
2690
2691 eprintln!(
2702 "[gap-029 2b control] phi: offset_node.is_some()={with_off} \
2703 ({} path; SymEnv live={})",
2704 if with_off { "device-offset" } else { "SymEnv" },
2705 !with_off,
2706 );
2707 }
2708
2709 #[test]
2712 fn phi_generate_loop_persistent_byte_exact_and_plans_once() {
2713 let cfg = tiny_cfg();
2714 let model = PhiModel {
2715 config: cfg.clone(),
2716 weights: make_tiny_phi(&cfg, 7777),
2717 };
2718
2719 let prompt = [1_u32, 5, 9];
2720 let max_new = 5; let max_seq_len = prompt.len() + max_new;
2722 let strategy = SamplingStrategy::Greedy;
2723
2724 let dev1 = Device::cpu();
2728 let mut cache1 = KvCache::with_capacity(
2729 cfg.n_layers,
2730 cfg.n_heads,
2731 cfg.head_dim,
2732 max_seq_len,
2733 DType::F32,
2734 &dev1,
2735 )
2736 .expect("with_capacity d1");
2737 let mut ctx1 = InferenceContext::new(dev1);
2738 let mut rng1: u64 = 0;
2739 let mut ref_tokens: Vec<u32> = prompt.to_vec();
2740 let mut ref_step_logits: Vec<Vec<f32>> = Vec::with_capacity(max_new);
2741 let mut last1 = model
2742 .forward_with_kv_context(&prompt, &mut cache1, &mut ctx1)
2743 .expect("d1 prefill");
2744 for _ in 0..max_new {
2745 let next = sample_logits(&last1, strategy, &mut rng1);
2746 ref_tokens.push(next);
2747 last1 = model
2748 .forward_with_kv_context(&[next], &mut cache1, &mut ctx1)
2749 .expect("d1 decode");
2750 ref_step_logits.push(last1.clone());
2751 }
2752
2753 let opt_before = fuel_tensor::pipelined_bridge::optimize_calls_thread_local();
2757
2758 let dev2 = Device::cpu();
2759 let mut cache2 = KvCache::with_capacity(
2760 cfg.n_layers,
2761 cfg.n_heads,
2762 cfg.head_dim,
2763 max_seq_len,
2764 DType::F32,
2765 &dev2,
2766 )
2767 .expect("with_capacity d2");
2768 let mut ctx2 = InferenceContext::new(dev2);
2769 let mut rng2: u64 = 0;
2770 let mut session: Option<fuel_tensor::inference_context::DecodeSession> = None;
2771 let mut d2_tokens: Vec<u32> = prompt.to_vec();
2772 let mut d2_step_logits: Vec<Vec<f32>> = Vec::with_capacity(max_new);
2773 let mut last2 = model
2774 .forward_with_kv_context_persistent(&prompt, &mut cache2, &mut ctx2, &mut session)
2775 .expect("d2 prefill");
2776 assert!(
2777 session.is_none(),
2778 "prefill (seq>1) must NOT build the held session"
2779 );
2780 for _ in 0..max_new {
2781 let next = sample_logits(&last2, strategy, &mut rng2);
2782 d2_tokens.push(next);
2783 last2 = model
2784 .forward_with_kv_context_persistent(&[next], &mut cache2, &mut ctx2, &mut session)
2785 .expect("d2 decode");
2786 d2_step_logits.push(last2.clone());
2787 }
2788
2789 let opt_after = fuel_tensor::pipelined_bridge::optimize_calls_thread_local();
2790
2791 assert_eq!(
2793 d2_tokens, ref_tokens,
2794 "persistent generate loop must produce the byte-identical token sequence \
2795 as the D1 rebuild path over {max_new} greedy tokens",
2796 );
2797
2798 assert_eq!(d2_step_logits.len(), ref_step_logits.len());
2800 for (i, (d2, d1)) in d2_step_logits
2801 .iter()
2802 .zip(ref_step_logits.iter())
2803 .enumerate()
2804 {
2805 assert_eq!(
2806 d2, d1,
2807 "persistent decode step {i} logits must be byte-identical to the D1 cached path",
2808 );
2809 }
2810
2811 assert_eq!(
2814 opt_after - opt_before,
2815 2,
2816 "persistent generate must optimize EXACTLY twice (1 prefill fallback + 1 \
2817 decode-session build) regardless of N={max_new} decode tokens: \
2818 {opt_before} -> {opt_after}",
2819 );
2820
2821 assert!(session.is_some(), "held session survives the decode loop");
2822 assert_eq!(cache2.cached_len, max_seq_len);
2823 assert_eq!(cache1.cached_len, max_seq_len);
2824
2825 let via_wrapper = model
2827 .generate_with_kv_context(&prompt, max_new, strategy, None, &Device::cpu(), DType::F32)
2828 .expect("generate_with_kv_context");
2829 assert_eq!(
2830 via_wrapper, ref_tokens,
2831 "generate_with_kv_context (wired to the persistent path) must produce the \
2832 byte-identical token sequence as the D1 reference",
2833 );
2834 }
2835
2836 #[test]
2858 fn phi_persistent_plan_reads_a_write_bytes_overwrite_without_rebuilding() {
2859 let cfg = tiny_cfg();
2860 let model = PhiModel {
2861 config: cfg.clone(),
2862 weights: make_tiny_phi(&cfg, 7777),
2863 };
2864 let prompt = [1_u32, 5, 9];
2865 let decode_steps_before_overwrite = 2;
2866 let max_seq_len = prompt.len() + decode_steps_before_overwrite + 1;
2867 let strategy = SamplingStrategy::Greedy;
2868
2869 let run_to_overwrite_point = || {
2873 let device = Device::cpu();
2874 let mut cache = KvCache::with_capacity(
2875 cfg.n_layers,
2876 cfg.n_heads,
2877 cfg.head_dim,
2878 max_seq_len,
2879 DType::F32,
2880 &device,
2881 )
2882 .expect("with_capacity");
2883 let mut ctx = InferenceContext::new(device);
2884 let mut rng: u64 = 0;
2885 let mut session: Option<fuel_tensor::inference_context::DecodeSession> = None;
2886 let mut tokens: Vec<u32> = prompt.to_vec();
2887 let mut last = model
2888 .forward_with_kv_context_persistent(&prompt, &mut cache, &mut ctx, &mut session)
2889 .expect("prefill");
2890 for _ in 0..decode_steps_before_overwrite {
2891 let next = sample_logits(&last, strategy, &mut rng);
2892 tokens.push(next);
2893 last = model
2894 .forward_with_kv_context_persistent(&[next], &mut cache, &mut ctx, &mut session)
2895 .expect("decode (pre-overwrite)");
2896 }
2897 (cache, ctx, session, tokens, rng)
2898 };
2899
2900 let (mut ref_cache, mut ref_ctx, mut ref_session, ref_tokens, _ref_rng) =
2902 run_to_overwrite_point();
2903 assert!(
2904 ref_session.is_some(),
2905 "the held DecodeSession must exist by now (built on the first decode token)",
2906 );
2907 let ref_next_logits = model
2908 .forward_with_kv_context_persistent(
2909 &[*ref_tokens.last().unwrap()],
2910 &mut ref_cache,
2911 &mut ref_ctx,
2912 &mut ref_session,
2913 )
2914 .expect("reference decode (no overwrite)");
2915
2916 let (mut ow_cache, mut ow_ctx, mut ow_session, ow_tokens, _ow_rng) =
2920 run_to_overwrite_point();
2921 assert_eq!(
2922 ow_tokens, ref_tokens,
2923 "both runs must reach an identical token stream before the overwrite \
2924 (same model, same seed, same prompt) — divergence must come ONLY from the write",
2925 );
2926
2927 let alloc_before = ow_cache.alloc_id();
2928 let loc_before = ow_cache.device_location();
2929 let opt_before_write = fuel_tensor::pipelined_bridge::optimize_calls_thread_local();
2930
2931 let payload: Vec<f32> = (0..(cfg.n_heads * cfg.head_dim))
2934 .map(|i| 9000.0 + i as f32)
2935 .collect();
2936 let payload_bytes: Vec<u8> = payload.iter().flat_map(|f| f.to_le_bytes()).collect();
2937 ow_cache
2938 .write_bytes(0, KvSlot::K, 0, 1, &payload_bytes, &Device::cpu())
2939 .expect("write_bytes");
2940
2941 assert_eq!(
2942 ow_cache.alloc_id(),
2943 alloc_before,
2944 "write_bytes must not re-mint alloc_id",
2945 );
2946 assert_eq!(
2947 ow_cache.device_location(),
2948 loc_before,
2949 "write_bytes must not clear device_location",
2950 );
2951
2952 let opt_after_write = fuel_tensor::pipelined_bridge::optimize_calls_thread_local();
2959 assert_eq!(
2960 opt_after_write - opt_before_write,
2961 1,
2962 "write_bytes's own one-off realize should cost exactly one optimize call \
2963 for its throwaway graph (same shape as DeviceKvPool::write_block_bytes) — \
2964 a different count means this assumption needs re-checking",
2965 );
2966
2967 let ow_next_logits = model
2968 .forward_with_kv_context_persistent(
2969 &[*ow_tokens.last().unwrap()],
2970 &mut ow_cache,
2971 &mut ow_ctx,
2972 &mut ow_session,
2973 )
2974 .expect("overwrite-run decode (post-overwrite)");
2975
2976 let opt_after_decode = fuel_tensor::pipelined_bridge::optimize_calls_thread_local();
2977 assert_eq!(
2978 opt_after_decode, opt_after_write,
2979 "the decode step AFTER write_bytes must not trigger a plan rebuild — \
2980 optimize_calls_thread_local must be unchanged across it specifically \
2981 (write_bytes's own one-off optimize, measured above, is expected and excluded)",
2982 );
2983
2984 assert_ne!(
2989 ow_next_logits, ref_next_logits,
2990 "the decode step after write_bytes must differ from the un-overwritten \
2991 reference — otherwise the held plan never read the write at all",
2992 );
2993 }
2994
2995 #[test]
3010 #[cfg(feature = "cuda")]
3011 #[ignore = "requires a live CUDA device"]
3012 fn phi_decode_node_placement_report_cuda() {
3013 use std::collections::BTreeMap;
3014
3015 let cfg = tiny_cfg();
3016 let dev: Device = match fuel_cuda_backend::CudaDevice::new(0) {
3017 Ok(d) => d.into(),
3018 Err(e) => {
3019 return fuel_test_support::hardware::skip(
3020 fuel_test_support::hardware::Hardware::Cuda,
3021 fuel_test_support::hardware::Missing::device(format!(
3022 "CudaDevice::new(0): {e:?}"
3023 )),
3024 );
3025 }
3026 };
3027 let model = PhiModel {
3028 config: cfg.clone(),
3029 weights: make_tiny_phi(&cfg, 7),
3030 };
3031 let prompt = [1_u32, 2, 3];
3032 let max_seq_len = prompt.len() + 4;
3033
3034 let mut cache = KvCache::with_capacity(
3035 cfg.n_layers,
3036 cfg.n_heads,
3037 cfg.head_dim,
3038 max_seq_len,
3039 DType::F32,
3040 &dev,
3041 )
3042 .expect("with_capacity");
3043 let mut ctx = InferenceContext::new(dev.clone());
3044 let mut sess: Option<fuel_tensor::inference_context::DecodeSession> = None;
3045 model
3046 .forward_with_kv_context_persistent(&prompt, &mut cache, &mut ctx, &mut sess)
3047 .expect("prefill");
3048 model
3049 .forward_with_kv_context_persistent(&[4], &mut cache, &mut ctx, &mut sess)
3050 .expect("first decode token builds the held plan");
3051 let s = sess.as_ref().expect("held session");
3052
3053 let opt = s.optimized();
3054 assert!(
3055 opt.has_placements(),
3056 "placement NOT COMPUTED — every lookup would be None and the report below would describe a missing instrument, not the graph",
3057 );
3058
3059 let g = s.graph().read().expect("graph lock");
3060 let mut by_op: BTreeMap<String, BTreeMap<String, usize>> = BTreeMap::new();
3061 let mut host_nodes: Vec<String> = Vec::new();
3062 for i in 0..g.len() {
3063 let id = fuel_graph::NodeId(i);
3064 let op_name = match &g.node(id).op {
3065 fuel_graph::Op::Fused(fid, _) => format!("Fused({fid:?})"),
3066 other => format!("{other:?}")
3067 .split(' ')
3068 .next()
3069 .unwrap_or("?")
3070 .to_string(),
3071 };
3072 let place = match opt.placement_of(id) {
3073 Some(d) => format!("{d:?}"),
3074 None => "None".to_string(),
3075 };
3076 if place.starts_with("Cpu") {
3077 host_nodes.push(format!("#{i} {op_name}"));
3078 }
3079 *by_op.entry(op_name).or_default().entry(place).or_insert(0) += 1;
3080 }
3081
3082 println!(
3083 "
3084=== Phi decode plan: node placement (CUDA) ==="
3085 );
3086 println!("total nodes: {}", g.len());
3087 for (op, places) in &by_op {
3088 let r: Vec<String> = places.iter().map(|(d, n)| format!("{d}x{n}")).collect();
3089 println!(" {op:<34} {}", r.join(" "));
3090 }
3091 println!(
3092 "
3093--- HOST-PLACED NODES ({}) ---",
3094 host_nodes.len()
3095 );
3096 for h in &host_nodes {
3097 println!(" {h}");
3098 }
3099 println!(
3100 "--- END ---
3101"
3102 );
3103 }
3104
3105 #[test]
3129 #[cfg(feature = "cuda")]
3130 #[ignore = "requires a live CUDA device"]
3131 fn phi_forward_with_kv_context_captured_matches_persistent() {
3132 let cfg = tiny_cfg();
3133
3134 let cuda = match fuel_cuda_backend::CudaDevice::new(0) {
3135 Ok(d) => d,
3136 Err(e) => {
3137 return fuel_test_support::hardware::skip(
3138 fuel_test_support::hardware::Hardware::Cuda,
3139 fuel_test_support::hardware::Missing::device(format!(
3140 "CudaDevice::new(0): {e:?}"
3141 )),
3142 );
3143 }
3144 };
3145 let dev: Device = cuda.into();
3146
3147 let prompt = [1_u32, 2, 3];
3148 let decode_tokens = [4_u32, 5, 6, 7]; let max_seq_len = prompt.len() + decode_tokens.len();
3150
3151 let model_ref = PhiModel {
3154 config: cfg.clone(),
3155 weights: make_tiny_phi(&cfg, 7),
3156 };
3157 let model_cap = PhiModel {
3158 config: cfg.clone(),
3159 weights: make_tiny_phi(&cfg, 7),
3160 };
3161
3162 let mut cache_ref = KvCache::with_capacity(
3164 cfg.n_layers,
3165 cfg.n_heads,
3166 cfg.head_dim,
3167 max_seq_len,
3168 DType::F32,
3169 &dev,
3170 )
3171 .expect("with_capacity ref");
3172 let mut ctx_ref = InferenceContext::new(dev.clone());
3173 let mut sess_ref: Option<fuel_tensor::inference_context::DecodeSession> = None;
3174 model_ref
3175 .forward_with_kv_context_persistent(
3176 &prompt,
3177 &mut cache_ref,
3178 &mut ctx_ref,
3179 &mut sess_ref,
3180 )
3181 .expect("ref prefill");
3182 let mut ref_logits: Vec<Vec<f32>> = Vec::with_capacity(decode_tokens.len());
3183 for &tok in &decode_tokens {
3184 ref_logits.push(
3185 model_ref
3186 .forward_with_kv_context_persistent(
3187 &[tok],
3188 &mut cache_ref,
3189 &mut ctx_ref,
3190 &mut sess_ref,
3191 )
3192 .expect("ref decode"),
3193 );
3194 }
3195
3196 let mut cache_cap = KvCache::with_capacity(
3198 cfg.n_layers,
3199 cfg.n_heads,
3200 cfg.head_dim,
3201 max_seq_len,
3202 DType::F32,
3203 &dev,
3204 )
3205 .expect("with_capacity captured");
3206 let mut ctx_cap = InferenceContext::new(dev.clone());
3207 let mut sess_cap: Option<fuel_tensor::inference_context::DecodeSession> = None;
3208 let mut captured: Option<fuel_dispatch::pipelined::CapturedDecodeSession> = None;
3209 model_cap
3210 .forward_with_kv_context_captured(
3211 &prompt,
3212 &mut cache_cap,
3213 &mut ctx_cap,
3214 &mut sess_cap,
3215 &mut captured,
3216 )
3217 .expect("captured prefill");
3218 assert!(
3219 captured.is_none(),
3220 "prefill (seq != 1) must NOT build a capture"
3221 );
3222
3223 for (i, &tok) in decode_tokens.iter().enumerate() {
3224 let got = model_cap
3225 .forward_with_kv_context_captured(
3226 &[tok],
3227 &mut cache_cap,
3228 &mut ctx_cap,
3229 &mut sess_cap,
3230 &mut captured,
3231 )
3232 .expect("captured decode");
3233
3234 assert_eq!(
3235 got, ref_logits[i],
3236 "Phi captured decode token {i} must be BYTE-IDENTICAL to the persistent path (same plan => same kernels). A mismatch here on tokens 3+ is the partial-rotary replay-bytes failure this test exists for.",
3237 );
3238
3239 if i == 0 {
3240 assert!(sess_cap.is_some(), "token 1 builds the held session");
3241 assert!(captured.is_none(), "token 1 must NOT build the capture yet");
3242 }
3243 }
3244
3245 assert_eq!(cache_cap.cached_len, max_seq_len);
3248 assert_eq!(cache_ref.cached_len, max_seq_len);
3249
3250 if captured.is_some() {
3268 println!("Phi capture FORMED — the decode graph is fully CUDA-resident");
3269 } else {
3270 println!(
3271 "Phi capture DECLINED (expected today) — host-placed fused LayerNormLastDim/ROPE force a cross-device Copy. Results were byte-identical via the persistent fallback, which is the property that matters: capture degrades, never fails."
3272 );
3273 }
3274 }
3275}
3276
3277#[cfg(test)]
3284mod bail_consolidation_tests {
3285 fn always_bails() -> fuel_ir::error::Result<()> {
3286 fuel_ir::bail!("deliberate failure for the fuel-core dissolution bail! consolidation test");
3287 #[allow(unreachable_code)]
3288 Ok(())
3289 }
3290
3291 #[test]
3292 fn fuel_core_bail_still_produces_a_typed_err_with_the_message() {
3293 let err = always_bails().expect_err("bail! must produce an Err, never panic");
3294 assert!(err.to_string().contains("deliberate failure"));
3295 }
3296}