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(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 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 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 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 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 let cache_shape = Shape::from_dims(&[batch, cfg.n_heads, max_seq_len, cfg.head_dim]);
762
763 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 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 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 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 None,
867 cached_len_sym,
868 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 cache,
882 ));
883
884 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 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 fuel_tensor::persistent_decode::rebind_and_realize_prebuilt(
913 self, tokens, cache, ctx, session, None,
914 )
915 }
916
917 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 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 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 #[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 #[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 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 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 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 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 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 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 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 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 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 let mut session: Option<fuel_tensor::inference_context::DecodeSession> = None;
1235
1236 #[cfg(feature = "cuda")]
1247 let mut captured: Option<fuel_dispatch::pipelined::CapturedDecodeSession> = None;
1248
1249 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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; 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 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
1747fn 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 Ok(cpu_dequant_q4_0_bytes(bytes))
1805 }
1806 GgmlDType::Q8_0 => Ok(cpu_dequant_q8_0_bytes(bytes)),
1807 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
1819fn 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 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
1847fn 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
1904fn 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 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 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 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 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 #[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 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 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 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 #[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 #[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 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 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 #[test]
2329 fn phi_decode_matches_non_cached_forward() {
2330 let cfg = tiny_cfg(); 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 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 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 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 #[test]
2409 fn phi_persistent_plan_once_matches_d1() {
2410 let cfg = tiny_cfg(); 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]; let max_seq_len = prompt.len() + decode_tokens.len();
2425
2426 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 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 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 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 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 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 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 #[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 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 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 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 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 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 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 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 #[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; let max_seq_len = prompt.len() + max_new;
2725 let strategy = SamplingStrategy::Greedy;
2726
2727 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 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 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 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 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 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 #[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 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 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 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 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 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 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 #[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 #[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]; let max_seq_len = prompt.len() + decode_tokens.len();
3153
3154 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 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 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 assert_eq!(cache_cap.cached_len, max_seq_len);
3251 assert_eq!(cache_ref.cached_len, max_seq_len);
3252
3253 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#[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}