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 fuel_tensor::lazy::invalidate_decode_pair_if_stale(
1045 session,
1046 captured,
1047 ctx,
1048 seq,
1049 cache.max_seq_len,
1050 cache.dtype.unwrap_or(DType::F32),
1051 cfg.n_layers,
1052 self.decode_shape_key(),
1053 cache,
1054 |s, ctx| self.drop_decode_session(s, ctx),
1055 );
1056
1057 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_formats::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_formats::safetensors::MmapedSafetensors,
1429 cfg: &PhiConfig,
1430 ) -> fuel_ir::error::Result<Self> {
1431 let kv_dim = cfg.n_heads * cfg.head_dim;
1432 let token_embedding = load_tensor_as_f32(st, "model.embed_tokens.weight")?;
1433 if token_embedding.len() != cfg.vocab_size * cfg.dim {
1434 fuel_ir::bail!(
1435 "embed_tokens: {} elements, expected {}",
1436 token_embedding.len(),
1437 cfg.vocab_size * cfg.dim,
1438 );
1439 }
1440
1441 let mut layers: Vec<PhiLayerWeights> = Vec::with_capacity(cfg.n_layers);
1442 for i in 0..cfg.n_layers {
1443 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 data_off = content.tensor_data_offset as usize;
1585
1586 let get_tensor_bytes = |name: &str| -> fuel_ir::error::Result<(
1588 &[u8],
1589 fuel_loaders::quantized::GgmlDType,
1590 Vec<usize>,
1591 )> {
1592 let info = content
1593 .tensor_infos
1594 .get(name)
1595 .ok_or_else(|| content.missing_tensor_error(name))?;
1596 let elems = info.shape.elem_count();
1597 let block_size = info.ggml_dtype.block_size();
1598 let bytes_len = elems / block_size * info.ggml_dtype.type_size();
1599 let start = data_off + info.offset as usize;
1600 Ok((
1601 mc.bytes_at(start, bytes_len)?,
1602 info.ggml_dtype,
1603 info.shape.dims().to_vec(),
1604 ))
1605 };
1606
1607 let load_f32 = |name: &str| -> fuel_ir::error::Result<Vec<f32>> {
1610 let (bytes, dt, _dims) = get_tensor_bytes(name)?;
1611 dequant_gguf_bytes_to_f32(bytes, dt, name)
1612 };
1613
1614 let load_weight = |name: &str,
1618 out_features: usize,
1619 in_features: usize|
1620 -> fuel_ir::error::Result<WeightStorage> {
1621 let (bytes, dt, dims) = get_tensor_bytes(name)?;
1622 let expected_elems = out_features * in_features;
1624 let actual_elems: usize = dims.iter().product();
1625 if actual_elems != expected_elems {
1626 fuel_ir::bail!(
1627 "gguf: tensor {name:?} has {actual_elems} elements, expected {expected_elems} for [{out_features}, {in_features}]",
1628 );
1629 }
1630 let force_f32 = std::env::var("FUEL_FORCE_F32").is_ok();
1635 match dt {
1636 fuel_loaders::quantized::GgmlDType::Q4_0 if !force_f32 => Ok(WeightStorage::Q4_0 {
1637 words: bytes_to_u32_arc(bytes),
1638 bytes_len: bytes.len(),
1639 in_features,
1640 out_features,
1641 }),
1642 _ => {
1643 let f32_out_in = dequant_gguf_bytes_to_f32(bytes, dt, name)?;
1649 let mut f32_in_out = vec![0.0_f32; out_features * in_features];
1650 for o in 0..out_features {
1651 for i in 0..in_features {
1652 f32_in_out[i * out_features + o] = f32_out_in[o * in_features + i];
1653 }
1654 }
1655 Ok(WeightStorage::F32(Arc::from(f32_in_out)))
1656 }
1657 }
1658 };
1659
1660 let token_embedding = load_f32("token_embd.weight")?;
1661 if token_embedding.len() != cfg.vocab_size * cfg.dim {
1662 fuel_ir::bail!(
1663 "gguf token_embd: {} elems, expected {}×{}",
1664 token_embedding.len(),
1665 cfg.vocab_size,
1666 cfg.dim,
1667 );
1668 }
1669
1670 let mut layers: Vec<PhiLayerWeights> = Vec::with_capacity(cfg.n_layers);
1671 let kv_dim = cfg.n_heads * cfg.head_dim;
1672
1673 for i in 0..cfg.n_layers {
1674 let prefix = format!("blk.{i}");
1675
1676 let attn_qkv_weight =
1683 load_weight(&format!("{prefix}.attn_qkv.weight"), 3 * cfg.dim, cfg.dim)?;
1684 let qkv_bias_vec = load_f32(&format!("{prefix}.attn_qkv.bias"))?;
1685 if qkv_bias_vec.len() != 3 * cfg.dim {
1686 fuel_ir::bail!(
1687 "gguf attn_qkv.bias: {} elems, expected {}",
1688 qkv_bias_vec.len(),
1689 3 * cfg.dim
1690 );
1691 }
1692 let qkv_bias: Arc<[f32]> = Arc::from(qkv_bias_vec);
1693 let _ = kv_dim; let attn_dense =
1696 load_weight(&format!("{prefix}.attn_output.weight"), cfg.dim, cfg.dim)?;
1697 let attn_dense_bias = Arc::from(load_f32(&format!("{prefix}.attn_output.bias"))?);
1698
1699 let mlp_fc1 = load_weight(&format!("{prefix}.ffn_up.weight"), cfg.ffn_dim, cfg.dim)?;
1700 let mlp_fc1_bias = Arc::from(load_f32(&format!("{prefix}.ffn_up.bias"))?);
1701 let mlp_fc2 = load_weight(&format!("{prefix}.ffn_down.weight"), cfg.dim, cfg.ffn_dim)?;
1702 let mlp_fc2_bias = Arc::from(load_f32(&format!("{prefix}.ffn_down.bias"))?);
1703
1704 let norm_gain = Arc::from(load_f32(&format!("{prefix}.attn_norm.weight"))?);
1705 let norm_bias = Arc::from(load_f32(&format!("{prefix}.attn_norm.bias"))?);
1706
1707 layers.push(PhiLayerWeights {
1708 attn_qkv: PhiQkv::Packed {
1709 qkv: attn_qkv_weight,
1710 qkv_bias,
1711 },
1712 attn_dense,
1713 attn_dense_bias,
1714 mlp_fc1,
1715 mlp_fc1_bias,
1716 mlp_fc2,
1717 mlp_fc2_bias,
1718 norm_gain,
1719 norm_bias,
1720 });
1721 }
1722
1723 let final_norm_gain = Arc::from(load_f32("output_norm.weight")?);
1724 let final_norm_bias = Arc::from(load_f32("output_norm.bias")?);
1725
1726 let output = load_weight("output.weight", cfg.vocab_size, cfg.dim)?;
1728 let output_bias = load_f32("output.bias").ok().map(Arc::from);
1729
1730 Ok(PhiWeights {
1731 instance: fuel_tensor::decode_shape::ModelInstanceId::next(),
1732 token_embedding: Arc::from(token_embedding),
1733 layers,
1734 final_norm_gain,
1735 final_norm_bias,
1736 output,
1737 output_bias,
1738 })
1739 }
1740}
1741
1742fn dequant_gguf_bytes_to_f32(
1747 bytes: &[u8],
1748 dt: fuel_loaders::quantized::GgmlDType,
1749 name: &str,
1750) -> fuel_ir::error::Result<Vec<f32>> {
1751 use fuel_loaders::quantized::GgmlDType;
1752 use half::{bf16, f16};
1753 match dt {
1754 GgmlDType::F32 => {
1755 if !bytes.len().is_multiple_of(4) {
1756 fuel_ir::bail!(
1757 "gguf {name}: F32 byte count {} not multiple of 4",
1758 bytes.len()
1759 );
1760 }
1761 Ok(bytes
1762 .as_chunks::<4>()
1763 .0
1764 .iter()
1765 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
1766 .collect())
1767 }
1768 GgmlDType::F16 => {
1769 if !bytes.len().is_multiple_of(2) {
1770 fuel_ir::bail!(
1771 "gguf {name}: F16 byte count {} not multiple of 2",
1772 bytes.len()
1773 );
1774 }
1775 Ok(bytes
1776 .as_chunks::<2>()
1777 .0
1778 .iter()
1779 .map(|c| f16::from_le_bytes([c[0], c[1]]).to_f32())
1780 .collect())
1781 }
1782 GgmlDType::BF16 => {
1783 if !bytes.len().is_multiple_of(2) {
1784 fuel_ir::bail!(
1785 "gguf {name}: BF16 byte count {} not multiple of 2",
1786 bytes.len()
1787 );
1788 }
1789 Ok(bytes
1790 .as_chunks::<2>()
1791 .0
1792 .iter()
1793 .map(|c| bf16::from_le_bytes([c[0], c[1]]).to_f32())
1794 .collect())
1795 }
1796 GgmlDType::Q4_0 => {
1797 Ok(cpu_dequant_q4_0_bytes(bytes))
1800 }
1801 GgmlDType::Q8_0 => Ok(cpu_dequant_q8_0_bytes(bytes)),
1802 GgmlDType::Q6K => Ok(cpu_dequant_via_trait::<fuel_quantized::BlockQ6K>(bytes)),
1804 GgmlDType::Q5K => Ok(cpu_dequant_via_trait::<fuel_quantized::BlockQ5K>(bytes)),
1805 GgmlDType::Q4K => Ok(cpu_dequant_via_trait::<fuel_quantized::BlockQ4K>(bytes)),
1806 GgmlDType::Q3K => Ok(cpu_dequant_via_trait::<fuel_quantized::BlockQ3K>(bytes)),
1807 GgmlDType::Q2K => Ok(cpu_dequant_via_trait::<fuel_quantized::BlockQ2K>(bytes)),
1808 other => fuel_ir::bail!(
1809 "gguf {name}: dequant-to-f32 for dtype {other:?} not implemented in lazy loader"
1810 ),
1811 }
1812}
1813
1814fn cpu_dequant_via_trait<T: fuel_quantized::GgmlType>(bytes: &[u8]) -> Vec<f32> {
1820 let block_bytes = std::mem::size_of::<T>();
1821 assert!(
1822 bytes.len().is_multiple_of(block_bytes),
1823 "cpu_dequant_via_trait: bytes {} not multiple of block_bytes {}",
1824 bytes.len(),
1825 block_bytes
1826 );
1827 let n_blocks = bytes.len() / block_bytes;
1828 let blocks = fuel_quantized::blocks_from_bytes_cow::<T>(bytes);
1836 debug_assert_eq!(blocks.len(), n_blocks);
1837 let mut out = vec![0.0_f32; n_blocks * T::BLCK_SIZE];
1838 T::to_float(&blocks, &mut out);
1839 out
1840}
1841
1842fn bytes_to_u32_arc(bytes: &[u8]) -> Arc<[u32]> {
1846 assert_eq!(
1847 bytes.len() % 4,
1848 0,
1849 "bytes_to_u32_arc: len must be multiple of 4"
1850 );
1851 let words: Vec<u32> = bytes
1852 .as_chunks::<4>()
1853 .0
1854 .iter()
1855 .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]]))
1856 .collect();
1857 Arc::from(words)
1858}
1859
1860fn cpu_dequant_q4_0_bytes(bytes: &[u8]) -> Vec<f32> {
1861 use half::f16;
1862 let bpb = 18usize;
1863 let epb = 32usize;
1864 let n_blocks = bytes.len() / bpb;
1865 let mut out = vec![0.0_f32; n_blocks * epb];
1866 for b in 0..n_blocks {
1867 let off = b * bpb;
1868 let d = f16::from_le_bytes([bytes[off], bytes[off + 1]]).to_f32();
1869 let base = b * epb;
1870 for kk in 0..16 {
1871 let packed = bytes[off + 2 + kk];
1872 let lo = (packed & 0x0F) as i32 - 8;
1873 let hi = ((packed >> 4) & 0x0F) as i32 - 8;
1874 out[base + kk] = lo as f32 * d;
1875 out[base + 16 + kk] = hi as f32 * d;
1876 }
1877 }
1878 out
1879}
1880
1881fn cpu_dequant_q8_0_bytes(bytes: &[u8]) -> Vec<f32> {
1882 use half::f16;
1883 let bpb = 34usize;
1884 let epb = 32usize;
1885 let n_blocks = bytes.len() / bpb;
1886 let mut out = vec![0.0_f32; n_blocks * epb];
1887 for b in 0..n_blocks {
1888 let off = b * bpb;
1889 let d = f16::from_le_bytes([bytes[off], bytes[off + 1]]).to_f32();
1890 let base = b * epb;
1891 for kk in 0..32 {
1892 let q = bytes[off + 2 + kk] as i8 as i32;
1893 out[base + kk] = q as f32 * d;
1894 }
1895 }
1896 out
1897}
1898
1899fn partial_rope(
1906 x: &Tensor,
1907 cos: &Tensor,
1908 sin: &Tensor,
1909 rotary_dim: usize,
1910 head_dim: usize,
1911) -> Tensor {
1912 if rotary_dim == head_dim {
1913 return x.rope_with_tables(cos, sin).unwrap();
1914 }
1915 let rank = x.shape().dims().len();
1916 let last = rank - 1;
1917 let x_rot = x.slice(last, 0, rotary_dim).unwrap();
1918 let x_pass = x.slice(last, rotary_dim, head_dim - rotary_dim).unwrap();
1919 let x_rot_rotated = x_rot.rope_with_tables(cos, sin).unwrap();
1920 x_rot_rotated.concat(&x_pass, last).unwrap()
1921}
1922
1923#[cfg(test)]
1924impl PhiConfig {
1925 pub(crate) fn from_hf_json_str_legacy(json: &str) -> fuel_ir::error::Result<Self> {
1928 let v: serde_json::Value = serde_json::from_str(json)
1929 .map_err(|e| fuel_ir::error::Error::Msg(format!("parsing config.json: {e}")))?;
1930
1931 let get_usize = |key: &str| -> fuel_ir::error::Result<usize> {
1932 v.get(key)
1933 .and_then(|x| x.as_u64())
1934 .map(|x| x as usize)
1935 .ok_or_else(|| {
1936 fuel_ir::error::Error::Msg(format!(
1937 "config.json: missing/invalid field {key:?}"
1938 ))
1939 })
1940 };
1941 let get_f64 = |key: &str| -> Option<f64> { v.get(key).and_then(|x| x.as_f64()) };
1942
1943 let vocab_size = get_usize("vocab_size")?;
1944 let dim = get_usize("hidden_size")?;
1945 let n_layers = get_usize("num_hidden_layers")?;
1946 let n_heads = get_usize("num_attention_heads")?;
1947 let ffn_dim = get_usize("intermediate_size")?;
1948 let head_dim = v
1949 .get("head_dim")
1950 .and_then(|x| x.as_u64())
1951 .map(|x| x as usize)
1952 .unwrap_or(dim / n_heads);
1953 let layer_norm_eps = get_f64("layer_norm_eps").unwrap_or(1e-5);
1954 let rope_base = get_f64("rope_theta").unwrap_or(10_000.0);
1955 let partial_rotary_factor = get_f64("partial_rotary_factor").unwrap_or(0.4);
1956 let rotary_dim = (partial_rotary_factor * head_dim as f64).round() as usize;
1957 if !rotary_dim.is_multiple_of(2) {
1958 fuel_ir::bail!(
1959 "PhiConfig: rotary_dim {rotary_dim} must be even (partial_rotary_factor={partial_rotary_factor}, head_dim={head_dim})"
1960 );
1961 }
1962 let tie_word_embeddings = v
1963 .get("tie_word_embeddings")
1964 .and_then(|x| x.as_bool())
1965 .unwrap_or(false);
1966
1967 Ok(PhiConfig {
1968 vocab_size,
1969 dim,
1970 n_layers,
1971 n_heads,
1972 head_dim,
1973 ffn_dim,
1974 layer_norm_eps,
1975 rope_base,
1976 partial_rotary_factor,
1977 rotary_dim,
1978 tie_word_embeddings,
1979 })
1980 }
1981}
1982#[cfg(test)]
1983mod phi_config_tests {
1984 use super::PhiConfig;
1985
1986 const DIFFERENTIAL_CORPUS: &[(&str, &str)] = &[
1998 (
1999 "ADDED: phi-2 shaped, explicit head_dim equal to the quotient",
2000 r#"{
2001 "vocab_size": 51200, "hidden_size": 2560, "num_hidden_layers": 32,
2002 "num_attention_heads": 32, "intermediate_size": 10240,
2003 "head_dim": 80, "layer_norm_eps": 1e-5, "rope_theta": 10000.0,
2004 "partial_rotary_factor": 0.4
2005 }"#,
2006 ),
2007 (
2008 "ADDED: minimal — every optional absent, head_dim derived",
2009 r#"{
2010 "vocab_size": 51200, "hidden_size": 1024, "num_hidden_layers": 16,
2011 "num_attention_heads": 16, "intermediate_size": 4096
2012 }"#,
2013 ),
2014 (
2015 "ADDED: explicit head_dim 96 != 2560/32 = 80, and rotary_dim CHAINS off it",
2016 r#"{
2017 "vocab_size": 51200, "hidden_size": 2560, "num_hidden_layers": 32,
2018 "num_attention_heads": 32, "intermediate_size": 10240,
2019 "head_dim": 96, "partial_rotary_factor": 0.4
2020 }"#,
2021 ),
2022 (
2023 "ADDED: odd rotary_dim — both paths must REJECT (0.5 * 10 = 5)",
2024 r#"{
2025 "vocab_size": 100, "hidden_size": 40, "num_hidden_layers": 2,
2026 "num_attention_heads": 4, "intermediate_size": 80,
2027 "partial_rotary_factor": 0.5
2028 }"#,
2029 ),
2030 ];
2031
2032 #[test]
2033 fn serde_path_agrees_with_the_legacy_parser_on_every_fixture() {
2034 assert_eq!(DIFFERENTIAL_CORPUS.len(), 4, "corpus shrank");
2035 for (name, json) in DIFFERENTIAL_CORPUS {
2036 let new = PhiConfig::from_hf_json_str(json);
2037 let old = PhiConfig::from_hf_json_str_legacy(json);
2038 match (new, old) {
2039 (Ok(a), Ok(b)) => assert_eq!(a, b, "differential mismatch on {name}"),
2040 (Err(_), Err(_)) => {}
2041 (Ok(_), Err(e)) => panic!("{name}: serde accepted, legacy rejected: {e}"),
2042 (Err(e), Ok(_)) => panic!("{name}: serde rejected, legacy accepted: {e}"),
2043 }
2044 }
2045 }
2046
2047 #[test]
2048 fn rotary_dim_chains_off_the_resolved_head_dim() {
2049 let cfg = PhiConfig::from_hf_json_str(DIFFERENTIAL_CORPUS[2].1).unwrap();
2055 assert_eq!(cfg.head_dim, 96, "explicit head_dim must survive");
2056 assert_eq!(
2057 cfg.rotary_dim, 38,
2058 "rotary_dim must chain off the RESOLVED head_dim"
2059 );
2060 assert_ne!(
2061 cfg.rotary_dim, 32,
2062 "32 is what reading the raw quotient would give"
2063 );
2064 }
2065
2066 #[test]
2067 fn odd_rotary_dim_is_rejected_by_both_paths() {
2068 let json = DIFFERENTIAL_CORPUS[3].1;
2069 assert!(
2070 PhiConfig::from_hf_json_str(json).is_err(),
2071 "0.5 * 10 = 5 is odd"
2072 );
2073 assert!(
2074 PhiConfig::from_hf_json_str_legacy(json).is_err(),
2075 "legacy must agree"
2076 );
2077 }
2078}
2079
2080#[cfg(test)]
2081mod phi_kv_context_tests {
2082 use super::*;
2083 use fuel_tensor::{inference_context::InferenceContext, inference_context::KvCache};
2084
2085 fn make_tiny_phi(cfg: &PhiConfig, seed: u32) -> PhiWeights {
2096 let mut s: u32 = seed;
2097 let mut next = || -> f32 {
2098 s = s.wrapping_mul(1103515245).wrapping_add(12345);
2099 ((s >> 16) as u16 as f32 / 65535.0 - 0.5) * 0.1
2100 };
2101 let mut vec_of = |n: usize| -> Arc<[f32]> {
2102 let v: Vec<f32> = (0..n).map(|_| next()).collect();
2103 Arc::from(v)
2104 };
2105 let d = cfg.dim;
2106 let kv_dim = cfg.n_heads * cfg.head_dim;
2107 PhiWeights {
2108 instance: fuel_tensor::decode_shape::ModelInstanceId::next(),
2109 token_embedding: vec_of(cfg.vocab_size * d),
2110 layers: (0..cfg.n_layers)
2111 .map(|_| PhiLayerWeights {
2112 attn_qkv: PhiQkv::Split {
2113 q: vec_of(d * d).into(),
2114 q_bias: vec_of(d),
2115 k: vec_of(d * kv_dim).into(),
2116 k_bias: vec_of(kv_dim),
2117 v: vec_of(d * kv_dim).into(),
2118 v_bias: vec_of(kv_dim),
2119 },
2120 attn_dense: vec_of(d * d).into(),
2121 attn_dense_bias: vec_of(d),
2122 mlp_fc1: vec_of(d * cfg.ffn_dim).into(),
2123 mlp_fc1_bias: vec_of(cfg.ffn_dim),
2124 mlp_fc2: vec_of(cfg.ffn_dim * d).into(),
2125 mlp_fc2_bias: vec_of(d),
2126 norm_gain: Arc::from(vec![1.0_f32; d]),
2127 norm_bias: vec_of(d),
2128 })
2129 .collect(),
2130 final_norm_gain: Arc::from(vec![1.0_f32; d]),
2131 final_norm_bias: vec_of(d),
2132 output: vec_of(d * cfg.vocab_size).into(),
2133 output_bias: Some(vec_of(cfg.vocab_size)),
2134 }
2135 }
2136
2137 fn tiny_cfg() -> PhiConfig {
2138 PhiConfig {
2139 vocab_size: 16,
2140 dim: 8,
2141 n_layers: 2,
2142 n_heads: 2,
2143 head_dim: 4,
2144 ffn_dim: 16,
2145 layer_norm_eps: 1e-5,
2146 rope_base: 10000.0,
2147 partial_rotary_factor: 0.5,
2148 rotary_dim: 2,
2149 tie_word_embeddings: false,
2150 }
2151 }
2152
2153 #[test]
2159 fn phi_kv_context_decode_consistent_with_monolithic_prefill() {
2160 let cfg = tiny_cfg();
2161 let model = PhiModel {
2162 config: cfg.clone(),
2163 weights: make_tiny_phi(&cfg, 7777),
2164 };
2165 let tokens = [1_u32, 5, 9, 12];
2166 let device = Device::cpu();
2167
2168 let mut cache_a = KvCache::with_capacity(
2170 cfg.n_layers,
2171 cfg.n_heads,
2172 cfg.head_dim,
2173 tokens.len(),
2174 DType::F32,
2175 &device,
2176 )
2177 .expect("cache_a");
2178 let mut ctx_a = InferenceContext::new(device.clone());
2179 let expected = model
2180 .forward_with_kv_context(&tokens, &mut cache_a, &mut ctx_a)
2181 .expect("monolithic prefill");
2182
2183 let mut cache_b = KvCache::with_capacity(
2185 cfg.n_layers,
2186 cfg.n_heads,
2187 cfg.head_dim,
2188 tokens.len(),
2189 DType::F32,
2190 &device,
2191 )
2192 .expect("cache_b");
2193 let mut ctx_b = InferenceContext::new(device.clone());
2194 model
2195 .forward_with_kv_context(&tokens[..3], &mut cache_b, &mut ctx_b)
2196 .expect("prefill B");
2197 let actual = model
2198 .forward_with_kv_context(&tokens[3..], &mut cache_b, &mut ctx_b)
2199 .expect("decode B");
2200
2201 assert_eq!(actual.len(), expected.len());
2202 for (i, (a, b)) in actual.iter().zip(expected.iter()).enumerate() {
2205 let diff = (a - b).abs();
2206 let rel = diff / a.abs().max(b.abs()).max(1e-6);
2207 assert!(
2208 diff < 5e-3 || rel < 1e-2,
2209 "logit[{i}]: chunked={a}, monolithic={b}, diff={diff}",
2210 );
2211 }
2212 assert_eq!(cache_a.cached_len, cache_b.cached_len);
2213 }
2214
2215 #[test]
2219 fn phi_generate_with_kv_context_greedy_is_deterministic() {
2220 let cfg = tiny_cfg();
2221 let model = PhiModel {
2222 config: cfg.clone(),
2223 weights: make_tiny_phi(&cfg, 7777),
2224 };
2225 let prompt = [1_u32, 5, 9];
2226 let max_new = 8;
2227 let device = Device::cpu();
2228
2229 let mut streamed = Vec::new();
2230 let run_a = model
2231 .generate_streaming_with_kv_context(
2232 &prompt,
2233 max_new,
2234 SamplingStrategy::Greedy,
2235 None,
2236 &device,
2237 DType::F32,
2238 |t| streamed.push(t),
2239 )
2240 .expect("run a");
2241 let run_b = model
2242 .generate_with_kv_context(
2243 &prompt,
2244 max_new,
2245 SamplingStrategy::Greedy,
2246 None,
2247 &device,
2248 DType::F32,
2249 )
2250 .expect("run b");
2251
2252 assert_eq!(run_a, run_b, "greedy generation must be deterministic");
2253 assert_eq!(run_a.len(), prompt.len() + max_new);
2254 assert_eq!(&run_a[..prompt.len()], &prompt);
2255 assert_eq!(
2256 streamed,
2257 &run_a[prompt.len()..],
2258 "callback sees exactly the new tokens"
2259 );
2260 for &t in &run_a {
2261 assert!((t as usize) < cfg.vocab_size, "token {t} out of vocab");
2262 }
2263 }
2264
2265 #[test]
2269 fn phi_forward_with_kv_context_rejects_invalid_cache() {
2270 let cfg = tiny_cfg();
2271 let model = PhiModel {
2272 config: cfg.clone(),
2273 weights: make_tiny_phi(&cfg, 7777),
2274 };
2275 let device = Device::cpu();
2276 let mut ctx = InferenceContext::new(device.clone());
2277
2278 let mut dims_cache = KvCache::with_dims(cfg.n_layers, cfg.n_heads, cfg.head_dim);
2280 let err = model
2281 .forward_with_kv_context(&[1, 2], &mut dims_cache, &mut ctx)
2282 .expect_err("with_dims cache must be rejected");
2283 assert!(format!("{err}").contains("with_capacity"));
2284
2285 let mut small_cache = KvCache::with_capacity(
2287 cfg.n_layers,
2288 cfg.n_heads,
2289 cfg.head_dim,
2290 2,
2291 DType::F32,
2292 &device,
2293 )
2294 .expect("small cache");
2295 model
2296 .forward_with_kv_context(&[1, 2], &mut small_cache, &mut ctx)
2297 .expect("fits exactly");
2298 let err = model
2299 .forward_with_kv_context(&[3], &mut small_cache, &mut ctx)
2300 .expect_err("overflow must be rejected");
2301 assert!(format!("{err}").contains("max_seq_len"));
2302 }
2303
2304 #[test]
2324 fn phi_decode_matches_non_cached_forward() {
2325 let cfg = tiny_cfg(); let model = PhiModel {
2327 config: cfg.clone(),
2328 weights: make_tiny_phi(&cfg, 7777),
2329 };
2330
2331 let prompt = [1_u32, 5, 9];
2332 let next_token = 12_u32;
2333 let full = [prompt[0], prompt[1], prompt[2], next_token];
2334 let device = Device::cpu();
2335
2336 let mut cache_ref = KvCache::with_capacity(
2338 cfg.n_layers,
2339 cfg.n_heads,
2340 cfg.head_dim,
2341 full.len(),
2342 DType::F32,
2343 &device,
2344 )
2345 .expect("with_capacity ref");
2346 let mut ctx_ref = InferenceContext::new(device.clone());
2347 let expected = model
2348 .forward_with_kv_context(&full, &mut cache_ref, &mut ctx_ref)
2349 .expect("monolithic prefill");
2350
2351 let mut cache = KvCache::with_capacity(
2354 cfg.n_layers,
2355 cfg.n_heads,
2356 cfg.head_dim,
2357 full.len(),
2358 DType::F32,
2359 &device,
2360 )
2361 .expect("with_capacity");
2362 let mut ctx = InferenceContext::new(device);
2363 let _prefill = model
2364 .forward_with_kv_context(&prompt, &mut cache, &mut ctx)
2365 .expect("prefill");
2366 assert_eq!(cache.cached_len, prompt.len());
2367 let actual = model
2368 .forward_with_kv_context(&[next_token], &mut cache, &mut ctx)
2369 .expect("decode");
2370 assert_eq!(cache.cached_len, full.len());
2371 assert_eq!(actual.len(), expected.len());
2372
2373 for (i, (a, b)) in actual.iter().zip(expected.iter()).enumerate() {
2376 let diff = (a - b).abs();
2377 let rel = diff / a.abs().max(b.abs()).max(1e-6);
2378 assert!(
2379 diff < 5e-3 || rel < 1e-2,
2380 "logit[{i}]: input-independent={a}, monolithic={b}, diff={diff}",
2381 );
2382 }
2383 }
2384
2385 #[test]
2404 fn phi_persistent_plan_once_matches_d1() {
2405 let cfg = tiny_cfg(); let model_d2 = PhiModel {
2409 config: cfg.clone(),
2410 weights: make_tiny_phi(&cfg, 7777),
2411 };
2412 let model_d1 = PhiModel {
2413 config: cfg.clone(),
2414 weights: make_tiny_phi(&cfg, 7777),
2415 };
2416
2417 let prompt = [1_u32, 5, 9];
2418 let decode_tokens = [12_u32, 3, 7, 2]; let max_seq_len = prompt.len() + decode_tokens.len();
2420
2421 let dev1 = Device::cpu();
2425 let mut cache1 = KvCache::with_capacity(
2426 cfg.n_layers,
2427 cfg.n_heads,
2428 cfg.head_dim,
2429 max_seq_len,
2430 DType::F32,
2431 &dev1,
2432 )
2433 .expect("with_capacity d1");
2434 let mut ctx1 = InferenceContext::new(dev1);
2435 let _ = model_d1
2436 .forward_with_kv_context(&prompt, &mut cache1, &mut ctx1)
2437 .expect("d1 prefill");
2438 let mut d1_expected: Vec<Vec<f32>> = Vec::with_capacity(decode_tokens.len());
2439 for &tok in &decode_tokens {
2440 d1_expected.push(
2441 model_d1
2442 .forward_with_kv_context(&[tok], &mut cache1, &mut ctx1)
2443 .expect("d1 decode"),
2444 );
2445 }
2446
2447 let dev2 = Device::cpu();
2449 let mut cache2 = KvCache::with_capacity(
2450 cfg.n_layers,
2451 cfg.n_heads,
2452 cfg.head_dim,
2453 max_seq_len,
2454 DType::F32,
2455 &dev2,
2456 )
2457 .expect("with_capacity d2");
2458 let mut ctx2 = InferenceContext::new(dev2);
2459 let mut session: Option<fuel_tensor::inference_context::DecodeSession> = None;
2460
2461 let _ = model_d2
2463 .forward_with_kv_context_persistent(&prompt, &mut cache2, &mut ctx2, &mut session)
2464 .expect("d2 prefill");
2465 assert!(
2466 session.is_none(),
2467 "prefill (seq>1) must NOT build the held session"
2468 );
2469
2470 let opt_before = fuel_tensor::pipelined_bridge::optimize_calls_thread_local();
2474 let mut len_at_token2: Option<usize> = None;
2475
2476 for (i, &tok) in decode_tokens.iter().enumerate() {
2477 let d2 = model_d2
2478 .forward_with_kv_context_persistent(&[tok], &mut cache2, &mut ctx2, &mut session)
2479 .expect("d2 decode");
2480
2481 assert_eq!(
2483 d2, d1_expected[i],
2484 "persistent decode token {i} must be byte-identical to the D1 cached path",
2485 );
2486
2487 let sess = session
2488 .as_ref()
2489 .expect("session built on first decode token");
2490 let graph_len = sess.graph_node_count();
2491 if i == 1 {
2492 len_at_token2 = Some(graph_len);
2493 } else if i >= 2 {
2494 assert_eq!(
2496 Some(graph_len),
2497 len_at_token2,
2498 "held graph must NOT grow from token 2 onward (token {i})",
2499 );
2500 }
2501 }
2502
2503 let opt_after = fuel_tensor::pipelined_bridge::optimize_calls_thread_local();
2505 assert_eq!(
2506 opt_after - opt_before,
2507 1,
2508 "persistent decode must optimize EXACTLY ONCE across {} decode tokens \
2509 (the first builds the session; the rest skip optimize): {opt_before} -> {opt_after}",
2510 decode_tokens.len(),
2511 );
2512
2513 assert_eq!(cache2.cached_len, max_seq_len);
2514 assert_eq!(cache1.cached_len, max_seq_len);
2515 }
2516
2517 #[test]
2568 fn phi_attended_len_sym_is_unreferenced_negative_control() {
2569 let cfg = tiny_cfg();
2570 let model = PhiModel {
2571 config: cfg.clone(),
2572 weights: make_tiny_phi(&cfg, 7777),
2573 };
2574 let prompt = [1_u32, 5, 9];
2575 let max_seq_len = prompt.len() + 4;
2576
2577 let dev = Device::cpu();
2578 let mut cache = KvCache::with_capacity(
2579 cfg.n_layers,
2580 cfg.n_heads,
2581 cfg.head_dim,
2582 max_seq_len,
2583 DType::F32,
2584 &dev,
2585 )
2586 .expect("with_capacity");
2587 let mut ctx = InferenceContext::new(dev.clone());
2588 let mut session: Option<fuel_tensor::inference_context::DecodeSession> = None;
2589
2590 let _ = model
2592 .forward_with_kv_context_persistent(&prompt, &mut cache, &mut ctx, &mut session)
2593 .expect("prefill");
2594 let _ = model
2595 .forward_with_kv_context_persistent(&[12], &mut cache, &mut ctx, &mut session)
2596 .expect("build decode session");
2597 let s = session.as_ref().expect("session built");
2598
2599 let cached_len = cache.cached_len;
2603 let next = [3_u32];
2604 let mk_data = || {
2605 model
2606 .build_token_rope_mask_arcs(&dev, cached_len, &next, s.max_seq_len())
2607 .expect("token data")
2608 };
2609
2610 let mut env_ok = fuel_ir::SymEnv::new();
2611 env_ok
2612 .bind(s.cached_len_sym(), cached_len)
2613 .expect("bind cached_len");
2614 let baseline = s.realize_token(&dev, mk_data(), &env_ok).expect("baseline");
2615
2616 let mut env_bad_attended = fuel_ir::SymEnv::new();
2618 env_bad_attended
2619 .bind(s.cached_len_sym(), cached_len)
2620 .expect("bind cached_len");
2621 env_bad_attended
2622 .bind(s.attended_len_sym(), cached_len + 4242)
2623 .expect("bind attended_len (wrong on purpose)");
2624 let perturbed_attended = s
2625 .realize_token(&dev, mk_data(), &env_bad_attended)
2626 .expect("realize with wrong attended_len");
2627
2628 let other = [6_u32];
2633 let data_other = model
2634 .build_token_rope_mask_arcs(&dev, cached_len, &other, s.max_seq_len())
2635 .expect("token data (different token)");
2636 let mut env_ok2 = fuel_ir::SymEnv::new();
2637 env_ok2
2638 .bind(s.cached_len_sym(), cached_len)
2639 .expect("bind cached_len");
2640 let perturbed_data = s
2641 .realize_token(&dev, data_other, &env_ok2)
2642 .expect("realize with different token");
2643 assert_ne!(
2644 perturbed_data, baseline,
2645 "control A FAILED: a DIFFERENT input token produced identical \
2646 logits, so realize_token is not responding to its inputs and no \
2647 verdict from this test means anything",
2648 );
2649
2650 let with_off = s.offset_node().is_some();
2652 let mut env_bad_cached = fuel_ir::SymEnv::new();
2653 env_bad_cached
2654 .bind(s.cached_len_sym(), cached_len + 1)
2655 .expect("bind cached_len (wrong on purpose)");
2656 let perturbed_cached = s
2657 .realize_token(&dev, mk_data(), &env_bad_cached)
2658 .expect("realize with wrong cached_len");
2659
2660 if with_off {
2666 assert_eq!(
2667 perturbed_cached, baseline,
2668 "on the device-offset path the KV offset rides the offset \
2669 BUFFER, so a wrong cached_len_sym should be inert — it moved \
2670 the output, meaning the symbol IS load-bearing here",
2671 );
2672 } else {
2673 assert_ne!(
2674 perturbed_cached, baseline,
2675 "on the SymEnv path the KV offset rides cached_len_sym, so a \
2676 wrong binding MUST move the output; it did not, so this test \
2677 cannot detect referencedness and its verdict is vacuous",
2678 );
2679 }
2680
2681 assert_eq!(
2682 perturbed_attended, baseline,
2683 "attended_len_sym IS referenced by Phi's decode graph — the \
2684 'carried for API parity but never referenced' comment at \
2685 lazy.rs:12088 is FALSE, and sharing per_token_sym_env between \
2686 Llama and Phi is NOT the no-op the GAP-029 2b design assumes",
2687 );
2688
2689 eprintln!(
2700 "[gap-029 2b control] phi: offset_node.is_some()={with_off} \
2701 ({} path; SymEnv live={})",
2702 if with_off { "device-offset" } else { "SymEnv" },
2703 !with_off,
2704 );
2705 }
2706
2707 #[test]
2710 fn phi_generate_loop_persistent_byte_exact_and_plans_once() {
2711 let cfg = tiny_cfg();
2712 let model = PhiModel {
2713 config: cfg.clone(),
2714 weights: make_tiny_phi(&cfg, 7777),
2715 };
2716
2717 let prompt = [1_u32, 5, 9];
2718 let max_new = 5; let max_seq_len = prompt.len() + max_new;
2720 let strategy = SamplingStrategy::Greedy;
2721
2722 let dev1 = Device::cpu();
2726 let mut cache1 = KvCache::with_capacity(
2727 cfg.n_layers,
2728 cfg.n_heads,
2729 cfg.head_dim,
2730 max_seq_len,
2731 DType::F32,
2732 &dev1,
2733 )
2734 .expect("with_capacity d1");
2735 let mut ctx1 = InferenceContext::new(dev1);
2736 let mut rng1: u64 = 0;
2737 let mut ref_tokens: Vec<u32> = prompt.to_vec();
2738 let mut ref_step_logits: Vec<Vec<f32>> = Vec::with_capacity(max_new);
2739 let mut last1 = model
2740 .forward_with_kv_context(&prompt, &mut cache1, &mut ctx1)
2741 .expect("d1 prefill");
2742 for _ in 0..max_new {
2743 let next = sample_logits(&last1, strategy, &mut rng1);
2744 ref_tokens.push(next);
2745 last1 = model
2746 .forward_with_kv_context(&[next], &mut cache1, &mut ctx1)
2747 .expect("d1 decode");
2748 ref_step_logits.push(last1.clone());
2749 }
2750
2751 let opt_before = fuel_tensor::pipelined_bridge::optimize_calls_thread_local();
2755
2756 let dev2 = Device::cpu();
2757 let mut cache2 = KvCache::with_capacity(
2758 cfg.n_layers,
2759 cfg.n_heads,
2760 cfg.head_dim,
2761 max_seq_len,
2762 DType::F32,
2763 &dev2,
2764 )
2765 .expect("with_capacity d2");
2766 let mut ctx2 = InferenceContext::new(dev2);
2767 let mut rng2: u64 = 0;
2768 let mut session: Option<fuel_tensor::inference_context::DecodeSession> = None;
2769 let mut d2_tokens: Vec<u32> = prompt.to_vec();
2770 let mut d2_step_logits: Vec<Vec<f32>> = Vec::with_capacity(max_new);
2771 let mut last2 = model
2772 .forward_with_kv_context_persistent(&prompt, &mut cache2, &mut ctx2, &mut session)
2773 .expect("d2 prefill");
2774 assert!(
2775 session.is_none(),
2776 "prefill (seq>1) must NOT build the held session"
2777 );
2778 for _ in 0..max_new {
2779 let next = sample_logits(&last2, strategy, &mut rng2);
2780 d2_tokens.push(next);
2781 last2 = model
2782 .forward_with_kv_context_persistent(&[next], &mut cache2, &mut ctx2, &mut session)
2783 .expect("d2 decode");
2784 d2_step_logits.push(last2.clone());
2785 }
2786
2787 let opt_after = fuel_tensor::pipelined_bridge::optimize_calls_thread_local();
2788
2789 assert_eq!(
2791 d2_tokens, ref_tokens,
2792 "persistent generate loop must produce the byte-identical token sequence \
2793 as the D1 rebuild path over {max_new} greedy tokens",
2794 );
2795
2796 assert_eq!(d2_step_logits.len(), ref_step_logits.len());
2798 for (i, (d2, d1)) in d2_step_logits
2799 .iter()
2800 .zip(ref_step_logits.iter())
2801 .enumerate()
2802 {
2803 assert_eq!(
2804 d2, d1,
2805 "persistent decode step {i} logits must be byte-identical to the D1 cached path",
2806 );
2807 }
2808
2809 assert_eq!(
2812 opt_after - opt_before,
2813 2,
2814 "persistent generate must optimize EXACTLY twice (1 prefill fallback + 1 \
2815 decode-session build) regardless of N={max_new} decode tokens: \
2816 {opt_before} -> {opt_after}",
2817 );
2818
2819 assert!(session.is_some(), "held session survives the decode loop");
2820 assert_eq!(cache2.cached_len, max_seq_len);
2821 assert_eq!(cache1.cached_len, max_seq_len);
2822
2823 let via_wrapper = model
2825 .generate_with_kv_context(&prompt, max_new, strategy, None, &Device::cpu(), DType::F32)
2826 .expect("generate_with_kv_context");
2827 assert_eq!(
2828 via_wrapper, ref_tokens,
2829 "generate_with_kv_context (wired to the persistent path) must produce the \
2830 byte-identical token sequence as the D1 reference",
2831 );
2832 }
2833
2834 #[test]
2856 fn phi_persistent_plan_reads_a_write_bytes_overwrite_without_rebuilding() {
2857 let cfg = tiny_cfg();
2858 let model = PhiModel {
2859 config: cfg.clone(),
2860 weights: make_tiny_phi(&cfg, 7777),
2861 };
2862 let prompt = [1_u32, 5, 9];
2863 let decode_steps_before_overwrite = 2;
2864 let max_seq_len = prompt.len() + decode_steps_before_overwrite + 1;
2865 let strategy = SamplingStrategy::Greedy;
2866
2867 let run_to_overwrite_point = || {
2871 let device = Device::cpu();
2872 let mut cache = KvCache::with_capacity(
2873 cfg.n_layers,
2874 cfg.n_heads,
2875 cfg.head_dim,
2876 max_seq_len,
2877 DType::F32,
2878 &device,
2879 )
2880 .expect("with_capacity");
2881 let mut ctx = InferenceContext::new(device);
2882 let mut rng: u64 = 0;
2883 let mut session: Option<fuel_tensor::inference_context::DecodeSession> = None;
2884 let mut tokens: Vec<u32> = prompt.to_vec();
2885 let mut last = model
2886 .forward_with_kv_context_persistent(&prompt, &mut cache, &mut ctx, &mut session)
2887 .expect("prefill");
2888 for _ in 0..decode_steps_before_overwrite {
2889 let next = sample_logits(&last, strategy, &mut rng);
2890 tokens.push(next);
2891 last = model
2892 .forward_with_kv_context_persistent(&[next], &mut cache, &mut ctx, &mut session)
2893 .expect("decode (pre-overwrite)");
2894 }
2895 (cache, ctx, session, tokens, rng)
2896 };
2897
2898 let (mut ref_cache, mut ref_ctx, mut ref_session, ref_tokens, _ref_rng) =
2900 run_to_overwrite_point();
2901 assert!(
2902 ref_session.is_some(),
2903 "the held DecodeSession must exist by now (built on the first decode token)",
2904 );
2905 let ref_next_logits = model
2906 .forward_with_kv_context_persistent(
2907 &[*ref_tokens.last().unwrap()],
2908 &mut ref_cache,
2909 &mut ref_ctx,
2910 &mut ref_session,
2911 )
2912 .expect("reference decode (no overwrite)");
2913
2914 let (mut ow_cache, mut ow_ctx, mut ow_session, ow_tokens, _ow_rng) =
2918 run_to_overwrite_point();
2919 assert_eq!(
2920 ow_tokens, ref_tokens,
2921 "both runs must reach an identical token stream before the overwrite \
2922 (same model, same seed, same prompt) — divergence must come ONLY from the write",
2923 );
2924
2925 let alloc_before = ow_cache.alloc_id();
2926 let loc_before = ow_cache.device_location();
2927 let opt_before_write = fuel_tensor::pipelined_bridge::optimize_calls_thread_local();
2928
2929 let payload: Vec<f32> = (0..(cfg.n_heads * cfg.head_dim))
2932 .map(|i| 9000.0 + i as f32)
2933 .collect();
2934 let payload_bytes: Vec<u8> = payload.iter().flat_map(|f| f.to_le_bytes()).collect();
2935 ow_cache
2936 .write_bytes(0, KvSlot::K, 0, 1, &payload_bytes, &Device::cpu())
2937 .expect("write_bytes");
2938
2939 assert_eq!(
2940 ow_cache.alloc_id(),
2941 alloc_before,
2942 "write_bytes must not re-mint alloc_id",
2943 );
2944 assert_eq!(
2945 ow_cache.device_location(),
2946 loc_before,
2947 "write_bytes must not clear device_location",
2948 );
2949
2950 let opt_after_write = fuel_tensor::pipelined_bridge::optimize_calls_thread_local();
2957 assert_eq!(
2958 opt_after_write - opt_before_write,
2959 1,
2960 "write_bytes's own one-off realize should cost exactly one optimize call \
2961 for its throwaway graph (same shape as DeviceKvPool::write_block_bytes) — \
2962 a different count means this assumption needs re-checking",
2963 );
2964
2965 let ow_next_logits = model
2966 .forward_with_kv_context_persistent(
2967 &[*ow_tokens.last().unwrap()],
2968 &mut ow_cache,
2969 &mut ow_ctx,
2970 &mut ow_session,
2971 )
2972 .expect("overwrite-run decode (post-overwrite)");
2973
2974 let opt_after_decode = fuel_tensor::pipelined_bridge::optimize_calls_thread_local();
2975 assert_eq!(
2976 opt_after_decode, opt_after_write,
2977 "the decode step AFTER write_bytes must not trigger a plan rebuild — \
2978 optimize_calls_thread_local must be unchanged across it specifically \
2979 (write_bytes's own one-off optimize, measured above, is expected and excluded)",
2980 );
2981
2982 assert_ne!(
2987 ow_next_logits, ref_next_logits,
2988 "the decode step after write_bytes must differ from the un-overwritten \
2989 reference — otherwise the held plan never read the write at all",
2990 );
2991 }
2992
2993 #[test]
3008 #[cfg(feature = "cuda")]
3009 #[ignore = "requires a live CUDA device"]
3010 fn phi_decode_node_placement_report_cuda() {
3011 use std::collections::BTreeMap;
3012
3013 let cfg = tiny_cfg();
3014 let dev: Device = match fuel_cuda_backend::CudaDevice::new(0) {
3015 Ok(d) => d.into(),
3016 Err(e) => {
3017 return fuel_test_support::hardware::skip(
3018 fuel_test_support::hardware::Hardware::Cuda,
3019 fuel_test_support::hardware::Missing::device(format!(
3020 "CudaDevice::new(0): {e:?}"
3021 )),
3022 );
3023 }
3024 };
3025 let model = PhiModel {
3026 config: cfg.clone(),
3027 weights: make_tiny_phi(&cfg, 7),
3028 };
3029 let prompt = [1_u32, 2, 3];
3030 let max_seq_len = prompt.len() + 4;
3031
3032 let mut cache = KvCache::with_capacity(
3033 cfg.n_layers,
3034 cfg.n_heads,
3035 cfg.head_dim,
3036 max_seq_len,
3037 DType::F32,
3038 &dev,
3039 )
3040 .expect("with_capacity");
3041 let mut ctx = InferenceContext::new(dev.clone());
3042 let mut sess: Option<fuel_tensor::inference_context::DecodeSession> = None;
3043 model
3044 .forward_with_kv_context_persistent(&prompt, &mut cache, &mut ctx, &mut sess)
3045 .expect("prefill");
3046 model
3047 .forward_with_kv_context_persistent(&[4], &mut cache, &mut ctx, &mut sess)
3048 .expect("first decode token builds the held plan");
3049 let s = sess.as_ref().expect("held session");
3050
3051 let opt = s.optimized();
3052 assert!(
3053 opt.has_placements(),
3054 "placement NOT COMPUTED — every lookup would be None and the report below would describe a missing instrument, not the graph",
3055 );
3056
3057 let g = s.graph().read().expect("graph lock");
3058 let mut by_op: BTreeMap<String, BTreeMap<String, usize>> = BTreeMap::new();
3059 let mut host_nodes: Vec<String> = Vec::new();
3060 for i in 0..g.len() {
3061 let id = fuel_graph::NodeId(i);
3062 let op_name = match &g.node(id).op {
3063 fuel_graph::Op::Fused(fid, _) => format!("Fused({fid:?})"),
3064 other => format!("{other:?}")
3065 .split(' ')
3066 .next()
3067 .unwrap_or("?")
3068 .to_string(),
3069 };
3070 let place = match opt.placement_of(id) {
3071 Some(d) => format!("{d:?}"),
3072 None => "None".to_string(),
3073 };
3074 if place.starts_with("Cpu") {
3075 host_nodes.push(format!("#{i} {op_name}"));
3076 }
3077 *by_op.entry(op_name).or_default().entry(place).or_insert(0) += 1;
3078 }
3079
3080 println!(
3081 "
3082=== Phi decode plan: node placement (CUDA) ==="
3083 );
3084 println!("total nodes: {}", g.len());
3085 for (op, places) in &by_op {
3086 let r: Vec<String> = places.iter().map(|(d, n)| format!("{d}x{n}")).collect();
3087 println!(" {op:<34} {}", r.join(" "));
3088 }
3089 println!(
3090 "
3091--- HOST-PLACED NODES ({}) ---",
3092 host_nodes.len()
3093 );
3094 for h in &host_nodes {
3095 println!(" {h}");
3096 }
3097 println!(
3098 "--- END ---
3099"
3100 );
3101 }
3102
3103 #[test]
3127 #[cfg(feature = "cuda")]
3128 #[ignore = "requires a live CUDA device"]
3129 fn phi_forward_with_kv_context_captured_matches_persistent() {
3130 let cfg = tiny_cfg();
3131
3132 let cuda = match fuel_cuda_backend::CudaDevice::new(0) {
3133 Ok(d) => d,
3134 Err(e) => {
3135 return fuel_test_support::hardware::skip(
3136 fuel_test_support::hardware::Hardware::Cuda,
3137 fuel_test_support::hardware::Missing::device(format!(
3138 "CudaDevice::new(0): {e:?}"
3139 )),
3140 );
3141 }
3142 };
3143 let dev: Device = cuda.into();
3144
3145 let prompt = [1_u32, 2, 3];
3146 let decode_tokens = [4_u32, 5, 6, 7]; let max_seq_len = prompt.len() + decode_tokens.len();
3148
3149 let model_ref = PhiModel {
3152 config: cfg.clone(),
3153 weights: make_tiny_phi(&cfg, 7),
3154 };
3155 let model_cap = PhiModel {
3156 config: cfg.clone(),
3157 weights: make_tiny_phi(&cfg, 7),
3158 };
3159
3160 let mut cache_ref = KvCache::with_capacity(
3162 cfg.n_layers,
3163 cfg.n_heads,
3164 cfg.head_dim,
3165 max_seq_len,
3166 DType::F32,
3167 &dev,
3168 )
3169 .expect("with_capacity ref");
3170 let mut ctx_ref = InferenceContext::new(dev.clone());
3171 let mut sess_ref: Option<fuel_tensor::inference_context::DecodeSession> = None;
3172 model_ref
3173 .forward_with_kv_context_persistent(
3174 &prompt,
3175 &mut cache_ref,
3176 &mut ctx_ref,
3177 &mut sess_ref,
3178 )
3179 .expect("ref prefill");
3180 let mut ref_logits: Vec<Vec<f32>> = Vec::with_capacity(decode_tokens.len());
3181 for &tok in &decode_tokens {
3182 ref_logits.push(
3183 model_ref
3184 .forward_with_kv_context_persistent(
3185 &[tok],
3186 &mut cache_ref,
3187 &mut ctx_ref,
3188 &mut sess_ref,
3189 )
3190 .expect("ref decode"),
3191 );
3192 }
3193
3194 let mut cache_cap = KvCache::with_capacity(
3196 cfg.n_layers,
3197 cfg.n_heads,
3198 cfg.head_dim,
3199 max_seq_len,
3200 DType::F32,
3201 &dev,
3202 )
3203 .expect("with_capacity captured");
3204 let mut ctx_cap = InferenceContext::new(dev.clone());
3205 let mut sess_cap: Option<fuel_tensor::inference_context::DecodeSession> = None;
3206 let mut captured: Option<fuel_dispatch::pipelined::CapturedDecodeSession> = None;
3207 model_cap
3208 .forward_with_kv_context_captured(
3209 &prompt,
3210 &mut cache_cap,
3211 &mut ctx_cap,
3212 &mut sess_cap,
3213 &mut captured,
3214 )
3215 .expect("captured prefill");
3216 assert!(
3217 captured.is_none(),
3218 "prefill (seq != 1) must NOT build a capture"
3219 );
3220
3221 for (i, &tok) in decode_tokens.iter().enumerate() {
3222 let got = model_cap
3223 .forward_with_kv_context_captured(
3224 &[tok],
3225 &mut cache_cap,
3226 &mut ctx_cap,
3227 &mut sess_cap,
3228 &mut captured,
3229 )
3230 .expect("captured decode");
3231
3232 assert_eq!(
3233 got, ref_logits[i],
3234 "Phi captured decode token {i} must be BYTE-IDENTICAL to the persistent path (same plan => same kernels). A mismatch here on tokens 3+ is the partial-rotary replay-bytes failure this test exists for.",
3235 );
3236
3237 if i == 0 {
3238 assert!(sess_cap.is_some(), "token 1 builds the held session");
3239 assert!(captured.is_none(), "token 1 must NOT build the capture yet");
3240 }
3241 }
3242
3243 assert_eq!(cache_cap.cached_len, max_seq_len);
3246 assert_eq!(cache_ref.cached_len, max_seq_len);
3247
3248 if captured.is_some() {
3266 println!("Phi capture FORMED — the decode graph is fully CUDA-resident");
3267 } else {
3268 println!(
3269 "Phi capture DECLINED (expected today) — host-placed fused LayerNormLastDim/ROPE force a cross-device Copy. Results were byte-identical via the persistent fallback, which is the property that matters: capture degrades, never fails."
3270 );
3271 }
3272 }
3273}
3274
3275#[cfg(test)]
3282mod bail_consolidation_tests {
3283 fn always_bails() -> fuel_ir::error::Result<()> {
3284 fuel_ir::bail!("deliberate failure for the fuel-core dissolution bail! consolidation test");
3285 #[allow(unreachable_code)]
3286 Ok(())
3287 }
3288
3289 #[test]
3290 fn fuel_core_bail_still_produces_a_typed_err_with_the_message() {
3291 let err = always_bails().expect_err("bail! must produce an Err, never panic");
3292 assert!(err.to_string().contains("deliberate failure"));
3293 }
3294}