1use crate::inference_context::InferenceContext;
43use crate::{DType, Device, Shape};
44use fuel_ir::shape::{Dim, Dims};
45use std::sync::Arc;
46
47#[derive(Clone, Debug)]
98pub struct Tensor {
99 pub(crate) inner: fuel_graph::NodeHandle,
104}
105
106impl Tensor {
107 pub fn from_f32(
129 data: impl Into<Arc<[f32]>>,
130 shape: impl Into<Shape>,
131 device: &crate::Device,
132 ) -> fuel_ir::Result<Self> {
133 Ok(Self {
134 inner: fuel_graph::NodeHandle::from_f32(data, shape, device.as_dyn())?,
135 })
136 }
137
138 pub fn graph_id(&self) -> fuel_graph::GraphId {
141 self.inner.graph_id()
142 }
143
144 pub fn graph(&self) -> &fuel_graph::SharedGraph {
147 self.inner.graph()
148 }
149
150 pub fn from_f32_on(
164 graph: &fuel_graph::SharedGraph,
165 data: impl Into<Arc<[f32]>>,
166 shape: impl Into<Shape>,
167 device: &crate::Device,
168 ) -> fuel_ir::Result<Self> {
169 Ok(Self {
170 inner: fuel_graph::NodeHandle::from_f32_on(graph, data, shape, device.as_dyn())?,
171 })
172 }
173
174 pub fn from_f64_on(
176 graph: &fuel_graph::SharedGraph,
177 data: impl Into<Arc<[f64]>>,
178 shape: impl Into<Shape>,
179 device: &crate::Device,
180 ) -> fuel_ir::Result<Self> {
181 Ok(Self {
182 inner: fuel_graph::NodeHandle::from_f64_on(graph, data, shape, device.as_dyn())?,
183 })
184 }
185
186 pub fn from_bf16_on(
190 graph: &fuel_graph::SharedGraph,
191 data: impl Into<Arc<[half::bf16]>>,
192 shape: impl Into<Shape>,
193 device: &crate::Device,
194 ) -> fuel_ir::Result<Self> {
195 Ok(Self {
196 inner: fuel_graph::NodeHandle::from_bf16_on(graph, data, shape, device.as_dyn())?,
197 })
198 }
199
200 pub fn from_f16_on(
202 graph: &fuel_graph::SharedGraph,
203 data: impl Into<Arc<[half::f16]>>,
204 shape: impl Into<Shape>,
205 device: &crate::Device,
206 ) -> fuel_ir::Result<Self> {
207 Ok(Self {
208 inner: fuel_graph::NodeHandle::from_f16_on(graph, data, shape, device.as_dyn())?,
209 })
210 }
211
212 pub fn from_u32_on(
215 graph: &fuel_graph::SharedGraph,
216 data: impl Into<Arc<[u32]>>,
217 shape: impl Into<Shape>,
218 device: &crate::Device,
219 ) -> fuel_ir::Result<Self> {
220 Ok(Self {
221 inner: fuel_graph::NodeHandle::from_u32_on(graph, data, shape, device.as_dyn())?,
222 })
223 }
224
225 pub fn from_f64(
232 data: impl Into<Arc<[f64]>>,
233 shape: impl Into<Shape>,
234 device: &crate::Device,
235 ) -> fuel_ir::Result<Self> {
236 Ok(Self {
237 inner: fuel_graph::NodeHandle::from_f64(data, shape, device.as_dyn())?,
238 })
239 }
240
241 pub fn from_bf16(
250 data: impl Into<Arc<[half::bf16]>>,
251 shape: impl Into<Shape>,
252 device: &crate::Device,
253 ) -> fuel_ir::Result<Self> {
254 Ok(Self {
255 inner: fuel_graph::NodeHandle::from_bf16(data, shape, device.as_dyn())?,
256 })
257 }
258
259 pub fn from_f16(
262 data: impl Into<Arc<[half::f16]>>,
263 shape: impl Into<Shape>,
264 device: &crate::Device,
265 ) -> fuel_ir::Result<Self> {
266 Ok(Self {
267 inner: fuel_graph::NodeHandle::from_f16(data, shape, device.as_dyn())?,
268 })
269 }
270
271 pub fn from_u32(
275 data: impl Into<Arc<[u32]>>,
276 shape: impl Into<Shape>,
277 device: &crate::Device,
278 ) -> fuel_ir::Result<Self> {
279 Ok(Self {
280 inner: fuel_graph::NodeHandle::from_u32(data, shape, device.as_dyn())?,
281 })
282 }
283
284 pub fn const_f32_like(
295 &self,
296 data: impl Into<Arc<[f32]>>,
297 shape: impl Into<Shape>,
298 ) -> std::result::Result<Self, fuel_ir::Error> {
299 Ok(Self {
300 inner: self.inner.const_f32_like(data, shape)?,
301 })
302 }
303
304 pub fn const_f16_like(
306 &self,
307 data: impl Into<Arc<[half::f16]>>,
308 shape: impl Into<Shape>,
309 ) -> std::result::Result<Self, fuel_ir::Error> {
310 Ok(Self {
311 inner: self.inner.const_f16_like(data, shape)?,
312 })
313 }
314
315 pub fn const_bf16_like(
319 &self,
320 data: impl Into<Arc<[half::bf16]>>,
321 shape: impl Into<Shape>,
322 ) -> std::result::Result<Self, fuel_ir::Error> {
323 Ok(Self {
324 inner: self.inner.const_bf16_like(data, shape)?,
325 })
326 }
327
328 pub fn const_like_dtype(
340 &self,
341 data: &[f32],
342 shape: impl Into<Shape>,
343 dtype: fuel_ir::DType,
344 ) -> std::result::Result<Self, fuel_ir::Error> {
345 match dtype {
346 fuel_ir::DType::F32 => self.const_f32_like(data.to_vec(), shape),
347 fuel_ir::DType::BF16 => {
348 let converted: Vec<half::bf16> =
349 data.iter().map(|&v| half::bf16::from_f32(v)).collect();
350 self.const_bf16_like(converted, shape)
351 }
352 other => Err(fuel_ir::Error::Msg(format!(
353 "const_like_dtype: unsupported activation dtype {other:?} \
354 (expected F32 or BF16)",
355 ))
356 .bt()),
357 }
358 }
359
360 pub fn into_graph_tensor(self) -> fuel_graph::NodeHandle {
364 self.inner
365 }
366
367 pub fn graph_tensor(&self) -> &fuel_graph::NodeHandle {
369 &self.inner
370 }
371
372 pub fn from_graph_tensor(t: fuel_graph::NodeHandle) -> Self {
376 Self { inner: t }
377 }
378
379 pub fn shape(&self) -> Shape {
383 self.inner.shape()
384 }
385
386 pub fn dtype(&self) -> DType {
388 self.inner.dtype()
389 }
390
391 pub fn graph_handle(&self) -> &fuel_graph::SharedGraph {
399 self.inner.graph()
400 }
401
402 pub fn node_id(&self) -> fuel_graph::NodeId {
404 self.inner.id()
405 }
406
407 pub fn rank(&self) -> usize {
409 self.inner.shape().dims().len()
410 }
411
412 pub fn elem_count(&self) -> usize {
414 self.inner.shape().elem_count()
415 }
416
417 pub fn numel(&self) -> usize {
419 self.elem_count()
420 }
421
422 pub fn dim<D: Dim>(&self, dim: D) -> std::result::Result<usize, fuel_ir::Error> {
426 let shape = self.inner.shape();
427 let dim = dim.to_index(&shape, "dim")?;
428 Ok(shape.dims()[dim])
429 }
430
431 pub fn add(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
436 self.check_strict_binary("add", other)?;
437 Ok(Self {
438 inner: self.inner.add(&other.inner),
439 })
440 }
441
442 pub fn sub(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
444 self.check_strict_binary("sub", other)?;
445 Ok(Self {
446 inner: self.inner.sub(&other.inner),
447 })
448 }
449
450 pub fn mul(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
452 self.check_strict_binary("mul", other)?;
453 Ok(Self {
454 inner: self.inner.mul(&other.inner),
455 })
456 }
457
458 pub fn div(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
460 self.check_strict_binary("div", other)?;
461 Ok(Self {
462 inner: self.inner.div(&other.inner),
463 })
464 }
465
466 pub fn maximum(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
468 self.check_strict_binary("maximum", other)?;
469 Ok(Self {
470 inner: self.inner.maximum(&other.inner),
471 })
472 }
473
474 pub fn minimum(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
476 self.check_strict_binary("minimum", other)?;
477 Ok(Self {
478 inner: self.inner.minimum(&other.inner),
479 })
480 }
481
482 pub fn fmax_ieee(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
486 self.check_strict_binary("fmax_ieee", other)?;
487 Ok(Self {
488 inner: self.inner.fmax_ieee(&other.inner),
489 })
490 }
491
492 pub fn fmin_ieee(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
495 self.check_strict_binary("fmin_ieee", other)?;
496 Ok(Self {
497 inner: self.inner.fmin_ieee(&other.inner),
498 })
499 }
500
501 pub fn rem_trunc(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
505 self.check_strict_binary("rem_trunc", other)?;
506 Ok(Self {
507 inner: self.inner.rem_trunc(&other.inner),
508 })
509 }
510
511 pub fn trunc(&self) -> Self {
515 Self {
516 inner: self.inner.trunc(),
517 }
518 }
519
520 pub fn eq(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
525 self.check_strict_binary("eq", other)?;
526 Ok(Self {
527 inner: self.inner.eq(&other.inner),
528 })
529 }
530
531 pub fn ne(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
535 self.check_strict_binary("ne", other)?;
536 Ok(Self {
537 inner: self.inner.ne(&other.inner),
538 })
539 }
540
541 pub fn lt(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
545 self.check_strict_binary("lt", other)?;
546 Ok(Self {
547 inner: self.inner.lt(&other.inner),
548 })
549 }
550
551 pub fn le(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
554 self.check_strict_binary("le", other)?;
555 Ok(Self {
556 inner: self.inner.le(&other.inner),
557 })
558 }
559
560 pub fn gt(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
563 self.check_strict_binary("gt", other)?;
564 Ok(Self {
565 inner: self.inner.gt(&other.inner),
566 })
567 }
568
569 pub fn ge(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
574 self.check_strict_binary("ge", other)?;
575 Ok(Self {
576 inner: self.inner.ge(&other.inner),
577 })
578 }
579
580 pub fn where_cond(&self, a: &Self, b: &Self) -> std::result::Result<Self, fuel_ir::Error> {
588 if self.inner.dtype() != fuel_ir::DType::Bool {
595 return Err(fuel_ir::Error::Msg(format!(
596 "where_cond: cond mask must be Bool, got {:?} — cast a numeric \
597 mask to Bool explicitly (GAP-168(c))",
598 self.inner.dtype(),
599 ))
600 .bt());
601 }
602 if a.inner.dtype() != b.inner.dtype() {
603 return Err(fuel_ir::Error::Msg(format!(
604 "where_cond: branches must share dtype, got a={:?} b={:?}",
605 a.inner.dtype(),
606 b.inner.dtype(),
607 ))
608 .bt());
609 }
610 let cond_dims = self.inner.shape();
611 let a_dims = a.inner.shape();
612 let b_dims = b.inner.shape();
613 if a_dims.dims() != cond_dims.dims() || b_dims.dims() != cond_dims.dims() {
614 return Err(fuel_ir::Error::Msg(format!(
615 "where_cond: shapes must match cond, got cond={:?} a={:?} b={:?}",
616 cond_dims.dims(),
617 a_dims.dims(),
618 b_dims.dims(),
619 ))
620 .bt());
621 }
622 Ok(Self {
623 inner: self.inner.where_cond(&a.inner, &b.inner),
624 })
625 }
626
627 pub fn broadcast_add(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
631 self.check_broadcast_binary("broadcast_add", other)?;
632 Ok(Self {
633 inner: self.inner.broadcast_add(&other.inner),
634 })
635 }
636
637 pub fn broadcast_sub(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
639 self.check_broadcast_binary("broadcast_sub", other)?;
640 Ok(Self {
641 inner: self.inner.broadcast_sub(&other.inner),
642 })
643 }
644
645 pub fn broadcast_mul(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
647 self.check_broadcast_binary("broadcast_mul", other)?;
648 Ok(Self {
649 inner: self.inner.broadcast_mul(&other.inner),
650 })
651 }
652
653 pub fn broadcast_div(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
655 self.check_broadcast_binary("broadcast_div", other)?;
656 Ok(Self {
657 inner: self.inner.broadcast_div(&other.inner),
658 })
659 }
660
661 fn check_strict_binary(
662 &self,
663 name: &'static str,
664 other: &Self,
665 ) -> std::result::Result<(), fuel_ir::Error> {
666 if self.inner.dtype() != other.inner.dtype() {
667 return Err(fuel_ir::Error::Msg(format!(
668 "{name}: dtype mismatch lhs={:?} rhs={:?}",
669 self.inner.dtype(),
670 other.inner.dtype(),
671 ))
672 .bt());
673 }
674 let a_shape = self.inner.shape();
675 let b_shape = other.inner.shape();
676 if a_shape.dims() != b_shape.dims() {
677 return Err(fuel_ir::Error::Msg(format!(
678 "{name}: shape mismatch lhs={:?} rhs={:?}",
679 a_shape.dims(),
680 b_shape.dims(),
681 ))
682 .bt());
683 }
684 Ok(())
685 }
686
687 fn check_broadcast_binary(
688 &self,
689 name: &'static str,
690 other: &Self,
691 ) -> std::result::Result<(), fuel_ir::Error> {
692 if self.inner.dtype() != other.inner.dtype() {
693 return Err(fuel_ir::Error::Msg(format!(
694 "{name}: dtype mismatch lhs={:?} rhs={:?}",
695 self.inner.dtype(),
696 other.inner.dtype(),
697 ))
698 .bt());
699 }
700 let a_shape = self.inner.shape();
701 let b_shape = other.inner.shape();
702 let a_dims = a_shape.dims();
703 let b_dims = b_shape.dims();
704 let rank = a_dims.len().max(b_dims.len());
707 for i in 0..rank {
708 let ad = a_dims
709 .get(a_dims.len().wrapping_sub(1 + i))
710 .copied()
711 .unwrap_or(1);
712 let bd = b_dims
713 .get(b_dims.len().wrapping_sub(1 + i))
714 .copied()
715 .unwrap_or(1);
716 if ad != bd && ad != 1 && bd != 1 {
717 return Err(fuel_ir::Error::Msg(format!(
718 "{name}: shapes {:?} and {:?} are not broadcast-compatible",
719 a_dims, b_dims,
720 ))
721 .bt());
722 }
723 }
724 Ok(())
725 }
726
727 pub fn neg(&self) -> Self {
731 Self {
732 inner: self.inner.neg(),
733 }
734 }
735
736 pub fn sqr(&self) -> Self {
738 Self {
739 inner: self.inner.sqr(),
740 }
741 }
742
743 pub fn sqrt(&self) -> Self {
745 Self {
746 inner: self.inner.sqrt(),
747 }
748 }
749
750 pub fn exp(&self) -> Self {
752 Self {
753 inner: self.inner.exp(),
754 }
755 }
756
757 pub fn log(&self) -> Self {
759 Self {
760 inner: self.inner.log(),
761 }
762 }
763
764 pub fn relu(&self) -> Self {
766 Self {
767 inner: self.inner.relu(),
768 }
769 }
770
771 pub fn silu(&self) -> Self {
773 Self {
774 inner: self.inner.silu(),
775 }
776 }
777
778 pub fn gelu_tanh(&self) -> Self {
780 Self {
781 inner: self.inner.gelu_tanh(),
782 }
783 }
784
785 pub fn sigmoid(&self) -> Self {
787 Self {
788 inner: self.inner.sigmoid(),
789 }
790 }
791
792 pub fn tanh(&self) -> Self {
794 Self {
795 inner: self.inner.tanh(),
796 }
797 }
798
799 pub fn sin(&self) -> Self {
801 Self {
802 inner: self.inner.sin(),
803 }
804 }
805
806 pub fn cos(&self) -> Self {
808 Self {
809 inner: self.inner.cos(),
810 }
811 }
812
813 pub fn step(&self) -> Self {
816 Self {
817 inner: self.inner.step(),
818 }
819 }
820
821 pub fn recip(&self) -> Self {
823 Self {
824 inner: self.inner.recip(),
825 }
826 }
827
828 pub fn abs(&self) -> Self {
830 Self {
831 inner: self.inner.abs(),
832 }
833 }
834
835 pub fn floor(&self) -> Self {
838 Self {
839 inner: self.inner.floor(),
840 }
841 }
842
843 pub fn ceil(&self) -> Self {
846 Self {
847 inner: self.inner.ceil(),
848 }
849 }
850
851 pub fn round(&self) -> Self {
856 Self {
857 inner: self.inner.round(),
858 }
859 }
860
861 pub fn sign(&self) -> Self {
865 Self {
866 inner: self.inner.sign(),
867 }
868 }
869
870 pub fn erf(&self) -> Self {
873 Self {
874 inner: self.inner.erf(),
875 }
876 }
877
878 pub fn gelu(&self) -> Self {
882 Self {
883 inner: self.inner.gelu(),
884 }
885 }
886
887 pub fn pow(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
893 Ok(Self {
894 inner: self.inner.pow(&other.inner)?,
895 })
896 }
897
898 pub fn rsqrt(&self) -> Self {
902 Self {
903 inner: self.inner.rsqrt(),
904 }
905 }
906
907 pub fn rem(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
913 Ok(Self {
914 inner: self.inner.rem(&other.inner)?,
915 })
916 }
917
918 pub fn flip<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
922 let shape = self.inner.shape();
923 let dim = dim.to_index(&shape, "flip")?;
924 Ok(Self {
925 inner: self.inner.flip(dim)?,
926 })
927 }
928
929 pub fn roll<D: Dim>(&self, dim: D, shift: i64) -> std::result::Result<Self, fuel_ir::Error> {
933 let shape = self.inner.shape();
934 let dim = dim.to_index(&shape, "roll")?;
935 Ok(Self {
936 inner: self.inner.roll(dim, shift)?,
937 })
938 }
939
940 pub fn cumsum<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
944 let shape = self.inner.shape();
945 let dim = dim.to_index(&shape, "cumsum")?;
946 Ok(Self {
947 inner: self.inner.cumsum(dim)?,
948 })
949 }
950
951 pub fn pad(
958 &self,
959 padding: Vec<(usize, usize)>,
960 mode: fuel_graph::PadMode,
961 value: f64,
962 ) -> std::result::Result<Self, fuel_ir::Error> {
963 Ok(Self {
964 inner: self.inner.pad(padding, mode, value)?,
965 })
966 }
967
968 pub fn powi(&self, n: i32) -> Self {
970 Self {
971 inner: self.inner.powi(n),
972 }
973 }
974
975 pub fn matmul(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
981 let a_dims = self.inner.shape().dims().to_vec();
982 let b_dims = other.inner.shape().dims().to_vec();
983 if a_dims.len() < 2 || b_dims.len() < 2 {
984 return Err(fuel_ir::Error::Msg(format!(
985 "matmul: both operands must be rank >= 2, got lhs={a_dims:?} rhs={b_dims:?}",
986 ))
987 .bt());
988 }
989 let a_k = a_dims[a_dims.len() - 1];
990 let b_k = b_dims[b_dims.len() - 2];
991 if a_k != b_k {
992 return Err(fuel_ir::Error::Msg(format!(
993 "matmul: contracting dim mismatch lhs[..., M, {a_k}] vs rhs[..., {b_k}, N]",
994 ))
995 .bt());
996 }
997 Ok(Self {
998 inner: self.inner.matmul(&other.inner),
999 })
1000 }
1001
1002 pub fn matmul_dyn_m(
1009 &self,
1010 other: &Self,
1011 row_count: fuel_ir::DynScalar,
1012 ) -> std::result::Result<Self, fuel_ir::Error> {
1013 let a_dims = self.inner.shape().dims().to_vec();
1014 let b_dims = other.inner.shape().dims().to_vec();
1015 if a_dims.len() < 2 || b_dims.len() < 2 {
1016 return Err(fuel_ir::Error::Msg(format!(
1017 "matmul_dyn_m: both operands must be rank >= 2, got lhs={a_dims:?} rhs={b_dims:?}",
1018 ))
1019 .bt());
1020 }
1021 let a_k = a_dims[a_dims.len() - 1];
1022 let b_k = b_dims[b_dims.len() - 2];
1023 if a_k != b_k {
1024 return Err(fuel_ir::Error::Msg(format!(
1025 "matmul_dyn_m: contracting dim mismatch lhs[..., M, {a_k}] vs rhs[..., {b_k}, N]",
1026 ))
1027 .bt());
1028 }
1029 Ok(Self {
1030 inner: self.inner.matmul_dyn_m(&other.inner, row_count),
1031 })
1032 }
1033
1034 pub fn qmatmul(
1043 &self,
1044 weight_bytes: &Self,
1045 quant_type: fuel_graph::QuantType,
1046 k: usize,
1047 n: usize,
1048 ) -> std::result::Result<Self, fuel_ir::Error> {
1049 if self.inner.dtype() != fuel_ir::DType::F32 {
1050 return Err(fuel_ir::Error::Msg(format!(
1051 "qmatmul: activations must be F32, got {:?}",
1052 self.inner.dtype(),
1053 ))
1054 .bt());
1055 }
1056 if weight_bytes.inner.dtype() != fuel_ir::DType::U32 {
1057 return Err(fuel_ir::Error::Msg(format!(
1058 "qmatmul: weight_bytes must be U32 (raw block bytes reinterpreted), got {:?}",
1059 weight_bytes.inner.dtype(),
1060 ))
1061 .bt());
1062 }
1063 let a_shape = self.inner.shape();
1064 let a_dims = a_shape.dims();
1065 if a_dims.len() < 2 {
1066 return Err(fuel_ir::Error::Msg(format!(
1067 "qmatmul: activations must be rank >= 2, got {a_dims:?}",
1068 ))
1069 .bt());
1070 }
1071 if a_dims[a_dims.len() - 1] != k {
1072 return Err(fuel_ir::Error::Msg(format!(
1073 "qmatmul: last dim of activations ({}) must equal k ({k})",
1074 a_dims[a_dims.len() - 1],
1075 ))
1076 .bt());
1077 }
1078 let block_size = quant_type.elements_per_block();
1079 if !k.is_multiple_of(block_size) {
1080 return Err(fuel_ir::Error::Msg(format!(
1081 "qmatmul: k={k} must be a multiple of {quant_type:?}'s block size ({block_size})",
1082 ))
1083 .bt());
1084 }
1085 let expected_bytes = n * (k / block_size) * quant_type.bytes_per_block();
1086 let expected_u32_elems = expected_bytes.div_ceil(4);
1087 let actual_elems = weight_bytes.inner.shape().elem_count();
1088 if actual_elems != expected_u32_elems {
1089 return Err(fuel_ir::Error::Msg(format!(
1090 "qmatmul: weight_bytes has {actual_elems} u32 elements, expected {expected_u32_elems} for N={n}, K={k}, {quant_type:?}",
1091 )).bt());
1092 }
1093 Ok(Self {
1094 inner: self.inner.qmatmul(&weight_bytes.inner, quant_type, k, n),
1095 })
1096 }
1097
1098 pub fn transpose(&self) -> std::result::Result<Self, fuel_ir::Error> {
1102 Ok(Self {
1103 inner: self.inner.try_transpose()?,
1104 })
1105 }
1106
1107 pub fn permute<D: Dims>(&self, axes: D) -> std::result::Result<Self, fuel_ir::Error> {
1111 let shape = self.inner.shape();
1112 let axes = axes.to_indexes(&shape, "permute")?;
1113 Ok(Self {
1114 inner: self.inner.try_permute(&axes)?,
1115 })
1116 }
1117
1118 pub fn reshape(&self, shape: impl Into<Shape>) -> std::result::Result<Self, fuel_ir::Error> {
1121 Ok(Self {
1122 inner: self.inner.try_reshape(shape)?,
1123 })
1124 }
1125
1126 pub fn squeeze<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
1134 let shape = self.inner.shape();
1135 let dim = dim.to_index(&shape, "squeeze")?;
1136 Ok(Self {
1137 inner: self.inner.squeeze(dim)?,
1138 })
1139 }
1140
1141 pub fn broadcast_to(
1144 &self,
1145 shape: impl Into<Shape>,
1146 ) -> std::result::Result<Self, fuel_ir::Error> {
1147 Ok(Self {
1148 inner: self.inner.try_broadcast_to(shape)?,
1149 })
1150 }
1151
1152 pub fn layer_norm_affine(
1162 &self,
1163 gain: std::sync::Arc<[f32]>,
1164 bias: std::sync::Arc<[f32]>,
1165 eps: f64,
1166 ) -> std::result::Result<Self, fuel_ir::Error> {
1167 let hidden = gain.len();
1168 debug_assert_eq!(
1169 bias.len(),
1170 hidden,
1171 "layer_norm_affine: gain ({}) and bias ({}) must have the same length",
1172 gain.len(),
1173 bias.len()
1174 );
1175 let normed = self.layer_norm_last_dim(eps)?;
1176 let dims_v: Vec<usize> = self.inner.shape().dims().to_vec();
1177 let mut affine_shape = vec![1_usize; dims_v.len()];
1178 affine_shape[dims_v.len() - 1] = hidden;
1179 let bc_shape = Shape::from_dims(&dims_v);
1180 let g = normed
1181 .const_f32_like(gain, Shape::from_dims(&[hidden]))?
1182 .reshape(Shape::from_dims(&affine_shape))?
1183 .broadcast_to(bc_shape.clone())?;
1184 let b = normed
1185 .const_f32_like(bias, Shape::from_dims(&[hidden]))?
1186 .reshape(Shape::from_dims(&affine_shape))?
1187 .broadcast_to(bc_shape)?;
1188 normed.mul(&g)?.add(&b)
1189 }
1190
1191 pub fn l2_normalize<D: Dim>(
1199 &self,
1200 dim: D,
1201 eps: f64,
1202 ) -> std::result::Result<Self, fuel_ir::Error> {
1203 let sq = self.sqr();
1204 let summed = sq.sum_keepdim(dim)?;
1205 let with_eps = if eps == 0.0 {
1206 summed
1207 } else {
1208 summed.add_scalar(eps)
1209 };
1210 let l2 = with_eps.sqrt();
1211 let dims_v: Vec<usize> = self.inner.shape().dims().to_vec();
1212 let l2_bc = l2.broadcast_to(Shape::from_dims(&dims_v))?;
1213 self.div(&l2_bc)
1214 }
1215
1216 pub fn repeat_interleave<D: Dim>(
1224 &self,
1225 dim: D,
1226 repeats: usize,
1227 ) -> std::result::Result<Self, fuel_ir::Error> {
1228 let shape = self.inner.shape();
1229 let dim = dim.to_index(&shape, "repeat_interleave")?;
1230 if repeats == 0 {
1231 return Err(fuel_ir::Error::Msg("repeat_interleave: repeats must be ≥ 1".into()).bt());
1232 }
1233 if repeats == 1 {
1234 return Ok(self.clone());
1235 }
1236 let dims_v: Vec<usize> = shape.dims().to_vec();
1237 let mut unsq_shape = dims_v.clone();
1238 unsq_shape.insert(dim + 1, 1);
1239 let mut bc_shape = unsq_shape.clone();
1240 bc_shape[dim + 1] = repeats;
1241 let unsq = self.reshape(Shape::from_dims(&unsq_shape))?;
1242 let bc = unsq.broadcast_to(Shape::from_dims(&bc_shape))?;
1243 let mut out_shape = dims_v.clone();
1244 out_shape[dim] *= repeats;
1245 bc.reshape(Shape::from_dims(&out_shape))
1246 }
1247
1248 pub fn slice<D: Dim>(
1252 &self,
1253 dim: D,
1254 start: usize,
1255 len: usize,
1256 ) -> std::result::Result<Self, fuel_ir::Error> {
1257 let shape = self.inner.shape();
1258 let dim = dim.to_index(&shape, "slice")?;
1259 let dim_size = shape.dims()[dim];
1260 if start.saturating_add(len) > dim_size {
1261 return Err(fuel_ir::Error::Msg(format!(
1262 "slice: start={start} + len={len} exceeds dim {dim} size {dim_size}",
1263 ))
1264 .bt());
1265 }
1266 Ok(Self {
1267 inner: self.inner.slice(dim, start, len),
1268 })
1269 }
1270
1271 pub fn concat<D: Dim>(
1274 &self,
1275 other: &Self,
1276 dim: D,
1277 ) -> std::result::Result<Self, fuel_ir::Error> {
1278 let shape = self.inner.shape();
1279 let dim = dim.to_index(&shape, "concat")?;
1280 let self_dims = shape.dims().to_vec();
1281 let other_dims = other.inner.shape().dims().to_vec();
1282 if self_dims.len() != other_dims.len() {
1283 return Err(fuel_ir::Error::Msg(format!(
1284 "concat: rank mismatch lhs={self_dims:?} rhs={other_dims:?}",
1285 ))
1286 .bt());
1287 }
1288 for (i, (&a, &b)) in self_dims.iter().zip(other_dims.iter()).enumerate() {
1289 if i != dim && a != b {
1290 return Err(fuel_ir::Error::Msg(format!(
1291 "concat: dim {i} mismatch lhs={a} rhs={b} (concat dim is {dim})",
1292 ))
1293 .bt());
1294 }
1295 }
1296 Ok(Self {
1297 inner: self.inner.concat(&other.inner, dim),
1298 })
1299 }
1300
1301 pub fn add_scalar(&self, c: f64) -> Self {
1303 Self {
1304 inner: self.inner.add_scalar(c),
1305 }
1306 }
1307
1308 pub fn mul_scalar(&self, c: f64) -> Self {
1310 Self {
1311 inner: self.inner.mul_scalar(c),
1312 }
1313 }
1314
1315 pub fn argmax_dim<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
1319 let shape = self.inner.shape();
1320 let dim = dim.to_index(&shape, "argmax_dim")?;
1321 Ok(Self {
1322 inner: self.inner.argmax_dim(dim),
1323 })
1324 }
1325
1326 pub fn realize_u32(&self) -> Vec<u32> {
1332 let graph = self.inner.graph().clone();
1333 let target = self.inner.id();
1334 let device = crate::Device::cpu();
1335 crate::pipelined_bridge::realize_one_as::<u32>(&graph, target, &device)
1336 .expect("realize_u32 via PipelinedExecutor")
1337 }
1338
1339 pub fn realize_u8(&self) -> Vec<u8> {
1348 let graph = self.inner.graph().clone();
1349 let target = self.inner.id();
1350 let device = crate::Device::cpu();
1351 crate::pipelined_bridge::realize_one_bytes(&graph, target, &device)
1352 .expect("realize_u8 via PipelinedExecutor")
1353 }
1354
1355 pub fn sum_all(&self) -> Self {
1359 Self {
1360 inner: self.inner.sum_all(),
1361 }
1362 }
1363
1364 pub fn mean_all(&self) -> Self {
1366 Self {
1367 inner: self.inner.mean_all(),
1368 }
1369 }
1370
1371 pub fn max_all(&self) -> Self {
1373 Self {
1374 inner: self.inner.max_all(),
1375 }
1376 }
1377
1378 pub fn min_all(&self) -> Self {
1380 Self {
1381 inner: self.inner.min_all(),
1382 }
1383 }
1384
1385 pub fn sum_dim<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
1388 let shape = self.inner.shape();
1389 let dim = dim.to_index(&shape, "sum_dim")?;
1390 Ok(Self {
1391 inner: self.inner.sum_dim(dim),
1392 })
1393 }
1394
1395 pub fn max_dim<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
1397 let shape = self.inner.shape();
1398 let dim = dim.to_index(&shape, "max_dim")?;
1399 Ok(Self {
1400 inner: self.inner.max_dim(dim),
1401 })
1402 }
1403
1404 pub fn min_dim<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
1406 let shape = self.inner.shape();
1407 let dim = dim.to_index(&shape, "min_dim")?;
1408 Ok(Self {
1409 inner: self.inner.min_dim(dim),
1410 })
1411 }
1412
1413 pub fn clamp(&self, min: f64, max: f64) -> Self {
1415 Self {
1416 inner: self.inner.clamp(min, max),
1417 }
1418 }
1419
1420 pub fn mean_dim<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
1422 let shape = self.inner.shape();
1423 let dim = dim.to_index(&shape, "mean_dim")?;
1424 Ok(Self {
1425 inner: self.inner.mean_dim(dim),
1426 })
1427 }
1428
1429 pub fn reduce_sum_to(&self, target: impl Into<Shape>) -> Self {
1433 Self {
1434 inner: self.inner.reduce_sum_to(target),
1435 }
1436 }
1437
1438 pub fn reduce_max_to(&self, target: impl Into<Shape>) -> Self {
1441 Self {
1442 inner: self.inner.reduce_max_to(target),
1443 }
1444 }
1445
1446 pub fn softmax_last_dim(&self) -> std::result::Result<Self, fuel_ir::Error> {
1451 let shape = self.inner.shape();
1452 let dims = shape.dims();
1453 if dims.is_empty() {
1454 return Err(fuel_ir::Error::Msg(
1455 "softmax_last_dim: input must be rank >= 1, got scalar".into(),
1456 )
1457 .bt());
1458 }
1459 Ok(Self {
1460 inner: self.inner.softmax_last_dim(),
1461 })
1462 }
1463
1464 pub fn nf4_matmul(&self, w_packed: &Self, absmax: &Self, block_size: usize) -> Self {
1468 Self {
1469 inner: self
1470 .inner
1471 .nf4_matmul(&w_packed.inner, &absmax.inner, block_size),
1472 }
1473 }
1474
1475 pub fn ssd_chunk_scan(
1480 &self,
1481 dt: &Self,
1482 a: &Self,
1483 b: &Self,
1484 c: &Self,
1485 chunk_size: usize,
1486 ) -> Self {
1487 Self {
1488 inner: self
1489 .inner
1490 .ssd_chunk_scan(&dt.inner, &a.inner, &b.inner, &c.inner, chunk_size),
1491 }
1492 }
1493
1494 pub fn selective_scan(
1500 &self,
1501 delta: &Self,
1502 a: &Self,
1503 b: &Self,
1504 c: &Self,
1505 delta_softplus: bool,
1506 ) -> Self {
1507 Self {
1508 inner: self.inner.selective_scan(
1509 &delta.inner,
1510 &a.inner,
1511 &b.inner,
1512 &c.inner,
1513 delta_softplus,
1514 ),
1515 }
1516 }
1517
1518 pub fn selective_scan_bundled(
1526 &self,
1527 delta: &Self,
1528 a: &Self,
1529 b: &Self,
1530 c: &Self,
1531 delta_softplus: bool,
1532 ) -> std::result::Result<(Self, Self), fuel_ir::Error> {
1533 let (y, last_state) = self.inner.selective_scan_bundled(
1534 &delta.inner,
1535 &a.inner,
1536 &b.inner,
1537 &c.inner,
1538 delta_softplus,
1539 )?;
1540 Ok((Self { inner: y }, Self { inner: last_state }))
1541 }
1542
1543 pub fn ssd_chunk_scan_bundled(
1547 &self,
1548 dt: &Self,
1549 a: &Self,
1550 b: &Self,
1551 c: &Self,
1552 chunk_size: usize,
1553 ) -> std::result::Result<(Self, Self), fuel_ir::Error> {
1554 let (y, last_state) = self
1555 .inner
1556 .ssd_chunk_scan_bundled(&dt.inner, &a.inner, &b.inner, &c.inner, chunk_size)?;
1557 Ok((Self { inner: y }, Self { inner: last_state }))
1558 }
1559
1560 pub fn nonzero_indices_bundled(
1572 &self,
1573 count_sym: fuel_ir::SymId,
1574 ) -> std::result::Result<(Self, Self), fuel_ir::Error> {
1575 let (indices, count) = self.inner.nonzero_indices_bundled(count_sym)?;
1576 Ok((Self { inner: indices }, Self { inner: count }))
1577 }
1578
1579 pub fn fresh_data_determined_sym(&self) -> fuel_ir::SymId {
1587 let graph = self.inner.graph();
1588 let g = graph.read().unwrap();
1589 g.next_data_determined_sym()
1590 }
1591
1592 pub fn causal_conv1d(&self, weight: &Self, bias: &Self, use_silu: bool) -> Self {
1597 Self {
1598 inner: self
1599 .inner
1600 .causal_conv1d(&weight.inner, &bias.inner, use_silu),
1601 }
1602 }
1603
1604 pub fn fused_softmax_cross_entropy(
1609 &self,
1610 targets: &Self,
1611 reduction: fuel_graph::registry::Reduction,
1612 ignore_index: i64,
1613 ) -> Self {
1614 Self {
1615 inner: self
1616 .inner
1617 .fused_softmax_cross_entropy(&targets.inner, reduction, ignore_index),
1618 }
1619 }
1620
1621 pub fn layer_norm_last_dim(&self, eps: f64) -> std::result::Result<Self, fuel_ir::Error> {
1624 let shape = self.inner.shape();
1625 let dims = shape.dims();
1626 if dims.last().copied().unwrap_or(0) == 0 {
1627 return Err(fuel_ir::Error::Msg(format!(
1628 "layer_norm_last_dim: input must have non-zero last dim, got {dims:?}",
1629 ))
1630 .bt());
1631 }
1632 Ok(Self {
1633 inner: self.inner.layer_norm_last_dim(eps),
1634 })
1635 }
1636
1637 pub fn rms_norm_last_dim(&self, eps: f64) -> std::result::Result<Self, fuel_ir::Error> {
1640 let shape = self.inner.shape();
1641 let dims = shape.dims();
1642 if dims.last().copied().unwrap_or(0) == 0 {
1643 return Err(fuel_ir::Error::Msg(format!(
1644 "rms_norm_last_dim: input must have non-zero last dim, got {dims:?}",
1645 ))
1646 .bt());
1647 }
1648 Ok(Self {
1649 inner: self.inner.rms_norm_last_dim(eps),
1650 })
1651 }
1652
1653 pub fn rope(&self, base: f64, start_pos: usize) -> std::result::Result<Self, fuel_ir::Error> {
1656 let shape = self.inner.shape();
1657 let dims = shape.dims();
1658 if dims.len() < 2 {
1659 return Err(fuel_ir::Error::Msg(format!(
1660 "rope: input must have rank >= 2, got {dims:?}",
1661 ))
1662 .bt());
1663 }
1664 Ok(Self {
1665 inner: self.inner.rope(base, start_pos),
1666 })
1667 }
1668
1669 pub fn rope_with_tables(
1676 &self,
1677 cos: &Self,
1678 sin: &Self,
1679 ) -> std::result::Result<Self, fuel_ir::Error> {
1680 if self.inner.dtype() != fuel_ir::DType::F32 {
1681 return Err(fuel_ir::Error::Msg(format!(
1682 "rope: only f32 is supported today, got {:?} (cast explicitly for other dtypes)",
1683 self.inner.dtype(),
1684 ))
1685 .bt());
1686 }
1687 let in_shape = self.inner.shape();
1688 let dims = in_shape.dims();
1689 let rank = dims.len();
1690 if rank < 2 {
1691 return Err(fuel_ir::Error::Msg(format!(
1692 "rope: input must have rank >= 2, got {dims:?}",
1693 ))
1694 .bt());
1695 }
1696 let seq = dims[rank - 2];
1697 let d = dims[rank - 1];
1698 if !d.is_multiple_of(2) {
1699 return Err(fuel_ir::Error::Msg(format!("rope: feature dim {d} must be even",)).bt());
1700 }
1701 let cos_shape = cos.inner.shape();
1702 let cos_dims = cos_shape.dims();
1703 if cos_dims != [seq, d] {
1704 return Err(fuel_ir::Error::Msg(format!(
1705 "rope_with_tables: cos shape {cos_dims:?} does not match [seq, d] = [{seq}, {d}]",
1706 ))
1707 .bt());
1708 }
1709 let sin_shape = sin.inner.shape();
1710 let sin_dims = sin_shape.dims();
1711 if sin_dims != [seq, d] {
1712 return Err(fuel_ir::Error::Msg(format!(
1713 "rope_with_tables: sin shape {sin_dims:?} does not match [seq, d] = [{seq}, {d}]",
1714 ))
1715 .bt());
1716 }
1717 Ok(Self {
1718 inner: self.inner.rope_with_tables(&cos.inner, &sin.inner),
1719 })
1720 }
1721
1722 pub fn rope_with_tables_decomposed(
1739 &self,
1740 cos: &Self,
1741 sin: &Self,
1742 ) -> std::result::Result<Self, fuel_ir::Error> {
1743 if self.inner.dtype() != fuel_ir::DType::F32 {
1744 return Err(fuel_ir::Error::Msg(format!(
1745 "rope: only f32 is supported today, got {:?} (cast explicitly for other dtypes)",
1746 self.inner.dtype(),
1747 ))
1748 .bt());
1749 }
1750 let in_shape = self.inner.shape();
1751 let dims = in_shape.dims();
1752 let rank = dims.len();
1753 if rank < 2 {
1754 return Err(fuel_ir::Error::Msg(format!(
1755 "rope: input must have rank >= 2, got {dims:?}",
1756 ))
1757 .bt());
1758 }
1759 let seq = dims[rank - 2];
1760 let d = dims[rank - 1];
1761 if !d.is_multiple_of(2) {
1762 return Err(fuel_ir::Error::Msg(format!("rope: feature dim {d} must be even",)).bt());
1763 }
1764 let cos_dims = cos.inner.shape();
1765 if cos_dims.dims() != [seq, d] {
1766 return Err(fuel_ir::Error::Msg(format!(
1767 "rope_with_tables_decomposed: cos shape {:?} does not match [seq, d] = [{seq}, {d}]",
1768 cos_dims.dims(),
1769 )).bt());
1770 }
1771 let sin_dims = sin.inner.shape();
1772 if sin_dims.dims() != [seq, d] {
1773 return Err(fuel_ir::Error::Msg(format!(
1774 "rope_with_tables_decomposed: sin shape {:?} does not match [seq, d] = [{seq}, {d}]",
1775 sin_dims.dims(),
1776 )).bt());
1777 }
1778 Ok(Self {
1779 inner: self
1780 .inner
1781 .rope_with_tables_decomposed(&cos.inner, &sin.inner),
1782 })
1783 }
1784
1785 pub fn index_select<D: Dim>(
1791 &self,
1792 dim: D,
1793 indices: &Self,
1794 ) -> std::result::Result<Self, fuel_ir::Error> {
1795 let shape = self.inner.shape();
1796 let dim = dim.to_index(&shape, "index_select")?;
1797 if indices.inner.dtype() != fuel_ir::DType::U32 {
1798 return Err(fuel_ir::Error::Msg(format!(
1799 "index_select: index tensor must be U32, got {:?}",
1800 indices.inner.dtype(),
1801 ))
1802 .bt());
1803 }
1804 let idx_shape = indices.inner.shape();
1805 let idx_dims = idx_shape.dims();
1806 if idx_dims.len() != 1 {
1807 return Err(fuel_ir::Error::Msg(format!(
1808 "index_select: index tensor must be rank 1, got {idx_dims:?}",
1809 ))
1810 .bt());
1811 }
1812 Ok(Self {
1813 inner: self.inner.index_select(dim, &indices.inner),
1814 })
1815 }
1816
1817 pub fn gather<D: Dim>(
1822 &self,
1823 dim: D,
1824 indices: &Self,
1825 ) -> std::result::Result<Self, fuel_ir::Error> {
1826 let shape = self.inner.shape();
1827 let dim = dim.to_index(&shape, "gather")?;
1828 if indices.inner.dtype() != fuel_ir::DType::U32 {
1829 return Err(fuel_ir::Error::Msg(format!(
1830 "gather: index tensor must be U32, got {:?}",
1831 indices.inner.dtype(),
1832 ))
1833 .bt());
1834 }
1835 let data_rank = shape.dims().len();
1836 let idx_shape = indices.inner.shape();
1837 let idx_rank = idx_shape.dims().len();
1838 if data_rank != idx_rank {
1839 return Err(fuel_ir::Error::Msg(format!(
1840 "gather: data and index must have the same rank, got {data_rank} vs {idx_rank}",
1841 ))
1842 .bt());
1843 }
1844 Ok(Self {
1845 inner: self.inner.gather(dim, &indices.inner),
1846 })
1847 }
1848
1849 pub fn to_dtype(&self, dtype: DType) -> std::result::Result<Self, fuel_ir::Error> {
1861 if self.inner.dtype() == dtype {
1862 return Ok(self.clone());
1863 }
1864 Ok(Self {
1865 inner: self.inner.cast(dtype),
1866 })
1867 }
1868
1869 pub fn detach(&self) -> Self {
1876 self.clone()
1877 }
1878
1879 pub fn track_op(&self) -> bool {
1883 true
1884 }
1885
1886 pub fn realize_f32(&self) -> Vec<f32> {
1930 let graph = self.inner.graph().clone();
1931 let target = self.inner.id();
1932 let device = crate::Device::cpu();
1933 crate::pipelined_bridge::realize_one_as::<f32>(&graph, target, &device)
1934 .expect("realize_f32 via PipelinedExecutor")
1935 }
1936
1937 pub fn realize_f32_reference(&self) -> Vec<f32> {
1953 let graph = self.inner.graph().clone();
1954 let target = self.inner.id();
1955 let device = crate::Device::cpu();
1956 crate::pipelined_bridge::realize_one_reference_as::<f32>(&graph, target, &device)
1957 .expect("realize_f32_reference via PipelinedExecutor")
1958 }
1959
1960 pub fn realize_f64(&self) -> Vec<f64> {
1973 let graph = self.inner.graph().clone();
1974 let target = self.inner.id();
1975 let device = crate::Device::cpu();
1976 crate::pipelined_bridge::realize_one_as::<f64>(&graph, target, &device)
1977 .expect("realize_f64 via PipelinedExecutor")
1978 }
1979
1980 pub fn realize_bf16(&self) -> Vec<half::bf16> {
1983 let graph = self.inner.graph().clone();
1984 let target = self.inner.id();
1985 let device = crate::Device::cpu();
1986 crate::pipelined_bridge::realize_one_as::<half::bf16>(&graph, target, &device)
1987 .expect("realize_bf16 via PipelinedExecutor")
1988 }
1989
1990 pub fn realize_f16(&self) -> Vec<half::f16> {
1993 let graph = self.inner.graph().clone();
1994 let target = self.inner.id();
1995 let device = crate::Device::cpu();
1996 crate::pipelined_bridge::realize_one_as::<half::f16>(&graph, target, &device)
1997 .expect("realize_f16 via PipelinedExecutor")
1998 }
1999
2000 #[cfg(feature = "cuda")]
2015 pub fn realize_f32_cuda(&self, device: &fuel_cuda_backend::CudaDevice) -> Vec<f32> {
2016 let graph = self.inner.graph().clone();
2017 let target = self.inner.id();
2018 let fc_device: crate::Device = device.clone().into();
2019 crate::pipelined_bridge::realize_one_as::<f32>(&graph, target, &fc_device)
2020 .expect("realize_f32_cuda via PipelinedExecutor")
2021 }
2022
2023 #[cfg(feature = "vulkan")]
2031 pub fn realize_f32_vulkan(
2032 &self,
2033 backend: &std::sync::Arc<fuel_vulkan_backend::VulkanBackend>,
2034 ) -> Vec<f32> {
2035 let graph = self.inner.graph().clone();
2036 let target = self.inner.id();
2037 let fc_device: crate::Device = backend.clone().into();
2038 crate::pipelined_bridge::realize_one_as::<f32>(&graph, target, &fc_device)
2039 .expect("realize_f32_vulkan via PipelinedExecutor")
2040 }
2041}
2042
2043pub fn realize_many_f32(tensors: &[&Tensor]) -> Vec<Vec<f32>> {
2045 if tensors.is_empty() {
2046 return Vec::new();
2047 }
2048 let graph = tensors[0].inner.graph().clone();
2049 let targets: Vec<fuel_graph::NodeId> = tensors.iter().map(|t| t.inner.id()).collect();
2050 let device = crate::Device::cpu();
2051 crate::pipelined_bridge::realize_many_as::<f32>(&graph, &targets, &device)
2052 .expect("realize_many_f32 via PipelinedExecutor")
2053}
2054
2055#[cfg(feature = "cuda")]
2058pub fn realize_many_f32_cuda(
2059 tensors: &[&Tensor],
2060 device: &fuel_cuda_backend::CudaDevice,
2061) -> Vec<Vec<f32>> {
2062 if tensors.is_empty() {
2063 return Vec::new();
2064 }
2065 let graph = tensors[0].inner.graph().clone();
2066 let targets: Vec<fuel_graph::NodeId> = tensors.iter().map(|t| t.inner.id()).collect();
2067 let fc_device: crate::Device = device.clone().into();
2068 crate::pipelined_bridge::realize_many_as::<f32>(&graph, &targets, &fc_device)
2069 .expect("realize_many_f32_cuda via PipelinedExecutor")
2070}
2071
2072#[cfg(test)]
2073mod tests {
2074 use super::*;
2075 use crate::Shape;
2076
2077 #[test]
2078 fn constructors_wrap_graph_tensor_correctly() {
2079 let t =
2080 Tensor::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), &Device::cpu()).unwrap();
2081 assert_eq!(t.dtype(), DType::F32);
2082 assert_eq!(t.shape().dims(), &[3]);
2083 assert_eq!(t.rank(), 1);
2084 assert_eq!(t.elem_count(), 3);
2085 }
2086
2087 #[test]
2088 fn add_builds_add_node_in_underlying_graph() {
2089 let a =
2090 Tensor::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), &Device::cpu()).unwrap();
2091 let b = a
2092 .const_f32_like(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]))
2093 .unwrap();
2094 let c = a.add(&b).unwrap();
2095 assert_eq!(c.shape().dims(), &[3]);
2096 assert!(std::sync::Arc::ptr_eq(
2099 c.graph_tensor().graph(),
2100 a.graph_tensor().graph(),
2101 ));
2102 }
2103
2104 #[test]
2105 fn chained_lazy_method_call_builds_sensible_graph() {
2106 let x = Tensor::from_f32(
2111 vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
2112 Shape::from_dims(&[2, 3]),
2113 &Device::cpu(),
2114 )
2115 .unwrap();
2116 let w = x
2117 .const_f32_like(
2118 vec![1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0],
2119 Shape::from_dims(&[3, 3]),
2120 )
2121 .unwrap();
2122 let y = x
2123 .rms_norm_last_dim(1e-6)
2124 .unwrap()
2125 .matmul(&w)
2126 .unwrap()
2127 .relu();
2128 assert_eq!(y.shape().dims(), &[2, 3]);
2129 assert_eq!(y.dtype(), DType::F32);
2130 }
2131
2132 #[test]
2133 fn rope_through_lazy_wrapper() {
2134 let x = Tensor::from_f32(
2136 vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0],
2137 Shape::from_dims(&[2, 4]),
2138 &Device::cpu(),
2139 )
2140 .unwrap();
2141 let y = x.rope(10000.0, 0).unwrap();
2142 assert_eq!(y.shape().dims(), &[2, 4]);
2143 assert_eq!(y.dtype(), DType::F32);
2144 }
2145
2146 #[test]
2147 fn rope_delta_rotate_equals_direct_shift() {
2148 let dev = Device::cpu();
2154 let (n_kv_heads, head_dim, bs) = (2usize, 4usize, 4usize);
2155 let theta = 10000.0;
2156 let (p0, m) = (0usize, 8usize); let raw: Vec<f32> = (0..bs * n_kv_heads * head_dim)
2158 .map(|i| (i as f32 * 0.017).sin())
2159 .collect();
2160 let rope_pool_at = |data: &[f32], start_pos: usize| -> Vec<f32> {
2164 let k = Tensor::from_f32(
2165 data.to_vec(),
2166 Shape::from_dims(&[bs, n_kv_heads, head_dim]),
2167 &dev,
2168 )
2169 .unwrap();
2170 let k4 = k
2171 .permute([1, 0, 2])
2172 .unwrap()
2173 .reshape(Shape::from_dims(&[1, n_kv_heads, bs, head_dim]))
2174 .unwrap();
2175 let (c, s) = k4.rope_tables_const(theta, start_pos, bs, head_dim);
2176 k4.rope_with_tables_decomposed(&c, &s)
2177 .unwrap()
2178 .reshape(Shape::from_dims(&[n_kv_heads, bs, head_dim]))
2179 .unwrap()
2180 .permute([1, 0, 2])
2181 .unwrap()
2182 .realize_f32()
2183 };
2184 let direct = rope_pool_at(&raw, p0 + m); let at_p0 = rope_pool_at(&raw, p0); let shifted =
2187 Tensor::rope_delta_rotate_block_f32(&dev, &at_p0, theta, m, bs, n_kv_heads, head_dim);
2188 let maxdiff = direct
2189 .iter()
2190 .zip(&shifted)
2191 .map(|(a, b)| (a - b).abs())
2192 .fold(0.0f32, f32::max);
2193 assert!(
2194 maxdiff < 1e-5,
2195 "delta-rotate == direct shift (maxdiff {maxdiff})"
2196 );
2197 }
2198
2199 #[test]
2200 fn cast_switches_dtype_through_wrapper() {
2201 let x =
2202 Tensor::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), &Device::cpu()).unwrap();
2203 let y = x.to_dtype(DType::F64).unwrap();
2204 assert_eq!(y.dtype(), DType::F64);
2205 assert_eq!(y.shape().dims(), &[3]);
2206 }
2207
2208 #[test]
2209 fn indexing_builds_correct_output_shape() {
2210 let data =
2211 Tensor::from_f32(vec![1.0; 12], Shape::from_dims(&[3, 4]), &Device::cpu()).unwrap();
2212 let idx = data
2213 .const_u32_like(vec![0, 2, 1], Shape::from_dims(&[3]))
2214 .unwrap();
2215 let out = data.index_select(0, &idx).unwrap();
2216 assert_eq!(out.shape().dims(), &[3, 4]);
2217 }
2218
2219 #[test]
2222 fn realize_f32_executes_the_underlying_graph() {
2223 let a =
2227 Tensor::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), &Device::cpu()).unwrap();
2228 let b = a
2229 .const_f32_like(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]))
2230 .unwrap();
2231 let c = a.add(&b).unwrap().mul(&a).unwrap();
2232 let result = c.realize_f32();
2233 assert_eq!(result, vec![5.0, 14.0, 27.0]);
2234 }
2235
2236 #[test]
2237 fn realize_f32_relu_and_maximum_propagate_nan_end_to_end() {
2238 let a = Tensor::from_f32(
2244 vec![f32::NAN, -2.0, 3.0],
2245 Shape::from_dims(&[3]),
2246 &Device::cpu(),
2247 )
2248 .unwrap();
2249 let relu_result = a.relu().realize_f32();
2250 assert!(
2251 relu_result[0].is_nan(),
2252 "relu(NaN) must propagate NaN through realize, got {}",
2253 relu_result[0]
2254 );
2255 assert_eq!(relu_result[1], 0.0, "relu(-2) must clip to 0");
2256 assert_eq!(relu_result[2], 3.0, "relu(3) must pass through");
2257
2258 let b = a
2259 .const_f32_like(vec![1.0, f32::NAN, 2.0], Shape::from_dims(&[3]))
2260 .unwrap();
2261 let max_result = a.maximum(&b).unwrap().realize_f32();
2262 assert!(
2263 max_result[0].is_nan(),
2264 "maximum(NaN, 1) must propagate NaN through realize, got {}",
2265 max_result[0]
2266 );
2267 assert!(
2268 max_result[1].is_nan(),
2269 "maximum(-2, NaN) must propagate NaN through realize, got {}",
2270 max_result[1]
2271 );
2272 assert_eq!(max_result[2], 3.0, "maximum(3, 2) non-NaN sanity");
2273 }
2274
2275 #[test]
2281 fn fmax_fmin_ieee_suppress_nan_where_prop_propagates() {
2282 let a = Tensor::from_f32(
2286 vec![f32::NAN, 2.0, 5.0],
2287 Shape::from_dims(&[3]),
2288 &Device::cpu(),
2289 )
2290 .unwrap();
2291 let b = a
2292 .const_f32_like(vec![3.0, f32::NAN, 4.0], Shape::from_dims(&[3]))
2293 .unwrap();
2294
2295 let fmax = a.fmax_ieee(&b).unwrap().realize_f32();
2296 assert_eq!(fmax[0], 3.0, "fmax_ieee(NaN,3) suppresses NaN → 3");
2297 assert_eq!(fmax[1], 2.0, "fmax_ieee(2,NaN) suppresses NaN → 2");
2298 assert_eq!(fmax[2], 5.0, "fmax_ieee(5,4) → 5");
2299 let max = a.maximum(&b).unwrap().realize_f32();
2300 assert!(
2301 max[0].is_nan() && max[1].is_nan(),
2302 "maximum PROPAGATES NaN — the divergence that makes fmax_ieee distinct"
2303 );
2304
2305 let fmin = a.fmin_ieee(&b).unwrap().realize_f32();
2306 assert_eq!(fmin[0], 3.0, "fmin_ieee(NaN,3) suppresses NaN → 3");
2307 assert_eq!(fmin[1], 2.0, "fmin_ieee(2,NaN) suppresses NaN → 2");
2308 assert_eq!(fmin[2], 4.0, "fmin_ieee(5,4) → 4");
2309 let min = a.minimum(&b).unwrap().realize_f32();
2310 assert!(
2311 min[0].is_nan() && min[1].is_nan(),
2312 "minimum PROPAGATES NaN — the divergence that makes fmin_ieee distinct"
2313 );
2314 }
2315
2316 #[test]
2317 fn fmax_fmin_ieee_signed_zero_tie_operand_a_wins_bitwise() {
2318 let a = Tensor::from_f32(vec![-0.0, 0.0], Shape::from_dims(&[2]), &Device::cpu()).unwrap();
2336 let b = a
2337 .const_f32_like(vec![0.0, -0.0], Shape::from_dims(&[2]))
2338 .unwrap();
2339
2340 let fmax = a.fmax_ieee(&b).unwrap().realize_f32();
2341 assert_eq!(
2342 fmax[0].to_bits(),
2343 (-0.0f32).to_bits(),
2344 "fmax_ieee(-0.0,+0.0): operand a wins the tie → -0.0 (bitwise)"
2345 );
2346 assert_eq!(
2347 fmax[1].to_bits(),
2348 (0.0f32).to_bits(),
2349 "fmax_ieee(+0.0,-0.0): operand a wins the tie → +0.0 (bitwise)"
2350 );
2351
2352 let fmin = a.fmin_ieee(&b).unwrap().realize_f32();
2353 assert_eq!(
2354 fmin[0].to_bits(),
2355 (-0.0f32).to_bits(),
2356 "fmin_ieee(-0.0,+0.0): operand a wins the tie → -0.0 (bitwise)"
2357 );
2358 assert_eq!(
2359 fmin[1].to_bits(),
2360 (0.0f32).to_bits(),
2361 "fmin_ieee(+0.0,-0.0): operand a wins the tie → +0.0 (bitwise)"
2362 );
2363 }
2364
2365 #[test]
2366 fn rem_trunc_diverges_from_floored_rem_on_opposite_signs() {
2367 let a = Tensor::from_f32(
2371 vec![-7.0, 7.0, -7.0],
2372 Shape::from_dims(&[3]),
2373 &Device::cpu(),
2374 )
2375 .unwrap();
2376 let b = a
2377 .const_f32_like(vec![3.0, -3.0, -3.0], Shape::from_dims(&[3]))
2378 .unwrap();
2379
2380 let rt = a.rem_trunc(&b).unwrap().realize_f32();
2381 assert_eq!(rt[0], -1.0, "-7 rem_trunc 3 = -1 (sign of dividend)");
2382 assert_eq!(rt[1], 1.0, "7 rem_trunc -3 = 1 (sign of dividend)");
2383 assert_eq!(rt[2], -1.0, "-7 rem_trunc -3 = -1");
2384 let rf = a.rem(&b).unwrap().realize_f32();
2385 assert_eq!(
2386 rf[0], 2.0,
2387 "-7 rem 3 = 2 (floored, sign of divisor) — the divergence from rem_trunc"
2388 );
2389 }
2390
2391 #[test]
2392 fn trunc_edges_signed_zero_nan_inf_bitwise() {
2393 let q = Tensor::from_f32(
2397 vec![
2398 2.7,
2399 -2.7,
2400 -0.0,
2401 0.0,
2402 f32::NAN,
2403 f32::INFINITY,
2404 f32::NEG_INFINITY,
2405 ],
2406 Shape::from_dims(&[7]),
2407 &Device::cpu(),
2408 )
2409 .unwrap();
2410 let t = q.trunc().realize_f32();
2411 assert_eq!(t[0], 2.0, "trunc(2.7) = 2 (toward zero)");
2412 assert_eq!(t[1], -2.0, "trunc(-2.7) = -2 (toward zero, NOT -3)");
2413 assert_eq!(
2414 t[2].to_bits(),
2415 (-0.0f32).to_bits(),
2416 "trunc(-0.0) must PRESERVE -0.0 (bitwise, not +0.0)"
2417 );
2418 assert_eq!(
2419 t[3].to_bits(),
2420 (0.0f32).to_bits(),
2421 "trunc(+0.0) = +0.0 (bitwise)"
2422 );
2423 assert!(t[4].is_nan(), "trunc(NaN) = NaN");
2424 assert_eq!(t[5], f32::INFINITY, "trunc(+inf) = +inf");
2425 assert_eq!(t[6], f32::NEG_INFINITY, "trunc(-inf) = -inf");
2426 }
2427
2428 #[test]
2429 fn realize_f32_matmul_hand_computed() {
2430 let a = Tensor::from_f32(
2432 vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
2433 Shape::from_dims(&[2, 3]),
2434 &Device::cpu(),
2435 )
2436 .unwrap();
2437 let b = a
2438 .const_f32_like(
2439 vec![7.0, 8.0, 9.0, 10.0, 11.0, 12.0],
2440 Shape::from_dims(&[3, 2]),
2441 )
2442 .unwrap();
2443 let c = a.matmul(&b).unwrap();
2444 assert_eq!(c.shape().dims(), &[2, 2]);
2445 assert_eq!(c.realize_f32(), vec![58.0, 64.0, 139.0, 154.0]);
2446 }
2447
2448 #[test]
2449 fn fast_and_reference_agree_on_medium_matmul() {
2450 let m = 64;
2455 let k = 96;
2456 let n = 32;
2457 let a_data: Vec<f32> = (0..m * k).map(|i| (i as f32 * 0.01).sin()).collect();
2458 let b_data: Vec<f32> = (0..k * n).map(|i| (i as f32 * 0.013).cos()).collect();
2459 let a = Tensor::from_f32(a_data, Shape::from_dims(&[m, k]), &Device::cpu()).unwrap();
2460 let b = a.const_f32_like(b_data, Shape::from_dims(&[k, n])).unwrap();
2461 let c = a.matmul(&b).unwrap();
2462 let fast = c.realize_f32();
2463 let reference = c.realize_f32();
2464 assert_eq!(fast.len(), reference.len());
2465 for (i, (&f, &r)) in fast.iter().zip(&reference).enumerate() {
2466 let diff = (f - r).abs();
2472 let rel = if r.abs() > 1e-6 { diff / r.abs() } else { 0.0 };
2473 assert!(
2474 diff < 1e-4 || rel < 1e-3,
2475 "at index {i}: fast={f}, reference={r}, diff={diff}, rel={rel}",
2476 );
2477 }
2478 }
2479
2480 fn ref_attention(
2485 q: &[f32],
2486 k: &[f32],
2487 v: &[f32],
2488 hq: usize,
2489 hkv: usize,
2490 sq: usize,
2491 sk: usize,
2492 d: usize,
2493 scale: f32,
2494 causal: bool,
2495 softcap: Option<f32>,
2496 alibi: Option<&[f32]>,
2497 ) -> Vec<f32> {
2498 let g = hq / hkv;
2499 let mut out = vec![0.0f32; hq * sq * d];
2500 for h in 0..hq {
2501 let hk = h / g;
2502 let qh = &q[h * sq * d..(h + 1) * sq * d];
2503 let kh = &k[hk * sk * d..(hk + 1) * sk * d];
2504 let vh = &v[hk * sk * d..(hk + 1) * sk * d];
2505 for i in 0..sq {
2506 let mut scores = vec![0.0f32; sk];
2507 for j in 0..sk {
2508 let mut s = 0.0f32;
2509 for l in 0..d {
2510 s += qh[i * d + l] * kh[j * d + l];
2511 }
2512 let mut sc = scale * s;
2513 if let Some(cap) = softcap {
2514 sc = cap * (sc / cap).tanh();
2515 }
2516 if let Some(slopes) = alibi {
2517 sc += slopes[h] * (j as f32 - i as f32);
2519 }
2520 scores[j] = if causal && j > i {
2521 f32::NEG_INFINITY
2522 } else {
2523 sc
2524 };
2525 }
2526 let m = scores.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
2527 let mut sum = 0.0f32;
2528 let exps: Vec<f32> = scores
2529 .iter()
2530 .map(|&s| {
2531 let e = (s - m).exp();
2532 sum += e;
2533 e
2534 })
2535 .collect();
2536 for l in 0..d {
2537 let mut o = 0.0f32;
2538 for j in 0..sk {
2539 o += (exps[j] / sum) * vh[j * d + l];
2540 }
2541 out[(h * sq + i) * d + l] = o;
2542 }
2543 }
2544 }
2545 out
2546 }
2547
2548 fn flash_decompose_vs_reference(
2554 hq: usize,
2555 hkv: usize,
2556 causal: bool,
2557 softcap: Option<f32>,
2558 alibi: bool,
2559 ) {
2560 let dev = Device::cpu();
2561 let (sq, sk, d) = (2usize, 2usize, 2usize);
2562 let q_data: Vec<f32> = (0..hq * sq * d).map(|i| (i as f32 * 0.1).sin()).collect();
2564 let k_data: Vec<f32> = (0..hkv * sk * d).map(|i| (i as f32 * 0.13).cos()).collect();
2565 let v_data: Vec<f32> = (0..hkv * sk * d).map(|i| i as f32 * 0.07 + 1.0).collect();
2566 #[allow(clippy::approx_constant)]
2569 let scale = 0.7071f32;
2570 let q = Tensor::from_f32(q_data.clone(), Shape::from_dims(&[1, hq, sq, d]), &dev).unwrap();
2571 let k = q
2572 .const_f32_like(k_data.clone(), Shape::from_dims(&[1, hkv, sk, d]))
2573 .unwrap();
2574 let v = q
2575 .const_f32_like(v_data.clone(), Shape::from_dims(&[1, hkv, sk, d]))
2576 .unwrap();
2577 let alibi_slopes: Option<Vec<f32>> = if alibi {
2579 Some((0..hq).map(|h| 0.5f32.powi(h as i32 + 1)).collect())
2580 } else {
2581 None
2582 };
2583 let alibi_t = alibi_slopes.as_ref().map(|s| {
2584 q.const_f32_like(s.clone(), Shape::from_dims(&[hq]))
2585 .unwrap()
2586 });
2587 let attn = q
2588 .flash_attn(&k, &v, alibi_t.as_ref(), scale, causal, None, None, softcap)
2589 .unwrap();
2590
2591 let graph = attn.inner.graph().clone();
2593 let id = attn.inner.id();
2594 let roots =
2595 fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
2596 assert_eq!(roots.len(), 1, "lowering should keep a single root");
2597 let got = crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &dev)
2598 .expect("realize decomposed FlashAttn on CPU");
2599
2600 let expected = ref_attention(
2601 &q_data,
2602 &k_data,
2603 &v_data,
2604 hq,
2605 hkv,
2606 sq,
2607 sk,
2608 d,
2609 scale,
2610 causal,
2611 softcap,
2612 alibi_slopes.as_deref(),
2613 );
2614 assert_eq!(got.len(), expected.len());
2615 for (i, (&g, &e)) in got.iter().zip(&expected).enumerate() {
2616 assert!(
2617 (g - e).abs() < 1e-4,
2618 "FlashAttn decompose mismatch (hq={hq} hkv={hkv} causal={causal} \
2619 softcap={softcap:?} alibi={alibi}) at {i}: got {g}, expected {e}",
2620 );
2621 }
2622 }
2623
2624 struct AttnCase {
2633 name: &'static str,
2634 q: Vec<f32>,
2635 k: Vec<f32>,
2636 v: Vec<f32>,
2637 sq: usize,
2638 sk: usize,
2639 causal: bool,
2640 wl: Option<usize>,
2641 }
2642
2643 fn attn_cases() -> Vec<AttnCase> {
2644 let nan = f32::NAN;
2645 let bq = vec![0.5f32, -0.25, 0.1, 0.9, -0.4, 0.3];
2646 let bk = vec![0.3f32, 0.2, -0.1, 0.6];
2647 let bv = vec![1.0f32, 2.0, 3.0, 4.0];
2648 let c = |name, q: Vec<f32>, k: Vec<f32>, v: Vec<f32>, sq, sk, causal, wl| AttnCase {
2649 name,
2650 q,
2651 k,
2652 v,
2653 sq,
2654 sk,
2655 causal,
2656 wl,
2657 };
2658 vec![
2659 c(
2660 "control",
2661 bq[..4].to_vec(),
2662 bk.clone(),
2663 bv.clone(),
2664 2,
2665 2,
2666 false,
2667 None,
2668 ),
2669 c(
2671 "fully-masked-row-mixed",
2672 bq.clone(),
2673 bk.clone(),
2674 bv.clone(),
2675 3,
2676 2,
2677 true,
2678 Some(0),
2679 ),
2680 c(
2681 "nan-q-row1",
2682 vec![0.5, -0.25, nan, 0.9],
2683 bk.clone(),
2684 bv.clone(),
2685 2,
2686 2,
2687 false,
2688 None,
2689 ),
2690 c(
2691 "nan-k-row1",
2692 bq[..4].to_vec(),
2693 vec![0.3, 0.2, nan, 0.6],
2694 bv.clone(),
2695 2,
2696 2,
2697 false,
2698 None,
2699 ),
2700 c(
2701 "nan-v-row1",
2702 bq[..4].to_vec(),
2703 bk.clone(),
2704 vec![1.0, 2.0, nan, 4.0],
2705 2,
2706 2,
2707 false,
2708 None,
2709 ),
2710 c(
2715 "nan-q-fully-masked-row",
2716 vec![0.5, -0.25, 0.1, 0.9, nan, 0.3],
2717 bk.clone(),
2718 bv.clone(),
2719 3,
2720 2,
2721 true,
2722 Some(0),
2723 ),
2724 c(
2726 "nan-k-masked-key",
2727 bq[..4].to_vec(),
2728 vec![0.3, 0.2, nan, nan],
2729 bv.clone(),
2730 2,
2731 2,
2732 true,
2733 None,
2734 ),
2735 c(
2736 "inf-k-masked-key",
2737 bq[..4].to_vec(),
2738 vec![0.3, 0.2, f32::INFINITY, f32::INFINITY],
2739 bv.clone(),
2740 2,
2741 2,
2742 true,
2743 None,
2744 ),
2745 c(
2746 "nan-v-masked-key",
2747 bq[..4].to_vec(),
2748 bk.clone(),
2749 vec![1.0, 2.0, nan, 4.0],
2750 2,
2751 2,
2752 true,
2753 None,
2754 ),
2755 ]
2756 }
2757
2758 #[derive(Debug, Clone, Copy)]
2760 enum Want {
2761 Nan,
2763 Val(f32),
2765 NanOrVal(f32),
2767 Any,
2769 }
2770
2771 fn attn_expected(name: &str) -> Vec<Want> {
2772 use Want::{Any as a, Nan as n, NanOrVal as o, Val as s};
2773 match name {
2774 "control" => vec![s(1.8943309), s(2.894331), s(2.1126559), s(3.1126556)],
2775 "fully-masked-row-mixed" => vec![s(1.0), s(2.0), s(3.0), s(4.0), s(0.0), s(0.0)],
2776 "nan-q-row1" => vec![s(1.8943309), s(2.894331), n, n],
2777 "nan-k-row1" => vec![n, n, n, n],
2778 "nan-v-row1" => vec![n, s(2.894331), n, s(3.1126556)],
2779 "nan-v-masked-key" => vec![o(1.0), o(2.0), n, s(3.1126556)],
2782 "nan-q-fully-masked-row" => vec![s(1.0), s(2.0), s(3.0), s(4.0), s(0.0), s(0.0)],
2783 "nan-k-masked-key" => vec![s(1.0), s(2.0), n, n],
2784 "inf-k-masked-key" => vec![s(1.0), s(2.0), a, a],
2785 other => panic!("no expectation for {other}"),
2786 }
2787 }
2788
2789 fn attn_check(name: &str, path: &str, got: &[f32], want: &[Want]) -> Option<String> {
2790 assert_eq!(got.len(), want.len(), "{name}/{path}");
2791 let bad: Vec<String> = got
2792 .iter()
2793 .zip(want)
2794 .enumerate()
2795 .filter(|(_, (g, w))| match w {
2796 Want::Nan => !g.is_nan(),
2797 Want::Val(x) => g.is_nan() || (**g - *x).abs() > 1e-4,
2798 Want::NanOrVal(x) => !g.is_nan() && (**g - *x).abs() > 1e-4,
2799 Want::Any => false,
2800 })
2801 .map(|(i, (g, w))| format!("[{i}] got {g} want {w:?}"))
2802 .collect();
2803 (!bad.is_empty()).then(|| format!("{name}/{path}: {}", bad.join("; ")))
2804 }
2805
2806 #[allow(clippy::approx_constant)]
2809 fn attn_tensor(c: &AttnCase) -> Tensor {
2810 let dev = Device::cpu();
2811 let q = Tensor::from_f32(c.q.clone(), Shape::from_dims(&[1, 1, c.sq, 2]), &dev).unwrap();
2812 let k = q
2813 .const_f32_like(c.k.clone(), Shape::from_dims(&[1, 1, c.sk, 2]))
2814 .unwrap();
2815 let v = q
2816 .const_f32_like(c.v.clone(), Shape::from_dims(&[1, 1, c.sk, 2]))
2817 .unwrap();
2818 q.flash_attn(&k, &v, None, 0.7071, c.causal, c.wl, None, None)
2819 .unwrap()
2820 }
2821
2822 #[test]
2823 fn flash_attn_fused_cpu_follows_the_masked_and_nan_row_contract() {
2824 let mut bad = Vec::new();
2825 for c in attn_cases() {
2826 let got = attn_tensor(&c).realize_f32();
2827 bad.extend(attn_check(c.name, "fused", &got, &attn_expected(c.name)));
2828 }
2829 assert!(bad.is_empty(), "{bad:#?}");
2830 }
2831
2832 #[test]
2833 fn flash_attn_decomposed_cpu_follows_the_masked_and_nan_row_contract() {
2834 let mut bad = Vec::new();
2835 for c in attn_cases() {
2836 let attn = attn_tensor(&c);
2837 let graph = attn.inner.graph().clone();
2838 let id = attn.inner.id();
2839 let roots =
2840 fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
2841 let got =
2842 crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &Device::cpu())
2843 .expect("realize decomposed FlashAttn on CPU");
2844 bad.extend(attn_check(
2845 c.name,
2846 "decomposed",
2847 &got,
2848 &attn_expected(c.name),
2849 ));
2850 }
2851 assert!(bad.is_empty(), "{bad:#?}");
2852 }
2853
2854 #[test]
2855 fn flash_attn_decompose_vanilla() {
2856 flash_decompose_vs_reference(1, 1, false, None, false);
2857 }
2858
2859 #[test]
2860 fn flash_attn_decompose_causal() {
2861 flash_decompose_vs_reference(1, 1, true, None, false);
2862 }
2863
2864 #[test]
2865 fn flash_attn_decompose_gqa_causal() {
2866 flash_decompose_vs_reference(2, 1, true, None, false); }
2868
2869 #[test]
2870 fn flash_attn_decompose_softcap() {
2871 flash_decompose_vs_reference(1, 1, false, Some(0.5), false); }
2873
2874 #[test]
2875 fn flash_attn_decompose_alibi() {
2876 flash_decompose_vs_reference(2, 2, false, None, true);
2879 }
2880
2881 #[test]
2882 fn flash_attn_decompose_alibi_causal() {
2883 flash_decompose_vs_reference(2, 2, true, None, true);
2884 }
2885
2886 fn ref_decode_attn(
2892 q: &[f32],
2893 k: &[f32],
2894 v: &[f32],
2895 hq: usize,
2896 hkv: usize,
2897 sq: usize,
2898 cap: usize,
2899 kl: usize,
2900 d: usize,
2901 scale: f32,
2902 causal: bool,
2903 ) -> Vec<f32> {
2904 let g = hq / hkv;
2905 let offset = kl - sq;
2906 let mut out = vec![0f32; hq * sq * d];
2907 for h in 0..hq {
2908 let hk = h / g;
2909 for i in 0..sq {
2910 let qh = &q[((h * sq) + i) * d..][..d];
2911 let mut scores = vec![f32::NEG_INFINITY; kl];
2912 for j in 0..kl {
2913 if causal && j > offset + i {
2914 continue;
2915 }
2916 let kh = &k[((hk * cap) + j) * d..][..d];
2917 let s: f32 = (0..d).map(|l| qh[l] * kh[l]).sum();
2918 scores[j] = scale * s;
2919 }
2920 let m = scores.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
2921 let mut sum = 0f32;
2922 let exps: Vec<f32> = scores
2923 .iter()
2924 .map(|&s| {
2925 let e = (s - m).exp();
2926 sum += e;
2927 e
2928 })
2929 .collect();
2930 for l in 0..d {
2931 let mut o = 0f32;
2932 for j in 0..kl {
2933 o += (exps[j] / sum) * v[((hk * cap) + j) * d + l];
2934 }
2935 out[(h * sq + i) * d + l] = o;
2936 }
2937 }
2938 }
2939 out
2940 }
2941
2942 #[test]
2950 fn flash_attn_decompose_concrete_klen() {
2951 use fuel_graph::Op;
2952 use fuel_graph::registry::FusedOps;
2953 use fuel_ir::DynScalar;
2954 let dev = Device::cpu();
2955 let (hq, hkv, sq, cap, kl, d) = (2usize, 1usize, 2usize, 4usize, 3usize, 2usize);
2956 #[allow(clippy::approx_constant)]
2959 let scale = 0.7071f32;
2960 let causal = true;
2961 let q_data: Vec<f32> = (0..hq * sq * d).map(|i| (i as f32 * 0.1).sin()).collect();
2962 let k_data: Vec<f32> = (0..hkv * cap * d)
2963 .map(|i| (i as f32 * 0.13).cos())
2964 .collect();
2965 let v_data: Vec<f32> = (0..hkv * cap * d).map(|i| i as f32 * 0.07 + 1.0).collect();
2966 let q = Tensor::from_f32(q_data.clone(), Shape::from_dims(&[1, hq, sq, d]), &dev).unwrap();
2967 let k = q
2968 .inner
2969 .const_f32_like(k_data.clone(), Shape::from_dims(&[1, hkv, cap, d]))
2970 .unwrap();
2971 let v = q
2972 .inner
2973 .const_f32_like(v_data.clone(), Shape::from_dims(&[1, hkv, cap, d]))
2974 .unwrap();
2975 let attn = q.inner.flash_attn_dyn(
2977 &k,
2978 &v,
2979 None,
2980 scale,
2981 causal,
2982 None,
2983 None,
2984 None,
2985 DynScalar::Concrete(kl),
2986 );
2987
2988 let graph = attn.graph().clone();
2989 let id = attn.id();
2990 let roots =
2991 fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
2992 assert_eq!(roots.len(), 1, "lowering should keep a single root");
2993
2994 {
2996 let g = graph.read().unwrap();
2997 let mut stack = vec![roots[0]];
2998 let mut seen = std::collections::HashSet::new();
2999 while let Some(nid) = stack.pop() {
3000 if !seen.insert(nid) {
3001 continue;
3002 }
3003 let node = g.node(nid);
3004 assert!(
3005 !matches!(node.op, Op::Fused(fid, _) if fid == FusedOps::FLASH_ATTN),
3006 "concrete-k_len FlashAttn still fused after lowering (self-return)",
3007 );
3008 for &inp in &node.inputs {
3009 stack.push(inp);
3010 }
3011 }
3012 }
3013
3014 let got = crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &dev)
3015 .expect("realize decomposed concrete-k_len FlashAttn on CPU");
3016 let expected = ref_decode_attn(
3017 &q_data, &k_data, &v_data, hq, hkv, sq, cap, kl, d, scale, causal,
3018 );
3019 assert_eq!(got.len(), expected.len());
3020 for (i, (&gv, &ev)) in got.iter().zip(&expected).enumerate() {
3021 assert!(
3022 (gv - ev).abs() < 1e-4,
3023 "concrete-k_len decode mismatch at {i}: got {gv}, expected {ev}",
3024 );
3025 }
3026 }
3027
3028 fn assert_f32_bits_eq(got: &[f32], want: &[f32], ctx: &str) {
3031 assert_eq!(got.len(), want.len(), "{ctx}: length mismatch");
3032 for (i, (&g, &w)) in got.iter().zip(want).enumerate() {
3033 assert_eq!(
3034 g.to_bits(),
3035 w.to_bits(),
3036 "{ctx}: bit mismatch at {i}: got {g} (0x{:08x}), want {w} (0x{:08x})",
3037 g.to_bits(),
3038 w.to_bits(),
3039 );
3040 }
3041 }
3042
3043 fn assert_f32_within_ulp(got: &[f32], want: &[f32], max_ulp: i64, ctx: &str) {
3047 assert_eq!(got.len(), want.len(), "{ctx}: length mismatch");
3048 for (i, (&g, &w)) in got.iter().zip(want).enumerate() {
3049 let d = (g.to_bits() as i64 - w.to_bits() as i64).abs();
3050 assert!(
3051 d <= max_ulp,
3052 "{ctx}: {d} ULP at {i} (> {max_ulp}): got {g} (0x{:08x}), want {w} (0x{:08x})",
3053 g.to_bits(),
3054 w.to_bits(),
3055 );
3056 }
3057 }
3058
3059 #[test]
3084 fn reduce_swap_sumdim_vs_reducesumto_bit_exact_on_cpu_backend() {
3085 let dev = Device::cpu();
3086 let (rows, cols) = (2usize, 4usize);
3087 let data: Vec<f32> = vec![1e8, 1.0, -1e8, 1.0, 3.0e7, 2.0, -3.0e7, -1.0];
3092
3093 let mut left_fold = vec![0.0f32; rows];
3096 let mut right_fold = vec![0.0f32; rows];
3097 for r in 0..rows {
3098 let row = &data[r * cols..(r + 1) * cols];
3099 let mut acc = 0.0f32;
3100 for &v in row.iter() {
3101 acc += v;
3102 }
3103 left_fold[r] = acc;
3104 let mut acc_r = 0.0f32;
3105 for &v in row.iter().rev() {
3106 acc_r += v;
3107 }
3108 right_fold[r] = acc_r;
3109 }
3110 assert_ne!(
3111 left_fold, right_fold,
3112 "test data must be accumulation-order-sensitive so the parity has teeth",
3113 );
3114
3115 let x = Tensor::from_f32(data.clone(), Shape::from_dims(&[rows, cols]), &dev).unwrap();
3116 let sumdim = x.inner.sum_dim(1);
3118 let got_sumdim = crate::pipelined_bridge::realize_one_as::<f32>(
3119 &sumdim.graph().clone(),
3120 sumdim.id(),
3121 &dev,
3122 )
3123 .expect("realize SumDim(last) on CPU");
3124 let reducesumto = x.inner.reduce_sum_to(Shape::from_dims(&[rows, 1]));
3126 let got_reducesumto = crate::pipelined_bridge::realize_one_as::<f32>(
3127 &reducesumto.graph().clone(),
3128 reducesumto.id(),
3129 &dev,
3130 )
3131 .expect("realize ReduceSumTo(keepdim) on CPU");
3132
3133 assert_f32_bits_eq(&got_sumdim, &got_reducesumto, "SumDim vs ReduceSumTo");
3135 assert_f32_bits_eq(&got_sumdim, &left_fold, "SumDim vs left-fold");
3138
3139 let maxdim = x.inner.max_dim(1);
3144 let got_maxdim = crate::pipelined_bridge::realize_one_as::<f32>(
3145 &maxdim.graph().clone(),
3146 maxdim.id(),
3147 &dev,
3148 )
3149 .expect("realize MaxDim(last) on CPU");
3150 let reducemaxto = x.inner.reduce_max_to(Shape::from_dims(&[rows, 1]));
3151 let got_reducemaxto = crate::pipelined_bridge::realize_one_as::<f32>(
3152 &reducemaxto.graph().clone(),
3153 reducemaxto.id(),
3154 &dev,
3155 )
3156 .expect("realize ReduceMaxTo(keepdim) on CPU");
3157 let row_max: Vec<f32> = (0..rows)
3158 .map(|r| {
3159 data[r * cols..(r + 1) * cols]
3160 .iter()
3161 .cloned()
3162 .fold(f32::NEG_INFINITY, f32::max)
3163 })
3164 .collect();
3165 assert_f32_bits_eq(&got_maxdim, &got_reducemaxto, "MaxDim vs ReduceMaxTo");
3166 assert_f32_bits_eq(&got_maxdim, &row_max, "MaxDim vs per-row max");
3167 }
3168
3169 #[test]
3189 fn softmax_last_dim_recipe_decompose_matches_legacy_on_cpu() {
3190 let dev = Device::cpu();
3191 let (rows, cols) = (3usize, 5usize);
3192 let data: Vec<f32> = (0..rows * cols)
3193 .map(|i| ((i as f32) * 0.37).sin() * 4.0 - (i as f32) * 0.11)
3194 .collect();
3195 let shape = || Shape::from_dims(&[rows, cols]);
3196 let keepdim = || Shape::from_dims(&[rows, 1]);
3197
3198 let recipe = Tensor::from_f32(data.clone(), shape(), &dev)
3200 .unwrap()
3201 .softmax_last_dim()
3202 .expect("softmax recipe build");
3203 let graph = recipe.inner.graph().clone();
3204 let id = recipe.inner.id();
3205 let roots =
3206 fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
3207 assert_eq!(roots.len(), 1, "lowering keeps a single root");
3208 let recipe_out = crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &dev)
3209 .expect("realize recipe-decomposed softmax on CPU");
3210
3211 let x = Tensor::from_f32(data.clone(), shape(), &dev).unwrap().inner;
3214 let m = x.reduce_max_to(keepdim());
3215 let mb = m.broadcast_to(shape());
3216 let s = x.sub(&mb);
3217 let e = s.exp();
3218 let d = e.reduce_sum_to(keepdim());
3219 let db = d.broadcast_to(shape());
3220 let legacy = e.div(&db);
3221 let legacy_out = crate::pipelined_bridge::realize_one_as::<f32>(
3222 &legacy.graph().clone(),
3223 legacy.id(),
3224 &dev,
3225 )
3226 .expect("realize legacy softmax on CPU");
3227
3228 assert_f32_bits_eq(&recipe_out, &legacy_out, "softmax recipe vs legacy");
3230 for r in 0..rows {
3232 let sum: f32 = recipe_out[r * cols..(r + 1) * cols].iter().sum();
3233 assert!((sum - 1.0).abs() < 1e-5, "row {r} softmax sum = {sum}");
3234 }
3235
3236 let fused_out = Tensor::from_f32(data.clone(), shape(), &dev)
3240 .unwrap()
3241 .softmax_last_dim()
3242 .expect("softmax fused build")
3243 .realize_f32();
3244 assert_f32_within_ulp(&recipe_out, &fused_out, 1, "softmax recipe vs fused kernel");
3245 }
3246
3247 #[test]
3255 fn rms_norm_last_dim_recipe_decompose_matches_legacy_on_cpu() {
3256 let dev = Device::cpu();
3257 let (rows, cols) = (3usize, 6usize);
3258 let eps = 1e-6f64;
3259 let data: Vec<f32> = (0..rows * cols)
3260 .map(|i| ((i as f32) * 0.29).cos() * 2.5 + 0.5)
3261 .collect();
3262 let shape = || Shape::from_dims(&[rows, cols]);
3263 let keepdim = || Shape::from_dims(&[rows, 1]);
3264
3265 let recipe = Tensor::from_f32(data.clone(), shape(), &dev)
3267 .unwrap()
3268 .rms_norm_last_dim(eps)
3269 .expect("rms_norm recipe build");
3270 let graph = recipe.inner.graph().clone();
3271 let id = recipe.inner.id();
3272 let roots =
3273 fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
3274 assert_eq!(roots.len(), 1, "lowering keeps a single root");
3275 let recipe_out = crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &dev)
3276 .expect("realize recipe-decomposed rms_norm on CPU");
3277
3278 let x = Tensor::from_f32(data.clone(), shape(), &dev).unwrap().inner;
3281 let sq = x.sqr();
3282 let mean = sq.mean_dim(1);
3283 let mean_kd = mean.reshape(keepdim());
3284 let denom_sq = mean_kd.add_scalar(eps);
3285 let denom = denom_sq.sqrt();
3286 let denom_b = denom.broadcast_to(shape());
3287 let legacy = x.div(&denom_b);
3288 let legacy_out = crate::pipelined_bridge::realize_one_as::<f32>(
3289 &legacy.graph().clone(),
3290 legacy.id(),
3291 &dev,
3292 )
3293 .expect("realize legacy rms_norm on CPU");
3294
3295 assert_f32_bits_eq(&recipe_out, &legacy_out, "rms_norm recipe vs legacy");
3297
3298 let fused_out = Tensor::from_f32(data.clone(), shape(), &dev)
3301 .unwrap()
3302 .rms_norm_last_dim(eps)
3303 .expect("rms_norm fused build")
3304 .realize_f32();
3305 assert_f32_within_ulp(
3306 &recipe_out,
3307 &fused_out,
3308 1,
3309 "rms_norm recipe vs fused kernel",
3310 );
3311 }
3312
3313 #[test]
3324 fn selective_scan_decompose_lowers_to_scan_and_matches() {
3325 use fuel_graph::Op;
3326 use fuel_graph::registry::FusedOps;
3327 let dev = Device::cpu();
3328 let u = Tensor::from_f32(vec![2.0f32], Shape::from_dims(&[1, 1, 1]), &dev).unwrap();
3329 let delta = u
3330 .const_f32_like(vec![0.5f32], Shape::from_dims(&[1, 1, 1]))
3331 .unwrap();
3332 let a = u
3333 .const_f32_like(vec![-1.0f32], Shape::from_dims(&[1, 1]))
3334 .unwrap();
3335 let b = u
3336 .const_f32_like(vec![3.0f32], Shape::from_dims(&[1, 1, 1]))
3337 .unwrap();
3338 let c = u
3339 .const_f32_like(vec![4.0f32], Shape::from_dims(&[1, 1, 1]))
3340 .unwrap();
3341 let y = u.selective_scan(&delta, &a, &b, &c, false);
3342
3343 let got = y.realize_f32();
3345 assert_eq!(got.len(), 1);
3346 assert!((got[0] - 12.0).abs() < 1e-4, "fused kernel y: {}", got[0]);
3347
3348 let graph = y.inner.graph().clone();
3351 let id = y.inner.id();
3352 let roots =
3353 fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
3354 assert_eq!(roots.len(), 1);
3355 let scan_id = {
3356 let g = graph.read().unwrap();
3357 let mut stack = vec![roots[0]];
3358 let mut seen = std::collections::HashSet::new();
3359 let mut scan_id = None;
3360 while let Some(nid) = stack.pop() {
3361 if !seen.insert(nid) {
3362 continue;
3363 }
3364 let node = g.node(nid);
3365 assert!(
3366 !matches!(node.op, Op::Fused(fid, _) if fid == FusedOps::SELECTIVE_SCAN),
3367 "SelectiveScan must lower to Op::Scan, not remain fused"
3368 );
3369 if matches!(node.op, Op::Scan { .. }) {
3370 scan_id = Some(nid);
3371 }
3372 for &inp in &node.inputs {
3373 stack.push(inp);
3374 }
3375 }
3376 scan_id.expect("an Op::Scan terminal must be present after lowering")
3377 };
3378 let ys = {
3380 let mut g = graph.write().unwrap();
3381 fuel_graph::scan::unroll_scan(&mut g, scan_id, 1)
3382 .expect("unroll")
3383 .0[0] };
3385 let oracle = crate::pipelined_bridge::realize_one_as::<f32>(&graph, ys, &dev)
3386 .expect("realize unrolled selective_scan oracle on CPU");
3387 assert!(
3388 oracle.iter().any(|&v| (v - 12.0).abs() < 1e-4),
3389 "unroll oracle must contain y = 12, got {oracle:?}"
3390 );
3391 }
3392
3393 #[test]
3406 fn ssd_chunk_scan_decompose_lowers_to_scan_and_matches() {
3407 use fuel_graph::Op;
3408 use fuel_graph::registry::FusedOps;
3409 let dev = Device::cpu();
3410 let x = Tensor::from_f32(vec![2.0f32], Shape::from_dims(&[1, 1, 1, 1]), &dev).unwrap();
3413 let dt = x
3414 .const_f32_like(vec![0.5f32], Shape::from_dims(&[1, 1, 1]))
3415 .unwrap();
3416 let a = x
3417 .const_f32_like(vec![-1.0f32], Shape::from_dims(&[1]))
3418 .unwrap();
3419 let b = x
3420 .const_f32_like(vec![3.0f32], Shape::from_dims(&[1, 1, 1, 1]))
3421 .unwrap();
3422 let c = x
3423 .const_f32_like(vec![4.0f32], Shape::from_dims(&[1, 1, 1, 1]))
3424 .unwrap();
3425 let y = x.ssd_chunk_scan(&dt, &a, &b, &c, 1);
3426
3427 let got = y.realize_f32();
3429 assert!(
3430 (got[0] - 12.0).abs() < 1e-4,
3431 "fused ssd kernel y: {}",
3432 got[0]
3433 );
3434
3435 let graph = y.inner.graph().clone();
3438 let id = y.inner.id();
3439 let roots =
3440 fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
3441 let scan_id = {
3442 let g = graph.read().unwrap();
3443 let mut stack = vec![roots[0]];
3444 let mut seen = std::collections::HashSet::new();
3445 let mut scan_id = None;
3446 while let Some(nid) = stack.pop() {
3447 if !seen.insert(nid) {
3448 continue;
3449 }
3450 let node = g.node(nid);
3451 assert!(
3452 !matches!(node.op, Op::Fused(fid, _) if fid == FusedOps::SSD_CHUNK_SCAN),
3453 "SsdChunkScan must lower to Op::Scan, not remain fused"
3454 );
3455 if matches!(node.op, Op::Scan { .. }) {
3456 scan_id = Some(nid);
3457 }
3458 for &inp in &node.inputs {
3459 stack.push(inp);
3460 }
3461 }
3462 scan_id.expect("an Op::Scan terminal must be present after lowering")
3463 };
3464 let ys = {
3465 let mut g = graph.write().unwrap();
3466 fuel_graph::scan::unroll_scan(&mut g, scan_id, 1)
3467 .expect("unroll")
3468 .0[0] };
3470 let oracle = crate::pipelined_bridge::realize_one_as::<f32>(&graph, ys, &dev)
3471 .expect("realize unrolled ssd_chunk_scan oracle on CPU");
3472 assert!(
3473 oracle.iter().any(|&v| (v - 12.0).abs() < 1e-4),
3474 "oracle y=12, got {oracle:?}"
3475 );
3476 }
3477
3478 #[test]
3485 fn affine_scan_bptt_matches_finite_difference() {
3486 use fuel_graph::{Node, NodeHandle, Op, ScanEmit, ScanRole};
3487 use fuel_ir::{DType, Shape};
3488 let dev = Device::cpu();
3489 let build = |init_v: f32,
3492 a_v: f32,
3493 b_v: f32|
3494 -> (
3495 std::sync::Arc<std::sync::RwLock<fuel_graph::Graph>>,
3496 fuel_graph::NodeId,
3497 fuel_graph::NodeHandle,
3498 fuel_graph::NodeHandle,
3499 fuel_graph::NodeHandle,
3500 ) {
3501 let init =
3502 NodeHandle::from_f32(vec![init_v], Shape::from_dims(&[1]), dev.as_dyn()).unwrap();
3503 let g = init.graph().clone();
3504 let a = NodeHandle::from_existing(g.clone(), init.id())
3505 .const_f32_like(vec![a_v], Shape::from_dims(&[1]))
3506 .unwrap();
3507 let b = NodeHandle::from_existing(g.clone(), init.id())
3508 .const_f32_like(vec![b_v], Shape::from_dims(&[1]))
3509 .unwrap();
3510 let nc = {
3511 let mut gw = g.write().unwrap();
3512 let s = Shape::from_dims(&[1]);
3513 let hole = gw.push(Node {
3514 op: Op::ScanPlaceholder {
3515 role: ScanRole::Carry,
3516 index: 0,
3517 },
3518 inputs: vec![],
3519 shape: s.clone(),
3520 dtype: DType::F32,
3521 });
3522 let ac = gw.push(Node {
3523 op: Op::Mul,
3524 inputs: vec![a.id(), hole],
3525 shape: s.clone(),
3526 dtype: DType::F32,
3527 });
3528 gw.push(Node {
3529 op: Op::Add,
3530 inputs: vec![ac, b.id()],
3531 shape: s.clone(),
3532 dtype: DType::F32,
3533 })
3534 };
3535 let nc_t = NodeHandle::from_existing(g.clone(), nc);
3536 let out = init
3537 .scan(
3538 &[],
3539 &[a.clone(), b.clone()],
3540 &nc_t,
3541 &nc_t,
3542 3,
3543 ScanEmit::Final,
3544 )
3545 .expect("scan");
3546 (g, out.id(), init, a, b)
3547 };
3548 let fwd = |init_v: f32, a_v: f32, b_v: f32| -> f32 {
3550 let (g, out_id, _i, _a, _b) = build(init_v, a_v, b_v);
3551 let scan_id = {
3552 let gr = g.read().unwrap();
3553 gr.node(out_id).inputs[0]
3554 };
3555 let carry = {
3556 let mut gw = g.write().unwrap();
3557 fuel_graph::scan::unroll_scan(&mut gw, scan_id, 3)
3558 .expect("unroll")
3559 .0[0] }; crate::pipelined_bridge::realize_one_as::<f32>(&g, carry, &dev).expect("realize")[0]
3562 };
3563 let (g, out_id, init, a, b) = build(1.0, 0.5, 0.1);
3565 let out = fuel_graph::NodeHandle::from_existing(g.clone(), out_id);
3566 let grads = out.backward();
3567 let realize_grad = |t: &fuel_graph::NodeHandle| {
3568 crate::pipelined_bridge::realize_one_as::<f32>(
3569 &g,
3570 grads.get(t).expect("grad").id(),
3571 &dev,
3572 )
3573 .expect("realize grad")[0]
3574 };
3575 let g_init = realize_grad(&init);
3576 let g_a = realize_grad(&a);
3577 let g_b = realize_grad(&b);
3578 let h = 1e-3f32;
3580 let fd = |dinit: f32, da: f32, db: f32| {
3581 (fwd(1.0 + dinit, 0.5 + da, 0.1 + db) - fwd(1.0 - dinit, 0.5 - da, 0.1 - db))
3582 / (2.0 * h)
3583 };
3584 assert!(
3585 (g_init - fd(h, 0.0, 0.0)).abs() < 2e-2,
3586 "d/dinit: autograd {g_init} vs FD {}",
3587 fd(h, 0.0, 0.0)
3588 );
3589 assert!(
3590 (g_a - fd(0.0, h, 0.0)).abs() < 2e-2,
3591 "d/da: autograd {g_a} vs FD {}",
3592 fd(0.0, h, 0.0)
3593 );
3594 assert!(
3595 (g_b - fd(0.0, 0.0, h)).abs() < 2e-2,
3596 "d/db: autograd {g_b} vs FD {}",
3597 fd(0.0, 0.0, h)
3598 );
3599 }
3600
3601 #[test]
3602 fn selective_scan_is_differentiable_backward_matches_fd() {
3603 let dev = Device::cpu();
3604 let fwd = |u_v: f32| -> f32 {
3605 let u = Tensor::from_f32(vec![u_v], Shape::from_dims(&[1, 1, 1]), &dev).unwrap();
3606 let delta = u
3607 .const_f32_like(vec![0.5f32], Shape::from_dims(&[1, 1, 1]))
3608 .unwrap();
3609 let a = u
3610 .const_f32_like(vec![-1.0f32], Shape::from_dims(&[1, 1]))
3611 .unwrap();
3612 let b = u
3613 .const_f32_like(vec![3.0f32], Shape::from_dims(&[1, 1, 1]))
3614 .unwrap();
3615 let c = u
3616 .const_f32_like(vec![4.0f32], Shape::from_dims(&[1, 1, 1]))
3617 .unwrap();
3618 u.selective_scan(&delta, &a, &b, &c, false).realize_f32()[0]
3619 };
3620 let u = Tensor::from_f32(vec![2.0f32], Shape::from_dims(&[1, 1, 1]), &dev).unwrap();
3622 let delta = u
3623 .const_f32_like(vec![0.5f32], Shape::from_dims(&[1, 1, 1]))
3624 .unwrap();
3625 let a = u
3626 .const_f32_like(vec![-1.0f32], Shape::from_dims(&[1, 1]))
3627 .unwrap();
3628 let b = u
3629 .const_f32_like(vec![3.0f32], Shape::from_dims(&[1, 1, 1]))
3630 .unwrap();
3631 let c = u
3632 .const_f32_like(vec![4.0f32], Shape::from_dims(&[1, 1, 1]))
3633 .unwrap();
3634 let y = u.selective_scan(&delta, &a, &b, &c, false);
3635 let grads = y.inner.backward();
3636 let g_u_id = grads.get(u.graph_tensor()).expect("grad u").id();
3637 let g_u =
3638 crate::pipelined_bridge::realize_one_as::<f32>(&u.inner.graph().clone(), g_u_id, &dev)
3639 .expect("realize")[0];
3640 let h = 1e-3;
3641 let fd = (fwd(2.0 + h) - fwd(2.0 - h)) / (2.0 * h);
3642 assert!(
3643 (g_u - fd).abs() < 5e-2,
3644 "selective_scan d/du: autograd {g_u} vs FD {fd}"
3645 );
3646 }
3647
3648 #[test]
3649 fn ssd_chunk_scan_is_differentiable_backward_matches_fd() {
3650 let dev = Device::cpu();
3651 let fwd = |x_v: f32| -> f32 {
3654 let x = Tensor::from_f32(vec![x_v], Shape::from_dims(&[1, 1, 1, 1]), &dev).unwrap();
3655 let dt = x
3656 .const_f32_like(vec![0.5f32], Shape::from_dims(&[1, 1, 1]))
3657 .unwrap();
3658 let a = x
3659 .const_f32_like(vec![-1.0f32], Shape::from_dims(&[1]))
3660 .unwrap();
3661 let b = x
3662 .const_f32_like(vec![3.0f32], Shape::from_dims(&[1, 1, 1, 1]))
3663 .unwrap();
3664 let c = x
3665 .const_f32_like(vec![4.0f32], Shape::from_dims(&[1, 1, 1, 1]))
3666 .unwrap();
3667 x.ssd_chunk_scan(&dt, &a, &b, &c, 1).realize_f32()[0]
3668 };
3669 let x = Tensor::from_f32(vec![2.0f32], Shape::from_dims(&[1, 1, 1, 1]), &dev).unwrap();
3671 let dt = x
3672 .const_f32_like(vec![0.5f32], Shape::from_dims(&[1, 1, 1]))
3673 .unwrap();
3674 let a = x
3675 .const_f32_like(vec![-1.0f32], Shape::from_dims(&[1]))
3676 .unwrap();
3677 let b = x
3678 .const_f32_like(vec![3.0f32], Shape::from_dims(&[1, 1, 1, 1]))
3679 .unwrap();
3680 let c = x
3681 .const_f32_like(vec![4.0f32], Shape::from_dims(&[1, 1, 1, 1]))
3682 .unwrap();
3683 let y = x.ssd_chunk_scan(&dt, &a, &b, &c, 1);
3684 let grads = y.inner.backward();
3685 let g_x_id = grads.get(x.graph_tensor()).expect("grad x").id();
3686 let g_x =
3687 crate::pipelined_bridge::realize_one_as::<f32>(&x.inner.graph().clone(), g_x_id, &dev)
3688 .expect("realize")[0];
3689 let h = 1e-3;
3690 let fd = (fwd(2.0 + h) - fwd(2.0 - h)) / (2.0 * h);
3691 assert!(
3692 (g_x - fd).abs() < 5e-2,
3693 "ssd_chunk_scan d/dx: autograd {g_x} vs FD {fd}"
3694 );
3695 }
3696
3697 fn act_grad_and_fd(
3700 x_v: f32,
3701 act: impl Fn(&Tensor) -> Tensor,
3702 fd_act: impl Fn(&Tensor) -> Tensor,
3703 ) -> (f32, f32) {
3704 let dev = Device::cpu();
3705 let x = Tensor::from_f32(vec![x_v], Shape::from_dims(&[1]), &dev).unwrap();
3706 let y = act(&x);
3707 let grads = y.inner.backward();
3708 let g_id = grads.get(x.graph_tensor()).expect("grad x").id();
3709 let g =
3710 crate::pipelined_bridge::realize_one_as::<f32>(&x.inner.graph().clone(), g_id, &dev)
3711 .expect("realize")[0];
3712 let fwd = |v: f32| -> f32 {
3713 let t = Tensor::from_f32(vec![v], Shape::from_dims(&[1]), &dev).unwrap();
3714 fd_act(&t).realize_f32()[0]
3715 };
3716 let h = 1e-2f32;
3717 (g, (fwd(x_v + h) - fwd(x_v - h)) / (2.0 * h))
3718 }
3719
3720 #[test]
3724 fn gelu_tanh_backward_matches_finite_difference() {
3725 for x_v in [-3.0f32, -1.5, -0.5, 0.0, 0.3, 1.0, 2.5] {
3726 let (g, fd) = act_grad_and_fd(x_v, |x| x.gelu_tanh(), |x| x.gelu_tanh());
3727 assert!(
3728 (g - fd).abs() < 2e-3,
3729 "gelu_tanh d/dx at {x_v}: autograd {g} vs FD {fd}"
3730 );
3731 }
3732 }
3733
3734 #[test]
3736 fn gelu_tanh_inplace_backward_matches_finite_difference() {
3737 for x_v in [-3.0f32, -1.5, -0.5, 0.0, 0.3, 1.0, 2.5] {
3738 let (g, fd) = act_grad_and_fd(x_v, |x| x.gelu_tanh_inplace(), |x| x.gelu_tanh());
3739 assert!(
3740 (g - fd).abs() < 2e-3,
3741 "gelu_tanh_inplace d/dx at {x_v}: autograd {g} vs FD {fd}"
3742 );
3743 }
3744 }
3745
3746 #[test]
3752 fn finite_difference_harness_rejects_a_wrong_activation_gradient() {
3753 let (g_silu, fd_gelu) = act_grad_and_fd(-1.5, |x| x.silu(), |x| x.gelu_tanh());
3754 assert!(
3755 (g_silu - fd_gelu).abs() > 2e-2,
3756 "silu grad {g_silu} too close to gelu_tanh FD {fd_gelu}: harness cannot discriminate"
3757 );
3758 }
3759
3760 fn grad_vs_fd(
3764 x_vals: &[f32],
3765 x_shape: &[usize],
3766 build: impl Fn(&Tensor) -> Tensor,
3767 ) -> (Vec<f32>, Vec<f32>) {
3768 grad_vs_fd_impl(x_vals, x_shape, build, false)
3769 }
3770
3771 fn grad_vs_fd_lowered(
3774 x_vals: &[f32],
3775 x_shape: &[usize],
3776 build: impl Fn(&Tensor) -> Tensor,
3777 ) -> (Vec<f32>, Vec<f32>) {
3778 grad_vs_fd_impl(x_vals, x_shape, build, true)
3779 }
3780
3781 fn grad_vs_fd_impl(
3782 x_vals: &[f32],
3783 x_shape: &[usize],
3784 build: impl Fn(&Tensor) -> Tensor,
3785 lower_forward: bool,
3786 ) -> (Vec<f32>, Vec<f32>) {
3787 let dev = Device::cpu();
3788 let x = Tensor::from_f32(x_vals.to_vec(), Shape::from_dims(x_shape), &dev).unwrap();
3789 let y = build(&x);
3790 let grads = y.inner.backward();
3791 let g_id = grads.get(x.graph_tensor()).expect("grad x").id();
3792 let g =
3793 crate::pipelined_bridge::realize_one_as::<f32>(&x.inner.graph().clone(), g_id, &dev)
3794 .expect("realize");
3795 let fwd_sum = |vals: &[f32]| -> f32 {
3796 let t = Tensor::from_f32(vals.to_vec(), Shape::from_dims(x_shape), &dev).unwrap();
3797 let y = build(&t);
3798 if lower_forward {
3799 let graph = y.inner.graph().clone();
3800 let roots = fuel_graph::opt::RuleRegistry::lowering_only()
3801 .optimize_to_fixpoint(&graph, &[y.inner.id()]);
3802 crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &dev)
3803 .expect("realize lowered forward")
3804 .iter()
3805 .sum()
3806 } else {
3807 y.realize_f32().iter().sum()
3808 }
3809 };
3810 let h = 1e-2f32;
3811 let fd = (0..x_vals.len())
3812 .map(|i| {
3813 let (mut p, mut m) = (x_vals.to_vec(), x_vals.to_vec());
3814 p[i] += h;
3815 m[i] -= h;
3816 (fwd_sum(&p) - fwd_sum(&m)) / (2.0 * h)
3817 })
3818 .collect();
3819 (g, fd)
3820 }
3821
3822 fn assert_grad_close(label: &str, g: &[f32], fd: &[f32]) {
3823 assert_eq!(g.len(), fd.len(), "{label}: length");
3824 for (i, (a, b)) in g.iter().zip(fd).enumerate() {
3825 assert!(
3826 (a - b).abs() < 5e-3 + 5e-3 * b.abs(),
3827 "{label}[{i}]: autograd {a} vs FD {b}"
3828 );
3829 }
3830 }
3831
3832 #[test]
3836 fn nf4_matmul_activation_gradient_matches_finite_difference() {
3837 let (g, fd) = grad_vs_fd(&[1.0, 2.0, 2.0, 4.0], &[1, 4], |act| {
3838 let w_packed = Tensor::from_graph_tensor(
3839 act.graph_tensor()
3840 .const_u8_like(vec![247_u8, 247, 127, 127], Shape::from_dims(&[2, 2]))
3841 .unwrap(),
3842 );
3843 let absmax = act
3844 .const_f32_like(vec![1.0_f32, 2.0, 10.0, 20.0], Shape::from_dims(&[2, 2]))
3845 .unwrap();
3846 act.nf4_matmul(&w_packed, &absmax, 2)
3847 });
3848 assert_grad_close("nf4_matmul d/dact", &g, &fd);
3849 }
3850
3851 #[test]
3856 fn awq_matmul_activation_gradient_matches_finite_difference() {
3857 let x_vals: Vec<f32> = (0..64).map(|k| ((k * 7) % 13) as f32 * 0.1 - 0.6).collect();
3858 let (g, fd) = grad_vs_fd_lowered(&x_vals, &[1, 64], |act| {
3859 let words: Vec<u32> = (0..64u32)
3860 .map(|i| i.wrapping_mul(0x9E37_79B1) ^ 0x1234_5678)
3861 .collect();
3862 let weight = act
3863 .graph_tensor()
3864 .const_u32_like(words, Shape::from_dims(&[8, 8]))
3865 .unwrap();
3866 let zeros = act
3867 .graph_tensor()
3868 .const_u32_like(vec![0x7777_7777; 16], Shape::from_dims(&[8, 2]))
3869 .unwrap();
3870 let scales: Vec<half::f16> = (0..128)
3871 .map(|i| half::f16::from_f32(0.05 + 0.01 * (i % 7) as f32))
3872 .collect();
3873 let scales = act
3874 .const_f16_like(scales, Shape::from_dims(&[8, 16]))
3875 .unwrap();
3876 Tensor::from_graph_tensor(act.graph_tensor().awq_matmul(
3877 &weight,
3878 &zeros,
3879 scales.graph_tensor(),
3880 64,
3881 8,
3882 ))
3883 });
3884 assert_grad_close("awq_matmul d/dact", &g, &fd);
3885 }
3886
3887 #[test]
3888 fn causal_conv1d_weight_and_bias_gradients_match_finite_difference() {
3889 let x_data = vec![0.3, -0.5, 0.8, 0.1, -0.2, 0.6, 0.4, -0.7];
3890 for use_silu in [false, true] {
3891 let (g, fd) = grad_vs_fd(&[0.5, -0.25, 0.75, 0.1, 0.9, -0.4], &[2, 1, 3], |w| {
3893 let x = w
3894 .const_f32_like(x_data.clone(), Shape::from_dims(&[1, 2, 4]))
3895 .unwrap();
3896 let b = w
3897 .const_f32_like(vec![0.05, -0.05], Shape::from_dims(&[2]))
3898 .unwrap();
3899 x.causal_conv1d(w, &b, use_silu)
3900 });
3901 assert_grad_close(&format!("causal_conv1d(silu={use_silu}) d/dw"), &g, &fd);
3902 let (g, fd) = grad_vs_fd(&[0.05, -0.05], &[2], |b| {
3904 let x = b
3905 .const_f32_like(x_data.clone(), Shape::from_dims(&[1, 2, 4]))
3906 .unwrap();
3907 let w = b
3908 .const_f32_like(
3909 vec![0.5, -0.25, 0.75, 0.1, 0.9, -0.4],
3910 Shape::from_dims(&[2, 1, 3]),
3911 )
3912 .unwrap();
3913 x.causal_conv1d(&w, b, use_silu)
3914 });
3915 assert_grad_close(&format!("causal_conv1d(silu={use_silu}) d/dbias"), &g, &fd);
3916 }
3917 }
3918
3919 #[test]
3920 fn causal_conv1d_input_gradient_matches_finite_difference() {
3921 for use_silu in [false, true] {
3923 let (g, fd) = grad_vs_fd(
3924 &[0.3, -0.5, 0.8, 0.1, -0.2, 0.6, 0.4, -0.7],
3925 &[1, 2, 4],
3926 |x| {
3927 let w = x
3928 .const_f32_like(
3929 vec![0.5, -0.25, 0.75, 0.1, 0.9, -0.4],
3930 Shape::from_dims(&[2, 1, 3]),
3931 )
3932 .unwrap();
3933 let b = x
3934 .const_f32_like(vec![0.05, -0.05], Shape::from_dims(&[2]))
3935 .unwrap();
3936 x.causal_conv1d(&w, &b, use_silu)
3937 },
3938 );
3939 assert_grad_close(&format!("causal_conv1d(silu={use_silu}) d/dx"), &g, &fd);
3940 }
3941 }
3942
3943 #[test]
3950 fn selective_scan_seqlen2_bptt_matches_finite_difference() {
3951 let dev = Device::cpu();
3952 let fwd = |u_vals: &[f32]| -> f32 {
3955 let u = Tensor::from_f32(u_vals.to_vec(), Shape::from_dims(&[1, 2, 1]), &dev).unwrap();
3956 let delta = u
3957 .const_f32_like(vec![0.7f32, 0.7], Shape::from_dims(&[1, 2, 1]))
3958 .unwrap();
3959 let a = u
3960 .const_f32_like(vec![-0.5f32], Shape::from_dims(&[1, 1]))
3961 .unwrap();
3962 let b = u
3963 .const_f32_like(vec![1.0f32, 1.0], Shape::from_dims(&[1, 2, 1]))
3964 .unwrap();
3965 let c = u
3966 .const_f32_like(vec![1.0f32, 1.0], Shape::from_dims(&[1, 2, 1]))
3967 .unwrap();
3968 u.selective_scan(&delta, &a, &b, &c, false)
3969 .realize_f32()
3970 .iter()
3971 .sum()
3972 };
3973 let u0 = vec![1.0f32, 2.0];
3974 let u = Tensor::from_f32(u0.clone(), Shape::from_dims(&[1, 2, 1]), &dev).unwrap();
3975 let delta = u
3976 .const_f32_like(vec![0.7f32, 0.7], Shape::from_dims(&[1, 2, 1]))
3977 .unwrap();
3978 let a = u
3979 .const_f32_like(vec![-0.5f32], Shape::from_dims(&[1, 1]))
3980 .unwrap();
3981 let b = u
3982 .const_f32_like(vec![1.0f32, 1.0], Shape::from_dims(&[1, 2, 1]))
3983 .unwrap();
3984 let c = u
3985 .const_f32_like(vec![1.0f32, 1.0], Shape::from_dims(&[1, 2, 1]))
3986 .unwrap();
3987 let y = u.selective_scan(&delta, &a, &b, &c, false);
3988 let grads = y.inner.backward(); let g_u_id = grads.get(u.graph_tensor()).expect("grad u").id();
3990 let g_u =
3991 crate::pipelined_bridge::realize_one_as::<f32>(&u.inner.graph().clone(), g_u_id, &dev)
3992 .expect("realize");
3993 let h = 1e-3f32;
3996 let mut up = u0.clone();
3997 up[0] += h;
3998 let mut um = u0.clone();
3999 um[0] -= h;
4000 let fd0 = (fwd(&up) - fwd(&um)) / (2.0 * h);
4001 assert!(
4002 (g_u[0] - fd0).abs() < 5e-2,
4003 "selective_scan seqlen2 dL/du_1: autograd {} vs FD {fd0}",
4004 g_u[0]
4005 );
4006 assert!(
4009 g_u[0].abs() > 0.5,
4010 "recurrent-gate grad must be non-trivial, got {g_u:?}"
4011 );
4012 }
4013
4014 #[test]
4015 fn ssd_chunk_scan_seqlen4_chunk2_bptt_matches_finite_difference() {
4016 let dev = Device::cpu();
4017 let fwd = |x_vals: &[f32]| -> f32 {
4021 let x =
4022 Tensor::from_f32(x_vals.to_vec(), Shape::from_dims(&[1, 4, 1, 1]), &dev).unwrap();
4023 let dt = x
4024 .const_f32_like(vec![0.6f32, 0.6, 0.6, 0.6], Shape::from_dims(&[1, 4, 1]))
4025 .unwrap();
4026 let a = x
4027 .const_f32_like(vec![-0.5f32], Shape::from_dims(&[1]))
4028 .unwrap();
4029 let b = x
4030 .const_f32_like(vec![1.0f32, 1.0, 1.0, 1.0], Shape::from_dims(&[1, 4, 1, 1]))
4031 .unwrap();
4032 let c = x
4033 .const_f32_like(vec![1.0f32, 1.0, 1.0, 1.0], Shape::from_dims(&[1, 4, 1, 1]))
4034 .unwrap();
4035 x.ssd_chunk_scan(&dt, &a, &b, &c, 2)
4036 .realize_f32()
4037 .iter()
4038 .sum()
4039 };
4040 let x0 = vec![1.0f32, 2.0, 3.0, 4.0];
4041 let x = Tensor::from_f32(x0.clone(), Shape::from_dims(&[1, 4, 1, 1]), &dev).unwrap();
4042 let dt = x
4043 .const_f32_like(vec![0.6f32, 0.6, 0.6, 0.6], Shape::from_dims(&[1, 4, 1]))
4044 .unwrap();
4045 let a = x
4046 .const_f32_like(vec![-0.5f32], Shape::from_dims(&[1]))
4047 .unwrap();
4048 let b = x
4049 .const_f32_like(vec![1.0f32, 1.0, 1.0, 1.0], Shape::from_dims(&[1, 4, 1, 1]))
4050 .unwrap();
4051 let c = x
4052 .const_f32_like(vec![1.0f32, 1.0, 1.0, 1.0], Shape::from_dims(&[1, 4, 1, 1]))
4053 .unwrap();
4054 let y = x.ssd_chunk_scan(&dt, &a, &b, &c, 2);
4055 let grads = y.inner.backward();
4056 let g_x_id = grads.get(x.graph_tensor()).expect("grad x").id();
4057 let g_x =
4058 crate::pipelined_bridge::realize_one_as::<f32>(&x.inner.graph().clone(), g_x_id, &dev)
4059 .expect("realize");
4060 let h = 1e-3f32;
4063 let mut xp = x0.clone();
4064 xp[0] += h;
4065 let mut xm = x0.clone();
4066 xm[0] -= h;
4067 let fd0 = (fwd(&xp) - fwd(&xm)) / (2.0 * h);
4068 assert!(
4069 (g_x[0] - fd0).abs() < 5e-2,
4070 "ssd_chunk_scan seqlen4 dL/dx_0: autograd {} vs FD {fd0}",
4071 g_x[0]
4072 );
4073 assert!(
4074 g_x[0].abs() > 0.5,
4075 "cross-chunk-gate grad must be non-trivial, got {g_x:?}"
4076 );
4077 }
4078
4079 fn find_scan_terminal(
4093 graph: &std::sync::Arc<std::sync::RwLock<fuel_graph::Graph>>,
4094 root: fuel_graph::NodeId,
4095 fused_id: fuel_graph::registry::FusedOpId,
4096 ) -> fuel_graph::NodeId {
4097 use fuel_graph::Op;
4098 let g = graph.read().unwrap();
4099 let mut stack = vec![root];
4100 let mut seen = std::collections::HashSet::new();
4101 let mut scan_id = None;
4102 while let Some(nid) = stack.pop() {
4103 if !seen.insert(nid) {
4104 continue;
4105 }
4106 let node = g.node(nid);
4107 assert!(
4108 !matches!(node.op, Op::Fused(fid, _) if fid == fused_id),
4109 "SSM op must lower to Op::Scan, not remain fused",
4110 );
4111 if matches!(node.op, Op::Scan { .. }) {
4112 scan_id = Some(nid);
4113 }
4114 for &inp in &node.inputs {
4115 stack.push(inp);
4116 }
4117 }
4118 scan_id.expect("an Op::Scan terminal must be present after lowering")
4119 }
4120
4121 fn scan_ys_to_fused_layout(ys: &[f32], seqlen: usize, batch: usize, tail: usize) -> Vec<f32> {
4134 assert_eq!(ys.len(), seqlen * batch * tail, "ys layout mismatch");
4135 let mut out = vec![0f32; ys.len()];
4136 for s in 0..seqlen {
4137 for bb in 0..batch {
4138 for t in 0..tail {
4139 out[(bb * seqlen + s) * tail + t] = ys[(s * batch + bb) * tail + t];
4140 }
4141 }
4142 }
4143 out
4144 }
4145
4146 #[test]
4162 fn selective_scan_multidim_unroll_matches_fused_kernel() {
4163 use fuel_graph::registry::FusedOps;
4164 let dev = Device::cpu();
4165 let (batch, seqlen, dim, dstate) = (2usize, 3usize, 2usize, 2usize);
4166 let u = Tensor::from_f32(
4168 vec![
4169 0.5, -0.3, 1.0, 0.2, -0.5, 0.7, 0.25, 0.9, -0.8, 0.4, 0.6, -0.1,
4170 ],
4171 Shape::from_dims(&[batch, seqlen, dim]),
4172 &dev,
4173 )
4174 .unwrap();
4175 let delta = u
4177 .const_f32_like(
4178 vec![
4179 0.1, 0.2, 0.3, 0.15, 0.25, 0.4, 0.35, 0.05, 0.2, 0.3, 0.12, 0.28,
4180 ],
4181 Shape::from_dims(&[batch, seqlen, dim]),
4182 )
4183 .unwrap();
4184 let a = u
4186 .const_f32_like(
4187 vec![-0.7, -0.3, -0.5, -0.9],
4188 Shape::from_dims(&[dim, dstate]),
4189 )
4190 .unwrap();
4191 let b = u
4193 .const_f32_like(
4194 vec![
4195 1.0, 0.5, 0.25, 0.75, 0.6, 0.2, 0.8, 0.4, 0.3, 0.9, 0.55, 0.15,
4196 ],
4197 Shape::from_dims(&[batch, seqlen, dstate]),
4198 )
4199 .unwrap();
4200 let c = u
4202 .const_f32_like(
4203 vec![2.0, 1.0, 0.5, 1.5, 0.8, 0.3, 1.2, 0.6, 0.9, 0.4, 0.7, 1.1],
4204 Shape::from_dims(&[batch, seqlen, dstate]),
4205 )
4206 .unwrap();
4207 let y = u.selective_scan(&delta, &a, &b, &c, false);
4208
4209 let fused = y.realize_f32();
4211 assert_eq!(fused.len(), batch * seqlen * dim);
4212
4213 let graph = y.inner.graph().clone();
4215 let roots = fuel_graph::opt::RuleRegistry::lowering_only()
4216 .optimize_to_fixpoint(&graph, &[y.inner.id()]);
4217 assert_eq!(roots.len(), 1);
4218 let scan_id = find_scan_terminal(&graph, roots[0], FusedOps::SELECTIVE_SCAN);
4219 let ys = {
4220 let mut g = graph.write().unwrap();
4221 fuel_graph::scan::unroll_scan(&mut g, scan_id, seqlen)
4222 .expect("unroll")
4223 .0[0] };
4225 let ys_flat = crate::pipelined_bridge::realize_one_as::<f32>(&graph, ys, &dev)
4226 .expect("realize selective_scan unroll oracle on CPU");
4227 let oracle = scan_ys_to_fused_layout(&ys_flat, seqlen, batch, dim);
4229 assert_eq!(oracle.len(), fused.len());
4230 let mut max_drift = 0f32;
4231 for (i, (o, f)) in oracle.iter().zip(fused.iter()).enumerate() {
4232 let d = (o - f).abs();
4233 max_drift = max_drift.max(d);
4234 assert!(
4238 d < 1e-3,
4239 "selective_scan multidim mismatch at {i}: oracle {o} vs fused {f} (drift {d})",
4240 );
4241 }
4242 eprintln!("selective_scan multidim: max honest drift = {max_drift:e}");
4243 }
4244
4245 #[test]
4251 fn selective_scan_softplus_multitoken_unroll_matches_fused_kernel() {
4252 use fuel_graph::registry::FusedOps;
4253 let dev = Device::cpu();
4254 let (batch, seqlen, dim, dstate) = (1usize, 3usize, 2usize, 2usize);
4255 let u = Tensor::from_f32(
4256 vec![0.5, -0.3, 1.0, 0.2, -0.5, 0.7],
4257 Shape::from_dims(&[batch, seqlen, dim]),
4258 &dev,
4259 )
4260 .unwrap();
4261 let delta = u
4263 .const_f32_like(
4264 vec![-0.5, 0.2, 0.8, -1.0, 0.3, -0.2],
4265 Shape::from_dims(&[batch, seqlen, dim]),
4266 )
4267 .unwrap();
4268 let a = u
4269 .const_f32_like(
4270 vec![-0.7, -0.3, -0.5, -0.9],
4271 Shape::from_dims(&[dim, dstate]),
4272 )
4273 .unwrap();
4274 let b = u
4275 .const_f32_like(
4276 vec![1.0, 0.5, 0.25, 0.75, 0.6, 0.2],
4277 Shape::from_dims(&[batch, seqlen, dstate]),
4278 )
4279 .unwrap();
4280 let c = u
4281 .const_f32_like(
4282 vec![2.0, 1.0, 0.5, 1.5, 0.8, 0.3],
4283 Shape::from_dims(&[batch, seqlen, dstate]),
4284 )
4285 .unwrap();
4286 let y = u.selective_scan(&delta, &a, &b, &c, true);
4287
4288 let fused = y.realize_f32();
4289 assert_eq!(fused.len(), batch * seqlen * dim);
4290
4291 let graph = y.inner.graph().clone();
4292 let roots = fuel_graph::opt::RuleRegistry::lowering_only()
4293 .optimize_to_fixpoint(&graph, &[y.inner.id()]);
4294 let scan_id = find_scan_terminal(&graph, roots[0], FusedOps::SELECTIVE_SCAN);
4295 let ys = {
4296 let mut g = graph.write().unwrap();
4297 fuel_graph::scan::unroll_scan(&mut g, scan_id, seqlen)
4298 .expect("unroll")
4299 .0[0] };
4301 let ys_flat = crate::pipelined_bridge::realize_one_as::<f32>(&graph, ys, &dev)
4302 .expect("realize selective_scan softplus oracle on CPU");
4303 let oracle = scan_ys_to_fused_layout(&ys_flat, seqlen, batch, dim);
4304 let mut max_drift = 0f32;
4305 for (i, (o, f)) in oracle.iter().zip(fused.iter()).enumerate() {
4306 let d = (o - f).abs();
4307 max_drift = max_drift.max(d);
4308 assert!(
4309 d < 1e-3,
4310 "selective_scan softplus mismatch at {i}: oracle {o} vs fused {f} (drift {d})",
4311 );
4312 }
4313 eprintln!("selective_scan softplus: max honest drift = {max_drift:e}");
4314 }
4315
4316 #[test]
4330 fn ssd_chunk_scan_multidim_unroll_matches_fused_kernel() {
4331 use fuel_graph::registry::FusedOps;
4332 let dev = Device::cpu();
4333 let (batch, seqlen, heads, head_dim, state_dim, chunk) =
4334 (2usize, 4usize, 2usize, 2usize, 2usize, 2usize);
4335 let x_data: Vec<f32> = (0..batch * seqlen * heads * head_dim)
4338 .map(|i| 0.20 + 0.05 * i as f32)
4339 .collect();
4340 let dt_data: Vec<f32> = (0..batch * seqlen * heads)
4341 .map(|i| 0.10 + 0.04 * i as f32)
4342 .collect();
4343 let b_data: Vec<f32> = (0..batch * seqlen * heads * state_dim)
4344 .map(|i| 0.15 + 0.03 * i as f32)
4345 .collect();
4346 let c_data: Vec<f32> = (0..batch * seqlen * heads * state_dim)
4347 .map(|i| 0.25 + 0.035 * i as f32)
4348 .collect();
4349 let x = Tensor::from_f32(
4350 x_data,
4351 Shape::from_dims(&[batch, seqlen, heads, head_dim]),
4352 &dev,
4353 )
4354 .unwrap();
4355 let dt = x
4356 .const_f32_like(dt_data, Shape::from_dims(&[batch, seqlen, heads]))
4357 .unwrap();
4358 let a = x
4359 .const_f32_like(vec![-0.6f32, -1.0], Shape::from_dims(&[heads]))
4360 .unwrap();
4361 let b = x
4362 .const_f32_like(b_data, Shape::from_dims(&[batch, seqlen, heads, state_dim]))
4363 .unwrap();
4364 let c = x
4365 .const_f32_like(c_data, Shape::from_dims(&[batch, seqlen, heads, state_dim]))
4366 .unwrap();
4367 let y = x.ssd_chunk_scan(&dt, &a, &b, &c, chunk);
4368
4369 let fused = y.realize_f32();
4371 assert_eq!(fused.len(), batch * seqlen * heads * head_dim);
4372
4373 let graph = y.inner.graph().clone();
4375 let roots = fuel_graph::opt::RuleRegistry::lowering_only()
4376 .optimize_to_fixpoint(&graph, &[y.inner.id()]);
4377 assert_eq!(roots.len(), 1);
4378 let scan_id = find_scan_terminal(&graph, roots[0], FusedOps::SSD_CHUNK_SCAN);
4379 let ys = {
4380 let mut g = graph.write().unwrap();
4381 fuel_graph::scan::unroll_scan(&mut g, scan_id, seqlen)
4382 .expect("unroll")
4383 .0[0] };
4385 let ys_flat = crate::pipelined_bridge::realize_one_as::<f32>(&graph, ys, &dev)
4386 .expect("realize ssd_chunk_scan unroll oracle on CPU");
4387 let oracle = scan_ys_to_fused_layout(&ys_flat, seqlen, batch, heads * head_dim);
4390 assert_eq!(oracle.len(), fused.len());
4391 let mut max_drift = 0f32;
4392 for (i, (o, f)) in oracle.iter().zip(fused.iter()).enumerate() {
4393 let d = (o - f).abs();
4394 max_drift = max_drift.max(d);
4395 assert!(
4396 d < 1e-3,
4397 "ssd_chunk_scan multidim mismatch at {i}: oracle {o} vs fused {f} (drift {d})",
4398 );
4399 }
4400 eprintln!("ssd_chunk_scan multidim: max honest drift = {max_drift:e}");
4401 }
4402
4403 #[test]
4412 fn nf4_matmul_decompose_matches_kernel() {
4413 use fuel_graph::Op;
4414 use fuel_graph::registry::FusedOps;
4415 let dev = Device::cpu();
4416 let weight = crate::nf4::nf4_from_bytes(
4418 vec![247_u8, 247, 127, 127],
4419 vec![1.0_f32, 2.0, 10.0, 20.0],
4420 2,
4421 4,
4422 2,
4423 &dev,
4424 )
4425 .expect("nf4_from_bytes");
4426 let act = Tensor::from_graph_tensor(
4427 weight
4428 .w_packed
4429 .graph_tensor()
4430 .const_f32_like(vec![1.0_f32, 2.0, 2.0, 4.0], Shape::from_dims(&[1, 4]))
4431 .unwrap(),
4432 );
4433 let y = weight.matmul(&act);
4434
4435 let graph = y.inner.graph().clone();
4437 let id = y.inner.id();
4438 let roots =
4439 fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
4440 assert_eq!(roots.len(), 1, "lowering should keep a single root");
4441
4442 {
4445 let g = graph.read().unwrap();
4446 let mut stack = vec![roots[0]];
4447 let mut seen = std::collections::HashSet::new();
4448 while let Some(nid) = stack.pop() {
4449 if !seen.insert(nid) {
4450 continue;
4451 }
4452 let node = g.node(nid);
4453 assert!(
4454 !matches!(node.op, Op::Fused(fid, _) if fid == FusedOps::NF4_MATMUL),
4455 "decomposed graph still contains an Op::Fused(NF4_MATMUL) island",
4456 );
4457 for &inp in &node.inputs {
4458 stack.push(inp);
4459 }
4460 }
4461 }
4462
4463 let got = crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &dev)
4464 .expect("realize decomposed Nf4Matmul on CPU");
4465 assert_eq!(got.len(), 2);
4466 assert!((got[0] - 10.0).abs() < 1e-4, "out 0: {}", got[0]);
4467 assert!((got[1] - 50.0).abs() < 1e-4, "out 1: {}", got[1]);
4468 }
4469
4470 fn lower_realize_fused(
4476 anchor: &Tensor,
4477 op: fuel_graph::Op,
4478 inputs: Vec<fuel_graph::NodeId>,
4479 shape: Shape,
4480 ) -> Vec<f32> {
4481 let graph = anchor.inner.graph().clone();
4482 let fused_id = {
4483 let mut g = graph.write().unwrap();
4484 g.push(fuel_graph::Node {
4485 op,
4486 inputs,
4487 shape,
4488 dtype: DType::F32,
4489 })
4490 };
4491 let roots = fuel_graph::opt::RuleRegistry::lowering_only()
4492 .optimize_to_fixpoint(&graph, &[fused_id]);
4493 assert_eq!(roots.len(), 1, "lowering keeps a single root");
4494 crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &Device::cpu())
4495 .expect("realize decomposed fused op on CPU")
4496 }
4497
4498 #[test]
4499 fn powi_backward_decompose_matches_reference() {
4500 use fuel_graph::registry::{FusedOpParams, FusedOps};
4501 let dev = Device::cpu();
4502 let exp = 3i32;
4503 let x_data = vec![1.5f32, -2.0, 0.5, 3.0];
4504 let up_data = vec![1.0f32, 0.5, 2.0, -1.0];
4505 let shape = Shape::from_dims(&[4]);
4506 let x = Tensor::from_f32(x_data.clone(), shape.clone(), &dev).unwrap();
4507 let up = x.const_f32_like(up_data.clone(), shape.clone()).unwrap();
4508 let got = lower_realize_fused(
4509 &x,
4510 fuel_graph::Op::Fused(FusedOps::POWI_BACKWARD, FusedOpParams::PowIBackward { exp }),
4511 vec![x.inner.id(), up.inner.id()],
4512 shape,
4513 );
4514 let expected: Vec<f32> = x_data
4516 .iter()
4517 .zip(&up_data)
4518 .map(|(&x, &u)| exp as f32 * x.powi(exp - 1) * u)
4519 .collect();
4520 assert_eq!(got.len(), expected.len());
4521 for (i, (&g, &e)) in got.iter().zip(&expected).enumerate() {
4522 assert!(
4523 (g - e).abs() < 1e-4,
4524 "powi_backward at {i}: got {g}, expected {e}"
4525 );
4526 }
4527 }
4528
4529 #[test]
4537 fn inplace_affine_decompose_matches_affine_reference() {
4538 use fuel_graph::registry::{FusedOpParams, FusedOps};
4539 let dev = Device::cpu();
4540 let (mul, add) = (2.5f64, -1.0f64);
4541 let x_data = vec![1.5f32, -2.0, 0.5, 3.0];
4542 let shape = Shape::from_dims(&[4]);
4543 let x = Tensor::from_f32(x_data.clone(), shape.clone(), &dev).unwrap();
4544 let got = lower_realize_fused(
4545 &x,
4546 fuel_graph::Op::Fused(
4547 FusedOps::INPLACE_AFFINE,
4548 FusedOpParams::InplaceAffine { mul, add },
4549 ),
4550 vec![x.inner.id()],
4551 shape,
4552 );
4553 let expected: Vec<f32> = x_data
4555 .iter()
4556 .map(|&v| (mul as f32) * v + add as f32)
4557 .collect();
4558 assert_eq!(got.len(), expected.len());
4559 for (i, (&g, &e)) in got.iter().zip(&expected).enumerate() {
4560 assert_eq!(g, e, "inplace_affine at {i}: got {g}, expected {e}");
4561 }
4562 }
4563
4564 #[test]
4565 fn softmax_last_dim_backward_decompose_matches_reference() {
4566 use fuel_graph::registry::{FusedOpParams, FusedOps};
4567 let dev = Device::cpu();
4568 let (rows, cols) = (2usize, 3usize);
4569 let logits = [[0.5f32, -1.0, 2.0], [1.0, 0.0, -0.5]];
4571 let mut s_data = Vec::new();
4572 for row in &logits {
4573 let m = row.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
4574 let exps: Vec<f32> = row.iter().map(|&v| (v - m).exp()).collect();
4575 let sum: f32 = exps.iter().sum();
4576 s_data.extend(exps.iter().map(|&e| e / sum));
4577 }
4578 let g_data = vec![1.0f32, -0.5, 0.3, 0.2, 1.5, -1.0];
4579 let shape = Shape::from_dims(&[rows, cols]);
4580 let s = Tensor::from_f32(s_data.clone(), shape.clone(), &dev).unwrap();
4581 let g = s.const_f32_like(g_data.clone(), shape.clone()).unwrap();
4582 let got = lower_realize_fused(
4583 &s,
4584 fuel_graph::Op::Fused(
4585 FusedOps::SOFTMAX_LAST_DIM_BACKWARD,
4586 FusedOpParams::SoftmaxLastDimBackward,
4587 ),
4588 vec![s.inner.id(), g.inner.id()],
4589 shape,
4590 );
4591 let mut expected = vec![0.0f32; rows * cols];
4593 for r in 0..rows {
4594 let dot: f32 = (0..cols)
4595 .map(|c| g_data[r * cols + c] * s_data[r * cols + c])
4596 .sum();
4597 for c in 0..cols {
4598 expected[r * cols + c] = s_data[r * cols + c] * (g_data[r * cols + c] - dot);
4599 }
4600 }
4601 for (i, (&gv, &ev)) in got.iter().zip(&expected).enumerate() {
4602 assert!(
4603 (gv - ev).abs() < 1e-5,
4604 "softmax_bwd at {i}: got {gv}, expected {ev}"
4605 );
4606 }
4607 }
4608
4609 #[test]
4610 fn rms_norm_last_dim_backward_decompose_matches_reference() {
4611 use fuel_graph::registry::{FusedOpParams, FusedOps};
4612 let dev = Device::cpu();
4613 let (rows, cols) = (2usize, 3usize);
4614 let eps = 1e-5f64;
4615 let x_data = vec![1.0f32, -2.0, 0.5, 3.0, 0.25, -1.5];
4616 let g_data = vec![0.5f32, 1.0, -0.3, 0.2, -1.0, 0.7];
4617 let shape = Shape::from_dims(&[rows, cols]);
4618 let x = Tensor::from_f32(x_data.clone(), shape.clone(), &dev).unwrap();
4619 let g = x.const_f32_like(g_data.clone(), shape.clone()).unwrap();
4620 let got = lower_realize_fused(
4621 &x,
4622 fuel_graph::Op::Fused(
4623 FusedOps::RMS_NORM_LAST_DIM_BACKWARD,
4624 FusedOpParams::RmsNormLastDimBackward { eps },
4625 ),
4626 vec![x.inner.id(), g.inner.id()],
4627 shape,
4628 );
4629 let n = cols as f32;
4631 let mut expected = vec![0.0f32; rows * cols];
4632 for r in 0..rows {
4633 let meansq: f32 = (0..cols).map(|c| x_data[r * cols + c].powi(2)).sum::<f32>() / n;
4634 let denom = meansq + eps as f32;
4635 let rrms = 1.0 / denom.sqrt();
4636 let s: f32 = (0..cols)
4637 .map(|c| g_data[r * cols + c] * x_data[r * cols + c])
4638 .sum();
4639 for c in 0..cols {
4640 let term = x_data[r * cols + c] * s / (n * denom);
4641 expected[r * cols + c] = rrms * (g_data[r * cols + c] - term);
4642 }
4643 }
4644 for (i, (&gv, &ev)) in got.iter().zip(&expected).enumerate() {
4645 assert!(
4646 (gv - ev).abs() < 1e-4,
4647 "rms_norm_bwd at {i}: got {gv}, expected {ev}"
4648 );
4649 }
4650 }
4651
4652 #[test]
4653 fn layer_norm_last_dim_backward_decompose_matches_reference() {
4654 use fuel_graph::registry::{FusedOpParams, FusedOps};
4655 let dev = Device::cpu();
4656 let (rows, cols) = (2usize, 3usize);
4657 let eps = 1e-5f64;
4658 let x_data = vec![1.0f32, -2.0, 0.5, 3.0, 0.25, -1.5];
4659 let g_data = vec![0.5f32, 1.0, -0.3, 0.2, -1.0, 0.7];
4660 let shape = Shape::from_dims(&[rows, cols]);
4661 let x = Tensor::from_f32(x_data.clone(), shape.clone(), &dev).unwrap();
4662 let g = x.const_f32_like(g_data.clone(), shape.clone()).unwrap();
4663 let got = lower_realize_fused(
4664 &x,
4665 fuel_graph::Op::Fused(
4666 FusedOps::LAYER_NORM_LAST_DIM_BACKWARD,
4667 FusedOpParams::LayerNormLastDimBackward { eps },
4668 ),
4669 vec![x.inner.id(), g.inner.id()],
4670 shape,
4671 );
4672 let n = cols as f32;
4674 let mut expected = vec![0.0f32; rows * cols];
4675 for r in 0..rows {
4676 let mean_x: f32 = (0..cols).map(|c| x_data[r * cols + c]).sum::<f32>() / n;
4677 let var: f32 = (0..cols)
4678 .map(|c| (x_data[r * cols + c] - mean_x).powi(2))
4679 .sum::<f32>()
4680 / n;
4681 let istd = 1.0 / (var + eps as f32).sqrt();
4682 let xhat: Vec<f32> = (0..cols)
4683 .map(|c| (x_data[r * cols + c] - mean_x) * istd)
4684 .collect();
4685 let mean_g: f32 = (0..cols).map(|c| g_data[r * cols + c]).sum::<f32>() / n;
4686 let mean_gxh: f32 = (0..cols)
4687 .map(|c| g_data[r * cols + c] * xhat[c])
4688 .sum::<f32>()
4689 / n;
4690 for c in 0..cols {
4691 expected[r * cols + c] =
4692 istd * (g_data[r * cols + c] - mean_g - xhat[c] * mean_gxh);
4693 }
4694 }
4695 for (i, (&gv, &ev)) in got.iter().zip(&expected).enumerate() {
4696 assert!(
4697 (gv - ev).abs() < 1e-4,
4698 "layer_norm_bwd at {i}: got {gv}, expected {ev}"
4699 );
4700 }
4701 }
4702
4703 #[test]
4704 fn reduce_max_to_backward_decompose_matches_reference() {
4705 use fuel_graph::registry::{FusedOpParams, FusedOps};
4706 let dev = Device::cpu();
4707 let x_data = vec![1.0f32, 3.0, 3.0, 2.0, 0.0, 1.0]; let up_data = vec![10.0f32, 5.0]; let x_shape = Shape::from_dims(&[2, 3]);
4711 let up_shape = Shape::from_dims(&[2, 1]);
4712 let x = Tensor::from_f32(x_data.clone(), x_shape.clone(), &dev).unwrap();
4713 let up = x.const_f32_like(up_data.clone(), up_shape).unwrap();
4714 let got = lower_realize_fused(
4715 &x,
4716 fuel_graph::Op::Fused(
4717 FusedOps::REDUCE_MAX_TO_BACKWARD,
4718 FusedOpParams::ReduceMaxToBackward,
4719 ),
4720 vec![x.inner.id(), up.inner.id()],
4721 x_shape,
4722 );
4723 let expected = vec![0.0f32, 5.0, 5.0, 5.0, 0.0, 0.0];
4725 for (i, (&gv, &ev)) in got.iter().zip(&expected).enumerate() {
4726 assert!(
4727 (gv - ev).abs() < 1e-5,
4728 "reduce_max_bwd at {i}: got {gv}, expected {ev}"
4729 );
4730 }
4731 }
4732
4733 fn causal_conv1d_check(use_silu: bool) {
4734 use fuel_graph::registry::{FusedOpParams, FusedOps};
4735 let dev = Device::cpu();
4736 let (b, c, k, seq) = (1usize, 2usize, 3usize, 2usize);
4737 let x_seq = seq + (k - 1); let x_data = vec![0.0f32, 1.0, 2.0, 3.0, 1.0, 0.0, -1.0, -2.0];
4740 let w_data = vec![0.5f32, 1.0, -0.5, 1.0, 0.0, 2.0];
4741 let bias_data = vec![0.1f32, -0.2];
4742 let x = Tensor::from_f32(x_data.clone(), Shape::from_dims(&[b, c, x_seq]), &dev).unwrap();
4743 let w = x
4744 .const_f32_like(w_data.clone(), Shape::from_dims(&[c, 1, k]))
4745 .unwrap();
4746 let bias = x
4747 .const_f32_like(bias_data.clone(), Shape::from_dims(&[c]))
4748 .unwrap();
4749 let got = lower_realize_fused(
4750 &x,
4751 fuel_graph::Op::Fused(
4752 FusedOps::CAUSAL_CONV1D,
4753 FusedOpParams::CausalConv1d { use_silu },
4754 ),
4755 vec![x.inner.id(), w.inner.id(), bias.inner.id()],
4756 Shape::from_dims(&[b, c, seq]),
4757 );
4758 let mut expected = vec![0.0f32; b * c * seq];
4760 for ch in 0..c {
4761 for t in 0..seq {
4762 let mut acc = 0.0f32;
4763 for kk in 0..k {
4764 acc += w_data[ch * k + kk] * x_data[ch * x_seq + t + kk];
4765 }
4766 acc += bias_data[ch];
4767 if use_silu {
4768 acc *= 1.0 / (1.0 + (-acc).exp());
4769 }
4770 expected[ch * seq + t] = acc;
4771 }
4772 }
4773 for (i, (&gv, &ev)) in got.iter().zip(&expected).enumerate() {
4774 assert!(
4775 (gv - ev).abs() < 1e-4,
4776 "causal_conv1d (silu={use_silu}) at {i}: got {gv}, expected {ev}",
4777 );
4778 }
4779 }
4780
4781 #[test]
4782 fn causal_conv1d_decompose_matches_reference() {
4783 causal_conv1d_check(false);
4784 causal_conv1d_check(true);
4785 }
4786
4787 #[test]
4788 fn flash_attn_backward_decompose_matches_reference() {
4789 use fuel_graph::registry::{FusedOpParams, FusedOps};
4790 let dev = Device::cpu();
4791 let (sq, sk, d) = (2usize, 2usize, 2usize);
4792 #[allow(clippy::approx_constant)]
4795 let scale = 0.7071f32;
4796 let q_data = vec![0.1f32, -0.2, 0.3, 0.5]; let k_data = vec![0.4f32, 0.1, -0.3, 0.2]; let v_data = vec![1.0f32, 2.0, -1.0, 0.5]; let do_data = vec![0.5f32, -1.0, 0.2, 0.3]; let qshape = Shape::from_dims(&[1, 1, sq, d]);
4801 let kshape = Shape::from_dims(&[1, 1, sk, d]);
4802 let q = Tensor::from_f32(q_data.clone(), qshape.clone(), &dev).unwrap();
4803 let k = q.const_f32_like(k_data.clone(), kshape.clone()).unwrap();
4804 let v = q.const_f32_like(v_data.clone(), kshape.clone()).unwrap();
4805 let dout = q.const_f32_like(do_data.clone(), qshape.clone()).unwrap();
4806 let params = FusedOpParams::FlashAttnBackward {
4807 softmax_scale: scale,
4808 causal: false,
4809 window_size_left: None,
4810 window_size_right: None,
4811 softcap: None,
4812 };
4813 let inputs = vec![q.inner.id(), k.inner.id(), v.inner.id(), dout.inner.id()];
4814 let dq = lower_realize_fused(
4815 &q,
4816 fuel_graph::Op::Fused(FusedOps::FLASH_ATTN_BACKWARD_Q, params.clone()),
4817 inputs.clone(),
4818 qshape.clone(),
4819 );
4820 let dk = lower_realize_fused(
4821 &q,
4822 fuel_graph::Op::Fused(FusedOps::FLASH_ATTN_BACKWARD_K, params.clone()),
4823 inputs.clone(),
4824 kshape.clone(),
4825 );
4826 let dv = lower_realize_fused(
4827 &q,
4828 fuel_graph::Op::Fused(FusedOps::FLASH_ATTN_BACKWARD_V, params),
4829 inputs,
4830 kshape,
4831 );
4832
4833 let mut p = vec![0.0f32; sq * sk];
4835 for i in 0..sq {
4836 let mut scores = vec![0.0f32; sk];
4837 for j in 0..sk {
4838 let mut s = 0.0f32;
4839 for l in 0..d {
4840 s += q_data[i * d + l] * k_data[j * d + l];
4841 }
4842 scores[j] = scale * s;
4843 }
4844 let m = scores.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
4845 let mut sum = 0.0f32;
4846 let e: Vec<f32> = scores
4847 .iter()
4848 .map(|&s| {
4849 let x = (s - m).exp();
4850 sum += x;
4851 x
4852 })
4853 .collect();
4854 for j in 0..sk {
4855 p[i * sk + j] = e[j] / sum;
4856 }
4857 }
4858 let mut ref_dv = vec![0.0f32; sk * d];
4860 for j in 0..sk {
4861 for l in 0..d {
4862 ref_dv[j * d + l] = (0..sq).map(|i| p[i * sk + j] * do_data[i * d + l]).sum();
4863 }
4864 }
4865 let mut dp = vec![0.0f32; sq * sk];
4867 for i in 0..sq {
4868 for j in 0..sk {
4869 dp[i * sk + j] = (0..d).map(|l| do_data[i * d + l] * v_data[j * d + l]).sum();
4870 }
4871 }
4872 let mut dsr = vec![0.0f32; sq * sk];
4874 for i in 0..sq {
4875 let rowdot: f32 = (0..sk).map(|j| dp[i * sk + j] * p[i * sk + j]).sum();
4876 for j in 0..sk {
4877 dsr[i * sk + j] = scale * p[i * sk + j] * (dp[i * sk + j] - rowdot);
4878 }
4879 }
4880 let mut ref_dq = vec![0.0f32; sq * d];
4882 for i in 0..sq {
4883 for l in 0..d {
4884 ref_dq[i * d + l] = (0..sk).map(|j| dsr[i * sk + j] * k_data[j * d + l]).sum();
4885 }
4886 }
4887 let mut ref_dk = vec![0.0f32; sk * d];
4888 for j in 0..sk {
4889 for l in 0..d {
4890 ref_dk[j * d + l] = (0..sq).map(|i| dsr[i * sk + j] * q_data[i * d + l]).sum();
4891 }
4892 }
4893 let check = |name: &str, got: &[f32], exp: &[f32]| {
4894 assert_eq!(got.len(), exp.len(), "{name} length");
4895 for (i, (&gv, &ev)) in got.iter().zip(exp).enumerate() {
4896 assert!(
4897 (gv - ev).abs() < 1e-4,
4898 "{name} at {i}: got {gv}, expected {ev}"
4899 );
4900 }
4901 };
4902 check("dQ", &dq, &ref_dq);
4903 check("dK", &dk, &ref_dk);
4904 check("dV", &dv, &ref_dv);
4905 }
4906
4907 #[test]
4908 fn paged_attn_decompose_matches_reference() {
4909 use fuel_graph::registry::{FusedOpParams, FusedOps};
4910 let dev = Device::cpu();
4911 let block_size = 2usize;
4913 let scale = 1.0f32;
4914 let kc = vec![
4917 1.0f32, 0.0, 0.0, 1.0, 9.0, 9.0, 9.0, 9.0, 1.0, 1.0, 2.0, 0.0,
4918 ];
4919 let vc = vec![
4920 1.0f32, 2.0, 3.0, 4.0, 0.0, 0.0, 0.0, 0.0, 5.0, 6.0, 7.0, 8.0,
4921 ];
4922 let q_data = vec![0.5f32, 0.5]; let bt = vec![0u32, 2u32]; let cl = vec![3u32]; let q = Tensor::from_f32(q_data.clone(), Shape::from_dims(&[1, 1, 1, 2]), &dev).unwrap();
4927 let kcache = q
4928 .const_f32_like(kc.clone(), Shape::from_dims(&[3, 2, 1, 2]))
4929 .unwrap();
4930 let vcache = q
4931 .const_f32_like(vc.clone(), Shape::from_dims(&[3, 2, 1, 2]))
4932 .unwrap();
4933 let block_table = q.const_u32_like(bt, Shape::from_dims(&[1, 2])).unwrap();
4934 let context_lens = q.const_u32_like(cl, Shape::from_dims(&[1])).unwrap();
4935 let params = FusedOpParams::PagedAttn {
4936 softmax_scale: scale,
4937 block_size,
4938 softcap: None,
4939 };
4940 let inputs = vec![
4941 q.inner.id(),
4942 kcache.inner.id(),
4943 vcache.inner.id(),
4944 block_table.inner.id(),
4945 context_lens.inner.id(),
4946 ];
4947 let got = lower_realize_fused(
4948 &q,
4949 fuel_graph::Op::Fused(FusedOps::PAGED_ATTN, params),
4950 inputs,
4951 Shape::from_dims(&[1, 1, 1, 2]),
4952 );
4953
4954 let (kv_len, ctx) = (4usize, 3usize);
4957 let mut k_seq = vec![];
4958 let mut v_seq = vec![];
4959 for &blk in &[0usize, 2usize] {
4960 for p in 0..block_size {
4961 let base = (blk * block_size + p) * 2; k_seq.push([kc[base], kc[base + 1]]);
4963 v_seq.push([vc[base], vc[base + 1]]);
4964 }
4965 }
4966 let mut scores = vec![0.0f32; kv_len];
4967 for j in 0..kv_len {
4968 let s = q_data[0] * k_seq[j][0] + q_data[1] * k_seq[j][1];
4969 scores[j] = if j >= ctx {
4970 f32::NEG_INFINITY
4971 } else {
4972 scale * s
4973 };
4974 }
4975 let m = scores.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
4976 let mut sum = 0.0f32;
4977 let e: Vec<f32> = scores
4978 .iter()
4979 .map(|&s| {
4980 let x = (s - m).exp();
4981 sum += x;
4982 x
4983 })
4984 .collect();
4985 let mut expected = vec![0.0f32; 2];
4986 for j in 0..kv_len {
4987 for l in 0..2 {
4988 expected[l] += (e[j] / sum) * v_seq[j][l];
4989 }
4990 }
4991 for (i, (&gv, &ev)) in got.iter().zip(&expected).enumerate() {
4992 assert!(
4993 (gv - ev).abs() < 1e-4,
4994 "paged_attn at {i}: got {gv}, expected {ev}"
4995 );
4996 }
4997 }
4998
4999 #[test]
5000 #[cfg(feature = "cuda")]
5001 fn cuda_executor_matches_cpu_on_add_mul() {
5002 let a =
5003 Tensor::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), &Device::cpu()).unwrap();
5004 let b = a
5005 .const_f32_like(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]))
5006 .unwrap();
5007 let c = a.add(&b).unwrap().mul(&a).unwrap();
5008 let cpu_result = c.realize_f32();
5009 let executor = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5010 let cuda_result = c.realize_f32_cuda(&executor);
5011 assert_eq!(cpu_result, cuda_result);
5012 }
5013
5014 #[test]
5032 #[cfg(feature = "cuda")]
5033 #[ignore = "requires a live CUDA device"]
5034 fn maximum_minimum_nan_convention_lazy_realize_smoke() {
5035 let cuda = match fuel_cuda_backend::CudaDevice::new(0) {
5036 Ok(d) => d,
5037 Err(e) => {
5038 return fuel_test_support::hardware::skip(
5039 fuel_test_support::hardware::Hardware::Cuda,
5040 fuel_test_support::hardware::Missing::device(format!(
5041 "CudaDevice::new(0): {e:?}"
5042 )),
5043 );
5044 }
5045 };
5046 let a = Tensor::from_f32(
5047 vec![f32::NAN, -2.0, 3.0, f32::NAN],
5048 Shape::from_dims(&[4]),
5049 &Device::cpu(),
5050 )
5051 .unwrap();
5052 let b = a
5053 .const_f32_like(vec![1.0, f32::NAN, 2.0, f32::NAN], Shape::from_dims(&[4]))
5054 .unwrap();
5055
5056 let max_lazy = a.maximum(&b).unwrap();
5057 let cpu_max = max_lazy.realize_f32();
5058 let cuda_max = max_lazy.realize_f32_cuda(&cuda);
5059 for i in 0..4 {
5060 assert_eq!(
5061 cpu_max[i].is_nan(),
5062 cuda_max[i].is_nan(),
5063 "maximum[{i}] NaN-ness must match: cpu={}, cuda={}",
5064 cpu_max[i],
5065 cuda_max[i],
5066 );
5067 if !cpu_max[i].is_nan() {
5068 assert_eq!(cpu_max[i], cuda_max[i], "maximum[{i}]");
5069 }
5070 }
5071
5072 let min_lazy = a.minimum(&b).unwrap();
5073 let cpu_min = min_lazy.realize_f32();
5074 let cuda_min = min_lazy.realize_f32_cuda(&cuda);
5075 for i in 0..4 {
5076 assert_eq!(
5077 cpu_min[i].is_nan(),
5078 cuda_min[i].is_nan(),
5079 "minimum[{i}] NaN-ness must match: cpu={}, cuda={}",
5080 cpu_min[i],
5081 cuda_min[i],
5082 );
5083 if !cpu_min[i].is_nan() {
5084 assert_eq!(cpu_min[i], cuda_min[i], "minimum[{i}]");
5085 }
5086 }
5087 }
5088
5089 #[test]
5112 #[cfg(feature = "cuda")]
5113 #[ignore = "requires a live CUDA device"]
5114 fn relu_nan_convention_lazy_realize_smoke() {
5115 let cuda = match fuel_cuda_backend::CudaDevice::new(0) {
5116 Ok(d) => d,
5117 Err(e) => {
5118 return fuel_test_support::hardware::skip(
5119 fuel_test_support::hardware::Hardware::Cuda,
5120 fuel_test_support::hardware::Missing::device(format!(
5121 "CudaDevice::new(0): {e:?}"
5122 )),
5123 );
5124 }
5125 };
5126 let a = Tensor::from_f32(
5127 vec![f32::NAN, -2.0, 3.0],
5128 Shape::from_dims(&[3]),
5129 &Device::cpu(),
5130 )
5131 .unwrap();
5132 let relu_lazy = a.relu();
5133 let cpu_result = relu_lazy.realize_f32();
5134 let cuda_result = relu_lazy.realize_f32_cuda(&cuda);
5135
5136 for i in 0..3 {
5137 assert_eq!(
5138 cpu_result[i].is_nan(),
5139 cuda_result[i].is_nan(),
5140 "relu[{i}] NaN-ness must match: cpu={}, cuda={}",
5141 cpu_result[i],
5142 cuda_result[i],
5143 );
5144 if !cpu_result[i].is_nan() {
5145 assert_eq!(cpu_result[i], cuda_result[i], "relu[{i}]");
5146 }
5147 }
5148 }
5149
5150 #[test]
5151 #[cfg(feature = "cuda")]
5152 fn cuda_executor_matches_cpu_on_matmul() {
5153 let a = Tensor::from_f32(
5154 vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
5155 Shape::from_dims(&[2, 3]),
5156 &Device::cpu(),
5157 )
5158 .unwrap();
5159 let b = a
5160 .const_f32_like(
5161 vec![7.0, 8.0, 9.0, 10.0, 11.0, 12.0],
5162 Shape::from_dims(&[3, 2]),
5163 )
5164 .unwrap();
5165 let c = a.matmul(&b).unwrap();
5166 let cpu = c.realize_f32();
5167 let exe = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5168 let cuda = c.realize_f32_cuda(&exe);
5169 assert_eq!(cpu.len(), cuda.len());
5170 for (i, (a, b)) in cpu.iter().zip(cuda.iter()).enumerate() {
5171 assert!((a - b).abs() < 1e-3, "matmul[{i}]: cpu={a}, cuda={b}",);
5172 }
5173 }
5174
5175 #[test]
5176 #[cfg(feature = "cuda")]
5177 fn cuda_executor_matches_cpu_on_broadcast_matmul() {
5178 let x = Tensor::from_f32(
5181 (0..12).map(|i| i as f32 * 0.1).collect::<Vec<_>>(),
5182 Shape::from_dims(&[1, 3, 4]),
5183 &Device::cpu(),
5184 )
5185 .unwrap();
5186 let w = x
5187 .const_f32_like(
5188 (0..8).map(|i| i as f32 * 0.2).collect::<Vec<_>>(),
5189 Shape::from_dims(&[4, 2]),
5190 )
5191 .unwrap();
5192 let y = x.matmul(&w).unwrap();
5193 let cpu = y.realize_f32();
5194 let exe = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5195 let cuda = y.realize_f32_cuda(&exe);
5196 assert_eq!(cpu.len(), cuda.len());
5197 for (i, (&a, &b)) in cpu.iter().zip(cuda.iter()).enumerate() {
5198 assert!((a - b).abs() < 1e-3, "bcast_mm[{i}]: cpu={a}, cuda={b}");
5199 }
5200 }
5201
5202 #[test]
5203 #[cfg(feature = "cuda")]
5204 fn cuda_executor_matches_cpu_on_permute() {
5205 let x = Tensor::from_f32(
5206 (0..24).map(|i| i as f32).collect::<Vec<_>>(),
5207 Shape::from_dims(&[1, 2, 3, 4]),
5208 &Device::cpu(),
5209 )
5210 .unwrap();
5211 let y = x.permute([0, 2, 1, 3_usize]).unwrap();
5212 let cpu = y.realize_f32();
5213 let exe = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5214 let cuda = y.realize_f32_cuda(&exe);
5215 assert_eq!(cpu, cuda, "permute mismatch");
5216 }
5217
5218 #[test]
5219 #[cfg(feature = "cuda")]
5220 fn cuda_executor_matches_cpu_on_softmax() {
5221 let x = Tensor::from_f32(
5222 vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
5223 Shape::from_dims(&[2, 3]),
5224 &Device::cpu(),
5225 )
5226 .unwrap();
5227 let y = x.softmax_last_dim().unwrap();
5228 let cpu = y.realize_f32();
5229 let exe = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5230 let cuda = y.realize_f32_cuda(&exe);
5231 assert_eq!(cpu.len(), cuda.len());
5232 for (i, (&a, &b)) in cpu.iter().zip(cuda.iter()).enumerate() {
5233 assert!((a - b).abs() < 1e-4, "softmax[{i}]: cpu={a}, cuda={b}");
5234 }
5235 }
5236
5237 #[test]
5252 #[cfg(feature = "cuda")]
5253 fn cuda_executor_matches_cpu_on_softmax_via_lowering() {
5254 let n = 24;
5257 let last = 5;
5258 let data: Vec<f32> = (0..n * last)
5259 .map(|i| ((i as f32) * 0.13).sin() * 2.0 - 0.7)
5260 .collect();
5261 let x = Tensor::from_f32(data, Shape::from_dims(&[n, last]), &Device::cpu()).unwrap();
5262 let y = x.softmax_last_dim().unwrap();
5263
5264 let cpu = y.realize_f32();
5267
5268 let graph = y.inner.graph().clone();
5274 let registry = fuel_graph::opt::RuleRegistry::lowering_only();
5275 let remapped = registry.optimize_to_fixpoint(&graph, &[y.inner.id()]);
5276 let dev = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5277 let fc_device: crate::Device = dev.clone().into();
5278 let cuda = crate::pipelined_bridge::realize_one_as::<f32>(&graph, remapped[0], &fc_device)
5279 .expect("realize lowered softmax on CUDA");
5280
5281 assert_eq!(cpu.len(), cuda.len());
5282 let mut max_abs_err = 0.0_f32;
5283 for (i, (&a, &b)) in cpu.iter().zip(cuda.iter()).enumerate() {
5284 let err = (a - b).abs();
5285 if err > max_abs_err {
5286 max_abs_err = err;
5287 }
5288 assert!(
5289 err < 1e-5,
5290 "lowered softmax[{i}]: cpu={a} (fused), cuda={b} (composed), err={err}",
5291 );
5292 }
5293 eprintln!("max_abs_err over lowered-vs-fused softmax: {max_abs_err:.3e}");
5294 }
5295
5296 #[test]
5297 #[cfg(feature = "cuda")]
5298 fn cuda_executor_matches_cpu_on_concat_slice() {
5299 let a = Tensor::from_f32(
5300 vec![1.0, 2.0, 3.0, 4.0],
5301 Shape::from_dims(&[2, 2]),
5302 &Device::cpu(),
5303 )
5304 .unwrap();
5305 let b = a
5306 .const_f32_like(vec![5.0, 6.0, 7.0, 8.0], Shape::from_dims(&[2, 2]))
5307 .unwrap();
5308 let cat = a.concat(&b, 1).unwrap(); let sliced = cat.slice(1, 1, 2).unwrap(); let cpu = sliced.realize_f32();
5311 let exe = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5312 let cuda = sliced.realize_f32_cuda(&exe);
5313 assert_eq!(cpu, cuda, "concat+slice mismatch");
5314 }
5315
5316 #[test]
5317 #[cfg(feature = "cuda")]
5318 fn cuda_executor_matches_cpu_on_rms_norm() {
5319 let x = Tensor::from_f32(
5320 (0..8).map(|i| i as f32 * 0.5 - 1.5).collect::<Vec<_>>(),
5321 Shape::from_dims(&[2, 4]),
5322 &Device::cpu(),
5323 )
5324 .unwrap();
5325 let y = x.rms_norm_last_dim(1e-5).unwrap();
5326 let cpu = y.realize_f32();
5327 let exe = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5328 let cuda = y.realize_f32_cuda(&exe);
5329 assert_eq!(cpu.len(), cuda.len());
5330 for (i, (&a, &b)) in cpu.iter().zip(cuda.iter()).enumerate() {
5331 assert!((a - b).abs() < 1e-3, "rms_norm[{i}]: cpu={a}, cuda={b}");
5332 }
5333 }
5334
5335 #[test]
5336 fn realize_f64_through_bridge() {
5337 let a =
5338 Tensor::from_f64(vec![1.5, 2.5, 3.5], Shape::from_dims(&[3]), &Device::cpu()).unwrap();
5339 let b = a.mul(&a).unwrap();
5340 assert_eq!(b.realize_f64(), vec![2.25, 6.25, 12.25]);
5341 }
5342
5343 #[test]
5354 fn gap327_realize_f32_on_f64_root_must_reject_not_reinterpret() {
5355 let t =
5356 Tensor::from_f64(vec![1.0_f64, 2.0], Shape::from_dims(&[2]), &Device::cpu()).unwrap();
5357 let graph = t.inner.graph().clone();
5358 let target = t.inner.id();
5359 let device = Device::cpu();
5360
5361 let prev_hook = std::panic::take_hook();
5364 std::panic::set_hook(Box::new(|_| {}));
5365 let ctl_f64 = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| t.realize_f64()));
5367 let ctl_f16 = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| t.realize_f16()));
5370 let subj_method =
5372 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| t.realize_f32()));
5373 std::panic::set_hook(prev_hook);
5374
5375 let subj_raw = crate::pipelined_bridge::realize_one_as::<f32>(&graph, target, &device);
5377 let bytes_view = crate::pipelined_bridge::realize_one_bytes(&graph, target, &device);
5380
5381 assert!(
5382 ctl_f64.is_ok(),
5383 "control: realize_f64 on an F64 root must succeed; got {ctl_f64:?}"
5384 );
5385 assert!(
5386 ctl_f16.is_err(),
5387 "positive control: realize_f16() on an F64 root must panic (guard fires); if it \
5388 does not, the harness is not observing panics and the subject asserts are vacuous"
5389 );
5390 assert!(
5391 subj_method.is_err(),
5392 "realize_f32() on an F64 root must REJECT (panic), not silently reinterpret bytes"
5393 );
5394 assert!(
5395 matches!(subj_raw, Err(fuel_ir::Error::UnexpectedDType { .. })),
5396 "realize_one_as::<f32> on an F64 root must return Err(UnexpectedDType), not \
5397 Ok(reinterpreted bytes); got {subj_raw:?}"
5398 );
5399 assert!(
5400 matches!(&bytes_view, Ok(b) if b.len() == 16),
5401 "byte view realize_one_bytes on an F64 [1.0, 2.0] root must return 16 raw bytes \
5402 (unguarded), not an error; got {bytes_view:?}"
5403 );
5404 }
5405
5406 #[test]
5407 fn lazy_tensor_mini_llama_block_forward() {
5408 let seq = 3;
5417 let d_head = 4; let num_heads = 2;
5419 let d_model = num_heads * d_head; let x_data: Vec<f32> = (0..seq * d_model).map(|i| i as f32 * 0.01).collect();
5423 let x =
5424 Tensor::from_f32(x_data, Shape::from_dims(&[1, seq, d_model]), &Device::cpu()).unwrap();
5425
5426 let w_q = x
5430 .const_f32_like(
5431 identity_matrix(d_model),
5432 Shape::from_dims(&[d_model, d_model]),
5433 )
5434 .unwrap();
5435 let w_k = x
5436 .const_f32_like(
5437 identity_matrix(d_model),
5438 Shape::from_dims(&[d_model, d_model]),
5439 )
5440 .unwrap();
5441 let w_v = x
5442 .const_f32_like(
5443 identity_matrix(d_model),
5444 Shape::from_dims(&[d_model, d_model]),
5445 )
5446 .unwrap();
5447 let w_o = x
5448 .const_f32_like(
5449 identity_matrix(d_model),
5450 Shape::from_dims(&[d_model, d_model]),
5451 )
5452 .unwrap();
5453
5454 let x_norm = x.rms_norm_last_dim(1e-6).unwrap();
5456 let q = x_norm.matmul(&w_q).unwrap();
5457 let k = x_norm.matmul(&w_k).unwrap();
5458 let v = x_norm.matmul(&w_v).unwrap();
5459
5460 let q_h = q
5462 .reshape(Shape::from_dims(&[1, seq, num_heads, d_head]))
5463 .unwrap()
5464 .permute([0, 2, 1, 3_usize])
5465 .unwrap();
5466 let k_h = k
5467 .reshape(Shape::from_dims(&[1, seq, num_heads, d_head]))
5468 .unwrap()
5469 .permute([0, 2, 1, 3_usize])
5470 .unwrap();
5471 let v_h = v
5472 .reshape(Shape::from_dims(&[1, seq, num_heads, d_head]))
5473 .unwrap()
5474 .permute([0, 2, 1, 3_usize])
5475 .unwrap();
5476
5477 let q_r = q_h.rope(10000.0, 0).unwrap();
5479 let k_r = k_h.rope(10000.0, 0).unwrap();
5480
5481 let k_t = k_r.transpose().unwrap();
5483 let scores = q_r.matmul(&k_t).unwrap();
5484 let attn = scores.softmax_last_dim().unwrap();
5485 let attn_v = attn.matmul(&v_h).unwrap();
5486
5487 let merged = attn_v
5489 .permute([0, 2, 1, 3_usize])
5490 .unwrap()
5491 .reshape(Shape::from_dims(&[1, seq, d_model]))
5492 .unwrap();
5493 let attn_out = merged.matmul(&w_o).unwrap();
5494 let h = x.add(&attn_out).unwrap();
5495
5496 let result = h.realize_f32();
5498 assert_eq!(result.len(), seq * d_model);
5499 for &v in &result {
5500 assert!(
5501 v.is_finite(),
5502 "bridge-based LLaMA block output non-finite: {v}"
5503 );
5504 }
5505 }
5506
5507 fn identity_matrix(n: usize) -> Vec<f32> {
5509 let mut out = vec![0.0_f32; n * n];
5510 for i in 0..n {
5511 out[i * n + i] = 1.0;
5512 }
5513 out
5514 }
5515}
5516
5517impl Tensor {
5521 pub fn const_u32_like(
5523 &self,
5524 data: impl Into<Arc<[u32]>>,
5525 shape: impl Into<Shape>,
5526 ) -> std::result::Result<Self, fuel_ir::Error> {
5527 Ok(Self {
5528 inner: self.inner.const_u32_like(data, shape)?,
5529 })
5530 }
5531
5532 pub fn const_placeholder_like(&self, shape: impl Into<Shape>, dtype: fuel_ir::DType) -> Self {
5543 Self {
5544 inner: self.inner.const_placeholder_like(shape, dtype),
5545 }
5546 }
5547
5548 pub fn write_slice(&self, source: &Self, ranges: Vec<(usize, usize)>) -> crate::Result<Self> {
5560 let inner = self.inner.write_slice(&source.inner, ranges)?;
5561 Ok(Self { inner })
5562 }
5563
5564 pub fn write_slice_dyn(
5572 &self,
5573 source: &Self,
5574 ranges: Vec<(usize, usize)>,
5575 dyn_axis: usize,
5576 offset: fuel_ir::DynScalar,
5577 ) -> crate::Result<Self> {
5578 let inner = self
5579 .inner
5580 .write_slice_dyn(&source.inner, ranges, dyn_axis, offset)?;
5581 Ok(Self { inner })
5582 }
5583
5584 pub fn write_slice_rotating(
5599 &self,
5600 source: &Self,
5601 position: &Self,
5602 axis: usize,
5603 modulus: usize,
5604 ranges: Vec<(usize, usize)>,
5605 ) -> crate::Result<Self> {
5606 let inner = self.inner.write_slice_rotating(
5607 &source.inner,
5608 &position.inner,
5609 axis,
5610 modulus,
5611 ranges,
5612 )?;
5613 Ok(Self { inner })
5614 }
5615
5616 pub fn write_slice_doff(
5629 &self,
5630 source: &Self,
5631 offset: &Self,
5632 axis: usize,
5633 ranges: Vec<(usize, usize)>,
5634 ) -> crate::Result<Self> {
5635 let inner = self
5636 .inner
5637 .write_slice_doff(&source.inner, &offset.inner, axis, ranges)?;
5638 Ok(Self { inner })
5639 }
5640
5641 pub fn conv2d(
5652 &self,
5653 weight: &Self,
5654 bias: Option<&Self>,
5655 stride: (usize, usize),
5656 padding: (usize, usize),
5657 groups: usize,
5658 ) -> std::result::Result<Self, fuel_ir::Error> {
5659 if groups < 1 {
5660 return Err(
5661 fuel_ir::Error::Msg(format!("conv2d: groups must be >= 1, got {groups}",)).bt(),
5662 );
5663 }
5664 let x_shape = self.inner.shape();
5665 let x_dims = x_shape.dims();
5666 let w_shape = weight.inner.shape();
5667 let w_dims = w_shape.dims();
5668 if x_dims.len() != 4 {
5669 return Err(fuel_ir::Error::Msg(format!(
5670 "conv2d: x must be rank 4 [N, Cin, H, W], got {x_dims:?}",
5671 ))
5672 .bt());
5673 }
5674 if w_dims.len() != 4 {
5675 return Err(fuel_ir::Error::Msg(format!(
5676 "conv2d: weight must be rank 4 [Cout, Cin/groups, Kh, Kw], got {w_dims:?}",
5677 ))
5678 .bt());
5679 }
5680 let (cin, h_in, w_in) = (x_dims[1], x_dims[2], x_dims[3]);
5681 let (cout, cin_per_g, kh, kw) = (w_dims[0], w_dims[1], w_dims[2], w_dims[3]);
5682 if cin != cin_per_g * groups {
5683 return Err(fuel_ir::Error::Msg(format!(
5684 "conv2d: x has {cin} in-channels but weight expects {} ({cin_per_g}*{groups})",
5685 cin_per_g * groups,
5686 ))
5687 .bt());
5688 }
5689 if cout % groups != 0 {
5690 return Err(fuel_ir::Error::Msg(format!(
5691 "conv2d: Cout={cout} must be divisible by groups={groups}",
5692 ))
5693 .bt());
5694 }
5695 if let Some(b) = bias {
5696 let b_shape = b.inner.shape();
5697 let b_dims = b_shape.dims();
5698 if b_dims != [cout] {
5699 return Err(fuel_ir::Error::Msg(format!(
5700 "conv2d: bias shape {b_dims:?} must match [Cout={cout}]",
5701 ))
5702 .bt());
5703 }
5704 }
5705 let (stride_h, stride_w) = stride;
5706 let (pad_h, pad_w) = padding;
5707 if stride_h < 1 || stride_w < 1 {
5708 return Err(fuel_ir::Error::Msg(format!(
5709 "conv2d: stride must be >= 1, got ({stride_h}, {stride_w})",
5710 ))
5711 .bt());
5712 }
5713 let h_padded = h_in + 2 * pad_h;
5714 let w_padded = w_in + 2 * pad_w;
5715 if h_padded < kh || w_padded < kw {
5716 return Err(fuel_ir::Error::Msg(format!(
5717 "conv2d: padded input ({h_padded}x{w_padded}) smaller than kernel ({kh}x{kw})",
5718 ))
5719 .bt());
5720 }
5721 Ok(Self {
5722 inner: self.inner.conv2d(
5723 &weight.inner,
5724 bias.map(|b| &b.inner),
5725 stride,
5726 padding,
5727 groups,
5728 ),
5729 })
5730 }
5731
5732 pub fn flash_attn(
5742 &self,
5743 k: &Self,
5744 v: &Self,
5745 alibi_slopes: Option<&Self>,
5746 softmax_scale: f32,
5747 causal: bool,
5748 window_size_left: Option<usize>,
5749 window_size_right: Option<usize>,
5750 softcap: Option<f32>,
5751 ) -> std::result::Result<Self, fuel_ir::Error> {
5752 let q_shape = self.inner.shape();
5753 let q_dims = q_shape.dims();
5754 let k_shape = k.inner.shape();
5755 let k_dims = k_shape.dims();
5756 let v_shape = v.inner.shape();
5757 let v_dims = v_shape.dims();
5758 if q_dims.len() != 4 {
5759 return Err(fuel_ir::Error::Msg(format!(
5760 "flash_attn: q must be rank 4 [B, Hq, Sq, D], got {q_dims:?}",
5761 ))
5762 .bt());
5763 }
5764 if k_dims.len() != 4 {
5765 return Err(fuel_ir::Error::Msg(format!(
5766 "flash_attn: k must be rank 4 [B, Hkv, Sk, D], got {k_dims:?}",
5767 ))
5768 .bt());
5769 }
5770 if v_dims.len() != 4 {
5771 return Err(fuel_ir::Error::Msg(format!(
5772 "flash_attn: v must be rank 4 [B, Hkv, Sk, D], got {v_dims:?}",
5773 ))
5774 .bt());
5775 }
5776 let (b, hq, _sq, d) = (q_dims[0], q_dims[1], q_dims[2], q_dims[3]);
5777 let (bk, hkv, sk, dk) = (k_dims[0], k_dims[1], k_dims[2], k_dims[3]);
5778 let (bv, hkv_v, sk_v, dv) = (v_dims[0], v_dims[1], v_dims[2], v_dims[3]);
5779 if b != bk || b != bv {
5780 return Err(fuel_ir::Error::Msg(
5781 format!("flash_attn: B mismatch q={b} k={bk} v={bv}",),
5782 )
5783 .bt());
5784 }
5785 if hkv != hkv_v {
5786 return Err(fuel_ir::Error::Msg(format!(
5787 "flash_attn: Hkv mismatch k={hkv} vs v={hkv_v}",
5788 ))
5789 .bt());
5790 }
5791 if sk != sk_v {
5792 return Err(fuel_ir::Error::Msg(
5793 format!("flash_attn: Sk mismatch k={sk} vs v={sk_v}",),
5794 )
5795 .bt());
5796 }
5797 if d != dk || d != dv {
5798 return Err(fuel_ir::Error::Msg(format!(
5799 "flash_attn: head_dim mismatch q={d} k={dk} v={dv}",
5800 ))
5801 .bt());
5802 }
5803 if hkv == 0 || hq % hkv != 0 {
5804 return Err(fuel_ir::Error::Msg(format!(
5805 "flash_attn: Hq={hq} must be a positive multiple of Hkv={hkv}",
5806 ))
5807 .bt());
5808 }
5809 if let Some(a) = alibi_slopes {
5810 let a_shape = a.inner.shape();
5811 let a_dims = a_shape.dims();
5812 if a_dims != [hq] {
5813 return Err(fuel_ir::Error::Msg(format!(
5814 "flash_attn: alibi_slopes must be [Hq={hq}], got {a_dims:?}",
5815 ))
5816 .bt());
5817 }
5818 }
5819 Ok(Self {
5820 inner: self.inner.flash_attn(
5821 &k.inner,
5822 &v.inner,
5823 alibi_slopes.map(|t| &t.inner),
5824 softmax_scale,
5825 causal,
5826 window_size_left,
5827 window_size_right,
5828 softcap,
5829 ),
5830 })
5831 }
5832
5833 pub fn paged_attn(
5843 &self,
5844 k_cache: &Self,
5845 v_cache: &Self,
5846 block_table: &Self,
5847 context_lens: &Self,
5848 alibi_slopes: Option<&Self>,
5849 softmax_scale: f32,
5850 block_size: usize,
5851 softcap: Option<f32>,
5852 ) -> std::result::Result<Self, fuel_ir::Error> {
5853 if block_size < 1 {
5854 return Err(fuel_ir::Error::Msg("paged_attn: block_size must be >= 1".into()).bt());
5855 }
5856 let q_shape = self.inner.shape();
5857 let q_dims = q_shape.dims();
5858 let kc_shape = k_cache.inner.shape();
5859 let kc_dims = kc_shape.dims();
5860 let vc_shape = v_cache.inner.shape();
5861 let vc_dims = vc_shape.dims();
5862 let bt_shape = block_table.inner.shape();
5863 let bt_dims = bt_shape.dims();
5864 let cl_shape = context_lens.inner.shape();
5865 let cl_dims = cl_shape.dims();
5866 if q_dims.len() != 4 {
5867 return Err(fuel_ir::Error::Msg(format!(
5868 "paged_attn: q must be rank 4 [B, Hq, Sq, D], got {q_dims:?}",
5869 ))
5870 .bt());
5871 }
5872 if kc_dims.len() != 4 {
5873 return Err(fuel_ir::Error::Msg(format!(
5874 "paged_attn: k_cache must be rank 4 [num_blocks, block_size, Hkv, D], got {kc_dims:?}",
5875 )).bt());
5876 }
5877 if vc_dims.len() != 4 {
5878 return Err(fuel_ir::Error::Msg(format!(
5879 "paged_attn: v_cache must be rank 4 [num_blocks, block_size, Hkv, D], got {vc_dims:?}",
5880 )).bt());
5881 }
5882 if bt_dims.len() != 2 {
5883 return Err(fuel_ir::Error::Msg(format!(
5884 "paged_attn: block_table must be rank 2 [B, max_blocks], got {bt_dims:?}",
5885 ))
5886 .bt());
5887 }
5888 if cl_dims.len() != 1 {
5889 return Err(fuel_ir::Error::Msg(format!(
5890 "paged_attn: context_lens must be rank 1 [B], got {cl_dims:?}",
5891 ))
5892 .bt());
5893 }
5894 let (b, hq, _sq, d) = (q_dims[0], q_dims[1], q_dims[2], q_dims[3]);
5895 if kc_dims[1] != block_size {
5896 return Err(fuel_ir::Error::Msg(format!(
5897 "paged_attn: k_cache block dim {} != block_size {block_size}",
5898 kc_dims[1],
5899 ))
5900 .bt());
5901 }
5902 if vc_dims[1] != block_size {
5903 return Err(fuel_ir::Error::Msg(format!(
5904 "paged_attn: v_cache block dim {} != block_size {block_size}",
5905 vc_dims[1],
5906 ))
5907 .bt());
5908 }
5909 let hkv = kc_dims[2];
5910 if vc_dims[2] != hkv {
5911 return Err(fuel_ir::Error::Msg(format!(
5912 "paged_attn: Hkv mismatch k_cache={hkv} vs v_cache={}",
5913 vc_dims[2],
5914 ))
5915 .bt());
5916 }
5917 if kc_dims[3] != d || vc_dims[3] != d {
5918 return Err(fuel_ir::Error::Msg(format!(
5919 "paged_attn: D mismatch q={d} k={} v={}",
5920 kc_dims[3], vc_dims[3],
5921 ))
5922 .bt());
5923 }
5924 if hkv == 0 || hq % hkv != 0 {
5925 return Err(fuel_ir::Error::Msg(format!(
5926 "paged_attn: Hq={hq} must be a positive multiple of Hkv={hkv}",
5927 ))
5928 .bt());
5929 }
5930 if bt_dims[0] != b {
5931 return Err(fuel_ir::Error::Msg(format!(
5932 "paged_attn: block_table batch dim {} != B={b}",
5933 bt_dims[0],
5934 ))
5935 .bt());
5936 }
5937 if cl_dims[0] != b {
5938 return Err(fuel_ir::Error::Msg(format!(
5939 "paged_attn: context_lens len {} != B={b}",
5940 cl_dims[0],
5941 ))
5942 .bt());
5943 }
5944 if block_table.inner.dtype() != fuel_ir::DType::U32 {
5945 return Err(fuel_ir::Error::Msg(format!(
5946 "paged_attn: block_table must be U32, got {:?}",
5947 block_table.inner.dtype(),
5948 ))
5949 .bt());
5950 }
5951 if context_lens.inner.dtype() != fuel_ir::DType::U32 {
5952 return Err(fuel_ir::Error::Msg(format!(
5953 "paged_attn: context_lens must be U32, got {:?}",
5954 context_lens.inner.dtype(),
5955 ))
5956 .bt());
5957 }
5958 if let Some(a) = alibi_slopes {
5959 let a_shape = a.inner.shape();
5960 let a_dims = a_shape.dims();
5961 if a_dims != [hq] {
5962 return Err(fuel_ir::Error::Msg(format!(
5963 "paged_attn: alibi_slopes must be [Hq={hq}], got {a_dims:?}",
5964 ))
5965 .bt());
5966 }
5967 }
5968 Ok(Self {
5969 inner: self.inner.paged_attn(
5970 &k_cache.inner,
5971 &v_cache.inner,
5972 &block_table.inner,
5973 &context_lens.inner,
5974 alibi_slopes.map(|t| &t.inner),
5975 softmax_scale,
5976 block_size,
5977 softcap,
5978 ),
5979 })
5980 }
5981
5982 pub fn conv_transpose2d(
5992 &self,
5993 weight: &Self,
5994 stride: (usize, usize),
5995 padding: (usize, usize),
5996 output_padding: (usize, usize),
5997 dilation: (usize, usize),
5998 groups: usize,
5999 ) -> std::result::Result<Self, fuel_ir::Error> {
6000 if groups < 1 {
6001 return Err(fuel_ir::Error::Msg(format!(
6002 "conv_transpose2d: groups must be >= 1, got {groups}",
6003 ))
6004 .bt());
6005 }
6006 let x_shape = self.inner.shape();
6007 let x_dims = x_shape.dims();
6008 let w_shape = weight.inner.shape();
6009 let w_dims = w_shape.dims();
6010 if x_dims.len() != 4 {
6011 return Err(fuel_ir::Error::Msg(format!(
6012 "conv_transpose2d: x must be rank 4 [N, Cin, H, W], got {x_dims:?}",
6013 ))
6014 .bt());
6015 }
6016 if w_dims.len() != 4 {
6017 return Err(fuel_ir::Error::Msg(format!(
6018 "conv_transpose2d: weight must be rank 4 [Cin, Cout/groups, Kh, Kw], got {w_dims:?}",
6019 )).bt());
6020 }
6021 let (cin, h_in, w_in) = (x_dims[1], x_dims[2], x_dims[3]);
6022 let (cin_w, cout_per_g, kh, kw) = (w_dims[0], w_dims[1], w_dims[2], w_dims[3]);
6023 if cin != cin_w {
6024 return Err(fuel_ir::Error::Msg(format!(
6025 "conv_transpose2d: x has {cin} in-channels but weight has {cin_w}",
6026 ))
6027 .bt());
6028 }
6029 if cin % groups != 0 {
6030 return Err(fuel_ir::Error::Msg(format!(
6031 "conv_transpose2d: Cin={cin} must be divisible by groups={groups}",
6032 ))
6033 .bt());
6034 }
6035 let (stride_h, stride_w) = stride;
6036 let (pad_h, pad_w) = padding;
6037 let (out_pad_h, out_pad_w) = output_padding;
6038 let (dil_h, dil_w) = dilation;
6039 if stride_h < 1 || stride_w < 1 {
6040 return Err(fuel_ir::Error::Msg(format!(
6041 "conv_transpose2d: stride must be >= 1, got ({stride_h}, {stride_w})",
6042 ))
6043 .bt());
6044 }
6045 if dil_h < 1 || dil_w < 1 {
6046 return Err(fuel_ir::Error::Msg(format!(
6047 "conv_transpose2d: dilation must be >= 1, got ({dil_h}, {dil_w})",
6048 ))
6049 .bt());
6050 }
6051 let h_out = h_in.saturating_sub(1) * stride_h + dil_h * (kh - 1) + out_pad_h + 1;
6052 let w_out = w_in.saturating_sub(1) * stride_w + dil_w * (kw - 1) + out_pad_w + 1;
6053 if h_out <= 2 * pad_h || w_out <= 2 * pad_w {
6054 return Err(fuel_ir::Error::Msg(format!(
6055 "conv_transpose2d: padding ({pad_h}x{pad_w}) is larger than the produced output dims ({h_out}x{w_out})",
6056 )).bt());
6057 }
6058 let _ = cout_per_g;
6059 Ok(Self {
6060 inner: self.inner.conv_transpose2d(
6061 &weight.inner,
6062 stride,
6063 padding,
6064 output_padding,
6065 dilation,
6066 groups,
6067 ),
6068 })
6069 }
6070
6071 pub fn conv_transpose1d(
6085 &self,
6086 weight: &Self,
6087 stride: usize,
6088 padding: usize,
6089 output_padding: usize,
6090 dilation: usize,
6091 groups: usize,
6092 ) -> std::result::Result<Self, fuel_ir::Error> {
6093 if groups < 1 {
6094 return Err(fuel_ir::Error::Msg(format!(
6095 "conv_transpose1d: groups must be >= 1, got {groups}",
6096 ))
6097 .bt());
6098 }
6099 let x_shape = self.inner.shape();
6100 let x_dims = x_shape.dims();
6101 let w_shape = weight.inner.shape();
6102 let w_dims = w_shape.dims();
6103 if x_dims.len() != 3 {
6104 return Err(fuel_ir::Error::Msg(format!(
6105 "conv_transpose1d: x must be rank 3 [N, Cin, Lin], got {x_dims:?}",
6106 ))
6107 .bt());
6108 }
6109 if w_dims.len() != 3 {
6110 return Err(fuel_ir::Error::Msg(format!(
6111 "conv_transpose1d: weight must be rank 3 [Cin, Cout/groups, K], got {w_dims:?}",
6112 ))
6113 .bt());
6114 }
6115 if stride < 1 {
6116 return Err(fuel_ir::Error::Msg(format!(
6117 "conv_transpose1d: stride must be >= 1, got {stride}",
6118 ))
6119 .bt());
6120 }
6121 if dilation < 1 {
6122 return Err(fuel_ir::Error::Msg(format!(
6123 "conv_transpose1d: dilation must be >= 1, got {dilation}",
6124 ))
6125 .bt());
6126 }
6127 let cin = x_dims[1];
6128 let cin_w = w_dims[0];
6129 if cin != cin_w {
6130 return Err(fuel_ir::Error::Msg(format!(
6131 "conv_transpose1d: x has {cin} in-channels but weight has {cin_w}",
6132 ))
6133 .bt());
6134 }
6135 if !cin.is_multiple_of(groups) {
6136 return Err(fuel_ir::Error::Msg(format!(
6137 "conv_transpose1d: Cin={cin} must be divisible by groups={groups}",
6138 ))
6139 .bt());
6140 }
6141 Ok(Self {
6142 inner: self.inner.conv_transpose1d(
6143 &weight.inner,
6144 stride,
6145 padding,
6146 output_padding,
6147 dilation,
6148 groups,
6149 ),
6150 })
6151 }
6152}
6153
6154impl Tensor {
6163 pub fn unsqueeze<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6169 let shape = self.inner.shape();
6170 let dim = dim.to_index_plus_one(&shape, "unsqueeze")?;
6171 Ok(Self {
6172 inner: self.inner.try_unsqueeze(dim)?,
6173 })
6174 }
6175
6176 pub fn triu(&self, diagonal: i64) -> std::result::Result<Self, fuel_ir::Error> {
6181 Ok(Self {
6182 inner: self.inner.triu(diagonal)?,
6183 })
6184 }
6185
6186 pub fn tril(&self, diagonal: i64) -> std::result::Result<Self, fuel_ir::Error> {
6189 Ok(Self {
6190 inner: self.inner.tril(diagonal)?,
6191 })
6192 }
6193
6194 pub fn log_softmax_last_dim(&self) -> std::result::Result<Self, fuel_ir::Error> {
6198 Ok(Self {
6199 inner: self.inner.log_softmax_last_dim()?,
6200 })
6201 }
6202
6203 pub fn softmax<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6212 let shape = self.inner.shape();
6213 let axis: usize = dim.to_index(&shape, "softmax")?;
6217 let m = self.max_keepdim(axis)?;
6218 let shifted = self.broadcast_sub(&m)?;
6219 let e = shifted.exp();
6220 let s = e.sum_keepdim(axis)?;
6221 e.broadcast_div(&s)
6222 }
6223
6224 pub fn log_softmax<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6234 let shape = self.inner.shape();
6235 let axis: usize = dim.to_index(&shape, "log_softmax")?;
6236 let m = self.max_keepdim(axis)?;
6237 let shifted = self.broadcast_sub(&m)?;
6238 let lse = shifted.exp().sum_keepdim(axis)?.log();
6239 shifted.broadcast_sub(&lse)
6240 }
6241
6242 pub fn argmin_dim<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6246 let shape = self.inner.shape();
6247 let dim = dim.to_index(&shape, "argmin_dim")?;
6248 Ok(Self {
6249 inner: self.inner.argmin_dim(dim),
6250 })
6251 }
6252
6253 pub fn masked_fill(
6259 &self,
6260 mask: &Self,
6261 value: fuel_ir::Scalar,
6262 ) -> std::result::Result<Self, fuel_ir::Error> {
6263 Ok(Self {
6264 inner: self.inner.masked_fill(&mask.inner, value)?,
6265 })
6266 }
6267
6268 pub fn index_add<D: Dim>(
6274 &self,
6275 dim: D,
6276 indices: &Self,
6277 src: &Self,
6278 ) -> std::result::Result<Self, fuel_ir::Error> {
6279 let shape = self.inner.shape();
6280 let dim = dim.to_index(&shape, "index_add")?;
6281 if indices.inner.dtype() != fuel_ir::DType::U32 {
6282 return Err(fuel_ir::Error::Msg(format!(
6283 "index_add: index must be U32, got {:?}",
6284 indices.inner.dtype(),
6285 ))
6286 .bt());
6287 }
6288 if self.inner.dtype() != src.inner.dtype() {
6289 return Err(fuel_ir::Error::Msg(format!(
6290 "index_add: base and src dtypes must match, got {:?} vs {:?}",
6291 self.inner.dtype(),
6292 src.inner.dtype(),
6293 ))
6294 .bt());
6295 }
6296 let base_dims = shape.dims();
6297 let src_shape = src.inner.shape();
6298 let src_dims = src_shape.dims();
6299 if base_dims.len() != src_dims.len() {
6300 return Err(fuel_ir::Error::Msg(format!(
6301 "index_add: base and src must have the same rank, got {} vs {}",
6302 base_dims.len(),
6303 src_dims.len(),
6304 ))
6305 .bt());
6306 }
6307 let idx_shape = indices.inner.shape();
6308 let idx_dims = idx_shape.dims();
6309 if idx_dims.len() != 1 {
6310 return Err(fuel_ir::Error::Msg(format!(
6311 "index_add: index must be rank 1, got {idx_dims:?}",
6312 ))
6313 .bt());
6314 }
6315 if src_dims[dim] != idx_dims[0] {
6316 return Err(fuel_ir::Error::Msg(format!(
6317 "index_add: src dim {dim} ({}) must match index length ({})",
6318 src_dims[dim], idx_dims[0],
6319 ))
6320 .bt());
6321 }
6322 Ok(Self {
6323 inner: self.inner.index_add(dim, &indices.inner, &src.inner),
6324 })
6325 }
6326
6327 pub fn scatter_add<D: Dim>(
6332 &self,
6333 dim: D,
6334 indices: &Self,
6335 src: &Self,
6336 ) -> std::result::Result<Self, fuel_ir::Error> {
6337 let shape = self.inner.shape();
6338 let dim = dim.to_index(&shape, "scatter_add")?;
6339 if indices.inner.dtype() != fuel_ir::DType::U32 {
6340 return Err(fuel_ir::Error::Msg(format!(
6341 "scatter_add: index must be U32, got {:?}",
6342 indices.inner.dtype(),
6343 ))
6344 .bt());
6345 }
6346 if self.inner.dtype() != src.inner.dtype() {
6347 return Err(fuel_ir::Error::Msg(format!(
6348 "scatter_add: base and src dtypes must match, got {:?} vs {:?}",
6349 self.inner.dtype(),
6350 src.inner.dtype(),
6351 ))
6352 .bt());
6353 }
6354 let idx_shape = indices.inner.shape();
6355 let src_shape = src.inner.shape();
6356 if idx_shape.dims() != src_shape.dims() {
6357 return Err(fuel_ir::Error::Msg(format!(
6358 "scatter_add: index and src must have the same shape, got {:?} vs {:?}",
6359 idx_shape.dims(),
6360 src_shape.dims(),
6361 ))
6362 .bt());
6363 }
6364 Ok(Self {
6365 inner: self.inner.scatter_add(dim, &indices.inner, &src.inner),
6366 })
6367 }
6368
6369 pub fn relu_inplace(&self) -> Self {
6379 Self {
6380 inner: self.inner.relu_inplace(),
6381 }
6382 }
6383
6384 pub fn silu_inplace(&self) -> Self {
6387 Self {
6388 inner: self.inner.silu_inplace(),
6389 }
6390 }
6391
6392 pub fn gelu_tanh_inplace(&self) -> Self {
6395 Self {
6396 inner: self.inner.gelu_tanh_inplace(),
6397 }
6398 }
6399
6400 pub fn tanh_inplace(&self) -> Self {
6403 Self {
6404 inner: self.inner.tanh_inplace(),
6405 }
6406 }
6407
6408 pub fn sigmoid_inplace(&self) -> Self {
6411 Self {
6412 inner: self.inner.sigmoid_inplace(),
6413 }
6414 }
6415
6416 pub fn affine_inplace(&self, mul: f64, add: f64) -> Self {
6419 Self {
6420 inner: self.inner.affine_inplace(mul, add),
6421 }
6422 }
6423
6424 pub fn const_f64_like(
6428 &self,
6429 data: impl Into<Arc<[f64]>>,
6430 shape: impl Into<Shape>,
6431 ) -> std::result::Result<Self, fuel_ir::Error> {
6432 Ok(Self {
6433 inner: self.inner.const_f64_like(data, shape)?,
6434 })
6435 }
6436
6437 pub fn const_i64_like(
6441 &self,
6442 data: impl Into<Arc<[i64]>>,
6443 shape: impl Into<Shape>,
6444 ) -> std::result::Result<Self, fuel_ir::Error> {
6445 Ok(Self {
6446 inner: self.inner.const_i64_like(data, shape)?,
6447 })
6448 }
6449
6450 pub fn on_device(self, device: &Device) -> Self {
6456 Self {
6457 inner: self.inner.on_device(device.location()),
6458 }
6459 }
6460
6461 pub fn release(&self) -> Self {
6465 Self {
6466 inner: self.inner.release(),
6467 }
6468 }
6469
6470 pub fn move_to_device(&self, device: &Device) -> Self {
6473 Self {
6474 inner: self.inner.move_to_device(device.location()),
6475 }
6476 }
6477
6478 pub fn copy_to_device(&self, device: &Device) -> Self {
6481 Self {
6482 inner: self.inner.copy_to_device(device.location()),
6483 }
6484 }
6485
6486 pub fn backward(&self) -> fuel_graph::GradMap {
6493 self.inner.backward()
6494 }
6495}
6496
6497impl Tensor {
6505 pub fn transpose_last_two(&self) -> std::result::Result<Self, fuel_ir::Error> {
6510 self.transpose()
6511 }
6512
6513 pub fn t(&self) -> std::result::Result<Self, fuel_ir::Error> {
6516 self.transpose()
6517 }
6518
6519 pub fn transpose_dims<D1: Dim, D2: Dim>(
6524 &self,
6525 dim1: D1,
6526 dim2: D2,
6527 ) -> std::result::Result<Self, fuel_ir::Error> {
6528 let shape = self.shape();
6529 let dim1 = dim1.to_index(&shape, "transpose_dims")?;
6530 let dim2 = dim2.to_index(&shape, "transpose_dims")?;
6531 if dim1 == dim2 {
6532 return Ok(self.clone());
6533 }
6534 let rank = shape.dims().len();
6535 let mut axes: Vec<usize> = (0..rank).collect();
6536 axes.swap(dim1, dim2);
6537 self.permute(axes.as_slice())
6538 }
6539
6540 pub fn flatten<D1: Dim, D2: Dim>(
6545 &self,
6546 start_dim: D1,
6547 end_dim: D2,
6548 ) -> std::result::Result<Self, fuel_ir::Error> {
6549 let shape = self.shape();
6550 let rank = shape.dims().len();
6551 if rank == 0 {
6552 return Ok(self.clone());
6553 }
6554 let start_dim = start_dim.to_index(&shape, "flatten")?;
6555 let end_dim = end_dim.to_index(&shape, "flatten")?;
6556 if start_dim > end_dim {
6557 return Err(fuel_ir::Error::Msg(format!(
6558 "flatten: start_dim={start_dim} > end_dim={end_dim}",
6559 ))
6560 .bt());
6561 }
6562 let dims = shape.dims();
6563 let merged: usize = dims[start_dim..=end_dim].iter().product();
6564 let mut new_dims: Vec<usize> = Vec::with_capacity(rank - (end_dim - start_dim));
6565 new_dims.extend_from_slice(&dims[..start_dim]);
6566 new_dims.push(merged);
6567 new_dims.extend_from_slice(&dims[end_dim + 1..]);
6568 self.reshape(new_dims)
6569 }
6570
6571 pub fn flatten_to<D: Dim>(&self, end_dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6573 self.flatten(0_usize, end_dim)
6574 }
6575
6576 pub fn flatten_from<D: Dim>(&self, start_dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6578 let rank = self.shape().dims().len();
6579 if rank == 0 {
6580 return Ok(self.clone());
6581 }
6582 self.flatten(start_dim, rank - 1)
6583 }
6584
6585 pub fn flatten_all(&self) -> std::result::Result<Self, fuel_ir::Error> {
6587 let rank = self.shape().dims().len();
6588 if rank == 0 {
6589 return Ok(self.clone());
6590 }
6591 self.flatten(0, rank - 1)
6592 }
6593
6594 pub fn stack<D: Dim>(args: &[&Self], dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6599 if args.is_empty() {
6600 return Err(fuel_ir::Error::Msg("stack: requires at least one tensor".into()).bt());
6601 }
6602 let reference_shape = args[0].shape();
6603 let reference_dims = reference_shape.dims().to_vec();
6604 let dim = dim.to_index_plus_one(&reference_shape, "stack")?;
6605 for (idx, t) in args.iter().enumerate().skip(1) {
6606 if t.shape().dims() != reference_dims.as_slice() {
6607 return Err(fuel_ir::Error::Msg(format!(
6608 "stack: tensor {idx} shape {:?} != reference shape {:?}",
6609 t.shape().dims(),
6610 reference_dims,
6611 ))
6612 .bt());
6613 }
6614 }
6615 let mut iter = args.iter();
6617 let first = iter.next().unwrap().unsqueeze(dim)?;
6618 let mut acc = first;
6619 for t in iter {
6620 let u = t.unsqueeze(dim)?;
6621 acc = acc.concat(&u, dim)?;
6622 }
6623 Ok(acc)
6624 }
6625
6626 pub fn sum_keepdim<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6636 let shape = self.shape();
6637 let dim = dim.to_index(&shape, "sum_keepdim")?;
6638 self.sum_dim(dim).unwrap().unsqueeze(dim)
6639 }
6640
6641 pub fn mean_keepdim<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6643 let shape = self.shape();
6644 let dim = dim.to_index(&shape, "mean_keepdim")?;
6645 self.mean_dim(dim).unwrap().unsqueeze(dim)
6646 }
6647
6648 pub fn max_keepdim<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6650 let shape = self.shape();
6651 let dim = dim.to_index(&shape, "max_keepdim")?;
6652 self.max_dim(dim).unwrap().unsqueeze(dim)
6653 }
6654
6655 pub fn min_keepdim<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6657 let shape = self.shape();
6658 let dim = dim.to_index(&shape, "min_keepdim")?;
6659 self.min_dim(dim).unwrap().unsqueeze(dim)
6663 }
6664
6665 pub fn var_keepdim<D: Dim>(
6683 &self,
6684 dim: D,
6685 correction: f64,
6686 ) -> std::result::Result<Self, fuel_ir::Error> {
6687 if correction.is_nan() {
6690 return Err(fuel_ir::Error::Msg(
6691 "var_keepdim: correction must not be NaN".to_string(),
6692 ));
6693 }
6694 let shape = self.shape();
6695 let dim = dim.to_index(&shape, "var_keepdim")?;
6696 let dims = shape.dims();
6697 let n = dims[dim];
6698 let mean = self.mean_keepdim(dim)?;
6699 let deviation = self.broadcast_sub(&mean).unwrap();
6700 let squares = deviation.sqr();
6701 let summed = squares.sum_keepdim(dim)?;
6703 let divisor = (n as f64 - correction).max(0.0);
6704 Ok(summed.mul_scalar(1.0 / divisor))
6705 }
6706
6707 pub fn var<D: Dim>(
6710 &self,
6711 dim: D,
6712 correction: f64,
6713 ) -> std::result::Result<Self, fuel_ir::Error> {
6714 let shape = self.shape();
6715 let dim = dim.to_index(&shape, "var")?;
6716 self.var_keepdim(dim, correction)?.squeeze(dim)
6717 }
6718
6719 pub fn affine(&self, mul: f64, add: f64) -> Self {
6726 self.mul_scalar(mul).add_scalar(add)
6727 }
6728
6729 pub fn scale_and_shift(&self, scale: f64, shift: f64) -> Self {
6733 self.affine(scale, shift)
6734 }
6735
6736 pub fn elu(&self, alpha: f64) -> Self {
6740 let neg_branch = self.exp().affine(alpha, -alpha);
6742 let zero = self
6747 .const_f32_like(vec![0.0; self.elem_count()], self.shape())
6748 .expect("elu: vec![_; self.elem_count()] against self.shape() -- same source");
6749 let mask = self.gt(&zero).unwrap();
6750 mask.where_cond(self, &neg_branch).unwrap()
6751 }
6752
6753 pub fn dot(&self, rhs: &Self) -> std::result::Result<Self, fuel_ir::Error> {
6756 let a = self.shape().dims().to_vec();
6757 let b = rhs.shape().dims().to_vec();
6758 if a.len() != 1 || b.len() != 1 {
6759 return Err(fuel_ir::Error::Msg(format!(
6760 "dot: requires rank-1 inputs, got lhs={a:?} rhs={b:?}",
6761 ))
6762 .bt());
6763 }
6764 if a[0] != b[0] {
6765 return Err(fuel_ir::Error::Msg(format!(
6766 "dot: length mismatch lhs={} rhs={}",
6767 a[0], b[0],
6768 ))
6769 .bt());
6770 }
6771 Ok(self.mul(rhs).unwrap().sum_all())
6772 }
6773
6774 pub fn mv(&self, rhs: &Self) -> std::result::Result<Self, fuel_ir::Error> {
6778 let a = self.shape().dims().to_vec();
6779 let b = rhs.shape().dims().to_vec();
6780 if a.len() != 2 || b.len() != 1 || a[1] != b[0] {
6781 return Err(fuel_ir::Error::Msg(format!(
6782 "mv: shape mismatch lhs={a:?} rhs={b:?} (need [m,n] · [n])",
6783 ))
6784 .bt());
6785 }
6786 let rhs_col = rhs.unsqueeze(1_usize)?;
6788 let prod = self.matmul(&rhs_col).unwrap();
6789 prod.squeeze(1_usize)
6790 }
6791
6792 pub fn matvec(&self, rhs: &Self) -> std::result::Result<Self, fuel_ir::Error> {
6795 self.mv(rhs)
6796 }
6797
6798 pub fn broadcast_matmul(&self, rhs: &Self) -> std::result::Result<Self, fuel_ir::Error> {
6802 self.matmul(rhs)
6803 }
6804
6805 pub fn ones_like(&self) -> std::result::Result<Self, fuel_ir::Error> {
6815 let n = self.elem_count();
6816 let shape = self.shape();
6817 match self.dtype() {
6818 DType::F32 => self.const_f32_like(vec![1.0_f32; n], shape),
6819 DType::F64 => self.const_f64_like(vec![1.0_f64; n], shape),
6820 DType::BF16 => self.const_bf16_like(vec![half::bf16::ONE; n], shape),
6821 DType::F16 => self.const_f16_like(vec![half::f16::ONE; n], shape),
6822 DType::U32 => self.const_u32_like(vec![1_u32; n], shape),
6823 DType::I64 => self.const_i64_like(vec![1_i64; n], shape),
6824 other => {
6825 Err(fuel_ir::Error::Msg(format!("ones_like: unsupported dtype {other:?}",)).bt())
6826 }
6827 }
6828 }
6829
6830 pub fn zeros_like(&self) -> std::result::Result<Self, fuel_ir::Error> {
6834 let n = self.elem_count();
6835 let shape = self.shape();
6836 match self.dtype() {
6837 DType::F32 => self.const_f32_like(vec![0.0_f32; n], shape),
6838 DType::F64 => self.const_f64_like(vec![0.0_f64; n], shape),
6839 DType::BF16 => self.const_bf16_like(vec![half::bf16::ZERO; n], shape),
6840 DType::F16 => self.const_f16_like(vec![half::f16::ZERO; n], shape),
6841 DType::U32 => self.const_u32_like(vec![0_u32; n], shape),
6842 DType::I64 => self.const_i64_like(vec![0_i64; n], shape),
6843 other => {
6844 Err(fuel_ir::Error::Msg(format!("zeros_like: unsupported dtype {other:?}",)).bt())
6845 }
6846 }
6847 }
6848
6849 pub fn ones(
6853 shape: impl Into<Shape>,
6854 dtype: DType,
6855 device: &Device,
6856 ) -> std::result::Result<Self, fuel_ir::Error> {
6857 let shape = shape.into();
6858 let n = shape.elem_count();
6859 match dtype {
6860 DType::F32 => Self::from_f32(vec![1.0_f32; n], shape, device),
6861 DType::F64 => Self::from_f64(vec![1.0_f64; n], shape, device),
6862 DType::BF16 => Self::from_bf16(vec![half::bf16::ONE; n], shape, device),
6863 DType::F16 => Self::from_f16(vec![half::f16::ONE; n], shape, device),
6864 DType::U32 => Self::from_u32(vec![1_u32; n], shape, device),
6865 other => Err(fuel_ir::Error::Msg(format!("ones: unsupported dtype {other:?}",)).bt()),
6866 }
6867 }
6868
6869 pub fn zeros(
6879 shape: impl Into<Shape>,
6880 dtype: DType,
6881 device: &Device,
6882 ) -> std::result::Result<Self, fuel_ir::Error> {
6883 let shape = shape.into();
6884 let n = shape.elem_count();
6885 match dtype {
6886 DType::F32 => Self::from_f32(vec![0.0_f32; n], shape, device),
6887 DType::F64 => Self::from_f64(vec![0.0_f64; n], shape, device),
6888 DType::BF16 => Self::from_bf16(vec![half::bf16::ZERO; n], shape, device),
6889 DType::F16 => Self::from_f16(vec![half::f16::ZERO; n], shape, device),
6890 DType::U32 => Self::from_u32(vec![0_u32; n], shape, device),
6891 other => Err(fuel_ir::Error::Msg(format!("zeros: unsupported dtype {other:?}",)).bt()),
6892 }
6893 }
6894
6895 pub fn full(
6904 shape: impl Into<Shape>,
6905 value: fuel_ir::Scalar,
6906 device: &Device,
6907 ) -> std::result::Result<Self, fuel_ir::Error> {
6908 let shape = shape.into();
6909 let n = shape.elem_count();
6910 match value {
6911 fuel_ir::Scalar::F32(v) => Self::from_f32(vec![v; n], shape, device),
6912 fuel_ir::Scalar::F64(v) => Self::from_f64(vec![v; n], shape, device),
6913 fuel_ir::Scalar::BF16(v) => Self::from_bf16(vec![v; n], shape, device),
6914 fuel_ir::Scalar::F16(v) => Self::from_f16(vec![v; n], shape, device),
6915 fuel_ir::Scalar::U32(v) => Self::from_u32(vec![v; n], shape, device),
6916 other => Err(fuel_ir::Error::Msg(format!(
6917 "full: unsupported scalar dtype {:?}",
6918 other.dtype(),
6919 ))
6920 .bt()),
6921 }
6922 }
6923
6924 pub fn eye(n: usize, dtype: DType, device: &Device) -> Self {
6927 let mut data = vec![0.0_f32; n * n];
6928 for i in 0..n {
6929 data[i * n + i] = 1.0;
6930 }
6931 let base = Self::from_f32(data, vec![n, n], device).expect(
6940 "eye: data is vec![_; n*n] and shape is [n, n] (elem_count n*n), \n both computed from `n` in this function -- lengths cannot disagree",
6941 );
6942 if dtype == DType::F32 {
6943 base
6944 } else {
6945 base.to_dtype(dtype).unwrap()
6946 }
6947 }
6948
6949 pub fn split_heads(
6955 &self,
6956 num_heads: usize,
6957 head_dim: usize,
6958 ) -> std::result::Result<Self, fuel_ir::Error> {
6959 let dims = self.inner.shape().dims().to_vec();
6960 debug_assert_eq!(
6961 dims.len(),
6962 3,
6963 "split_heads: input must be rank 3 (B, N, embed), got {dims:?}"
6964 );
6965 debug_assert_eq!(
6966 dims[2],
6967 num_heads * head_dim,
6968 "split_heads: trailing dim ({}) != num_heads * head_dim ({} * {} = {})",
6969 dims[2],
6970 num_heads,
6971 head_dim,
6972 num_heads * head_dim
6973 );
6974 let b = dims[0];
6975 let n = dims[1];
6976 self.reshape(Shape::from_dims(&[b, n, num_heads, head_dim]))?
6977 .permute([0, 2, 1, 3_usize])
6978 }
6979
6980 pub fn merge_heads(&self) -> std::result::Result<Self, fuel_ir::Error> {
6984 let dims = self.inner.shape().dims().to_vec();
6985 debug_assert_eq!(
6986 dims.len(),
6987 4,
6988 "merge_heads: input must be rank 4 (B, heads, N, head_dim), got {dims:?}"
6989 );
6990 let b = dims[0];
6991 let num_heads = dims[1];
6992 let n = dims[2];
6993 let head_dim = dims[3];
6994 self.permute([0, 2, 1, 3_usize])?
6995 .reshape(Shape::from_dims(&[b, n, num_heads * head_dim]))
6996 }
6997
6998 pub fn add_trailing_bias(
7009 &self,
7010 bias: std::sync::Arc<[f32]>,
7011 ) -> std::result::Result<Self, fuel_ir::Error> {
7012 let n = bias.len();
7013 let bias_t = self.const_like_dtype(&bias, Shape::from_dims(&[n]), self.dtype())?;
7019 self.broadcast_add(&bias_t)
7020 }
7021
7022 pub fn embed_tokens(
7034 embed_table: std::sync::Arc<[f32]>,
7035 vocab_size: usize,
7036 hidden: usize,
7037 tokens: &[u32],
7038 device: &crate::Device,
7039 ) -> std::result::Result<Self, fuel_ir::Error> {
7040 let seq = tokens.len();
7041 if seq == 0 {
7042 return Err(fuel_ir::Error::Msg("embed_tokens: tokens must be non-empty".into()).bt());
7043 }
7044 let embed = Self::from_f32(embed_table, Shape::from_dims(&[vocab_size, hidden]), device)?;
7045 let token_ids = embed.const_u32_like(tokens.to_vec(), Shape::from_dims(&[seq]))?;
7046 embed
7047 .index_select(0_usize, &token_ids)?
7048 .reshape(Shape::from_dims(&[1, seq, hidden]))
7049 }
7050
7051 pub fn embed_tokens_anchored(
7059 &self,
7060 embed_table: std::sync::Arc<[f32]>,
7061 vocab_size: usize,
7062 hidden: usize,
7063 tokens: &[u32],
7064 ) -> std::result::Result<Self, fuel_ir::Error> {
7065 let seq = tokens.len();
7066 if seq == 0 {
7067 return Err(fuel_ir::Error::Msg(
7068 "embed_tokens_anchored: tokens must be non-empty".into(),
7069 )
7070 .bt());
7071 }
7072 let embed = self.const_f32_like(embed_table, Shape::from_dims(&[vocab_size, hidden]))?;
7073 let token_ids = self.const_u32_like(tokens.to_vec(), Shape::from_dims(&[seq]))?;
7074 embed
7075 .index_select(0_usize, &token_ids)?
7076 .reshape(Shape::from_dims(&[1, seq, hidden]))
7077 }
7078
7079 pub fn rope_tables_const(
7090 &self,
7091 theta: f64,
7092 start_pos: usize,
7093 seq: usize,
7094 head_dim: usize,
7095 ) -> (Self, Self) {
7096 let (cos_data, sin_data) = fuel_graph::build_rope_tables(theta, start_pos, seq, head_dim);
7097 let rope_shape = Shape::from_dims(&[seq, head_dim]);
7098 let rope_cos = self
7104 .const_f32_like(cos_data, rope_shape.clone())
7105 .expect("rope tables: build_rope_tables must return seq*head_dim elements");
7106 let rope_sin = self
7107 .const_f32_like(sin_data, rope_shape)
7108 .expect("rope tables: build_rope_tables must return seq*head_dim elements");
7109 (rope_cos, rope_sin)
7110 }
7111
7112 pub fn rope_delta_tables_const(
7124 &self,
7125 theta: f64,
7126 delta: usize,
7127 rows: usize,
7128 head_dim: usize,
7129 ) -> (Self, Self) {
7130 let (c1, s1) = fuel_graph::build_rope_tables(theta, delta, 1, head_dim);
7131 let mut cos = Vec::with_capacity(rows * head_dim);
7132 let mut sin = Vec::with_capacity(rows * head_dim);
7133 for _ in 0..rows {
7134 cos.extend_from_slice(&c1);
7135 sin.extend_from_slice(&s1);
7136 }
7137 let shape = Shape::from_dims(&[rows, head_dim]);
7138 (
7142 self.const_f32_like(cos, shape.clone()).expect(
7143 "rope tables: rows appends of c1 (local); c1 has head_dim elements (not local)",
7144 ),
7145 self.const_f32_like(sin, shape).expect(
7146 "rope tables: rows appends of s1 (local); s1 has head_dim elements (not local)",
7147 ),
7148 )
7149 }
7150
7151 pub fn rope_delta_rotate_block_f32(
7166 dev: &crate::Device,
7167 k_block: &[f32],
7168 theta: f64,
7169 delta: usize,
7170 block_size: usize,
7171 n_kv_heads: usize,
7172 head_dim: usize,
7173 ) -> Vec<f32> {
7174 let pool_shape = Shape::from_dims(&[block_size, n_kv_heads, head_dim]);
7175 let k = Tensor::from_f32(k_block.to_vec(), pool_shape, dev).expect(
7186 "rope_delta_rotate_block_f32: k_block length must equal block_size*n_kv_heads*head_dim -- both caller-supplied, so this function cannot prove it; the -> Vec<f32> signature has no error channel (see the sibling permute/reshape expects)",
7187 );
7188 let k4 = k
7189 .permute([1, 0, 2])
7190 .expect("rope_delta_rotate_block_f32: permute [bs,Hkv,D]->[Hkv,bs,D]")
7191 .reshape(Shape::from_dims(&[1, n_kv_heads, block_size, head_dim]))
7192 .expect("rope_delta_rotate_block_f32: reshape to [1,Hkv,bs,D]");
7193 let (cos, sin) = k4.rope_delta_tables_const(theta, delta, block_size, head_dim);
7194 k4.rope_with_tables_decomposed(&cos, &sin)
7195 .expect("rope_delta_rotate_block_f32: rope_with_tables_decomposed")
7196 .reshape(Shape::from_dims(&[n_kv_heads, block_size, head_dim]))
7197 .expect("rope_delta_rotate_block_f32: reshape back to [Hkv,bs,D]")
7198 .permute([1, 0, 2])
7199 .expect("rope_delta_rotate_block_f32: permute [Hkv,bs,D]->[bs,Hkv,D]")
7200 .realize_f32()
7201 }
7202
7203 pub fn rope_tables_const_batched(
7216 &self,
7217 theta: f64,
7218 positions: &[usize],
7219 head_dim: usize,
7220 ) -> (Self, Self) {
7221 let b = positions.len();
7222 let mut cos_data = Vec::with_capacity(b * head_dim);
7223 let mut sin_data = Vec::with_capacity(b * head_dim);
7224 for &pos in positions {
7225 let (c, s) = fuel_graph::build_rope_tables(theta, pos, 1, head_dim);
7226 cos_data.extend_from_slice(&c);
7227 sin_data.extend_from_slice(&s);
7228 }
7229 let shape = Shape::from_dims(&[b, 1, 1, head_dim]);
7230 let rope_cos = self
7237 .const_f32_like(cos_data, shape.clone())
7238 .expect("batched rope tables: b IS positions.len() (local); build_rope_tables must yield head_dim per position (not local)");
7239 let rope_sin = self
7240 .const_f32_like(sin_data, shape)
7241 .expect("batched rope tables: b IS positions.len() (local); build_rope_tables must yield head_dim per position (not local)");
7242 (rope_cos, rope_sin)
7243 }
7244
7245 pub fn rope_tables_const_with_inv_freq(
7250 &self,
7251 inv_freq: &[f64],
7252 start_pos: usize,
7253 seq: usize,
7254 head_dim: usize,
7255 ) -> (Self, Self) {
7256 let (cos_data, sin_data) =
7257 fuel_graph::build_rope_tables_with_inv_freq(inv_freq, start_pos, seq, head_dim);
7258 let rope_shape = Shape::from_dims(&[seq, head_dim]);
7259 let rope_cos = self.const_f32_like(cos_data, rope_shape.clone()).expect(
7262 "rope tables: build_rope_tables_with_inv_freq must return seq*head_dim elements",
7263 );
7264 let rope_sin = self.const_f32_like(sin_data, rope_shape).expect(
7265 "rope tables: build_rope_tables_with_inv_freq must return seq*head_dim elements",
7266 );
7267 (rope_cos, rope_sin)
7268 }
7269
7270 pub fn rope_tables_const_batched_with_inv_freq(
7273 &self,
7274 inv_freq: &[f64],
7275 positions: &[usize],
7276 head_dim: usize,
7277 ) -> (Self, Self) {
7278 let b = positions.len();
7279 let mut cos_data = Vec::with_capacity(b * head_dim);
7280 let mut sin_data = Vec::with_capacity(b * head_dim);
7281 for &pos in positions {
7282 let (c, s) = fuel_graph::build_rope_tables_with_inv_freq(inv_freq, pos, 1, head_dim);
7283 cos_data.extend_from_slice(&c);
7284 sin_data.extend_from_slice(&s);
7285 }
7286 let shape = Shape::from_dims(&[b, 1, 1, head_dim]);
7287 let rope_cos = self
7290 .const_f32_like(cos_data, shape.clone())
7291 .expect("batched rope tables: b IS positions.len() (local); build_rope_tables_with_inv_freq must yield head_dim per position (not local)");
7292 let rope_sin = self
7293 .const_f32_like(sin_data, shape)
7294 .expect("batched rope tables: b IS positions.len() (local); build_rope_tables_with_inv_freq must yield head_dim per position (not local)");
7295 (rope_cos, rope_sin)
7296 }
7297
7298 pub fn rope_batched(
7318 &self,
7319 cos: &Self,
7320 sin: &Self,
7321 ) -> std::result::Result<Self, fuel_ir::Error> {
7322 let dims: Vec<usize> = self.inner.shape().dims().to_vec();
7323 let rank = dims.len();
7324 if rank < 2 {
7325 return Err(fuel_ir::Error::Msg(format!(
7326 "rope_batched: expected rank >= 2, got {dims:?}",
7327 ))
7328 .bt());
7329 }
7330 let d = dims[rank - 1];
7331 if !d.is_multiple_of(2) {
7332 return Err(
7333 fuel_ir::Error::Msg(format!("rope_batched: head_dim {d} must be even",)).bt(),
7334 );
7335 }
7336 let half = d / 2;
7337 let target = Shape::from_dims(&dims);
7338
7339 let cos_b = cos.broadcast_to(target.clone())?;
7340 let sin_b = sin.broadcast_to(target)?;
7341
7342 let first = self.slice(rank - 1, 0, half)?;
7343 let second = self.slice(rank - 1, half, half)?;
7344 let rotated = second.neg().concat(&first, rank - 1)?;
7345
7346 let left = self.mul(&cos_b)?;
7347 let right = rotated.mul(&sin_b)?;
7348 left.add(&right)
7349 }
7350
7351 pub fn rope_partial(
7362 &self,
7363 rope_cos: &Self,
7364 rope_sin: &Self,
7365 rope_dim: usize,
7366 ) -> std::result::Result<Self, fuel_ir::Error> {
7367 let dims = self.inner.shape();
7368 let dims = dims.dims();
7369 let head_dim = *dims.last().ok_or_else(|| {
7370 fuel_ir::Error::Msg("rope_partial: receiver must have at least one dimension".into())
7371 .bt()
7372 })?;
7373 if rope_dim == head_dim {
7374 return self.rope_with_tables(rope_cos, rope_sin);
7375 }
7376 if rope_dim > head_dim {
7377 return Err(fuel_ir::Error::Msg(format!(
7378 "rope_partial: rope_dim={rope_dim} exceeds head_dim={head_dim}",
7379 ))
7380 .bt());
7381 }
7382 let last = dims.len() - 1;
7383 let pass_dim = head_dim - rope_dim;
7384 let rot = self.slice(last, 0, rope_dim)?;
7385 let pass = self.slice(last, rope_dim, pass_dim)?;
7386 let rot_rotated = rot.rope_with_tables(rope_cos, rope_sin)?;
7387 rot_rotated.concat(&pass, last)
7388 }
7389
7390 pub fn add_optional_trailing_bias(
7395 &self,
7396 bias: Option<&std::sync::Arc<[f32]>>,
7397 ) -> std::result::Result<Self, fuel_ir::Error> {
7398 match bias {
7399 None => Ok(self.clone()),
7400 Some(b) => self.add_trailing_bias(std::sync::Arc::clone(b)),
7401 }
7402 }
7403
7404 pub fn softcap(&self, cap: f64) -> Self {
7410 self.mul_scalar(1.0 / cap).tanh().mul_scalar(cap)
7411 }
7412
7413 pub fn softcap_optional(&self, cap: Option<f64>) -> Self {
7417 match cap {
7418 Some(c) if c > 0.0 => self.softcap(c),
7419 _ => self.clone(),
7420 }
7421 }
7422
7423 pub fn rms_norm_affine_with_offset(
7432 &self,
7433 gain: &[f32],
7434 offset: f32,
7435 eps: f64,
7436 ) -> std::result::Result<Self, fuel_ir::Error> {
7437 let shifted: std::sync::Arc<[f32]> =
7438 std::sync::Arc::from(gain.iter().map(|g| *g + offset).collect::<Vec<_>>());
7439 self.rms_norm_affine(shifted, eps)
7440 }
7441
7442 pub fn rms_norm_affine(
7447 &self,
7448 gain: std::sync::Arc<[f32]>,
7449 eps: f64,
7450 ) -> std::result::Result<Self, fuel_ir::Error> {
7451 let hidden = gain.len();
7452 let normed = self.rms_norm_last_dim(eps)?;
7453 let gain_t = self.const_f32_like(gain, Shape::from_dims(&[hidden]))?;
7454 normed.broadcast_mul(&gain_t)
7455 }
7456
7457 pub fn global_avg_pool_2d(&self) -> std::result::Result<Self, fuel_ir::Error> {
7467 let dims = self.inner.shape().dims().to_vec();
7468 debug_assert_eq!(
7469 dims.len(),
7470 4,
7471 "global_avg_pool_2d: input must be rank 4 (B, C, H, W), got {dims:?}"
7472 );
7473 self.mean_dim(3_usize)?.mean_dim(2_usize)
7475 }
7476
7477 pub fn channel_affine_4d(
7489 &self,
7490 gain: std::sync::Arc<[f32]>,
7491 bias: std::sync::Arc<[f32]>,
7492 ) -> std::result::Result<Self, fuel_ir::Error> {
7493 let dims = self.inner.shape().dims().to_vec();
7494 debug_assert_eq!(
7495 dims.len(),
7496 4,
7497 "channel_affine_4d: input must be rank 4 (B, C, H, W), got {dims:?}"
7498 );
7499 let channels = dims[1];
7500 debug_assert_eq!(
7501 gain.len(),
7502 channels,
7503 "channel_affine_4d: gain len ({}) != C ({})",
7504 gain.len(),
7505 channels
7506 );
7507 debug_assert_eq!(
7508 bias.len(),
7509 channels,
7510 "channel_affine_4d: bias len ({}) != C ({})",
7511 bias.len(),
7512 channels
7513 );
7514 let w_t = self
7515 .const_f32_like(gain, Shape::from_dims(&[channels]))?
7516 .reshape(Shape::from_dims(&[1, channels, 1, 1]))?;
7517 let b_t = self
7518 .const_f32_like(bias, Shape::from_dims(&[channels]))?
7519 .reshape(Shape::from_dims(&[1, channels, 1, 1]))?;
7520 self.broadcast_mul(&w_t)?.broadcast_add(&b_t)
7521 }
7522
7523 pub fn additive_causal_mask_like(anchor: &Tensor, seq_len: usize) -> Self {
7532 let mut data = vec![0.0_f32; seq_len * seq_len];
7533 for i in 0..seq_len {
7534 for j in (i + 1)..seq_len {
7535 data[i * seq_len + j] = f32::NEG_INFINITY;
7536 }
7537 }
7538 anchor
7542 .const_f32_like(
7543 std::sync::Arc::from(data),
7544 Shape::from_dims(&[seq_len, seq_len]),
7545 )
7546 .expect(
7547 "additive_causal_mask_like: vec![_; seq_len*seq_len] against [seq_len, seq_len]",
7548 )
7549 }
7550
7551 pub fn tril2(n: usize, dtype: DType, device: &Device) -> Self {
7554 let mut data = vec![0.0_f32; n * n];
7555 for i in 0..n {
7556 for j in 0..=i {
7557 data[i * n + j] = 1.0;
7558 }
7559 }
7560 let base = Self::from_f32(data, vec![n, n], device).expect(
7569 "tril2: data is vec![_; n*n] and shape is [n, n] (elem_count n*n), \n both computed from `n` in this function -- lengths cannot disagree",
7570 );
7571 if dtype == DType::F32 {
7572 base
7573 } else {
7574 base.to_dtype(dtype).unwrap()
7575 }
7576 }
7577
7578 pub fn triu2(n: usize, dtype: DType, device: &Device) -> Self {
7580 let mut data = vec![0.0_f32; n * n];
7581 for i in 0..n {
7582 for j in i..n {
7583 data[i * n + j] = 1.0;
7584 }
7585 }
7586 let base = Self::from_f32(data, vec![n, n], device).expect(
7595 "triu2: data is vec![_; n*n] and shape is [n, n] (elem_count n*n), \n both computed from `n` in this function -- lengths cannot disagree",
7596 );
7597 if dtype == DType::F32 {
7598 base
7599 } else {
7600 base.to_dtype(dtype).unwrap()
7601 }
7602 }
7603
7604 pub fn narrow<D: Dim>(
7611 &self,
7612 dim: D,
7613 start: usize,
7614 len: usize,
7615 ) -> std::result::Result<Self, fuel_ir::Error> {
7616 self.slice(dim, start, len)
7617 }
7618
7619 pub fn chunk<D: Dim>(
7625 &self,
7626 chunks: usize,
7627 dim: D,
7628 ) -> std::result::Result<Vec<Self>, fuel_ir::Error> {
7629 let shape = self.shape();
7630 let dim = dim.to_index(&shape, "chunk")?;
7631 if chunks == 0 {
7632 return Err(fuel_ir::Error::Msg("chunk: chunks must be > 0".into()).bt());
7633 }
7634 let dims = shape.dims();
7635 let size = dims[dim];
7636 if size < chunks {
7637 return Ok((0..size).map(|i| self.slice(dim, i, 1).unwrap()).collect());
7638 }
7639 let base = size / chunks;
7640 let extra = size % chunks;
7641 let mut out = Vec::with_capacity(chunks);
7642 let mut start = 0;
7643 for i in 0..chunks {
7644 let len = if i < extra { base + 1 } else { base };
7645 out.push(self.slice(dim, start, len).unwrap());
7646 start += len;
7647 }
7648 Ok(out)
7649 }
7650
7651 pub fn get(&self, i: usize) -> std::result::Result<Self, fuel_ir::Error> {
7654 let dims = self.shape().dims().to_vec();
7655 if dims.is_empty() {
7656 return Ok(self.clone());
7657 }
7658 self.slice(0, i, 1).unwrap().squeeze(0)
7659 }
7660
7661 pub fn get_on_dim<D: Dim>(
7665 &self,
7666 dim: D,
7667 index: usize,
7668 ) -> std::result::Result<Self, fuel_ir::Error> {
7669 let shape = self.shape();
7670 let dim = dim.to_index(&shape, "get_on_dim")?;
7671 self.slice(dim, index, 1).unwrap().squeeze(dim)
7672 }
7673
7674 pub fn sum_dims<D: Dims>(&self, dims: D) -> std::result::Result<Self, fuel_ir::Error> {
7678 let shape = self.shape();
7679 let mut sorted = dims.to_indexes(&shape, "sum_dims")?;
7680 sorted.sort_by(|a, b| b.cmp(a));
7681 sorted.dedup();
7682 let mut acc = self.clone();
7683 for d in sorted {
7684 acc = acc.sum_dim(d)?;
7685 }
7686 Ok(acc)
7687 }
7688
7689 pub fn mean_dims<D: Dims>(&self, dims: D) -> std::result::Result<Self, fuel_ir::Error> {
7692 let shape = self.shape();
7693 let mut sorted = dims.to_indexes(&shape, "mean_dims")?;
7694 sorted.sort_by(|a, b| b.cmp(a));
7695 sorted.dedup();
7696 let mut acc = self.clone();
7697 for d in sorted {
7698 acc = acc.mean_dim(d)?;
7699 }
7700 Ok(acc)
7701 }
7702
7703 pub fn sum_dims_keepdim(&self, dims: &[usize]) -> std::result::Result<Self, fuel_ir::Error> {
7708 let mut sorted: Vec<usize> = dims.to_vec();
7709 sorted.sort();
7710 sorted.dedup();
7711 let mut acc = self.clone();
7712 for d in sorted {
7713 acc = acc.sum_keepdim(d)?;
7714 }
7715 Ok(acc)
7716 }
7717
7718 pub fn mean_dims_keepdim(&self, dims: &[usize]) -> std::result::Result<Self, fuel_ir::Error> {
7720 let mut sorted: Vec<usize> = dims.to_vec();
7721 sorted.sort();
7722 sorted.dedup();
7723 let mut acc = self.clone();
7724 for d in sorted {
7725 acc = acc.mean_keepdim(d)?;
7726 }
7727 Ok(acc)
7728 }
7729
7730 pub fn rand_like(&self, lo: f64, up: f64) -> std::result::Result<Self, fuel_ir::Error> {
7733 Self::rand(self.shape(), lo, up, self.dtype(), &Device::cpu())
7734 }
7735
7736 pub fn randn_like(&self, mean: f64, stdev: f64) -> std::result::Result<Self, fuel_ir::Error> {
7739 Self::randn(self.shape(), mean, stdev, self.dtype(), &Device::cpu())
7740 }
7741
7742 pub fn rand(
7746 shape: impl Into<Shape>,
7747 lo: f64,
7748 up: f64,
7749 dtype: DType,
7750 device: &Device,
7751 ) -> std::result::Result<Self, fuel_ir::Error> {
7752 use rand::RngExt;
7753 let shape = shape.into();
7754 let n = shape.elem_count();
7755 let mut rng = rand::rng();
7756 match dtype {
7757 DType::F32 => {
7758 let data: Vec<f32> = (0..n).map(|_| rng.random_range(lo..up) as f32).collect();
7759 Self::from_f32(data, shape, device)
7760 }
7761 DType::F64 => {
7762 let data: Vec<f64> = (0..n).map(|_| rng.random_range(lo..up)).collect();
7763 Self::from_f64(data, shape, device)
7764 }
7765 DType::BF16 => {
7766 let data: Vec<half::bf16> = (0..n)
7767 .map(|_| fuel_ir::round::bf16_from_f64(rng.random_range(lo..up)))
7768 .collect();
7769 Self::from_bf16(data, shape, device)
7770 }
7771 DType::F16 => {
7772 let data: Vec<half::f16> = (0..n)
7773 .map(|_| fuel_ir::round::f16_from_f64(rng.random_range(lo..up)))
7774 .collect();
7775 Self::from_f16(data, shape, device)
7776 }
7777 other => {
7778 Err(fuel_ir::Error::Msg(format!("Tensor::rand: unsupported dtype {other:?}",)).bt())
7779 }
7780 }
7781 }
7782
7783 pub fn randn(
7787 shape: impl Into<Shape>,
7788 mean: f64,
7789 stdev: f64,
7790 dtype: DType,
7791 device: &Device,
7792 ) -> std::result::Result<Self, fuel_ir::Error> {
7793 use rand_distr::{Distribution, Normal};
7794 let shape = shape.into();
7795 let n = shape.elem_count();
7796 let normal = Normal::new(mean, stdev).map_err(|e| {
7797 fuel_ir::Error::Msg(format!("Tensor::randn: invalid stdev={stdev}: {e}",)).bt()
7798 })?;
7799 let mut rng = rand::rng();
7800 match dtype {
7801 DType::F32 => {
7802 let data: Vec<f32> = (0..n).map(|_| normal.sample(&mut rng) as f32).collect();
7803 Self::from_f32(data, shape, device)
7804 }
7805 DType::F64 => {
7806 let data: Vec<f64> = (0..n).map(|_| normal.sample(&mut rng)).collect();
7807 Self::from_f64(data, shape, device)
7808 }
7809 DType::BF16 => {
7810 let data: Vec<half::bf16> = (0..n)
7811 .map(|_| fuel_ir::round::bf16_from_f64(normal.sample(&mut rng)))
7812 .collect();
7813 Self::from_bf16(data, shape, device)
7814 }
7815 DType::F16 => {
7816 let data: Vec<half::f16> = (0..n)
7817 .map(|_| fuel_ir::round::f16_from_f64(normal.sample(&mut rng)))
7818 .collect();
7819 Self::from_f16(data, shape, device)
7820 }
7821 other => Err(fuel_ir::Error::Msg(format!(
7822 "Tensor::randn: unsupported dtype {other:?}",
7823 ))
7824 .bt()),
7825 }
7826 }
7827
7828 pub fn arange(start: f32, end: f32, device: &Device) -> Self {
7831 Self::arange_step(start, end, 1.0, device)
7832 }
7833
7834 pub fn arange_step(start: f32, end: f32, step: f32, device: &Device) -> Self {
7839 assert!(step != 0.0, "arange_step: step must be non-zero");
7840 let mut data = Vec::new();
7841 let mut current = start;
7842 if step > 0.0 {
7843 while current < end {
7844 data.push(current);
7845 current += step;
7846 }
7847 } else {
7848 while current > end {
7849 data.push(current);
7850 current += step;
7851 }
7852 }
7853 let n = data.len();
7854 Self::from_f32(data, vec![n], device).expect(
7861 "arange_step: shape is [n] where n IS data.len(), computed one line above from that same buffer -- the lengths cannot disagree",
7862 )
7863 }
7864
7865 pub fn linspace(start: f32, end: f32, n: usize, device: &Device) -> Self {
7868 assert!(n >= 1, "linspace: n must be >= 1");
7869 if n == 1 {
7870 return Self::from_f32(vec![start], vec![1], device)
7872 .expect("linspace: vec![start] has exactly 1 element and the shape is [1]");
7873 }
7874 let step = (end - start) / ((n - 1) as f32);
7875 let data: Vec<f32> = (0..n).map(|i| start + step * (i as f32)).collect();
7876 Self::from_f32(data, vec![n], device).expect(
7879 "linspace: data is (0..n).map(..).collect() so it has exactly n elements, and the shape is [n] -- both from the same `n`",
7880 )
7881 }
7882
7883 pub fn norm(&self) -> Self {
7885 self.sqr().sum_all().sqrt()
7886 }
7887
7888 pub fn conv1d(
7903 &self,
7904 weight: &Self,
7905 bias: Option<&Self>,
7906 stride: usize,
7907 padding: usize,
7908 groups: usize,
7909 ) -> std::result::Result<Self, fuel_ir::Error> {
7910 let x_dims = self.shape().dims().to_vec();
7911 let w_dims = weight.shape().dims().to_vec();
7912 if x_dims.len() != 3 {
7913 return Err(fuel_ir::Error::Msg(format!(
7914 "conv1d: x must be rank 3 [N, Cin, T], got {x_dims:?}",
7915 ))
7916 .bt());
7917 }
7918 if w_dims.len() != 3 {
7919 return Err(fuel_ir::Error::Msg(format!(
7920 "conv1d: weight must be rank 3 [Cout, Cin/groups, K], got {w_dims:?}",
7921 ))
7922 .bt());
7923 }
7924 if groups < 1 {
7925 return Err(fuel_ir::Error::Msg("conv1d: groups must be ≥ 1".into()).bt());
7926 }
7927 if stride < 1 {
7928 return Err(fuel_ir::Error::Msg("conv1d: stride must be ≥ 1".into()).bt());
7929 }
7930 let x_4d = self.unsqueeze(2_usize)?;
7932 let w_4d = weight.unsqueeze(2_usize)?;
7933 let out_4d = x_4d.conv2d(&w_4d, bias, (1, stride), (0, padding), groups)?;
7934 out_4d.squeeze(2)
7935 }
7936
7937 pub fn conv1d_with_algo<A>(
7942 &self,
7943 weight: &Self,
7944 bias: Option<&Self>,
7945 stride: usize,
7946 padding: usize,
7947 groups: usize,
7948 _algo: A,
7949 ) -> std::result::Result<Self, fuel_ir::Error> {
7950 self.conv1d(weight, bias, stride, padding, groups)
7951 }
7952
7953 pub fn avg_pool2d(
7963 &self,
7964 kernel: (usize, usize),
7965 stride: (usize, usize),
7966 padding: (usize, usize),
7967 count_include_pad: bool,
7968 ) -> std::result::Result<Self, fuel_ir::Error> {
7969 let dims = self.shape().dims().to_vec();
7970 if dims.len() != 4 {
7971 return Err(fuel_ir::Error::Msg(format!(
7972 "avg_pool2d: input must be rank 4 [N, C, H, W], got {dims:?}",
7973 ))
7974 .bt());
7975 }
7976 let (c, h, w) = (dims[1], dims[2], dims[3]);
7977 let (kh, kw) = kernel;
7978 if kh == 0 || kw == 0 {
7979 return Err(
7980 fuel_ir::Error::Msg("avg_pool2d: kernel sizes must be positive".into()).bt(),
7981 );
7982 }
7983
7984 if count_include_pad || padding == (0, 0) {
7989 let inv = 1.0_f32 / ((kh * kw) as f32);
7990 let weight =
7994 self.const_f32_like(vec![inv; c * kh * kw], Shape::from_dims(&[c, 1, kh, kw]))?;
7995 return self.conv2d(&weight, None, stride, padding, c);
7996 }
7997
7998 if let Some((axis, out_idx)) = first_zero_tap_output_index(h, kh, stride.0, padding.0)
8013 .map(|i| ("H", i))
8014 .or_else(|| first_zero_tap_output_index(w, kw, stride.1, padding.1).map(|i| ("W", i)))
8015 {
8016 return Err(fuel_ir::Error::Msg(format!(
8017 "avg_pool2d: count_include_pad=false has no valid (non-padded) \
8018 taps for output position {out_idx} on the {axis} axis \
8019 (kernel={kernel:?}, stride={stride:?}, padding={padding:?}, \
8020 input H×W={h}×{w}) — the average would divide by zero",
8021 ))
8022 .bt());
8023 }
8024
8025 let sum_weight = self.const_f32_like(
8026 vec![1.0_f32; c * kh * kw],
8027 Shape::from_dims(&[c, 1, kh, kw]),
8028 )?;
8029 let summed = self.conv2d(&sum_weight, None, stride, padding, c)?;
8030
8031 let ones_hw = self.const_f32_like(vec![1.0_f32; h * w], Shape::from_dims(&[1, 1, h, w]))?;
8035 let count_weight =
8036 self.const_f32_like(vec![1.0_f32; kh * kw], Shape::from_dims(&[1, 1, kh, kw]))?;
8037 let count = ones_hw.conv2d(&count_weight, None, stride, padding, 1)?;
8038
8039 summed.broadcast_div(&count)
8040 }
8041
8042 pub fn avg_pool2d_with_stride(
8046 &self,
8047 kernel: (usize, usize),
8048 stride: (usize, usize),
8049 ) -> std::result::Result<Self, fuel_ir::Error> {
8050 self.avg_pool2d(kernel, stride, (0, 0), true)
8053 }
8054
8055 pub fn max_pool2d(
8070 &self,
8071 kernel: (usize, usize),
8072 stride: (usize, usize),
8073 padding: (usize, usize),
8074 ) -> std::result::Result<Self, fuel_ir::Error> {
8075 self.max_pool2d_with_pad_value(kernel, stride, padding, f32::NEG_INFINITY)
8083 }
8084
8085 pub fn max_pool2d_with_pad_value(
8091 &self,
8092 kernel: (usize, usize),
8093 stride: (usize, usize),
8094 padding: (usize, usize),
8095 pad_value: f32,
8096 ) -> std::result::Result<Self, fuel_ir::Error> {
8097 let dims = self.shape().dims().to_vec();
8098 if dims.len() != 4 {
8099 return Err(fuel_ir::Error::Msg(format!(
8100 "max_pool2d: input must be rank 4 [N, C, H, W], got {dims:?}",
8101 ))
8102 .bt());
8103 }
8104 let (n, c, h, w) = (dims[0], dims[1], dims[2], dims[3]);
8105 let (kh, kw) = kernel;
8106 let (sh, sw) = stride;
8107 let (ph, pw) = padding;
8108 if kh == 0 || kw == 0 {
8109 return Err(
8110 fuel_ir::Error::Msg("max_pool2d: kernel sizes must be positive".into()).bt(),
8111 );
8112 }
8113 if sh == 0 || sw == 0 {
8114 return Err(fuel_ir::Error::Msg("max_pool2d: strides must be positive".into()).bt());
8115 }
8116 let h_padded_min = h + 2 * ph;
8117 let w_padded_min = w + 2 * pw;
8118 if h_padded_min < kh || w_padded_min < kw {
8119 return Err(fuel_ir::Error::Msg(format!(
8120 "max_pool2d: padded input ({h_padded_min}×{w_padded_min}) smaller than kernel ({kh}×{kw})",
8121 )).bt());
8122 }
8123 let h_out = (h_padded_min - kh) / sh + 1;
8124 let w_out = (w_padded_min - kw) / sw + 1;
8125 let h_total = h_out * sh + (kh - 1);
8128 let w_total = w_out * sw + (kw - 1);
8129 let extra_h = h_total.saturating_sub(h_padded_min);
8130 let extra_w = w_total.saturating_sub(w_padded_min);
8131 let padded = self
8132 .pad_with_value(2, ph, ph + extra_h, pad_value)?
8133 .pad_with_value(3, pw, pw + extra_w, pad_value)?;
8134 let mut acc: Option<Tensor> = None;
8136 for ky in 0..kh {
8137 let row_slice = padded.slice(2, ky, h_out * sh).unwrap();
8141 let row_reshaped = row_slice.reshape(vec![n, c, h_out, sh, w_total])?;
8144 let row_tap = row_reshaped.slice(3, 0, 1).unwrap().squeeze(3)?;
8145 for kx in 0..kw {
8146 let col_slice = row_tap.slice(3, kx, w_out * sw).unwrap();
8147 let col_reshaped = col_slice.reshape(vec![n, c, h_out, w_out, sw])?;
8148 let win = col_reshaped.slice(4, 0, 1).unwrap().squeeze(4)?;
8149 acc = Some(match acc {
8150 None => win,
8151 Some(a) => a.maximum(&win).unwrap(),
8152 });
8153 }
8154 }
8155 acc.ok_or_else(|| fuel_ir::Error::Msg("max_pool2d: empty kernel".into()).bt())
8156 }
8157
8158 pub fn max_pool2d_with_stride(
8160 &self,
8161 kernel: (usize, usize),
8162 stride: (usize, usize),
8163 ) -> std::result::Result<Self, fuel_ir::Error> {
8164 self.max_pool2d(kernel, stride, (0, 0))
8165 }
8166
8167 pub fn upsample_nearest2d(&self, scale: usize) -> std::result::Result<Self, fuel_ir::Error> {
8177 if scale == 0 {
8178 return Err(
8179 fuel_ir::Error::Msg("upsample_nearest2d: scale must be positive".into()).bt(),
8180 );
8181 }
8182 let dims = self.shape().dims().to_vec();
8183 if dims.len() != 4 {
8184 return Err(fuel_ir::Error::Msg(format!(
8185 "upsample_nearest2d: input must be rank 4 [N, C, H, W], got {dims:?}",
8186 ))
8187 .bt());
8188 }
8189 if scale == 1 {
8190 return Ok(self.clone());
8191 }
8192 let (n, c, h, w) = (dims[0], dims[1], dims[2], dims[3]);
8193 let expanded = self.reshape(vec![n, c, h, 1, w, 1])?;
8195 let h_expanded = (0..scale)
8197 .fold(None, |acc: Option<Tensor>, _| {
8198 Some(match acc {
8199 None => expanded.clone(),
8200 Some(a) => a.concat(&expanded, 3).unwrap(),
8201 })
8202 })
8203 .unwrap();
8204 let h_then_w = (0..scale)
8205 .fold(None, |acc: Option<Tensor>, _| {
8206 Some(match acc {
8207 None => h_expanded.clone(),
8208 Some(a) => a.concat(&h_expanded, 5).unwrap(),
8209 })
8210 })
8211 .unwrap();
8212 h_then_w.reshape(vec![n, c, h * scale, w * scale])
8213 }
8214
8215 pub fn upsample_nearest1d(&self, scale: usize) -> std::result::Result<Self, fuel_ir::Error> {
8219 if scale == 0 {
8220 return Err(
8221 fuel_ir::Error::Msg("upsample_nearest1d: scale must be positive".into()).bt(),
8222 );
8223 }
8224 let dims = self.shape().dims().to_vec();
8225 if dims.len() != 3 {
8226 return Err(fuel_ir::Error::Msg(format!(
8227 "upsample_nearest1d: input must be rank 3 [N, C, T], got {dims:?}",
8228 ))
8229 .bt());
8230 }
8231 if scale == 1 {
8232 return Ok(self.clone());
8233 }
8234 let (n, c, t) = (dims[0], dims[1], dims[2]);
8235 let expanded = self.reshape(vec![n, c, t, 1])?;
8236 let replicated = (0..scale)
8237 .fold(None, |acc: Option<Tensor>, _| {
8238 Some(match acc {
8239 None => expanded.clone(),
8240 Some(a) => a.concat(&expanded, 3).unwrap(),
8241 })
8242 })
8243 .unwrap();
8244 replicated.reshape(vec![n, c, t * scale])
8245 }
8246
8247 pub fn interpolate2d(
8257 &self,
8258 target_h: usize,
8259 target_w: usize,
8260 ) -> std::result::Result<Self, fuel_ir::Error> {
8261 let dims = self.shape().dims().to_vec();
8262 if dims.len() != 4 {
8263 return Err(fuel_ir::Error::Msg(format!(
8264 "interpolate2d: input must be rank 4 [N, C, H, W], got {dims:?}",
8265 ))
8266 .bt());
8267 }
8268 let h = dims[2];
8269 let w = dims[3];
8270 if h == 0 || w == 0 || target_h == 0 || target_w == 0 {
8271 return Err(fuel_ir::Error::Msg(
8272 "interpolate2d: input + target spatial dims must be positive".into(),
8273 )
8274 .bt());
8275 }
8276 if target_h == h && target_w == w {
8278 return Ok(self.clone());
8279 }
8280 if target_h.is_multiple_of(h) && target_w.is_multiple_of(w) && target_h / h == target_w / w
8284 {
8285 return self.upsample_nearest2d(target_h / h);
8286 }
8287 let h_idx: Vec<u32> = (0..target_h)
8291 .map(|oi| ((oi * h) / target_h).min(h - 1) as u32)
8292 .collect();
8293 let w_idx: Vec<u32> = (0..target_w)
8294 .map(|oj| ((oj * w) / target_w).min(w - 1) as u32)
8295 .collect();
8296 let h_idx_tensor = self.const_u32_like(h_idx, fuel_ir::Shape::from_dims(&[target_h]))?;
8297 let w_idx_tensor = self.const_u32_like(w_idx, fuel_ir::Shape::from_dims(&[target_w]))?;
8298 let after_h = self.index_select(2_usize, &h_idx_tensor)?;
8299 after_h.index_select(3_usize, &w_idx_tensor)
8300 }
8301
8302 pub fn interpolate1d(&self, target_t: usize) -> std::result::Result<Self, fuel_ir::Error> {
8306 let dims = self.shape().dims().to_vec();
8307 if dims.len() != 3 {
8308 return Err(fuel_ir::Error::Msg(format!(
8309 "interpolate1d: input must be rank 3 [N, C, T], got {dims:?}",
8310 ))
8311 .bt());
8312 }
8313 let t = dims[2];
8314 if t == 0 {
8315 return Err(
8316 fuel_ir::Error::Msg("interpolate1d: input length must be positive".into()).bt(),
8317 );
8318 }
8319 if !target_t.is_multiple_of(t) {
8320 return Err(fuel_ir::Error::Msg(format!(
8321 "interpolate1d: target {target_t} must be integer multiple of input {t}; non-integer ratios are future work",
8322 )).bt());
8323 }
8324 self.upsample_nearest1d(target_t / t)
8325 }
8326
8327 pub fn pad_with_zeros<D: Dim>(
8331 &self,
8332 dim: D,
8333 left: usize,
8334 right: usize,
8335 ) -> std::result::Result<Self, fuel_ir::Error> {
8336 self.pad_with_value(dim, left, right, 0.0)
8337 }
8338
8339 pub fn pad_with_value<D: Dim>(
8346 &self,
8347 dim: D,
8348 before: usize,
8349 after: usize,
8350 value: f32,
8351 ) -> std::result::Result<Self, fuel_ir::Error> {
8352 let shape = self.shape();
8353 let dim = dim.to_index(&shape, "pad_with_value")?;
8354 let rank = shape.dims().len();
8355 if before == 0 && after == 0 {
8356 return Ok(self.clone());
8357 }
8358 let mut padding: Vec<(usize, usize)> = vec![(0, 0); rank];
8359 padding[dim] = (before, after);
8360 self.pad(padding, fuel_graph::PadMode::Constant, value as f64)
8361 }
8362
8363 pub fn meshgrid(
8376 args: &[&Self],
8377 xy_indexing: bool,
8378 ) -> std::result::Result<Vec<Self>, fuel_ir::Error> {
8379 if args.len() < 2 {
8380 return Err(fuel_ir::Error::Msg(
8381 "meshgrid: requires at least two rank-1 tensors".into(),
8382 )
8383 .bt());
8384 }
8385 let ordered: Vec<&Self> = if xy_indexing {
8386 args.iter().rev().copied().collect()
8387 } else {
8388 args.to_vec()
8389 };
8390 let mut lens = Vec::with_capacity(ordered.len());
8391 for (i, t) in ordered.iter().enumerate() {
8392 let dims = t.shape().dims().to_vec();
8393 if dims.len() != 1 {
8394 return Err(fuel_ir::Error::Msg(format!(
8395 "meshgrid: input {i} must be rank 1, got shape {dims:?}",
8396 ))
8397 .bt());
8398 }
8399 lens.push(dims[0]);
8400 }
8401 let mut grids = Vec::with_capacity(ordered.len());
8402 for (idx, t) in ordered.iter().enumerate() {
8403 let mut shape = vec![1_usize; ordered.len()];
8404 shape[idx] = lens[idx];
8405 let placed = t.reshape(shape)?;
8406 let mut repeats = lens.clone();
8407 repeats[idx] = 1;
8408 let grid = placed.repeat(repeats)?;
8409 grids.push(grid);
8410 }
8411 if xy_indexing {
8412 grids.reverse();
8413 }
8414 Ok(grids)
8415 }
8416
8417 pub fn repeat(&self, repeats: impl Into<Shape>) -> std::result::Result<Self, fuel_ir::Error> {
8421 let repeats = repeats.into();
8422 let repeats: Vec<usize> = repeats.dims().to_vec();
8423 let self_rank = self.shape().dims().len();
8424 let target_rank = repeats.len();
8425 let mut work = if self_rank < target_rank {
8426 let pad_count = target_rank - self_rank;
8427 let mut new_shape: Vec<usize> = vec![1; pad_count];
8428 new_shape.extend_from_slice(self.shape().dims());
8429 self.reshape(new_shape)?
8430 } else if self_rank > target_rank {
8431 return Err(fuel_ir::Error::Msg(format!(
8432 "repeat: repeats rank {target_rank} smaller than tensor rank {self_rank}",
8433 ))
8434 .bt());
8435 } else {
8436 self.clone()
8437 };
8438 for (axis, &n) in repeats.iter().enumerate() {
8439 if n == 0 {
8440 return Err(fuel_ir::Error::Msg(format!(
8441 "repeat: zero repeat count at axis {axis} not supported",
8442 ))
8443 .bt());
8444 }
8445 if n == 1 {
8446 continue;
8447 }
8448 let base = work.clone();
8450 for _ in 1..n {
8451 work = work.concat(&base, axis)?;
8452 }
8453 }
8454 Ok(work)
8455 }
8456}
8457
8458fn first_zero_tap_output_index(
8467 dim: usize,
8468 kernel: usize,
8469 stride: usize,
8470 pad: usize,
8471) -> Option<usize> {
8472 let out_dim = (dim + 2 * pad).saturating_sub(kernel) / stride + 1;
8473 (0..out_dim).find(|&o| {
8474 let start = o as isize * stride as isize - pad as isize;
8475 let end = start + kernel as isize;
8476 let valid_start = start.max(0);
8477 let valid_end = end.min(dim as isize);
8478 valid_end <= valid_start
8479 })
8480}
8481
8482impl Tensor {
8485 pub fn from_safetensors_bytes(
8497 bytes: &[u8],
8498 dtype: safetensors::Dtype,
8499 shape: &[usize],
8500 device: &Device,
8501 ) -> crate::Result<Self> {
8502 use safetensors::Dtype;
8503 let shape_obj = Shape::from_dims(shape);
8504 let elem_count = shape_obj.elem_count();
8505
8506 let check_len = |expected: usize| -> crate::Result<()> {
8507 if bytes.len() != expected {
8508 crate::bail!(
8509 "from_safetensors_bytes: expected {expected} bytes for dtype {dtype:?} \
8510 and shape {shape:?}, got {}",
8511 bytes.len(),
8512 );
8513 }
8514 Ok(())
8515 };
8516
8517 match dtype {
8518 Dtype::F32 => {
8519 check_len(elem_count * 4)?;
8520 let mut data = Vec::with_capacity(elem_count);
8521 for chunk in bytes.as_chunks::<4>().0.iter() {
8522 data.push(f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
8523 }
8524 Self::from_f32(data, shape_obj, device)
8525 }
8526 Dtype::F64 => {
8527 check_len(elem_count * 8)?;
8528 let mut data = Vec::with_capacity(elem_count);
8529 for chunk in bytes.as_chunks::<8>().0.iter() {
8530 let arr: [u8; 8] = *chunk;
8531 data.push(f64::from_le_bytes(arr));
8532 }
8533 Self::from_f64(data, shape_obj, device)
8534 }
8535 Dtype::BF16 => {
8536 check_len(elem_count * 2)?;
8537 let mut data = Vec::with_capacity(elem_count);
8538 for chunk in bytes.as_chunks::<2>().0.iter() {
8539 let raw = u16::from_le_bytes([chunk[0], chunk[1]]);
8540 data.push(half::bf16::from_bits(raw));
8541 }
8542 Self::from_bf16(data, shape_obj, device)
8543 }
8544 Dtype::F16 => {
8545 check_len(elem_count * 2)?;
8546 let mut data = Vec::with_capacity(elem_count);
8547 for chunk in bytes.as_chunks::<2>().0.iter() {
8548 let raw = u16::from_le_bytes([chunk[0], chunk[1]]);
8549 data.push(half::f16::from_bits(raw));
8550 }
8551 Self::from_f16(data, shape_obj, device)
8552 }
8553 Dtype::U32 => {
8554 check_len(elem_count * 4)?;
8555 let mut data = Vec::with_capacity(elem_count);
8556 for chunk in bytes.as_chunks::<4>().0.iter() {
8557 data.push(u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
8558 }
8559 Self::from_u32(data, shape_obj, device)
8560 }
8561 other => crate::bail!(
8562 "from_safetensors_bytes: unsupported dtype {other:?} — extend Tensor's \
8563 safetensors loader to handle it",
8564 ),
8565 }
8566 }
8567
8568 pub fn from_safetensors_view(
8572 view: &safetensors::tensor::TensorView<'_>,
8573 device: &Device,
8574 ) -> crate::Result<Self> {
8575 Self::from_safetensors_bytes(view.data(), view.dtype(), view.shape(), device)
8576 }
8577}
8578
8579pub type LayerNormPair = (Arc<[f32]>, Arc<[f32]>);
8583
8584pub type ConvWeightBias = (Arc<[f32]>, Arc<[f32]>);
8588
8589#[derive(Debug, Clone)]
8612pub enum WeightStorage {
8613 F32(Arc<[f32]>),
8614 BF16(Arc<[half::bf16]>),
8615 F16(Arc<[half::f16]>),
8619 Q4_0 {
8629 words: Arc<[u32]>,
8630 bytes_len: usize,
8631 in_features: usize,
8632 out_features: usize,
8633 },
8634 Ggml {
8640 qtype: fuel_graph::QuantType,
8641 words: Arc<[u32]>,
8642 bytes_len: usize,
8643 in_features: usize,
8644 out_features: usize,
8645 },
8646 Awq(Arc<crate::awq::AwqHostWeight>),
8651 WithLoRA {
8662 base: Box<WeightStorage>,
8663 lora_a: Arc<[f32]>,
8665 lora_b: Arc<[f32]>,
8667 rank: usize,
8668 alpha: f32,
8670 in_features: usize,
8671 out_features: usize,
8672 },
8673}
8674
8675impl WeightStorage {
8676 pub fn from_ggml_bytes(
8691 dtype: fuel_ir::quantized::GgmlDType,
8692 bytes: &[u8],
8693 in_features: usize,
8694 out_features: usize,
8695 ) -> Option<Self> {
8696 use fuel_ir::quantized::GgmlDType;
8697 let qtype = match dtype {
8698 GgmlDType::Q8_0 => fuel_graph::QuantType::Q8_0,
8699 GgmlDType::Q4K => fuel_graph::QuantType::Q4_K_M,
8700 GgmlDType::Q6K => fuel_graph::QuantType::Q6K,
8701 GgmlDType::Q3K => fuel_graph::QuantType::Q3K,
8702 GgmlDType::Q5K => fuel_graph::QuantType::Q5K,
8703 GgmlDType::Iq4Nl => fuel_graph::QuantType::Iq4Nl,
8704 GgmlDType::Iq4Xs => fuel_graph::QuantType::Iq4Xs,
8705 GgmlDType::Iq3S => fuel_graph::QuantType::Iq3S,
8706 GgmlDType::F32
8709 | GgmlDType::F16
8710 | GgmlDType::BF16
8711 | GgmlDType::Q4_0
8712 | GgmlDType::Q4_1
8713 | GgmlDType::Q5_0
8714 | GgmlDType::Q5_1
8715 | GgmlDType::Q8_1
8716 | GgmlDType::Q2K
8717 | GgmlDType::Q8K
8718 | GgmlDType::Iq2Xxs
8719 | GgmlDType::Iq2Xs
8720 | GgmlDType::Iq3Xxs
8721 | GgmlDType::Iq1S
8722 | GgmlDType::Iq2S
8723 | GgmlDType::Iq1M
8724 | GgmlDType::Tq1_0
8725 | GgmlDType::Tq2_0
8726 | GgmlDType::Mxfp4
8727 | GgmlDType::Nvfp4 => return None,
8728 };
8729 let block = qtype.elements_per_block();
8730 if in_features == 0 || !in_features.is_multiple_of(block) {
8731 return None;
8732 }
8733 if bytes.len() != out_features * (in_features / block) * qtype.bytes_per_block() {
8734 return None;
8735 }
8736 let mut padded = bytes.to_vec();
8738 padded.resize(bytes.len().div_ceil(4) * 4, 0);
8739 let words: Vec<u32> = padded
8740 .as_chunks::<4>()
8741 .0
8742 .iter()
8743 .map(|c| u32::from_le_bytes(*c))
8744 .collect();
8745 Some(Self::Ggml {
8746 qtype,
8747 words: Arc::from(words),
8748 bytes_len: bytes.len(),
8749 in_features,
8750 out_features,
8751 })
8752 }
8753
8754 pub fn resident_bytes(&self) -> usize {
8758 match self {
8759 Self::F32(a) => a.len() * std::mem::size_of::<f32>(),
8760 Self::BF16(a) => a.len() * std::mem::size_of::<half::bf16>(),
8761 Self::F16(a) => a.len() * std::mem::size_of::<half::f16>(),
8762 Self::Q4_0 { bytes_len, .. } | Self::Ggml { bytes_len, .. } => *bytes_len,
8763 Self::Awq(w) => {
8764 w.weight.len() * std::mem::size_of::<u32>()
8765 + w.zeros.len() * std::mem::size_of::<u32>()
8766 + w.scales.len() * std::mem::size_of::<half::f16>()
8767 }
8768 Self::WithLoRA {
8769 base,
8770 lora_a,
8771 lora_b,
8772 ..
8773 } => base.resident_bytes() + (lora_a.len() + lora_b.len()) * std::mem::size_of::<f32>(),
8774 }
8775 }
8776
8777 pub fn elem_count(&self) -> usize {
8778 match self {
8779 Self::F32(a) => a.len(),
8780 Self::BF16(a) => a.len(),
8781 Self::F16(a) => a.len(),
8782 Self::Q4_0 {
8784 in_features,
8785 out_features,
8786 ..
8787 }
8788 | Self::Ggml {
8789 in_features,
8790 out_features,
8791 ..
8792 } => *in_features * *out_features,
8793 Self::Awq(w) => w.ic * w.oc,
8794 Self::WithLoRA {
8795 in_features,
8796 out_features,
8797 ..
8798 } => *in_features * *out_features,
8799 }
8800 }
8801
8802 pub fn dtype(&self) -> fuel_ir::DType {
8803 match self {
8804 Self::F32(_) => fuel_ir::DType::F32,
8805 Self::BF16(_) => fuel_ir::DType::BF16,
8806 Self::F16(_) => fuel_ir::DType::F16,
8807 Self::Q4_0 { .. } | Self::Ggml { .. } => fuel_ir::DType::U32,
8811 Self::Awq(_) => fuel_ir::DType::U32,
8813 Self::WithLoRA { base, .. } => base.dtype(),
8816 }
8817 }
8818
8819 pub fn const_like(
8830 &self,
8831 anchor: &Tensor,
8832 shape: Shape,
8833 ) -> std::result::Result<Tensor, fuel_ir::Error> {
8834 match self {
8835 Self::F32(a) => anchor.const_f32_like(a.clone(), shape),
8836 Self::BF16(a) => anchor.const_bf16_like(a.clone(), shape),
8837 Self::F16(a) => anchor.const_f16_like(a.clone(), shape),
8838 Self::Q4_0 { words, .. } | Self::Ggml { words, .. } => {
8839 let _ = shape; anchor.const_u32_like(Arc::clone(words), Shape::from_dims(&[words.len()]))
8842 }
8843 Self::Awq(_) => Err(fuel_ir::Error::Msg(
8844 "WeightStorage::Awq::const_like is not supported — an AWQ weight is three operands \
8845 (weight, zeros, scales), applied via apply_linear."
8846 .into(),
8847 )
8848 .bt()),
8849 Self::WithLoRA { .. } => Err(fuel_ir::Error::Msg(
8850 "WeightStorage::WithLoRA::const_like is not supported \
8851 — the base + LoRA update must be applied via \
8852 apply_linear to produce the right graph structure."
8853 .into(),
8854 )
8855 .bt()),
8856 }
8857 }
8858
8859 pub fn apply_linear_with_bias(
8868 &self,
8869 x: &Tensor,
8870 in_features: usize,
8871 out_features: usize,
8872 bias: std::sync::Arc<[f32]>,
8873 ) -> std::result::Result<Tensor, fuel_ir::Error> {
8874 if bias.len() != out_features {
8875 return Err(fuel_ir::Error::Msg(format!(
8880 "apply_linear_with_bias: bias len ({}) != out_features ({out_features})",
8881 bias.len(),
8882 ))
8883 .bt());
8884 }
8885 let projected = self.apply_linear(x, in_features, out_features)?;
8886 let bias_t = projected.const_f32_like(bias, Shape::from_dims(&[out_features]))?;
8887 projected.broadcast_add(&bias_t)
8888 }
8889
8890 pub fn apply_linear(
8908 &self,
8909 x: &Tensor,
8910 in_features: usize,
8911 out_features: usize,
8912 ) -> std::result::Result<Tensor, fuel_ir::Error> {
8913 let x_dims = x.shape().dims().to_vec();
8919 match x_dims.last() {
8920 Some(&k) if k == in_features => {}
8921 _ => {
8922 return Err(fuel_ir::Error::Msg(format!(
8923 "apply_linear({in_features} -> {out_features}): input shape {x_dims:?} \
8924 must have trailing dim {in_features}",
8925 ))
8926 .bt());
8927 }
8928 }
8929 match self {
8930 Self::F32(_) | Self::BF16(_) | Self::F16(_) => {
8931 let w = self.const_like(x, Shape::from_dims(&[in_features, out_features]))?;
8932 x.matmul(&w)
8933 }
8934 Self::Q4_0 {
8935 in_features: expected_in,
8936 out_features: expected_out,
8937 ..
8938 } => {
8939 if *expected_in != in_features || *expected_out != out_features {
8940 return Err(fuel_ir::Error::Msg(format!(
8941 "WeightStorage::Q4_0 shape mismatch: stored \
8942 [{expected_in}, {expected_out}], requested \
8943 [{in_features}, {out_features}]",
8944 ))
8945 .bt());
8946 }
8947 let w_bytes = self.const_like(x, Shape::from_dims(&[in_features, out_features]))?;
8948 x.qmatmul(
8949 &w_bytes,
8950 fuel_graph::QuantType::Q4_0,
8951 in_features,
8952 out_features,
8953 )
8954 }
8955 Self::Ggml {
8956 qtype,
8957 in_features: expected_in,
8958 out_features: expected_out,
8959 ..
8960 } => {
8961 if *expected_in != in_features || *expected_out != out_features {
8962 return Err(fuel_ir::Error::Msg(format!(
8963 "WeightStorage::Ggml({qtype:?}) shape mismatch: stored [{expected_in}, {expected_out}], requested [{in_features}, {out_features}]",
8964 ))
8965 .bt());
8966 }
8967 let w_bytes = self.const_like(x, Shape::from_dims(&[in_features, out_features]))?;
8968 x.qmatmul(&w_bytes, *qtype, in_features, out_features)
8969 }
8970 Self::Awq(w) => {
8971 if w.ic != in_features || w.oc != out_features {
8972 return Err(fuel_ir::Error::Msg(format!(
8973 "WeightStorage::Awq shape mismatch: stored [{}, {}], requested [{in_features}, {out_features}]",
8974 w.ic, w.oc,
8975 ))
8976 .bt());
8977 }
8978 w.matmul(x, 8)
8981 }
8982 Self::WithLoRA {
8983 base,
8984 lora_a,
8985 lora_b,
8986 rank,
8987 alpha,
8988 in_features: expected_in,
8989 out_features: expected_out,
8990 } => {
8991 if *expected_in != in_features || *expected_out != out_features {
8992 return Err(fuel_ir::Error::Msg(format!(
8993 "WeightStorage::WithLoRA shape mismatch: stored \
8994 [{expected_in}, {expected_out}], requested \
8995 [{in_features}, {out_features}]",
8996 ))
8997 .bt());
8998 }
8999 let base_out = base.apply_linear(x, in_features, out_features)?;
9001 let a_t =
9003 x.const_f32_like(Arc::clone(lora_a), Shape::from_dims(&[in_features, *rank]))?;
9004 let b_t =
9005 x.const_f32_like(Arc::clone(lora_b), Shape::from_dims(&[*rank, out_features]))?;
9006 let scale = *alpha as f64 / *rank as f64;
9007 let lora_path = Tensor {
9009 inner: x.matmul(&a_t)?.matmul(&b_t)?.inner.mul_scalar(scale),
9010 };
9011 base_out.add(&lora_path)
9012 }
9013 }
9014 }
9015
9016 pub fn apply_linear_dyn_m(
9029 &self,
9030 x: &Tensor,
9031 in_features: usize,
9032 out_features: usize,
9033 row_count: fuel_ir::DynScalar,
9034 ) -> std::result::Result<Tensor, fuel_ir::Error> {
9035 match self {
9036 Self::F32(_) => {
9037 let w = self
9039 .const_like(x, Shape::from_dims(&[in_features, out_features]))
9040 .expect("apply_linear_dyn_m F32 arm: const_like cannot fail for F32");
9041 x.matmul_dyn_m(&w, row_count)
9042 }
9043 other => Err(fuel_ir::Error::Msg(format!(
9044 "apply_linear_dyn_m: sparse-MoE dispatch is F32-only today, got {:?} \
9045 weight (cast the expert weights to F32)",
9046 other.dtype(),
9047 ))
9048 .bt()),
9049 }
9050 }
9051
9052 pub fn with_lora(
9057 self,
9058 lora_a: Arc<[f32]>,
9059 lora_b: Arc<[f32]>,
9060 rank: usize,
9061 alpha: f32,
9062 in_features: usize,
9063 out_features: usize,
9064 ) -> Self {
9065 assert_eq!(
9066 lora_a.len(),
9067 in_features * rank,
9068 "lora_a length {} does not match in_features ({in_features}) × rank ({rank}) = {}",
9069 lora_a.len(),
9070 in_features * rank,
9071 );
9072 assert_eq!(
9073 lora_b.len(),
9074 rank * out_features,
9075 "lora_b length {} does not match rank ({rank}) × out_features ({out_features}) = {}",
9076 lora_b.len(),
9077 rank * out_features,
9078 );
9079 assert!(
9080 !matches!(self, Self::WithLoRA { .. }),
9081 "with_lora: base is already WithLoRA (nested adapters unsupported)",
9082 );
9083 Self::WithLoRA {
9084 base: Box::new(self),
9085 lora_a,
9086 lora_b,
9087 rank,
9088 alpha,
9089 in_features,
9090 out_features,
9091 }
9092 }
9093}
9094
9095impl From<Arc<[f32]>> for WeightStorage {
9099 fn from(a: Arc<[f32]>) -> Self {
9100 Self::F32(a)
9101 }
9102}
9103impl From<Vec<f32>> for WeightStorage {
9104 fn from(v: Vec<f32>) -> Self {
9105 Self::F32(Arc::from(v))
9106 }
9107}
9108impl From<Arc<[half::bf16]>> for WeightStorage {
9109 fn from(a: Arc<[half::bf16]>) -> Self {
9110 Self::BF16(a)
9111 }
9112}
9113impl From<Vec<half::bf16>> for WeightStorage {
9114 fn from(v: Vec<half::bf16>) -> Self {
9115 Self::BF16(Arc::from(v))
9116 }
9117}
9118
9119#[derive(Debug, Clone)]
9131pub struct LayerWeights {
9132 pub attn_q: WeightStorage,
9134 pub attn_q_bias: Option<Arc<[f32]>>,
9136 pub attn_k: WeightStorage,
9138 pub attn_k_bias: Option<Arc<[f32]>>,
9140 pub attn_v: WeightStorage,
9142 pub attn_v_bias: Option<Arc<[f32]>>,
9144 pub attn_o: WeightStorage,
9146 pub ffn_gate: WeightStorage,
9148 pub ffn_up: WeightStorage,
9150 pub ffn_down: WeightStorage,
9152 pub attn_norm_gain: Arc<[f32]>,
9155 pub ffn_norm_gain: Arc<[f32]>,
9157}
9158
9159pub fn invalidate_decode_pair_if_stale<C>(
9160 session: &mut Option<crate::inference_context::DecodeSession>,
9161 captured: &mut Option<C>,
9162 ctx: &mut InferenceContext,
9163 seq: usize,
9164 max_seq_len: Option<usize>,
9165 cache_dtype: DType,
9166 n_layers: usize,
9167 shape_key: u64,
9168 kv: &dyn crate::inference_context::KvRebindSource,
9169 drop_session: impl FnOnce(
9170 &mut Option<crate::inference_context::DecodeSession>,
9171 &mut InferenceContext,
9172 ),
9173) -> SessionDisposition {
9174 refresh_decode_session(
9175 session,
9176 ctx,
9177 seq,
9178 max_seq_len,
9179 cache_dtype,
9180 n_layers,
9181 shape_key,
9182 kv,
9183 || *captured = None,
9187 drop_session,
9188 )
9189}
9190
9191#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9193pub enum SessionDisposition {
9194 Absent,
9196 Kept,
9198 Rebound,
9201 Dropped(Option<crate::inference_context::RebindRefusal>),
9205}
9206
9207pub fn refresh_decode_session(
9232 session: &mut Option<crate::inference_context::DecodeSession>,
9233 ctx: &mut InferenceContext,
9234 seq: usize,
9235 max_seq_len: Option<usize>,
9236 cache_dtype: DType,
9237 n_layers: usize,
9238 shape_key: u64,
9239 kv: &dyn crate::inference_context::KvRebindSource,
9240 on_invalidate: impl FnOnce(),
9241 drop_session: impl FnOnce(
9242 &mut Option<crate::inference_context::DecodeSession>,
9243 &mut InferenceContext,
9244 ),
9245) -> SessionDisposition {
9246 use crate::inference_context::PlanValidity;
9247
9248 let verdict = match (session.as_ref(), max_seq_len) {
9249 (None, _) => return SessionDisposition::Absent,
9250 (Some(s), Some(msl)) => {
9251 s.validity_for(seq, msl, n_layers, cache_dtype, shape_key, kv.alloc_id())
9252 }
9253 (Some(_), None) => PlanValidity::Stale,
9256 };
9257 if verdict == PlanValidity::Valid {
9258 return SessionDisposition::Kept;
9259 }
9260
9261 on_invalidate();
9262
9263 let refusal = if verdict == PlanValidity::AllocationChanged {
9264 match session.as_mut().map(|s| s.rebind_kv(kv)) {
9265 Some(Ok(())) => return SessionDisposition::Rebound,
9266 Some(Err(r)) => Some(r),
9267 None => None,
9271 }
9272 } else {
9273 None
9274 };
9275
9276 drop_session(session, ctx);
9277 SessionDisposition::Dropped(refusal)
9278}
9279
9280pub fn build_decode_causal_mask(cached_len: usize, seq: usize, max_seq_len: usize) -> Vec<f32> {
9281 let mut mask_data = vec![0.0_f32; seq * max_seq_len];
9282 for q_idx in 0..seq {
9283 let abs_q = cached_len + q_idx;
9284 for k_idx in (abs_q + 1)..max_seq_len {
9285 mask_data[q_idx * max_seq_len + k_idx] = f32::NEG_INFINITY;
9286 }
9287 }
9288 mask_data
9289}
9290
9291pub fn build_decode_causal_mask_windowed(
9331 cached_len: usize,
9332 seq: usize,
9333 max_seq_len: usize,
9334 window: usize,
9335) -> Vec<f32> {
9336 let mut mask_data = vec![0.0_f32; seq * max_seq_len];
9337 for q_idx in 0..seq {
9338 let abs_q = cached_len + q_idx;
9339 for k_idx in 0..max_seq_len {
9340 if k_idx > abs_q || k_idx + window <= abs_q {
9342 mask_data[q_idx * max_seq_len + k_idx] = f32::NEG_INFINITY;
9343 }
9344 }
9345 }
9346 mask_data
9347}
9348
9349#[cfg(test)]
9350mod decode_mask_tests {
9351 use super::{build_decode_causal_mask, build_decode_causal_mask_windowed};
9352
9353 fn attendable(row: &[f32]) -> Vec<u8> {
9356 row.iter().map(|&v| u8::from(v == 0.0)).collect()
9357 }
9358
9359 #[test]
9366 fn windowed_mask_excludes_positions_older_than_the_window() {
9367 let m = build_decode_causal_mask_windowed(3, 1, 6, 2);
9368 assert_eq!(
9369 attendable(&m),
9370 vec![0, 0, 1, 1, 0, 0],
9371 "window=2 at absolute position 3 must attend to exactly {{2, 3}}",
9372 );
9373 }
9374
9375 #[test]
9380 fn windowed_mask_offsets_each_row_by_cached_len() {
9381 let m = build_decode_causal_mask_windowed(1, 2, 5, 2);
9382 assert_eq!(
9383 attendable(&m[0..5]),
9384 vec![1, 1, 0, 0, 0],
9385 "row 0 = abs pos 1"
9386 );
9387 assert_eq!(
9388 attendable(&m[5..10]),
9389 vec![0, 1, 1, 0, 0],
9390 "row 1 = abs pos 2"
9391 );
9392 }
9393
9394 #[test]
9403 fn window_wider_than_capacity_is_byte_identical_to_the_dense_mask() {
9404 for (cached_len, seq, max_seq_len) in [(0, 1, 8), (3, 1, 8), (0, 4, 8), (2, 3, 8)] {
9405 let dense = build_decode_causal_mask(cached_len, seq, max_seq_len);
9406 let windowed =
9407 build_decode_causal_mask_windowed(cached_len, seq, max_seq_len, max_seq_len);
9408 assert_eq!(
9409 dense, windowed,
9410 "window == max_seq_len must equal dense at \
9411 (cached_len={cached_len}, seq={seq}, max_seq_len={max_seq_len})",
9412 );
9413 }
9414 }
9415
9416 #[test]
9425 fn decode_row_matches_the_prefill_mask_row_at_the_same_position() {
9426 let (n, window, max_seq_len) = (6_usize, 3_usize, 10_usize);
9427
9428 let mut prefill = vec![0.0_f32; n * n];
9430 for i in 0..n {
9431 for j in 0..n {
9432 if j > i || j + window <= i {
9433 prefill[i * n + j] = f32::NEG_INFINITY;
9434 }
9435 }
9436 }
9437
9438 for p in 0..n {
9439 let decode = build_decode_causal_mask_windowed(p, 1, max_seq_len, window);
9440 assert_eq!(
9441 attendable(&decode[0..n]),
9442 attendable(&prefill[p * n..(p + 1) * n]),
9443 "decode at cached_len={p} must match prefill row {p}",
9444 );
9445 assert!(
9446 decode[n..].iter().all(|&v| v == f32::NEG_INFINITY),
9447 "the unwritten tail beyond position {n} must stay masked",
9448 );
9449 }
9450 }
9451
9452 }
9493
9494pub fn flash_window_bounds(window: Option<usize>) -> (Option<usize>, Option<usize>) {
9532 match window {
9533 None => (None, None),
9534 Some(w) => (Some(w.saturating_sub(1)), Some(0)),
9535 }
9536}
9537
9538pub fn offer_flash_decode_arm_for_region(
9543 graph: &fuel_graph::SharedGraph,
9544 q: fuel_graph::NodeId,
9545 k: fuel_graph::NodeId,
9546 v: fuel_graph::NodeId,
9547 decomposed_out: fuel_graph::NodeId,
9548 reconverge: fuel_graph::NodeId,
9549 softmax_scale: f32,
9550 attended_len_sym: fuel_ir::SymId,
9551 attn_window: Option<usize>,
9552 softcap: Option<f32>,
9553 cap: fuel_dispatch::decode_flash::FlashArmCapability,
9554) -> crate::Result<Option<fuel_graph::NodeId>> {
9555 use fuel_dispatch::decode_flash::{DecodeFlashSpec, offer_decode_flash_arm};
9556 let (window_size_left, window_size_right) = flash_window_bounds(attn_window);
9557 let spec = DecodeFlashSpec {
9558 q,
9559 k,
9560 v,
9561 alibi: None,
9562 softmax_scale,
9563 causal: true,
9564 window_size_left,
9571 window_size_right,
9572 softcap,
9573 k_len: fuel_ir::DynScalar::Sym(attended_len_sym),
9574 decomposed_out,
9575 reconverge,
9576 };
9577 let mut g = graph.write().map_err(|_| {
9578 fuel_ir::Error::Msg("graph lock poisoned during flash-arm offer".into()).bt()
9579 })?;
9580 offer_decode_flash_arm(&mut g, &spec, cap)
9581}
9582
9583pub fn apply_affine_rms_norm(x: &Tensor, gain: &Arc<[f32]>, dim: usize, eps: f64) -> Tensor {
9584 assert_eq!(
9585 gain.len(),
9586 dim,
9587 "apply_affine_rms_norm: gain length must equal dim"
9588 );
9589 let normalized = x.rms_norm_last_dim(eps).unwrap();
9590 let gain_t = x
9596 .const_like_dtype(gain, Shape::from_dims(&[dim]), x.dtype())
9597 .expect("apply_affine_rms_norm: activation dtype must be F32 or BF16");
9598 normalized.broadcast_mul(&gain_t).unwrap()
9599}
9600
9601pub fn load_tensor_as_f32(
9608 st: &fuel_formats::safetensors::MmapedSafetensors,
9609 name: &str,
9610) -> crate::Result<Vec<f32>> {
9611 use safetensors::Dtype;
9612 let view = st.get(name)?;
9613 let bytes = view.data();
9614 match view.dtype() {
9615 Dtype::F32 => {
9616 let mut out = Vec::with_capacity(bytes.len() / 4);
9617 for chunk in bytes.as_chunks::<4>().0.iter() {
9618 out.push(f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
9619 }
9620 Ok(out)
9621 }
9622 Dtype::F64 => {
9623 let mut out = Vec::with_capacity(bytes.len() / 8);
9624 for chunk in bytes.as_chunks::<8>().0.iter() {
9625 let arr: [u8; 8] = *chunk;
9626 out.push(f64::from_le_bytes(arr) as f32);
9627 }
9628 Ok(out)
9629 }
9630 Dtype::BF16 => {
9631 let mut out = Vec::with_capacity(bytes.len() / 2);
9632 for chunk in bytes.as_chunks::<2>().0.iter() {
9633 let raw = u16::from_le_bytes([chunk[0], chunk[1]]);
9634 out.push(half::bf16::from_bits(raw).to_f32());
9635 }
9636 Ok(out)
9637 }
9638 Dtype::F16 => {
9639 let mut out = Vec::with_capacity(bytes.len() / 2);
9640 for chunk in bytes.as_chunks::<2>().0.iter() {
9641 let raw = u16::from_le_bytes([chunk[0], chunk[1]]);
9642 out.push(half::f16::from_bits(raw).to_f32());
9643 }
9644 Ok(out)
9645 }
9646 other => {
9647 crate::bail!("load_tensor_as_f32: unsupported dtype {other:?} for tensor {name:?}",)
9648 }
9649 }
9650}
9651
9652pub fn load_transposed_matrix(
9659 st: &fuel_formats::safetensors::MmapedSafetensors,
9660 name: &str,
9661 out_features: usize,
9662 in_features: usize,
9663) -> crate::Result<Vec<f32>> {
9664 let flat = load_tensor_as_f32(st, name)?;
9665 if flat.len() != out_features * in_features {
9666 crate::bail!(
9667 "load_transposed_matrix: tensor {name:?} has {} elements, expected {} ({out_features} × {in_features})",
9668 flat.len(),
9669 out_features * in_features,
9670 );
9671 }
9672 let mut out = vec![0.0_f32; out_features * in_features];
9676 for i in 0..out_features {
9677 for j in 0..in_features {
9678 out[j * out_features + i] = flat[i * in_features + j];
9679 }
9680 }
9681 Ok(out)
9682}
9683
9684pub fn load_transposed_matrix_preserve_dtype(
9696 st: &fuel_formats::safetensors::MmapedSafetensors,
9697 name: &str,
9698 out_features: usize,
9699 in_features: usize,
9700) -> crate::Result<WeightStorage> {
9701 use safetensors::Dtype;
9702 let view = st.get(name)?;
9703 let bytes = view.data();
9704 let expected = out_features * in_features;
9705 match view.dtype() {
9706 Dtype::BF16 => {
9707 if bytes.len() != expected * 2 {
9708 crate::bail!(
9709 "load_transposed_matrix_preserve_dtype: bf16 tensor {name:?} has {} bytes, expected {}",
9710 bytes.len(),
9711 expected * 2,
9712 );
9713 }
9714 let mut out = vec![half::bf16::ZERO; expected];
9717 for i in 0..out_features {
9718 for j in 0..in_features {
9719 let src_off = (i * in_features + j) * 2;
9720 let bits = u16::from_le_bytes([bytes[src_off], bytes[src_off + 1]]);
9721 out[j * out_features + i] = half::bf16::from_bits(bits);
9722 }
9723 }
9724 Ok(WeightStorage::BF16(Arc::from(out)))
9725 }
9726 _ => {
9727 let flat = load_transposed_matrix(st, name, out_features, in_features)?;
9731 Ok(WeightStorage::F32(Arc::from(flat)))
9732 }
9733 }
9734}
9735
9736#[derive(Debug, Clone, Copy, Default)]
9738pub enum SamplingStrategy {
9739 #[default]
9741 Greedy,
9742 Temperature { temp: f32, seed: u64 },
9747}
9748
9749fn argmax_logits(logits: &[f32]) -> fuel_ir::Result<u32> {
9758 if logits.is_empty() {
9759 return Err(fuel_ir::error::Error::Msg(
9760 "sample_logits: empty logits".into(),
9761 ));
9762 }
9763 if let Some(at) = logits.iter().position(|v| v.is_nan()) {
9764 return Err(fuel_ir::error::Error::Msg(format!(
9765 "sample_logits: logit {at} of {} is NaN (the model produced NaN); refusing to pick a token",
9766 logits.len()
9767 )));
9768 }
9769 let mut best = 0usize;
9770 for (i, &v) in logits.iter().enumerate() {
9771 if v > logits[best] {
9772 best = i;
9773 }
9774 }
9775 Ok(best as u32)
9776}
9777
9778pub fn sample_logits(
9786 logits: &[f32],
9787 strategy: SamplingStrategy,
9788 rng_state: &mut u64,
9789) -> fuel_ir::Result<u32> {
9790 match strategy {
9791 SamplingStrategy::Greedy => argmax_logits(logits),
9792 SamplingStrategy::Temperature { temp, .. } if temp.is_nan() || temp <= 0.0 => {
9795 argmax_logits(logits)
9796 }
9797 SamplingStrategy::Temperature { temp, .. } => {
9798 if let Some(at) = logits.iter().position(|v| !v.is_finite()) {
9799 return Err(fuel_ir::error::Error::Msg(format!(
9800 "sample_logits: logit {at} of {} is not finite; refusing to sample",
9801 logits.len()
9802 )));
9803 }
9804 if logits.is_empty() {
9805 return Err(fuel_ir::error::Error::Msg(
9806 "sample_logits: empty logits".into(),
9807 ));
9808 }
9809 let inv_temp = 1.0 / temp;
9812 let scaled: Vec<f32> = logits.iter().map(|&x| x * inv_temp).collect();
9813 let max = scaled.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
9814 let exp: Vec<f32> = scaled.iter().map(|&x| (x - max).exp()).collect();
9815 let sum: f32 = exp.iter().sum();
9816 let probs: Vec<f32> = exp.iter().map(|&x| x / sum).collect();
9817 Ok(sample_multinomial(&probs, rng_state))
9818 }
9819 }
9820}
9821
9822pub fn spec_argmax(logits: &[f32]) -> fuel_ir::Result<u32> {
9832 argmax_logits(logits)
9833}
9834
9835pub fn spec_softmax_temp(logits: &[f32], temp: f32) -> Vec<f32> {
9837 let inv_t = if temp == 0.0 { 1.0 } else { 1.0 / temp };
9838 let max = logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
9839 let exp: Vec<f32> = logits.iter().map(|&x| ((x - max) * inv_t).exp()).collect();
9840 let sum: f32 = exp.iter().sum();
9841 exp.iter().map(|&x| x / sum).collect()
9842}
9843
9844pub fn spec_next_u01(state: &mut u64) -> f32 {
9846 *state = state
9847 .wrapping_mul(6364136223846793005)
9848 .wrapping_add(1442695040888963407);
9849 (*state >> 32) as f32 / u32::MAX as f32
9850}
9851
9852pub fn spec_sample_cat(probs: &[f32], state: &mut u64) -> u32 {
9854 let u = spec_next_u01(state);
9855 let mut cum = 0.0_f32;
9856 for (i, &p) in probs.iter().enumerate() {
9857 cum += p;
9858 if u <= cum {
9859 return i as u32;
9860 }
9861 }
9862 (probs.len() - 1) as u32
9863}
9864
9865pub fn sample_multinomial(probs: &[f32], rng_state: &mut u64) -> u32 {
9869 *rng_state = rng_state
9871 .wrapping_mul(6364136223846793005)
9872 .wrapping_add(1442695040888963407);
9873 let u = (*rng_state >> 32) as f32 / u32::MAX as f32;
9874 let mut cumulative = 0.0_f32;
9875 for (i, &p) in probs.iter().enumerate() {
9876 cumulative += p;
9877 if u <= cumulative {
9878 return i as u32;
9879 }
9880 }
9881 (probs.len() - 1) as u32
9883}
9884
9885#[cfg(test)]
9886mod lora_tests {
9887 use super::*;
9888 use crate::Shape;
9889
9890 #[test]
9891 fn with_lora_matches_manual_base_plus_lora() {
9892 let in_f = 4;
9894 let out_f = 3;
9895 let rank = 2;
9896 let alpha = 8.0_f32;
9897
9898 let anchor =
9899 Tensor::from_f32(vec![0.0_f32; 1], Shape::from_dims(&[1]), &Device::cpu()).unwrap();
9900 let base_vec: Vec<f32> = (0..in_f * out_f).map(|i| (i as f32) * 0.1).collect();
9902 let lora_a_vec: Vec<f32> = (0..in_f * rank).map(|i| (i as f32) * 0.05).collect();
9903 let lora_b_vec: Vec<f32> = (0..rank * out_f).map(|i| (i as f32) * 0.02).collect();
9904
9905 let ws = WeightStorage::F32(Arc::from(base_vec.clone())).with_lora(
9906 Arc::from(lora_a_vec.clone()),
9907 Arc::from(lora_b_vec.clone()),
9908 rank,
9909 alpha,
9910 in_f,
9911 out_f,
9912 );
9913
9914 let batch = 2;
9916 let x_data: Vec<f32> = (0..batch * in_f).map(|i| (i as f32) * 0.1 + 0.5).collect();
9917 let x = anchor
9918 .const_f32_like(x_data.clone(), Shape::from_dims(&[batch, in_f]))
9919 .unwrap();
9920 let y = ws.apply_linear(&x, in_f, out_f).unwrap();
9921 let got = y.realize_f32().to_vec();
9922
9923 let mut expected = vec![0.0_f32; batch * out_f];
9925 for b in 0..batch {
9926 for j in 0..out_f {
9927 let mut acc = 0.0_f32;
9928 for k in 0..in_f {
9930 acc += x_data[b * in_f + k] * base_vec[k * out_f + j];
9931 }
9932 let scale = alpha as f64 / rank as f64;
9934 for r in 0..rank {
9935 let mut xar = 0.0_f32;
9936 for k in 0..in_f {
9937 xar += x_data[b * in_f + k] * lora_a_vec[k * rank + r];
9938 }
9939 acc += (xar * lora_b_vec[r * out_f + j]) * scale as f32;
9940 }
9941 expected[b * out_f + j] = acc;
9942 }
9943 }
9944
9945 for (i, (&e, &g)) in expected.iter().zip(got.iter()).enumerate() {
9946 let diff = (e - g).abs();
9947 assert!(
9948 diff <= 1e-4,
9949 "LoRA mismatch at {i}: expected {e}, got {g} (diff {diff})",
9950 );
9951 }
9952 }
9953
9954 #[test]
9955 #[should_panic(expected = "lora_a length")]
9956 fn with_lora_rejects_mismatched_a_shape() {
9957 let ws = WeightStorage::F32(Arc::from(vec![0.0_f32; 12])); let bad_a = Arc::from(vec![0.0_f32; 3]); let b = Arc::from(vec![0.0_f32; 6]); let _ = ws.with_lora(bad_a, b, 2, 8.0, 4, 3);
9961 }
9962
9963 #[test]
9975 fn apply_linear_errors_on_trailing_dim_mismatch() {
9976 let ws = WeightStorage::F32(Arc::from(vec![0.0_f32; 12])); let x = Tensor::from_f32(
9978 vec![0.0_f32; 10],
9979 Shape::from_dims(&[2, 5]), &Device::cpu(),
9981 )
9982 .unwrap();
9983 let err = ws
9984 .apply_linear(&x, 4, 3)
9985 .expect_err("must not panic, must Err");
9986 let msg = err.to_string();
9987 assert!(
9988 msg.contains("trailing dim 4"),
9989 "error should name the expected trailing dim, got: {msg}",
9990 );
9991 }
9992
9993 #[test]
9994 fn apply_linear_errors_on_q4_0_stored_shape_mismatch() {
9995 let ws = WeightStorage::Q4_0 {
9998 words: Arc::from(vec![0_u32; 8]),
9999 bytes_len: 18, in_features: 4,
10001 out_features: 4,
10002 };
10003 let x =
10004 Tensor::from_f32(vec![0.0_f32; 8], Shape::from_dims(&[2, 4]), &Device::cpu()).unwrap();
10005 let err = ws
10008 .apply_linear(&x, 4, 7)
10009 .expect_err("must not panic, must Err");
10010 let msg = err.to_string();
10011 assert!(
10012 msg.contains("Q4_0 shape mismatch"),
10013 "error should name the stored/requested disagreement, got: {msg}",
10014 );
10015 }
10016
10017 #[test]
10018 fn apply_linear_with_bias_errors_on_wrong_bias_length() {
10019 let ws = WeightStorage::F32(Arc::from(vec![0.0_f32; 12])); let x =
10021 Tensor::from_f32(vec![0.0_f32; 8], Shape::from_dims(&[2, 4]), &Device::cpu()).unwrap();
10022 let bias: Arc<[f32]> = Arc::from(vec![0.0_f32; 2]); let err = ws
10024 .apply_linear_with_bias(&x, 4, 3, bias)
10025 .expect_err("wrong-length bias must Err in EVERY profile, not just debug");
10026 assert!(
10027 err.to_string().contains("bias len"),
10028 "error should name the bias length, got: {err}",
10029 );
10030 }
10031}
10032
10033#[cfg(test)]
10034mod safetensors_bridge_tests {
10035 use super::*;
10036
10037 #[test]
10038 fn from_safetensors_bytes_round_trip_f32() {
10039 let original: Vec<f32> = vec![1.0, -2.5, 3.25, 0.0];
10043 let mut bytes = Vec::with_capacity(original.len() * 4);
10044 for &v in &original {
10045 bytes.extend_from_slice(&v.to_le_bytes());
10046 }
10047 let t =
10048 Tensor::from_safetensors_bytes(&bytes, safetensors::Dtype::F32, &[4], &Device::cpu())
10049 .unwrap();
10050 assert_eq!(t.shape().dims(), &[4]);
10051 assert_eq!(t.dtype(), DType::F32);
10052 assert_eq!(t.realize_f32(), original);
10053 }
10054
10055 #[test]
10056 fn from_safetensors_bytes_round_trip_bf16() {
10057 let original_f32: Vec<f32> = vec![0.5, -1.0, 2.0, 4.0];
10058 let bf16_vec: Vec<half::bf16> = original_f32
10059 .iter()
10060 .map(|&v| half::bf16::from_f32(v))
10061 .collect();
10062 let mut bytes = Vec::with_capacity(bf16_vec.len() * 2);
10063 for b in &bf16_vec {
10064 bytes.extend_from_slice(&b.to_bits().to_le_bytes());
10065 }
10066 let t =
10067 Tensor::from_safetensors_bytes(&bytes, safetensors::Dtype::BF16, &[4], &Device::cpu())
10068 .unwrap();
10069 assert_eq!(t.dtype(), DType::BF16);
10070 let realized = t.realize_bf16();
10073 assert_eq!(realized, bf16_vec);
10074 }
10075
10076 #[test]
10077 fn from_safetensors_bytes_rejects_wrong_byte_count() {
10078 let bad_bytes = vec![0_u8; 4];
10081 let result = Tensor::from_safetensors_bytes(
10082 &bad_bytes,
10083 safetensors::Dtype::F32,
10084 &[3],
10085 &Device::cpu(),
10086 );
10087 assert!(result.is_err());
10088 }
10089}
10090
10091#[cfg(test)]
10100mod phase_a1_wrapper_tests {
10101 use super::*;
10102
10103 fn cpu_f32(data: Vec<f32>, shape: &[usize]) -> Tensor {
10104 Tensor::from_f32(data, shape.to_vec(), &Device::cpu()).unwrap()
10105 }
10106
10107 #[test]
10108 fn unsqueeze_adds_size_one_dim() {
10109 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
10110 let out = t.unsqueeze(0_usize).unwrap();
10111 assert_eq!(out.shape().dims(), &[1, 2, 2]);
10112 assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0, 4.0]);
10113 }
10114
10115 #[test]
10116 fn unsqueeze_errors_out_of_bounds() {
10117 let t = cpu_f32(vec![1.0, 2.0], &[2]);
10118 assert!(t.unsqueeze(0_usize).is_ok());
10120 assert!(t.unsqueeze(1_usize).is_ok());
10121 assert!(t.unsqueeze(2_usize).is_err());
10122 }
10123
10124 #[test]
10125 fn try_reshape_errors_on_size_mismatch() {
10126 let t = cpu_f32(vec![1.0; 6], &[2, 3]);
10127 assert!(t.reshape(vec![3, 2]).is_ok());
10128 assert!(t.reshape(vec![2, 2]).is_err());
10129 }
10130
10131 #[test]
10132 fn try_permute_validates_axes() {
10133 let t = cpu_f32(vec![0.0; 24], &[2, 3, 4]);
10134 assert!(t.permute((2_usize, 0_usize, 1_usize)).is_ok());
10136 assert!(t.permute([2_usize, 0, 1]).is_ok());
10137 assert!(t.permute([0_usize, 1]).is_err()); assert!(t.permute([0_usize, 0, 1]).is_err()); }
10140
10141 #[test]
10142 fn try_transpose_requires_rank_two_plus() {
10143 let scalar = cpu_f32(vec![1.0], &[1]);
10144 let _ = scalar.transpose();
10146 }
10147
10148 #[test]
10149 fn triu_tril_shape_preserved() {
10150 let t = cpu_f32(vec![1.0; 9], &[3, 3]);
10151 let upper = t.triu(0).unwrap();
10152 let lower = t.tril(0).unwrap();
10153 assert_eq!(upper.shape().dims(), &[3, 3]);
10154 assert_eq!(lower.shape().dims(), &[3, 3]);
10155 assert_eq!(
10157 lower.realize_f32(),
10158 vec![1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0]
10159 );
10160 }
10161
10162 #[test]
10163 fn triu_rejects_rank_one() {
10164 let t = cpu_f32(vec![1.0, 2.0], &[2]);
10165 assert!(t.triu(0).is_err());
10166 }
10167
10168 #[test]
10169 fn log_softmax_last_dim_shape_preserved() {
10170 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
10171 let out = t.log_softmax_last_dim().unwrap();
10172 assert_eq!(out.shape().dims(), &[2, 2]);
10173 for v in out.realize_f32() {
10175 assert!(v <= 0.0 + 1e-6, "log_softmax produced positive value: {v}");
10176 }
10177 }
10178
10179 #[test]
10180 fn softmax_general_axis_matches_hand_computed_rank3_middle_axis() {
10181 let data: Vec<f32> = vec![
10190 -1.0, 0.0, 0.0, -3.0, -2.0, -1.0, -2.0, -1.0, -1.0, -1.0, 0.0, 0.0, ];
10199 let t = cpu_f32(data, &[2, 3, 2]);
10200 let out = t.softmax(1_usize).unwrap();
10201 assert_eq!(out.shape().dims(), &[2, 3, 2]);
10202 let v = out.realize_f32();
10203
10204 let lane_softmax = |xs: [f32; 3]| -> [f32; 3] {
10206 let m = xs.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
10207 let exps = [(xs[0] - m).exp(), (xs[1] - m).exp(), (xs[2] - m).exp()];
10208 let s = exps[0] + exps[1] + exps[2];
10209 [exps[0] / s, exps[1] / s, exps[2] / s]
10210 };
10211 let lanes: [[f32; 3]; 4] = [
10213 [-1.0, 0.0, -2.0], [0.0, -3.0, -1.0], [-2.0, -1.0, 0.0], [-1.0, -1.0, 0.0], ];
10218 let refs: Vec<[f32; 3]> = lanes.iter().map(|l| lane_softmax(*l)).collect();
10219
10220 for b in 0..2 {
10222 for c in 0..2 {
10223 let lane_ix = b * 2 + c;
10224 for r in 0..3 {
10225 let got = v[b * 6 + r * 2 + c];
10226 let want = refs[lane_ix][r];
10227 assert!(
10228 (got - want).abs() < 1e-6,
10229 "softmax mismatch at (b={b}, r={r}, c={c}): got {got}, want {want}",
10230 );
10231 }
10232 let sum: f32 = (0..3).map(|r| v[b * 6 + r * 2 + c]).sum();
10234 assert!((sum - 1.0).abs() < 1e-6, "lane (b={b},c={c}) sums to {sum}");
10235 }
10236 }
10237 }
10238
10239 #[test]
10240 fn softmax_last_axis_matches_softmax_last_dim() {
10241 let data: Vec<f32> = vec![
10242 1.0, 2.0, -1.0, 0.5, 0.0, -2.0, 3.0, 1.5, 4.0, -1.0, 2.0, 0.0, -3.0, 0.25, 0.75, 1.0,
10244 ];
10245 let t = cpu_f32(data, &[2, 2, 4]);
10246 let via_general = t.softmax(2_usize).unwrap();
10247 let via_fused = t.softmax_last_dim().unwrap();
10248 assert_eq!(via_general.shape().dims(), via_fused.shape().dims());
10249 let g = via_general.realize_f32();
10250 let f = via_fused.realize_f32();
10251 assert_eq!(g.len(), f.len());
10252 for (i, (a, b)) in g.iter().zip(f.iter()).enumerate() {
10253 assert!(
10254 (a - b).abs() < 1e-6,
10255 "softmax (general axis=2) vs softmax_last_dim diverge at {i}: {a} vs {b}",
10256 );
10257 }
10258 }
10259
10260 #[test]
10261 fn log_softmax_general_axis_matches_hand_computed_rank3_middle_axis() {
10262 let data: Vec<f32> = vec![
10265 -1.0, 0.0, 0.0, -3.0, -2.0, -1.0, -2.0, -1.0, -1.0, -1.0, 0.0, 0.0,
10266 ];
10267 let t = cpu_f32(data, &[2, 3, 2]);
10268 let out = t.log_softmax(1_usize).unwrap();
10269 assert_eq!(out.shape().dims(), &[2, 3, 2]);
10270 let v = out.realize_f32();
10271
10272 let lane_log_softmax = |xs: [f32; 3]| -> [f32; 3] {
10273 let m = xs.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
10274 let shifted = [xs[0] - m, xs[1] - m, xs[2] - m];
10275 let lse = (shifted[0].exp() + shifted[1].exp() + shifted[2].exp()).ln();
10276 [shifted[0] - lse, shifted[1] - lse, shifted[2] - lse]
10277 };
10278 let lanes: [[f32; 3]; 4] = [
10279 [-1.0, 0.0, -2.0],
10280 [0.0, -3.0, -1.0],
10281 [-2.0, -1.0, 0.0],
10282 [-1.0, -1.0, 0.0],
10283 ];
10284 let refs: Vec<[f32; 3]> = lanes.iter().map(|l| lane_log_softmax(*l)).collect();
10285
10286 for b in 0..2 {
10287 for c in 0..2 {
10288 let lane_ix = b * 2 + c;
10289 for r in 0..3 {
10290 let got = v[b * 6 + r * 2 + c];
10291 let want = refs[lane_ix][r];
10292 assert!(
10293 (got - want).abs() < 1e-6,
10294 "log_softmax mismatch at (b={b}, r={r}, c={c}): got {got}, want {want}",
10295 );
10296 assert!(got <= 1e-6, "log_softmax produced positive value: {got}");
10298 }
10299 }
10300 }
10301 }
10302
10303 #[test]
10304 fn log_softmax_last_axis_matches_log_softmax_last_dim() {
10305 let data: Vec<f32> = vec![
10306 1.0, 2.0, -1.0, 0.5, 0.0, -2.0, 3.0, 1.5, 4.0, -1.0, 2.0, 0.0, -3.0, 0.25, 0.75, 1.0,
10307 ];
10308 let t = cpu_f32(data, &[2, 2, 4]);
10309 let via_general = t.log_softmax(2_usize).unwrap();
10310 let via_fused = t.log_softmax_last_dim().unwrap();
10311 assert_eq!(via_general.shape().dims(), via_fused.shape().dims());
10312 let g = via_general.realize_f32();
10313 let f = via_fused.realize_f32();
10314 assert_eq!(g.len(), f.len());
10315 for (i, (a, b)) in g.iter().zip(f.iter()).enumerate() {
10316 assert!(
10317 (a - b).abs() < 1e-6,
10318 "log_softmax (general axis=2) vs log_softmax_last_dim diverge at {i}: {a} vs {b}",
10319 );
10320 }
10321 }
10322
10323 #[test]
10324 fn argmin_dim_drops_reduced_axis() {
10325 let t = cpu_f32(vec![3.0, 1.0, 2.0, 0.5, 5.0, 4.0], &[2, 3]);
10326 let out = t.argmin_dim(1_usize).unwrap();
10327 assert_eq!(out.shape().dims(), &[2]);
10328 assert_eq!(out.dtype(), DType::U32);
10329 assert_eq!(out.realize_u32(), vec![1, 0]);
10330 }
10331
10332 #[test]
10333 fn masked_fill_smoke() {
10334 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
10335 let probe = t
10338 .const_f32_like(vec![0.0, 1.0, 1.0, 0.0], vec![2, 2])
10339 .unwrap();
10340 let threshold = t.const_f32_like(vec![0.5; 4], vec![2, 2]).unwrap();
10341 let mask = probe.gt(&threshold).unwrap(); let out = t.masked_fill(&mask, fuel_ir::Scalar::F32(-9.0)).unwrap();
10343 assert_eq!(out.realize_f32(), vec![1.0, -9.0, -9.0, 4.0]);
10344 }
10345
10346 #[test]
10352 fn bool_is_distinguishable_from_u8_end_to_end() {
10353 let t = cpu_f32(vec![0.0, 5.0, 3.0, 0.0], &[4]);
10358 let thr = t.const_f32_like(vec![0.5; 4], vec![4]).unwrap();
10359 let mask = t.gt(&thr).unwrap();
10360 assert_eq!(mask.dtype(), DType::Bool, "gt yields Bool, not U8");
10361 assert_eq!(mask.realize_u8(), vec![0, 1, 1, 0], "mask bytes are 0/1");
10362
10363 let u8_vals = t
10370 .const_f32_like(vec![0.0, 5.0, 3.0, 0.0], vec![4])
10371 .unwrap()
10372 .to_dtype(DType::U8)
10373 .unwrap();
10374 assert_eq!(u8_vals.dtype(), DType::U8);
10375 assert_eq!(
10376 u8_vals.realize_u8(),
10377 vec![0, 5, 3, 0],
10378 "negative control: the U8 source must really hold 5 and 3, else the \
10379 conversion assertion below cannot discriminate"
10380 );
10381
10382 let as_bool = u8_vals.to_dtype(DType::Bool).unwrap();
10386 assert_eq!(as_bool.dtype(), DType::Bool);
10387 assert_eq!(
10388 as_bool.realize_u8(),
10389 vec![0, 1, 1, 0],
10390 "U8->Bool must CONVERT (5 -> 1), not reinterpret (5 -> 5)"
10391 );
10392
10393 assert_eq!(
10395 as_bool.to_dtype(DType::F32).unwrap().realize_f32(),
10396 vec![0.0, 1.0, 1.0, 0.0],
10397 "Bool->F32 yields 0.0/1.0"
10398 );
10399 assert_eq!(
10402 mask.to_dtype(DType::U8).unwrap().realize_u8(),
10403 vec![0, 1, 1, 0]
10404 );
10405
10406 let err = t.masked_fill(&u8_vals, fuel_ir::Scalar::F32(-9.0));
10411 assert!(
10412 err.is_err(),
10413 "a U8 mask must be REJECTED by masked_fill — Bool and U8 are \
10414 byte-identical, so accepting it would 'work' and erase the distinction"
10415 );
10416 }
10417
10418 #[test]
10432 fn float_to_bool_lowering_preserves_ieee_semantics() {
10433 let t = cpu_f32(
10434 vec![
10435 0.0,
10436 -0.0,
10437 5.0,
10438 -3.0,
10439 f32::NAN,
10440 f32::INFINITY,
10441 f32::NEG_INFINITY,
10442 ],
10443 &[7],
10444 );
10445 let b = t.to_dtype(DType::Bool).unwrap();
10446 assert_eq!(b.dtype(), DType::Bool, "to_dtype(Bool) still yields Bool");
10447 assert_eq!(
10448 b.realize_u8(),
10449 vec![0, 0, 1, 1, 1, 1, 1],
10450 "0 and -0.0 are false; every other value including NaN and both \
10451 infinities is true",
10452 );
10453 }
10454
10455 #[test]
10456 fn index_add_smoke() {
10457 let base = cpu_f32(vec![1.0, 1.0, 1.0, 1.0], &[2, 2]);
10458 let src = base
10459 .const_f32_like(vec![10.0, 20.0, 30.0, 40.0], vec![2, 2])
10460 .unwrap();
10461 let indices = base.const_u32_like(vec![0_u32, 0_u32], vec![2]).unwrap();
10462 let out = base.index_add(0, &indices, &src).unwrap();
10463 assert_eq!(out.shape().dims(), &[2, 2]);
10464 let v = out.realize_f32();
10466 assert_eq!(v[0], 41.0); assert_eq!(v[1], 61.0); assert_eq!(v[2], 1.0);
10469 assert_eq!(v[3], 1.0);
10470 }
10471
10472 #[test]
10473 fn scatter_add_smoke() {
10474 let base = cpu_f32(vec![0.0, 0.0, 0.0, 0.0], &[2, 2]);
10475 let src = base
10476 .const_f32_like(vec![5.0, 6.0, 7.0, 8.0], vec![2, 2])
10477 .unwrap();
10478 let indices = base
10479 .const_u32_like(vec![0_u32, 1_u32, 1_u32, 0_u32], vec![2, 2])
10480 .unwrap();
10481 let out = base.scatter_add(0, &indices, &src).unwrap();
10482 assert_eq!(out.shape().dims(), &[2, 2]);
10483 }
10484
10485 #[test]
10486 fn inplace_activations_compile_and_run() {
10487 let t = cpu_f32(vec![-1.0, 0.5, -3.0, 2.0], &[4]);
10488 let r = cpu_f32(vec![-1.0, 0.5, -3.0, 2.0], &[4]).relu_inplace();
10490 let _ = cpu_f32(vec![-1.0, 0.5, -3.0, 2.0], &[4]).silu_inplace();
10491 let _ = cpu_f32(vec![-1.0, 0.5, -3.0, 2.0], &[4]).gelu_tanh_inplace();
10492 let _ = cpu_f32(vec![-1.0, 0.5, -3.0, 2.0], &[4]).tanh_inplace();
10493 let _ = cpu_f32(vec![-1.0, 0.5, -3.0, 2.0], &[4]).sigmoid_inplace();
10494 let _ = t.affine_inplace(2.0, 1.0);
10495 let v = r.realize_f32();
10497 assert_eq!(v, vec![0.0, 0.5, 0.0, 2.0]);
10498 }
10499
10500 #[test]
10501 fn const_f64_like_round_trips() {
10502 let anchor = cpu_f32(vec![0.0], &[1]);
10503 let t = anchor.const_f64_like(vec![1.5, 2.5, 3.5], vec![3]).unwrap();
10504 assert_eq!(t.shape().dims(), &[3]);
10505 assert_eq!(t.dtype(), DType::F64);
10506 assert_eq!(t.realize_f64(), vec![1.5, 2.5, 3.5]);
10507 }
10508
10509 #[test]
10510 fn const_i64_like_round_trips() {
10511 let anchor = cpu_f32(vec![0.0], &[1]);
10512 let t = anchor.const_i64_like(vec![-1_i64, 2, -3], vec![3]).unwrap();
10513 assert_eq!(t.shape().dims(), &[3]);
10514 assert_eq!(t.dtype(), DType::I64);
10515 }
10516
10517 #[test]
10518 fn on_device_smoke_cpu() {
10519 let t = cpu_f32(vec![1.0, 2.0], &[2]);
10520 let pinned = t.on_device(&Device::cpu());
10521 assert_eq!(pinned.realize_f32(), vec![1.0, 2.0]);
10522 }
10523
10524 #[test]
10525 fn copy_to_device_same_device_round_trips() {
10526 let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
10527 let copied = t.copy_to_device(&Device::cpu());
10528 assert_eq!(copied.realize_f32(), vec![1.0, 2.0, 3.0]);
10529 }
10530}
10531
10532#[cfg(test)]
10536mod phase_a2_composite_tests {
10537 use super::*;
10538
10539 fn cpu_f32(data: Vec<f32>, shape: &[usize]) -> Tensor {
10540 Tensor::from_f32(data, shape.to_vec(), &Device::cpu()).unwrap()
10541 }
10542
10543 #[test]
10544 fn transpose_last_two_swaps_last_two_dims() {
10545 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
10546 let out = t.transpose_last_two().unwrap();
10547 assert_eq!(out.shape().dims(), &[3, 2]);
10548 assert_eq!(out.realize_f32(), vec![1.0, 4.0, 2.0, 5.0, 3.0, 6.0]);
10549 }
10550
10551 #[test]
10552 fn t_is_alias_of_transpose_last_two() {
10553 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
10554 assert_eq!(
10555 t.t().unwrap().realize_f32(),
10556 t.transpose_last_two().unwrap().realize_f32()
10557 );
10558 }
10559
10560 #[test]
10561 fn transpose_dims_swaps_arbitrary_axes() {
10562 let t = cpu_f32((0..24).map(|i| i as f32).collect(), &[2, 3, 4]);
10563 let out = t.transpose_dims(0, 2).unwrap();
10564 assert_eq!(out.shape().dims(), &[4, 3, 2]);
10565 }
10566
10567 #[test]
10568 fn transpose_dims_identity_when_same_axis() {
10569 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
10570 let out = t.transpose_dims(0, 0).unwrap();
10571 assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0, 4.0]);
10572 }
10573
10574 #[test]
10575 fn transpose_dims_errors_out_of_bounds() {
10576 let t = cpu_f32(vec![0.0; 6], &[2, 3]);
10577 assert!(t.transpose_dims(0, 2).is_err());
10578 assert!(t.transpose_dims(5, 0).is_err());
10579 }
10580
10581 #[test]
10582 fn flatten_merges_middle_dims() {
10583 let t = cpu_f32(vec![0.0; 24], &[2, 3, 4]);
10584 let out = t.flatten(0, 1).unwrap();
10585 assert_eq!(out.shape().dims(), &[6, 4]);
10586 }
10587
10588 #[test]
10589 fn flatten_to_merges_leading_dims() {
10590 let t = cpu_f32(vec![0.0; 24], &[2, 3, 4]);
10591 let out = t.flatten_to(1).unwrap();
10592 assert_eq!(out.shape().dims(), &[6, 4]);
10593 }
10594
10595 #[test]
10596 fn flatten_from_merges_trailing_dims() {
10597 let t = cpu_f32(vec![0.0; 24], &[2, 3, 4]);
10598 let out = t.flatten_from(1).unwrap();
10599 assert_eq!(out.shape().dims(), &[2, 12]);
10600 }
10601
10602 #[test]
10603 fn flatten_all_produces_rank_one() {
10604 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
10605 let out = t.flatten_all().unwrap();
10606 assert_eq!(out.shape().dims(), &[6]);
10607 assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
10608 }
10609
10610 #[test]
10620 fn rope_batched_matches_single_position_rope_row_by_row() {
10621 let lcg = |n: usize, seed: u32| -> Vec<f32> {
10622 let mut s = seed;
10623 (0..n)
10624 .map(|_| {
10625 s = s.wrapping_mul(1103515245).wrapping_add(12345);
10626 ((s >> 16) as u16 as f32 / 65535.0 - 0.5) * 0.5
10627 })
10628 .collect()
10629 };
10630 let (b, heads, hd) = (3usize, 4usize, 8usize);
10631 let base = 10000.0f64;
10632 let positions = [0usize, 7, 3];
10633
10634 let x_data = lcg(b * heads * hd, 11);
10635 let x = cpu_f32(x_data.clone(), &[b, heads, 1, hd]);
10636 let (cos, sin) = x.rope_tables_const_batched(base, &positions, hd);
10637 let got = x.rope_batched(&cos, &sin).unwrap().realize_f32();
10638
10639 let per_row = heads * hd;
10640 for (row, &pos) in positions.iter().enumerate() {
10641 let row_data = x_data[row * per_row..(row + 1) * per_row].to_vec();
10642 let xr = cpu_f32(row_data, &[1, heads, 1, hd]);
10643 let (c, s) = xr.rope_tables_const(base, pos, 1, hd);
10644 let want = xr
10645 .rope_with_tables_decomposed(&c, &s)
10646 .unwrap()
10647 .realize_f32();
10648 assert_eq!(
10649 &got[row * per_row..(row + 1) * per_row],
10650 &want[..],
10651 "row {row} (position {pos}) != decomposed RoPE at that position",
10652 );
10653 }
10654
10655 let shared = [positions[0]; 3];
10660 let (c0, s0) = x.rope_tables_const_batched(base, &shared, hd);
10661 let wrong = x.rope_batched(&c0, &s0).unwrap().realize_f32();
10662 for (row, &pos) in positions.iter().enumerate().skip(1) {
10663 assert_ne!(
10664 &wrong[row * per_row..(row + 1) * per_row],
10665 &got[row * per_row..(row + 1) * per_row],
10666 "CONTROL: row {row} at shared position 0 matched its own position \
10667 {pos} — per-row RoPE not applied, or comparison blind to it",
10668 );
10669 }
10670 }
10671
10672 #[test]
10673 fn flatten_errors_on_bad_range() {
10674 let t = cpu_f32(vec![0.0; 6], &[2, 3]);
10675 assert!(t.flatten(0, 5).is_err());
10676 assert!(t.flatten(2, 1).is_err()); }
10678
10679 #[test]
10680 fn split_heads_then_merge_heads_round_trip() {
10681 let x = cpu_f32((0..12).map(|i| i as f32).collect(), &[1, 2, 6]);
10683 let split = x.split_heads(2, 3).unwrap();
10684 assert_eq!(split.shape().dims(), &[1, 2, 2, 3]);
10685 let merged = split.merge_heads().unwrap();
10686 assert_eq!(merged.shape().dims(), &[1, 2, 6]);
10687 let m = merged.realize_f32();
10688 let original = x.realize_f32();
10689 for (a, b) in m.iter().zip(original.iter()) {
10690 assert!((a - b).abs() < 1e-7, "{a} vs {b}");
10691 }
10692 }
10693
10694 #[test]
10695 fn rope_tables_const_shapes_and_anchoring() {
10696 let anchor = cpu_f32(vec![0.0_f32; 8], &[1, 4, 2]);
10697 let (cos, sin) = anchor.rope_tables_const(10_000.0, 0, 4, 8);
10698 assert_eq!(cos.shape().dims(), &[4, 8]);
10699 assert_eq!(sin.shape().dims(), &[4, 8]);
10700 let cv = cos.realize_f32();
10702 let sv = sin.realize_f32();
10703 for i in 0..8 {
10705 assert!((cv[i] - 1.0).abs() < 1e-5, "cos[0,{i}] = {}", cv[i]);
10706 assert!(sv[i].abs() < 1e-5, "sin[0,{i}] = {}", sv[i]);
10707 }
10708 }
10709
10710 #[test]
10711 fn embed_tokens_shape_and_lookup() {
10712 let vocab_size = 5;
10715 let hidden = 3;
10716 let table: Vec<f32> = (0..vocab_size)
10717 .flat_map(|i| vec![i as f32, i as f32 + 0.5, i as f32 + 1.0])
10718 .collect();
10719 let tokens = vec![1_u32, 3, 0];
10720 let out = Tensor::embed_tokens(
10721 std::sync::Arc::from(table),
10722 vocab_size,
10723 hidden,
10724 &tokens,
10725 &crate::Device::cpu(),
10726 )
10727 .unwrap();
10728 assert_eq!(out.shape().dims(), &[1, 3, hidden]);
10729 let v = out.realize_f32();
10730 let want = [
10731 1.0_f32, 1.5, 2.0, 3.0, 3.5, 4.0, 0.0, 0.5, 1.0, ];
10735 for (i, (&got, &exp)) in v.iter().zip(want.iter()).enumerate() {
10736 assert!((got - exp).abs() < 1e-5, "row {i}: got={got} want={exp}");
10737 }
10738 }
10739
10740 #[test]
10741 fn embed_tokens_anchored_lives_on_receiver_graph() {
10742 let vocab_size = 4;
10746 let hidden = 2;
10747 let table: Vec<f32> = (0..vocab_size)
10748 .flat_map(|i| vec![i as f32, i as f32 * 2.0])
10749 .collect();
10750 let table_arc: std::sync::Arc<[f32]> = std::sync::Arc::from(table);
10751 let tokens = vec![2_u32, 1];
10752
10753 let anchor = cpu_f32(vec![0.0_f32], &[1]);
10754 let embedded = anchor
10755 .embed_tokens_anchored(
10756 std::sync::Arc::clone(&table_arc),
10757 vocab_size,
10758 hidden,
10759 &tokens,
10760 )
10761 .unwrap();
10762 assert_eq!(embedded.shape().dims(), &[1, 2, hidden]);
10763
10764 let one_scaled = anchor
10766 .const_f32_like(std::sync::Arc::from(vec![1.0_f32]), Shape::from_dims(&[1]))
10767 .unwrap();
10768 let _ = embedded
10769 .add(
10770 &one_scaled
10771 .reshape(Shape::from_dims(&[1, 1, 1]))
10772 .unwrap()
10773 .broadcast_to(Shape::from_dims(&[1, 2, hidden]))
10774 .unwrap(),
10775 )
10776 .unwrap();
10777 let v = embedded.realize_f32();
10778 let want = [
10779 2.0_f32, 4.0, 1.0, 2.0, ];
10782 for (i, (&got, &exp)) in v.iter().zip(want.iter()).enumerate() {
10783 assert!((got - exp).abs() < 1e-5, "row {i}: got={got} want={exp}");
10784 }
10785 }
10786
10787 #[test]
10788 fn embed_tokens_empty_returns_error() {
10789 let r = Tensor::embed_tokens(
10790 std::sync::Arc::from(vec![0.0_f32]),
10791 1,
10792 1,
10793 &[],
10794 &crate::Device::cpu(),
10795 );
10796 assert!(r.is_err());
10797 }
10798
10799 #[test]
10800 fn softcap_matches_tanh_form() {
10801 let x = cpu_f32(vec![0.0_f32, 5.0, -5.0, 30.0], &[1, 4]);
10803 let capped = x.softcap(10.0).realize_f32();
10804 let expect = [0.0_f32, 4.6212, -4.6212, 9.9505];
10806 for (i, (&got, &want)) in capped.iter().zip(expect.iter()).enumerate() {
10807 assert!(
10808 (got - want).abs() < 1e-3,
10809 "softcap[{i}] got={got} want={want}"
10810 );
10811 }
10812 }
10813
10814 #[test]
10815 fn softcap_optional_none_returns_input_unchanged() {
10816 let x = cpu_f32(vec![1.0_f32, -2.0, 30.0], &[1, 3]);
10817 let out = x.softcap_optional(None).realize_f32();
10818 let expect = [1.0_f32, -2.0, 30.0];
10819 for (g, w) in out.iter().zip(expect.iter()) {
10820 assert!((g - w).abs() < 1e-6);
10821 }
10822 let out = x.softcap_optional(Some(0.0)).realize_f32();
10824 for (g, w) in out.iter().zip(expect.iter()) {
10825 assert!((g - w).abs() < 1e-6);
10826 }
10827 }
10828
10829 #[test]
10830 fn rope_partial_full_dim_matches_rope_with_tables() {
10831 let qk = cpu_f32(vec![1.0_f32; 1 * 1 * 2 * 4], &[1, 1, 2, 4]);
10833 let (cos, sin) = qk.rope_tables_const(10_000.0, 0, 2, 4);
10834 let via_partial = qk.rope_partial(&cos, &sin, 4).unwrap();
10835 let via_full = qk.rope_with_tables(&cos, &sin).unwrap();
10836 let a = via_partial.realize_f32();
10837 let b = via_full.realize_f32();
10838 for (i, (av, bv)) in a.iter().zip(b.iter()).enumerate() {
10839 assert!((av - bv).abs() < 1e-6, "{i}: {av} vs {bv}");
10840 }
10841 }
10842
10843 #[test]
10844 fn rope_partial_pass_through_suffix_unchanged() {
10845 let qk = cpu_f32(
10849 vec![
10850 1.0_f32, 2.0, 3.0, 4.0,
10852 ],
10853 &[1, 1, 1, 4],
10854 );
10855 let (cos, sin) = qk.rope_tables_const(10_000.0, 0, 1, 2);
10856 let out = qk.rope_partial(&cos, &sin, 2).unwrap().realize_f32();
10857 for (i, &v) in out.iter().enumerate() {
10858 let expect = [1.0_f32, 2.0, 3.0, 4.0][i];
10859 assert!((v - expect).abs() < 1e-6, "{i}: {v} != {expect}");
10860 }
10861 }
10862
10863 #[test]
10864 fn add_optional_trailing_bias_none_returns_input_unchanged() {
10865 let a = cpu_f32(vec![1.0_f32, 2.0, 3.0], &[1, 3]);
10866 let original = a.realize_f32();
10867 let out = a.add_optional_trailing_bias(None).unwrap();
10868 assert_eq!(out.realize_f32(), original);
10869 }
10870
10871 #[test]
10872 fn add_optional_trailing_bias_some_applies_add() {
10873 let a = cpu_f32(vec![1.0_f32, 2.0, 3.0], &[1, 3]);
10874 let bias = std::sync::Arc::<[f32]>::from(vec![10.0_f32, 20.0, 30.0]);
10875 let out = a.add_optional_trailing_bias(Some(&bias)).unwrap();
10876 assert_eq!(out.realize_f32(), vec![11.0, 22.0, 33.0]);
10877 }
10878
10879 #[test]
10880 fn add_trailing_bias_broadcasts_across_leading_dims() {
10881 let x = cpu_f32(vec![1.0_f32, 2.0, 3.0, 10.0, 20.0, 30.0], &[2, 3]);
10883 let bias = std::sync::Arc::<[f32]>::from(vec![100.0_f32, 200.0, 300.0]);
10884 let out = x.add_trailing_bias(bias).unwrap();
10885 assert_eq!(out.shape().dims(), &[2, 3]);
10886 let v = out.realize_f32();
10887 assert_eq!(v, vec![101.0, 202.0, 303.0, 110.0, 220.0, 330.0]);
10888 }
10889
10890 #[test]
10891 fn rms_norm_affine_with_offset_adds_offset_to_each_gain() {
10892 let x = cpu_f32(vec![1.0_f32, 2.0, 3.0], &[1, 3]);
10893 let gain_raw: [f32; 3] = [-0.5, 0.0, 0.5];
10894 let via_offset = x.rms_norm_affine_with_offset(&gain_raw, 1.0, 1e-6).unwrap();
10895 let gain_shifted = std::sync::Arc::<[f32]>::from(vec![0.5_f32, 1.0, 1.5]);
10896 let via_plain = x.rms_norm_affine(gain_shifted, 1e-6).unwrap();
10897 let a = via_offset.realize_f32();
10898 let b = via_plain.realize_f32();
10899 for (x, y) in a.iter().zip(b.iter()) {
10900 assert!((x - y).abs() < 1e-6, "{x} vs {y}");
10901 }
10902 }
10903
10904 #[test]
10905 fn global_avg_pool_2d_averages_spatial_dims() {
10906 let x = cpu_f32(
10910 vec![
10911 1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0,
10912 ],
10913 &[1, 2, 2, 3],
10914 );
10915 let out = x.global_avg_pool_2d().unwrap();
10916 assert_eq!(out.shape().dims(), &[1, 2]);
10917 let v = out.realize_f32();
10918 assert!((v[0] - 3.5).abs() < 1e-5);
10919 assert!((v[1] - 35.0).abs() < 1e-4);
10920 }
10921
10922 #[test]
10923 fn channel_affine_4d_applies_per_channel_gain_and_bias() {
10924 let x = cpu_f32(
10926 vec![
10927 1.0_f32, 2.0, 3.0, 4.0, 10.0, 20.0, 30.0, 40.0, ],
10930 &[1, 2, 2, 2],
10931 );
10932 let gain = std::sync::Arc::<[f32]>::from(vec![2.0_f32, 0.5]);
10933 let bias = std::sync::Arc::<[f32]>::from(vec![1.0_f32, -10.0]);
10934 let out = x.channel_affine_4d(gain, bias).unwrap();
10935 let v = out.realize_f32();
10936 assert_eq!(&v[0..4], &[3.0, 5.0, 7.0, 9.0]);
10938 assert_eq!(&v[4..8], &[-5.0, 0.0, 5.0, 10.0]);
10940 }
10941
10942 #[test]
10943 fn additive_causal_mask_has_strict_lower_triangle() {
10944 let anchor = cpu_f32(vec![0.0_f32], &[1]);
10945 let mask = Tensor::additive_causal_mask_like(&anchor, 4);
10946 assert_eq!(mask.shape().dims(), &[4, 4]);
10947 let v = mask.realize_f32();
10948 for i in 0..4 {
10954 for j in 0..4 {
10955 let got = v[i * 4 + j];
10956 if j > i {
10957 assert!(
10958 got.is_infinite() && got.is_sign_negative(),
10959 "above-diag (i={i}, j={j}) should be -inf, got {got}"
10960 );
10961 } else {
10962 assert_eq!(
10963 got, 0.0,
10964 "on/below-diag (i={i}, j={j}) should be 0, got {got}"
10965 );
10966 }
10967 }
10968 }
10969 }
10970
10971 #[test]
10972 fn layer_norm_affine_unit_gain_zero_bias_matches_layer_norm_last_dim() {
10973 let a = cpu_f32(vec![1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
10974 let gain = std::sync::Arc::<[f32]>::from(vec![1.0_f32; 3]);
10975 let bias = std::sync::Arc::<[f32]>::from(vec![0.0_f32; 3]);
10976 let out_affine = a.layer_norm_affine(gain, bias, 1e-5).unwrap();
10977 let out_plain = a.layer_norm_last_dim(1e-5).unwrap();
10978 let va = out_affine.realize_f32();
10979 let vp = out_plain.realize_f32();
10980 for (a, b) in va.iter().zip(vp.iter()) {
10981 assert!((a - b).abs() < 1e-5, "{a} vs {b}");
10982 }
10983 }
10984
10985 #[test]
10986 fn layer_norm_affine_applies_gain_and_bias() {
10987 let a = cpu_f32(vec![1.0_f32, 2.0, 3.0], &[1, 3]);
10988 let gain = std::sync::Arc::<[f32]>::from(vec![2.0_f32, 0.5, 1.5]);
10989 let bias = std::sync::Arc::<[f32]>::from(vec![10.0_f32, -5.0, 0.0]);
10990 let out = a.layer_norm_affine(gain, bias, 1e-5).unwrap();
10991 let v = out.realize_f32();
10992 let mean = 2.0_f32;
10994 let var = ((1.0 - mean).powi(2) + (2.0 - mean).powi(2) + (3.0 - mean).powi(2)) / 3.0;
10995 let den = (var + 1e-5_f32).sqrt();
10996 let expected = [
10997 ((1.0 - mean) / den) * 2.0 + 10.0,
10998 ((2.0 - mean) / den) * 0.5 + (-5.0),
10999 ((3.0 - mean) / den) * 1.5 + 0.0,
11000 ];
11001 for (got, want) in v.iter().zip(expected.iter()) {
11002 assert!((got - want).abs() < 1e-4, "{got} vs {want}");
11003 }
11004 }
11005
11006 #[test]
11007 fn l2_normalize_last_dim_unit_norm_per_row() {
11008 let a = cpu_f32(vec![3.0, 4.0, 0.0, 1.0, 2.0, 2.0], &[2, 3]);
11010 let out = a.l2_normalize(1_usize, 1e-12).unwrap();
11011 assert_eq!(out.shape().dims(), &[2, 3]);
11012 let v = out.realize_f32();
11013 let row0_norm = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
11014 let row1_norm = (v[3] * v[3] + v[4] * v[4] + v[5] * v[5]).sqrt();
11015 assert!((row0_norm - 1.0).abs() < 1e-5, "row 0 norm = {row0_norm}");
11016 assert!((row1_norm - 1.0).abs() < 1e-5, "row 1 norm = {row1_norm}");
11017 assert!((v[0] - 0.6).abs() < 1e-5);
11019 assert!((v[1] - 0.8).abs() < 1e-5);
11020 assert!(v[2].abs() < 1e-5);
11021 }
11022
11023 #[test]
11024 fn l2_normalize_eps_zero_works_when_nonzero() {
11025 let a = cpu_f32(vec![1.0_f32, 0.0], &[2]);
11026 let out = a.l2_normalize(0_usize, 0.0).unwrap();
11027 let v = out.realize_f32();
11028 assert!((v[0] - 1.0).abs() < 1e-6);
11029 assert!(v[1].abs() < 1e-6);
11030 }
11031
11032 #[test]
11033 fn repeat_interleave_last_dim_matches_torch_semantics() {
11034 let a = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
11038 let out = a.repeat_interleave(1_usize, 2).unwrap();
11039 assert_eq!(out.shape().dims(), &[2, 6]);
11040 assert_eq!(
11041 out.realize_f32(),
11042 vec![1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0, 5.0, 5.0, 6.0, 6.0]
11043 );
11044 }
11045
11046 #[test]
11047 fn repeat_interleave_middle_dim() {
11048 let a = cpu_f32((0..8).map(|i| i as f32).collect(), &[2, 2, 2]);
11050 let out = a.repeat_interleave(1_usize, 3).unwrap();
11051 assert_eq!(out.shape().dims(), &[2, 6, 2]);
11052 let v = out.realize_f32();
11054 assert_eq!(&v[0..6], &[0.0, 1.0, 0.0, 1.0, 0.0, 1.0]);
11055 assert_eq!(&v[6..12], &[2.0, 3.0, 2.0, 3.0, 2.0, 3.0]);
11056 }
11057
11058 #[test]
11059 fn repeat_interleave_repeats_one_is_noop() {
11060 let a = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11061 let out = a.repeat_interleave(0_usize, 1).unwrap();
11062 assert_eq!(out.shape().dims(), &[3]);
11063 assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0]);
11064 }
11065
11066 #[test]
11067 fn repeat_interleave_repeats_zero_errors() {
11068 let a = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11069 assert!(a.repeat_interleave(0_usize, 0).is_err());
11070 }
11071
11072 #[test]
11073 fn stack_adds_leading_dim() {
11074 let a = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11075 let b = a.const_f32_like(vec![4.0, 5.0, 6.0], vec![3]).unwrap();
11076 let out = Tensor::stack(&[&a, &b], 0).unwrap();
11077 assert_eq!(out.shape().dims(), &[2, 3]);
11078 assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
11079 }
11080
11081 #[test]
11082 fn stack_adds_trailing_dim() {
11083 let a = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11084 let b = a.const_f32_like(vec![4.0, 5.0, 6.0], vec![3]).unwrap();
11085 let out = Tensor::stack(&[&a, &b], 1).unwrap();
11086 assert_eq!(out.shape().dims(), &[3, 2]);
11087 assert_eq!(out.realize_f32(), vec![1.0, 4.0, 2.0, 5.0, 3.0, 6.0]);
11088 }
11089
11090 #[test]
11091 fn stack_rejects_mismatched_shapes() {
11092 let a = cpu_f32(vec![1.0, 2.0], &[2]);
11093 let b = a.const_f32_like(vec![3.0, 4.0, 5.0], vec![3]).unwrap();
11094 assert!(Tensor::stack(&[&a, &b], 0).is_err());
11095 }
11096
11097 #[test]
11098 fn stack_rejects_empty_input() {
11099 let result = Tensor::stack(&[], 0);
11100 assert!(result.is_err());
11101 }
11102
11103 #[test]
11104 fn repeat_tiles_along_each_dim() {
11105 let t = cpu_f32(vec![1.0, 2.0], &[2]);
11106 let out = t.repeat(vec![3]).unwrap();
11107 assert_eq!(out.shape().dims(), &[6]);
11108 assert_eq!(out.realize_f32(), vec![1.0, 2.0, 1.0, 2.0, 1.0, 2.0]);
11109 }
11110
11111 #[test]
11112 fn repeat_extends_rank_when_needed() {
11113 let t = cpu_f32(vec![1.0, 2.0], &[2]);
11114 let out = t.repeat(vec![3, 2]).unwrap();
11116 assert_eq!(out.shape().dims(), &[3, 4]);
11117 }
11118
11119 #[test]
11120 fn repeat_identity_with_all_ones() {
11121 let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11122 let out = t.repeat(vec![1]).unwrap();
11123 assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0]);
11124 }
11125}
11126
11127#[cfg(test)]
11131mod phase_a3_keepdim_tests {
11132 use super::*;
11133
11134 fn cpu_f32(data: Vec<f32>, shape: &[usize]) -> Tensor {
11135 Tensor::from_f32(data, shape.to_vec(), &Device::cpu()).unwrap()
11136 }
11137
11138 #[test]
11139 fn sum_keepdim_preserves_dim_as_one() {
11140 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11141 let out = t.sum_keepdim(1_usize).unwrap();
11142 assert_eq!(out.shape().dims(), &[2, 1]);
11143 assert_eq!(out.realize_f32(), vec![3.0, 7.0]);
11144 }
11145
11146 #[test]
11147 fn mean_keepdim_preserves_dim_as_one() {
11148 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11149 let out = t.mean_keepdim(0_usize).unwrap();
11150 assert_eq!(out.shape().dims(), &[1, 2]);
11151 assert_eq!(out.realize_f32(), vec![2.0, 3.0]);
11152 }
11153
11154 #[test]
11155 fn max_keepdim_preserves_dim_as_one() {
11156 let t = cpu_f32(vec![1.0, 3.0, 2.0, 4.0], &[2, 2]);
11157 let out = t.max_keepdim(1_usize).unwrap();
11158 assert_eq!(out.shape().dims(), &[2, 1]);
11159 assert_eq!(out.realize_f32(), vec![3.0, 4.0]);
11160 }
11161
11162 #[test]
11163 fn min_keepdim_preserves_dim_as_one() {
11164 let t = cpu_f32(vec![1.0, 3.0, 2.0, 4.0], &[2, 2]);
11165 let out = t.min_keepdim(1_usize).unwrap();
11166 assert_eq!(out.shape().dims(), &[2, 1]);
11167 assert_eq!(out.realize_f32(), vec![1.0, 2.0]);
11168 }
11169
11170 fn var_in(dtype: &str, data: &[f64], shape: &[usize], dim: usize, correction: f64) -> Vec<f64> {
11177 let dev = Device::cpu();
11178 let s = Shape::from_dims(shape);
11179 match dtype {
11180 "f32" => Tensor::from_f32(data.iter().map(|&x| x as f32).collect::<Vec<_>>(), s, &dev)
11181 .unwrap()
11182 .var(dim, correction)
11183 .unwrap()
11184 .realize_f32()
11185 .iter()
11186 .map(|&x| x as f64)
11187 .collect(),
11188 "f64" => Tensor::from_f64(data.to_vec(), s, &dev)
11189 .unwrap()
11190 .var(dim, correction)
11191 .unwrap()
11192 .realize_f64(),
11193 "f16" => Tensor::from_f16(
11194 data.iter()
11195 .map(|&x| half::f16::from_f64(x))
11196 .collect::<Vec<_>>(),
11197 s,
11198 &dev,
11199 )
11200 .unwrap()
11201 .var(dim, correction)
11202 .unwrap()
11203 .realize_f16()
11204 .iter()
11205 .map(|x| x.to_f64())
11206 .collect(),
11207 "bf16" => Tensor::from_bf16(
11208 data.iter()
11209 .map(|&x| half::bf16::from_f64(x))
11210 .collect::<Vec<_>>(),
11211 s,
11212 &dev,
11213 )
11214 .unwrap()
11215 .var(dim, correction)
11216 .unwrap()
11217 .realize_bf16()
11218 .iter()
11219 .map(|x| x.to_f64())
11220 .collect(),
11221 other => panic!("dtype {other}"),
11222 }
11223 }
11224
11225 #[test]
11227 fn var_rejects_a_nan_correction() {
11228 let dev = Device::cpu();
11229 let x = Tensor::from_f32(vec![1.0, 3.0], Shape::from_dims(&[2]), &dev).unwrap();
11230 assert!(x.var_keepdim(0, f64::NAN).is_err());
11231 assert!(x.var_keepdim(0, 1.0).is_ok());
11233 }
11234
11235 #[test]
11236 fn var_divisor_is_clamped_at_zero_in_every_dtype() {
11237 for dt in ["f32", "f64", "f16", "bf16"] {
11238 assert!(var_in(dt, &[5.0], &[1], 0, 1.0)[0].is_nan(), "{dt} [5] c=1");
11240 let v = var_in(dt, &[5.0, 7.0], &[2, 1], 1, 1.0);
11241 assert!(v[0].is_nan() && v[1].is_nan(), "{dt} [[5],[7]] c=1: {v:?}");
11242 assert_eq!(
11244 var_in(dt, &[1.0, 3.0], &[2], 0, 2.0)[0],
11245 f64::INFINITY,
11246 "{dt} [1,3] c=2"
11247 );
11248 assert!(var_in(dt, &[5.0], &[1], 0, 2.0)[0].is_nan(), "{dt} [5] c=2");
11250 assert_eq!(
11251 var_in(dt, &[1.0, 3.0], &[2], 0, 3.0)[0],
11252 f64::INFINITY,
11253 "{dt} [1,3] c=3"
11254 );
11255 assert_eq!(var_in(dt, &[5.0], &[1], 0, 0.0)[0], 0.0, "{dt} [5] c=0");
11257 assert_eq!(
11258 var_in(dt, &[1.0, 3.0], &[2], 0, 1.0)[0],
11259 2.0,
11260 "{dt} [1,3] c=1"
11261 );
11262 }
11263 }
11264
11265 #[test]
11266 fn var_matches_unbiased_formula_with_correction_1() {
11267 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
11269 let out = t.var(1, 1.0).unwrap();
11270 assert_eq!(out.shape().dims(), &[2]);
11271 let v = out.realize_f32();
11272 assert!((v[0] - 1.0).abs() < 1e-5, "var row 0 = {} != 1.0", v[0]);
11273 assert!((v[1] - 1.0).abs() < 1e-5, "var row 1 = {} != 1.0", v[1]);
11274 }
11275
11276 #[test]
11281 fn var_population_with_correction_0() {
11282 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
11284 let out = t.var(1, 0.0).unwrap();
11285 let v = out.realize_f32();
11286 let want = 2.0 / 3.0;
11287 assert!(
11288 (v[0] - want).abs() < 1e-5,
11289 "population var row 0 = {} != {want}",
11290 v[0]
11291 );
11292 assert!(
11293 (v[1] - want).abs() < 1e-5,
11294 "population var row 1 = {} != {want}",
11295 v[1]
11296 );
11297 }
11298
11299 #[test]
11300 fn var_keepdim_preserves_dim() {
11301 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
11302 let out = t.var_keepdim(1, 1.0).unwrap();
11303 assert_eq!(out.shape().dims(), &[2, 1]);
11304 }
11305
11306 #[test]
11307 fn var_errors_out_of_bounds() {
11308 let t = cpu_f32(vec![1.0, 2.0], &[2]);
11309 assert!(t.var(3, 1.0).is_err());
11310 assert!(t.var_keepdim(3, 1.0).is_err());
11311 }
11312}
11313
11314#[cfg(test)]
11318mod phase_a4_composite_tests {
11319 use super::*;
11320
11321 fn cpu_f32(data: Vec<f32>, shape: &[usize]) -> Tensor {
11322 Tensor::from_f32(data, shape.to_vec(), &Device::cpu()).unwrap()
11323 }
11324
11325 #[test]
11326 fn affine_applies_mul_then_add() {
11327 let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11328 let out = t.affine(2.0, 10.0);
11329 assert_eq!(out.realize_f32(), vec![12.0, 14.0, 16.0]);
11330 }
11331
11332 #[test]
11333 fn scale_and_shift_alias_of_affine() {
11334 let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11335 assert_eq!(
11336 t.scale_and_shift(2.0, 10.0).realize_f32(),
11337 t.affine(2.0, 10.0).realize_f32(),
11338 );
11339 }
11340
11341 #[test]
11342 fn elu_matches_reference_values() {
11343 let t = cpu_f32(vec![1.0, 0.0, -1.0, -2.0], &[4]);
11344 let out = t.elu(1.0);
11345 let v = out.realize_f32();
11346 assert!((v[0] - 1.0).abs() < 1e-5);
11349 assert!(v[1].abs() < 1e-5);
11350 assert!((v[2] - ((-1.0_f32).exp() - 1.0)).abs() < 1e-5);
11351 assert!((v[3] - ((-2.0_f32).exp() - 1.0)).abs() < 1e-5);
11352 }
11353
11354 #[test]
11355 fn dot_of_rank_one_vectors() {
11356 let a = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11357 let b = a.const_f32_like(vec![4.0, 5.0, 6.0], vec![3]).unwrap();
11358 let out = a.dot(&b).unwrap();
11359 assert_eq!(out.shape().elem_count(), 1);
11360 let v = out.realize_f32();
11361 assert_eq!(v[0], 32.0); }
11363
11364 #[test]
11365 fn dot_rejects_non_rank_one() {
11366 let a = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11367 let b = a
11368 .const_f32_like(vec![1.0, 2.0, 3.0, 4.0], vec![2, 2])
11369 .unwrap();
11370 assert!(a.dot(&b).is_err());
11371 }
11372
11373 #[test]
11374 fn dot_rejects_length_mismatch() {
11375 let a = cpu_f32(vec![1.0, 2.0], &[2]);
11376 let b = a.const_f32_like(vec![1.0, 2.0, 3.0], vec![3]).unwrap();
11377 assert!(a.dot(&b).is_err());
11378 }
11379
11380 #[test]
11381 fn mv_matrix_times_vector() {
11382 let m = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
11383 let v = m.const_f32_like(vec![1.0, 1.0, 1.0], vec![3]).unwrap();
11384 let out = m.mv(&v).unwrap();
11385 assert_eq!(out.shape().dims(), &[2]);
11386 assert_eq!(out.realize_f32(), vec![6.0, 15.0]);
11387 }
11388
11389 #[test]
11390 fn matvec_is_mv_alias() {
11391 let m = cpu_f32(vec![1.0, 0.0, 0.0, 1.0], &[2, 2]);
11392 let v = m.const_f32_like(vec![3.0, 4.0], vec![2]).unwrap();
11393 let a = m.mv(&v).unwrap().realize_f32();
11394 let b = m.matvec(&v).unwrap().realize_f32();
11395 assert_eq!(a, b);
11396 }
11397
11398 #[test]
11399 fn mv_rejects_shape_mismatch() {
11400 let m = cpu_f32(vec![1.0; 6], &[2, 3]);
11401 let v = m.const_f32_like(vec![1.0, 1.0], vec![2]).unwrap();
11402 assert!(m.mv(&v).is_err());
11403 }
11404
11405 #[test]
11406 fn broadcast_matmul_passes_through_to_matmul() {
11407 let a = cpu_f32(vec![1.0, 0.0, 0.0, 1.0], &[2, 2]);
11408 let b = a
11409 .const_f32_like(vec![5.0, 6.0, 7.0, 8.0], vec![2, 2])
11410 .unwrap();
11411 let out = a.broadcast_matmul(&b).unwrap();
11412 assert_eq!(out.realize_f32(), vec![5.0, 6.0, 7.0, 8.0]);
11413 }
11414}
11415
11416#[cfg(test)]
11420mod phase_a5_factory_tests {
11421 use super::*;
11422
11423 fn cpu_f32(data: Vec<f32>, shape: &[usize]) -> Tensor {
11424 Tensor::from_f32(data, shape.to_vec(), &Device::cpu()).unwrap()
11425 }
11426
11427 #[test]
11428 fn ones_like_matches_shape_dtype_graph() {
11429 let t = cpu_f32(vec![5.0, 6.0, 7.0, 8.0], &[2, 2]);
11430 let ones = t.ones_like().unwrap();
11431 assert_eq!(ones.shape().dims(), t.shape().dims());
11432 assert_eq!(ones.dtype(), t.dtype());
11433 assert_eq!(ones.realize_f32(), vec![1.0; 4]);
11434 }
11435
11436 #[test]
11437 fn zeros_like_matches_shape_dtype_graph() {
11438 let t = cpu_f32(vec![5.0, 6.0, 7.0], &[3]);
11439 let zeros = t.zeros_like().unwrap();
11440 assert_eq!(zeros.realize_f32(), vec![0.0; 3]);
11441 }
11442
11443 #[test]
11444 fn static_ones_f32() {
11445 let t = Tensor::ones(vec![2, 3], DType::F32, &Device::cpu()).unwrap();
11446 assert_eq!(t.shape().dims(), &[2, 3]);
11447 assert_eq!(t.realize_f32(), vec![1.0; 6]);
11448 }
11449
11450 #[test]
11451 fn static_zeros_f64() {
11452 let t = Tensor::zeros(vec![4], DType::F64, &Device::cpu()).unwrap();
11453 assert_eq!(t.dtype(), DType::F64);
11454 assert_eq!(t.realize_f64(), vec![0.0; 4]);
11455 }
11456
11457 #[test]
11458 fn full_with_f32_scalar() {
11459 let t = Tensor::full(vec![5], fuel_ir::Scalar::F32(2.5), &Device::cpu()).unwrap();
11460 assert_eq!(t.realize_f32(), vec![2.5; 5]);
11461 }
11462
11463 #[test]
11464 fn eye_identity_matrix() {
11465 let t = Tensor::eye(3, DType::F32, &Device::cpu());
11466 assert_eq!(t.shape().dims(), &[3, 3]);
11467 assert_eq!(
11468 t.realize_f32(),
11469 vec![1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0],
11470 );
11471 }
11472
11473 #[test]
11474 fn tril2_lower_triangular_ones() {
11475 let t = Tensor::tril2(3, DType::F32, &Device::cpu());
11476 assert_eq!(
11477 t.realize_f32(),
11478 vec![1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0],
11479 );
11480 }
11481
11482 #[test]
11483 fn triu2_upper_triangular_ones() {
11484 let t = Tensor::triu2(3, DType::F32, &Device::cpu());
11485 assert_eq!(
11486 t.realize_f32(),
11487 vec![1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0],
11488 );
11489 }
11490
11491 #[test]
11492 fn meshgrid_ij_indexing_two_inputs() {
11493 let x = Tensor::from_f32(vec![1.0_f32, 2.0, 3.0], vec![3], &Device::cpu()).unwrap();
11494 let y = x.const_f32_like(vec![4.0_f32, 5.0], vec![2]).unwrap();
11495 let grids = Tensor::meshgrid(&[&x, &y], false).unwrap();
11496 assert_eq!(grids.len(), 2);
11497 assert_eq!(grids[0].shape().dims(), &[3, 2]);
11499 assert_eq!(grids[1].shape().dims(), &[3, 2]);
11500 assert_eq!(grids[0].realize_f32(), vec![1.0, 1.0, 2.0, 2.0, 3.0, 3.0]);
11502 assert_eq!(grids[1].realize_f32(), vec![4.0, 5.0, 4.0, 5.0, 4.0, 5.0]);
11504 }
11505
11506 #[test]
11507 fn meshgrid_xy_indexing_swaps_first_two() {
11508 let x = Tensor::from_f32(vec![1.0_f32, 2.0, 3.0], vec![3], &Device::cpu()).unwrap();
11509 let y = x.const_f32_like(vec![4.0_f32, 5.0], vec![2]).unwrap();
11510 let grids = Tensor::meshgrid(&[&x, &y], true).unwrap();
11511 assert_eq!(grids[0].shape().dims(), &[2, 3]);
11513 assert_eq!(grids[1].shape().dims(), &[2, 3]);
11514 assert_eq!(grids[0].realize_f32(), vec![1.0, 2.0, 3.0, 1.0, 2.0, 3.0]);
11516 assert_eq!(grids[1].realize_f32(), vec![4.0, 4.0, 4.0, 5.0, 5.0, 5.0]);
11518 }
11519
11520 #[test]
11521 fn meshgrid_rejects_single_input() {
11522 let x = Tensor::from_f32(vec![1.0_f32, 2.0], vec![2], &Device::cpu()).unwrap();
11523 assert!(Tensor::meshgrid(&[&x], false).is_err());
11524 }
11525
11526 #[test]
11527 fn meshgrid_rejects_non_rank_one() {
11528 let x = Tensor::from_f32(vec![1.0; 4], vec![2, 2], &Device::cpu()).unwrap();
11529 let y = x.const_f32_like(vec![1.0, 2.0], vec![2]).unwrap();
11530 assert!(Tensor::meshgrid(&[&x, &y], false).is_err());
11531 }
11532
11533 #[test]
11536 fn narrow_is_slice_alias() {
11537 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0], &[5]);
11538 let a = t.narrow(0, 1, 3).unwrap().realize_f32();
11539 let b = t.slice(0, 1, 3).unwrap().realize_f32();
11540 assert_eq!(a, b);
11541 assert_eq!(a, vec![2.0, 3.0, 4.0]);
11542 }
11543
11544 #[test]
11545 fn chunk_splits_evenly() {
11546 let t = cpu_f32((1..=6).map(|i| i as f32).collect(), &[6]);
11547 let parts = t.chunk(3, 0).unwrap();
11548 assert_eq!(parts.len(), 3);
11549 assert_eq!(parts[0].realize_f32(), vec![1.0, 2.0]);
11550 assert_eq!(parts[1].realize_f32(), vec![3.0, 4.0]);
11551 assert_eq!(parts[2].realize_f32(), vec![5.0, 6.0]);
11552 }
11553
11554 #[test]
11555 fn chunk_distributes_remainder_to_leading() {
11556 let t = cpu_f32((1..=7).map(|i| i as f32).collect(), &[7]);
11558 let parts = t.chunk(3, 0).unwrap();
11559 assert_eq!(parts.len(), 3);
11560 assert_eq!(parts[0].realize_f32(), vec![1.0, 2.0, 3.0]);
11561 assert_eq!(parts[1].realize_f32(), vec![4.0, 5.0]);
11562 assert_eq!(parts[2].realize_f32(), vec![6.0, 7.0]);
11563 }
11564
11565 #[test]
11566 fn chunk_returns_singletons_when_size_less_than_chunks() {
11567 let t = cpu_f32(vec![1.0, 2.0], &[2]);
11568 let parts = t.chunk(5, 0).unwrap();
11569 assert_eq!(parts.len(), 2);
11570 assert_eq!(parts[0].realize_f32(), vec![1.0]);
11571 assert_eq!(parts[1].realize_f32(), vec![2.0]);
11572 }
11573
11574 #[test]
11575 fn get_at_first_dim() {
11576 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[3, 2]);
11577 let row1 = t.get(1).unwrap();
11578 assert_eq!(row1.shape().dims(), &[2]);
11579 assert_eq!(row1.realize_f32(), vec![3.0, 4.0]);
11580 }
11581
11582 #[test]
11583 fn get_on_dim_arbitrary_axis() {
11584 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[3, 2]);
11585 let col0 = t.get_on_dim(1, 0).unwrap();
11586 assert_eq!(col0.shape().dims(), &[3]);
11587 assert_eq!(col0.realize_f32(), vec![1.0, 3.0, 5.0]);
11588 }
11589
11590 #[test]
11591 fn sum_dims_multi_dim_reduces_to_smaller() {
11592 let t = cpu_f32(vec![1.0; 24], &[2, 3, 4]);
11594 let s = t.sum_dims([0, 2_usize]).unwrap();
11595 assert_eq!(s.shape().dims(), &[3]);
11596 assert_eq!(s.realize_f32(), vec![8.0; 3]);
11598 }
11599
11600 #[test]
11601 fn mean_dims_multi_dim() {
11602 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11603 let m = t.mean_dims([0, 1_usize]).unwrap();
11604 assert_eq!(m.shape().dims(), &[] as &[usize]);
11605 assert_eq!(m.realize_f32(), vec![2.5]);
11606 }
11607
11608 #[test]
11609 fn sum_dims_keepdim_preserves_rank() {
11610 let t = cpu_f32(vec![1.0; 24], &[2, 3, 4]);
11611 let s = t.sum_dims_keepdim(&[0, 2]).unwrap();
11612 assert_eq!(s.shape().dims(), &[1, 3, 1]);
11613 }
11614
11615 #[test]
11616 fn mean_dims_keepdim_preserves_rank() {
11617 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11618 let m = t.mean_dims_keepdim(&[0, 1]).unwrap();
11619 assert_eq!(m.shape().dims(), &[1, 1]);
11620 assert_eq!(m.realize_f32(), vec![2.5]);
11621 }
11622
11623 #[test]
11624 fn rand_like_matches_shape_dtype() {
11625 let t = cpu_f32(vec![0.0; 6], &[2, 3]);
11626 let r = t.rand_like(-1.0, 1.0).unwrap();
11627 assert_eq!(r.shape().dims(), t.shape().dims());
11628 assert_eq!(r.dtype(), t.dtype());
11629 for v in r.realize_f32() {
11631 assert!((-1.0..1.0).contains(&v), "sample {v} out of [-1, 1)");
11632 }
11633 }
11634
11635 #[test]
11636 fn randn_like_matches_shape_dtype() {
11637 let t = cpu_f32(vec![0.0; 4], &[4]);
11638 let r = t.randn_like(0.0, 1.0).unwrap();
11639 assert_eq!(r.shape().dims(), &[4]);
11640 assert_eq!(r.dtype(), DType::F32);
11641 for v in r.realize_f32() {
11643 assert!(v.is_finite());
11644 }
11645 }
11646
11647 #[test]
11648 fn static_rand_f32() {
11649 let t = Tensor::rand(vec![100], 0.0, 1.0, DType::F32, &Device::cpu()).unwrap();
11650 let v = t.realize_f32();
11651 let mean: f32 = v.iter().sum::<f32>() / v.len() as f32;
11653 assert!((0.3..0.7).contains(&mean), "mean {mean} too far from 0.5");
11654 }
11655
11656 #[test]
11657 fn static_randn_f64() {
11658 let t = Tensor::randn(vec![1000], 0.0, 1.0, DType::F64, &Device::cpu()).unwrap();
11659 let v = t.realize_f64();
11660 let mean: f64 = v.iter().sum::<f64>() / v.len() as f64;
11661 assert!(mean.abs() < 0.2, "mean {mean} too far from 0");
11663 }
11664
11665 #[test]
11666 fn arange_int_step() {
11667 let t = Tensor::arange(0.0, 5.0, &Device::cpu());
11668 assert_eq!(t.shape().dims(), &[5]);
11669 assert_eq!(t.realize_f32(), vec![0.0, 1.0, 2.0, 3.0, 4.0]);
11670 }
11671
11672 #[test]
11673 fn arange_step_fractional() {
11674 let t = Tensor::arange_step(2.0, 4.0, 0.5, &Device::cpu());
11675 assert_eq!(t.realize_f32(), vec![2.0, 2.5, 3.0, 3.5]);
11676 }
11677
11678 #[test]
11679 fn arange_step_negative_descends() {
11680 let t = Tensor::arange_step(5.0, 0.0, -1.0, &Device::cpu());
11681 assert_eq!(t.realize_f32(), vec![5.0, 4.0, 3.0, 2.0, 1.0]);
11682 }
11683
11684 #[test]
11685 fn linspace_includes_endpoints() {
11686 let t = Tensor::linspace(0.0, 1.0, 5, &Device::cpu());
11687 assert_eq!(t.shape().dims(), &[5]);
11688 let v = t.realize_f32();
11689 assert!((v[0] - 0.0).abs() < 1e-6);
11690 assert!((v[4] - 1.0).abs() < 1e-6);
11691 assert!((v[2] - 0.5).abs() < 1e-6);
11692 }
11693
11694 #[test]
11695 fn linspace_n_one_returns_start() {
11696 let t = Tensor::linspace(7.0, 99.0, 1, &Device::cpu());
11697 assert_eq!(t.realize_f32(), vec![7.0]);
11698 }
11699
11700 #[test]
11701 fn norm_is_sqrt_sum_sq() {
11702 let t = Tensor::from_f32(vec![3.0_f32, 4.0], vec![2], &Device::cpu()).unwrap();
11703 let n = t.norm();
11704 assert!((n.realize_f32()[0] - 5.0).abs() < 1e-6);
11705 }
11706
11707 #[test]
11708 fn pad_with_zeros_left_and_right() {
11709 let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11710 let p = t.pad_with_zeros(0, 2, 1).unwrap();
11711 assert_eq!(p.shape().dims(), &[6]);
11712 assert_eq!(p.realize_f32(), vec![0.0, 0.0, 1.0, 2.0, 3.0, 0.0]);
11713 }
11714
11715 #[test]
11716 fn pad_with_zeros_identity_when_both_zero() {
11717 let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11718 let p = t.pad_with_zeros(0, 0, 0).unwrap();
11719 assert_eq!(p.realize_f32(), vec![1.0, 2.0, 3.0]);
11720 }
11721
11722 #[test]
11723 fn pad_with_zeros_rejects_bad_dim() {
11724 let t = cpu_f32(vec![1.0, 2.0], &[2]);
11725 assert!(t.pad_with_zeros(3, 1, 1).is_err());
11726 }
11727
11728 #[test]
11729 fn pad_with_value_zero_matches_pad_with_zeros() {
11730 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11733 let via_zeros = t.pad_with_zeros(0, 1, 2).unwrap();
11734 let via_value = t.pad_with_value(0, 1, 2, 0.0).unwrap();
11735 assert_eq!(via_zeros.shape().dims(), via_value.shape().dims());
11736 assert_eq!(via_zeros.shape().dims(), &[5, 2]);
11737 assert_eq!(via_zeros.realize_f32(), via_value.realize_f32());
11738 assert_eq!(
11739 via_value.realize_f32(),
11740 vec![0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 0.0, 0.0, 0.0, 0.0],
11741 );
11742 }
11743
11744 #[test]
11745 fn pad_with_value_neg_inf_then_max_reduce_ignores_pad() {
11746 let t = cpu_f32(vec![-1.0, -2.0, -3.0], &[3]);
11750 let padded = t.pad_with_value(0, 2, 2, f32::NEG_INFINITY).unwrap();
11751 assert_eq!(padded.shape().dims(), &[7]);
11752 let v = padded.realize_f32();
11753 assert!(v[0].is_infinite() && v[0].is_sign_negative());
11755 assert!(v[1].is_infinite() && v[1].is_sign_negative());
11756 assert_eq!(v[2], -1.0);
11757 assert_eq!(v[3], -2.0);
11758 assert_eq!(v[4], -3.0);
11759 assert!(v[5].is_infinite() && v[5].is_sign_negative());
11760 assert!(v[6].is_infinite() && v[6].is_sign_negative());
11761 let m = padded.max_all().realize_f32();
11763 assert_eq!(m, vec![-1.0]);
11764 }
11765
11766 #[test]
11767 fn pad_with_value_identity_when_both_zero() {
11768 let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11771 let p = t.pad_with_value(0, 0, 0, f32::NEG_INFINITY).unwrap();
11772 assert_eq!(p.realize_f32(), vec![1.0, 2.0, 3.0]);
11773 }
11774
11775 #[test]
11776 fn pad_with_value_rejects_bad_dim() {
11777 let t = cpu_f32(vec![1.0, 2.0], &[2]);
11778 assert!(t.pad_with_value(3, 1, 1, 0.0).is_err());
11779 }
11780
11781 #[test]
11782 fn max_pool2d_with_pad_value_neg_inf_on_negative_interior() {
11783 let x = cpu_f32(
11794 vec![-1.0, -2.0, -3.0, -4.0, -5.0, -6.0, -7.0, -8.0, -9.0],
11795 &[1, 1, 3, 3],
11796 );
11797 let out = x
11798 .max_pool2d_with_pad_value((3, 3), (1, 1), (1, 1), f32::NEG_INFINITY)
11799 .unwrap();
11800 assert_eq!(out.shape().dims(), &[1, 1, 3, 3]);
11801 let v = out.realize_f32();
11802 assert_eq!(v[0], -1.0);
11805 assert_eq!(v[4], -1.0);
11807 assert_eq!(v[8], -5.0);
11810
11811 let default_pad = x.max_pool2d((3, 3), (1, 1), (1, 1)).unwrap();
11821 let vd = default_pad.realize_f32();
11822 assert_eq!(
11823 vd[0], -1.0,
11824 "max_pool2d's default must now match NEG_INFINITY padding, not 0.0"
11825 );
11826 assert_eq!(vd[8], -5.0);
11827
11828 let explicit_zero_pad = x
11829 .max_pool2d_with_pad_value((3, 3), (1, 1), (1, 1), 0.0)
11830 .unwrap();
11831 let vz = explicit_zero_pad.realize_f32();
11832 assert_eq!(
11833 vz[0], 0.0,
11834 "explicit 0.0 padding must still be reachable via max_pool2d_with_pad_value"
11835 );
11836 assert_eq!(vz[8], 0.0);
11837 }
11838
11839 #[test]
11840 fn max_pool2d_with_pad_value_zero_matches_max_pool2d() {
11841 let data: Vec<f32> = (0..16).map(|i| i as f32).collect();
11844 let x = cpu_f32(data, &[1, 1, 4, 4]);
11845 let a = x.max_pool2d((2, 2), (2, 2), (0, 0)).unwrap();
11846 let b = x
11847 .max_pool2d_with_pad_value((2, 2), (2, 2), (0, 0), 0.0)
11848 .unwrap();
11849 assert_eq!(a.shape().dims(), b.shape().dims());
11850 assert_eq!(a.realize_f32(), b.realize_f32());
11851 }
11852
11853 #[test]
11856 fn conv1d_identity_kernel_passes_input_through() {
11857 let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0], &[1, 1, 5]);
11859 let w = x.const_f32_like(vec![1.0], vec![1, 1, 1]).unwrap();
11860 let out = x.conv1d(&w, None, 1, 0, 1).unwrap();
11861 assert_eq!(out.shape().dims(), &[1, 1, 5]);
11862 assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0, 4.0, 5.0]);
11863 }
11864
11865 #[test]
11866 fn conv1d_sum_kernel_two_wide() {
11867 let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[1, 1, 4]);
11869 let w = x.const_f32_like(vec![1.0, 1.0], vec![1, 1, 2]).unwrap();
11870 let out = x.conv1d(&w, None, 1, 0, 1).unwrap();
11871 assert_eq!(out.shape().dims(), &[1, 1, 3]);
11872 assert_eq!(out.realize_f32(), vec![3.0, 5.0, 7.0]);
11873 }
11874
11875 #[test]
11876 fn conv1d_with_bias_applies_correctly() {
11877 let x = cpu_f32(vec![1.0, 1.0, 1.0], &[1, 1, 3]);
11878 let w = x.const_f32_like(vec![1.0], vec![1, 1, 1]).unwrap();
11879 let bias = x.const_f32_like(vec![10.0], vec![1]).unwrap();
11880 let out = x.conv1d(&w, Some(&bias), 1, 0, 1).unwrap();
11881 assert_eq!(out.realize_f32(), vec![11.0, 11.0, 11.0]);
11882 }
11883
11884 #[test]
11885 fn conv1d_stride_two_halves_output() {
11886 let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[1, 1, 6]);
11888 let w = x.const_f32_like(vec![1.0, 1.0], vec![1, 1, 2]).unwrap();
11889 let out = x.conv1d(&w, None, 2, 0, 1).unwrap();
11890 assert_eq!(out.shape().dims(), &[1, 1, 3]);
11891 assert_eq!(out.realize_f32(), vec![3.0, 7.0, 11.0]);
11892 }
11893
11894 #[test]
11895 fn conv1d_padding_one_preserves_length() {
11896 let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[1, 1, 4]);
11898 let w = x
11899 .const_f32_like(vec![1.0, 1.0, 1.0], vec![1, 1, 3])
11900 .unwrap();
11901 let out = x.conv1d(&w, None, 1, 1, 1).unwrap();
11902 assert_eq!(out.shape().dims(), &[1, 1, 4]);
11903 assert_eq!(out.realize_f32(), vec![3.0, 6.0, 9.0, 7.0]);
11906 }
11907
11908 #[test]
11909 fn conv1d_multi_channel_output() {
11910 let x = cpu_f32(vec![1.0, 2.0, 3.0], &[1, 1, 3]);
11912 let w = x.const_f32_like(vec![2.0, -1.0], vec![2, 1, 1]).unwrap();
11914 let out = x.conv1d(&w, None, 1, 0, 1).unwrap();
11915 assert_eq!(out.shape().dims(), &[1, 2, 3]);
11916 assert_eq!(out.realize_f32(), vec![2.0, 4.0, 6.0, -1.0, -2.0, -3.0]);
11918 }
11919
11920 #[test]
11921 fn conv1d_rejects_rank_two_input() {
11922 let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11923 let w = x.const_f32_like(vec![1.0], vec![1, 1, 1]).unwrap();
11924 assert!(x.conv1d(&w, None, 1, 0, 1).is_err());
11925 }
11926
11927 #[test]
11928 fn conv1d_rejects_rank_two_weight() {
11929 let x = cpu_f32(vec![1.0; 4], &[1, 1, 4]);
11930 let w = x.const_f32_like(vec![1.0], vec![1, 1]).unwrap();
11931 assert!(x.conv1d(&w, None, 1, 0, 1).is_err());
11932 }
11933
11934 #[test]
11935 fn conv1d_rejects_zero_groups_or_stride() {
11936 let x = cpu_f32(vec![1.0; 4], &[1, 1, 4]);
11937 let w = x.const_f32_like(vec![1.0], vec![1, 1, 1]).unwrap();
11938 assert!(x.conv1d(&w, None, 0, 0, 1).is_err());
11939 assert!(x.conv1d(&w, None, 1, 0, 0).is_err());
11940 }
11941
11942 #[test]
11943 fn conv1d_with_algo_ignores_algo_param() {
11944 let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[1, 1, 4]);
11945 let w = x.const_f32_like(vec![1.0, 1.0], vec![1, 1, 2]).unwrap();
11946 let a = x.conv1d_with_algo(&w, None, 1, 0, 1, "unused").unwrap();
11948 let b = x.conv1d(&w, None, 1, 0, 1).unwrap();
11949 assert_eq!(a.realize_f32(), b.realize_f32());
11950 }
11951
11952 #[test]
11955 fn avg_pool2d_2x2_stride2() {
11956 let data: Vec<f32> = (0..16).map(|i| i as f32).collect();
11958 let x = cpu_f32(data, &[1, 1, 4, 4]);
11959 let out = x.avg_pool2d((2, 2), (2, 2), (0, 0), true).unwrap();
11960 assert_eq!(out.shape().dims(), &[1, 1, 2, 2]);
11961 let v = out.realize_f32();
11965 assert!((v[0] - 2.5).abs() < 1e-5);
11966 assert!((v[1] - 4.5).abs() < 1e-5);
11967 assert!((v[2] - 10.5).abs() < 1e-5);
11968 assert!((v[3] - 12.5).abs() < 1e-5);
11969 }
11970
11971 #[test]
11972 fn avg_pool2d_3x3_stride1_padding1_preserves_size() {
11973 let x = cpu_f32(vec![1.0; 16], &[1, 1, 4, 4]);
11974 let out = x.avg_pool2d((3, 3), (1, 1), (1, 1), true).unwrap();
11975 assert_eq!(out.shape().dims(), &[1, 1, 4, 4]);
11976 }
11977
11978 #[test]
11996 fn avg_pool2d_excludes_padding_keeps_uniform_data_exactly_at_its_true_value() {
11997 let x = cpu_f32(vec![1.0; 16], &[1, 1, 4, 4]);
11998 let included = x.avg_pool2d((3, 3), (1, 1), (1, 1), true).unwrap();
11999 let excluded = x.avg_pool2d((3, 3), (1, 1), (1, 1), false).unwrap();
12000 assert_eq!(included.shape().dims(), excluded.shape().dims());
12001
12002 let ve = excluded.realize_f32();
12003 for (i, &v) in ve.iter().enumerate() {
12004 assert!(
12005 (v - 1.0).abs() < 1e-5,
12006 "count_include_pad=false must be exactly 1.0 at every position \
12007 (all real taps are 1.0) — position {i} got {v}",
12008 );
12009 }
12010
12011 let vi = included.realize_f32();
12012 assert!(
12013 (vi[0] - 1.0).abs() > 0.1,
12014 "count_include_pad=true must NOT match at a corner (4 of 9 taps \
12015 real → 4/9, far from 1.0) — got {}, modes should disagree here",
12016 vi[0]
12017 );
12018 }
12019
12020 #[test]
12029 fn avg_pool2d_excludes_padding_from_divisor_discriminating() {
12030 let x = cpu_f32(vec![10.0, 10.0, 10.0, 10.0], &[1, 1, 2, 2]);
12031 let included = x.avg_pool2d((2, 2), (1, 1), (1, 1), true).unwrap();
12032 let excluded = x.avg_pool2d((2, 2), (1, 1), (1, 1), false).unwrap();
12033 let vi = included.realize_f32();
12034 let ve = excluded.realize_f32();
12035 assert!(
12036 (vi[0] - 2.5).abs() < 1e-5,
12037 "count_include_pad=true: top-left = 10/4 = 2.5, got {}",
12038 vi[0]
12039 );
12040 assert!(
12041 (ve[0] - 10.0).abs() < 1e-5,
12042 "count_include_pad=false: top-left = 10/1 (ONE real tap) = 10.0, got {}",
12043 ve[0]
12044 );
12045 }
12046
12047 #[test]
12052 fn avg_pool2d_rejects_zero_valid_tap_window() {
12053 let x = cpu_f32(vec![5.0], &[1, 1, 1, 1]);
12054 let err = x
12055 .avg_pool2d((1, 1), (1, 1), (2, 2), false)
12056 .expect_err("a window with zero real taps must be rejected, not silently NaN");
12057 let msg = err.to_string();
12058 assert!(
12059 msg.contains("divide by zero") || msg.contains("no valid"),
12060 "error should explain the zero-valid-tap cause, got: {msg}"
12061 );
12062
12063 let ok = x.avg_pool2d((1, 1), (1, 1), (2, 2), true);
12068 assert!(
12069 ok.is_ok(),
12070 "count_include_pad=true must still accept this shape (uniform divisor, never zero)"
12071 );
12072 }
12073
12074 #[test]
12075 fn avg_pool2d_multi_channel() {
12076 let x = cpu_f32(vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0], &[1, 2, 2, 2]);
12078 let out = x.avg_pool2d((2, 2), (2, 2), (0, 0), true).unwrap();
12079 assert_eq!(out.shape().dims(), &[1, 2, 1, 1]);
12080 assert_eq!(out.realize_f32(), vec![0.0, 1.0]);
12081 }
12082
12083 #[test]
12084 fn max_pool2d_2x2_stride2() {
12085 let data: Vec<f32> = (0..16).map(|i| i as f32).collect();
12086 let x = cpu_f32(data, &[1, 1, 4, 4]);
12087 let out = x.max_pool2d((2, 2), (2, 2), (0, 0)).unwrap();
12088 assert_eq!(out.shape().dims(), &[1, 1, 2, 2]);
12089 assert_eq!(out.realize_f32(), vec![5.0, 7.0, 13.0, 15.0]);
12091 }
12092
12093 #[test]
12094 fn max_pool2d_3x3_stride1_padding1() {
12095 let x = cpu_f32(
12096 vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0],
12097 &[1, 1, 3, 3],
12098 );
12099 let out = x.max_pool2d((3, 3), (1, 1), (1, 1)).unwrap();
12100 assert_eq!(out.shape().dims(), &[1, 1, 3, 3]);
12101 let v = out.realize_f32();
12103 assert!((v[4] - 9.0).abs() < 1e-5);
12105 }
12106
12107 #[test]
12108 fn upsample_nearest2d_2x() {
12109 let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[1, 1, 2, 2]);
12110 let out = x.upsample_nearest2d(2).unwrap();
12111 assert_eq!(out.shape().dims(), &[1, 1, 4, 4]);
12112 assert_eq!(
12114 out.realize_f32(),
12115 vec![
12116 1.0, 1.0, 2.0, 2.0, 1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0, 3.0, 3.0, 4.0, 4.0,
12117 ],
12118 );
12119 }
12120
12121 #[test]
12122 fn upsample_nearest2d_3x() {
12123 let x = cpu_f32(vec![5.0], &[1, 1, 1, 1]);
12124 let out = x.upsample_nearest2d(3).unwrap();
12125 assert_eq!(out.shape().dims(), &[1, 1, 3, 3]);
12126 assert_eq!(out.realize_f32(), vec![5.0; 9]);
12127 }
12128
12129 #[test]
12130 fn upsample_nearest2d_identity_scale_one() {
12131 let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[1, 1, 2, 2]);
12132 let out = x.upsample_nearest2d(1).unwrap();
12133 assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0, 4.0]);
12134 }
12135
12136 #[test]
12137 fn upsample_nearest1d_2x() {
12138 let x = cpu_f32(vec![1.0, 2.0, 3.0], &[1, 1, 3]);
12139 let out = x.upsample_nearest1d(2).unwrap();
12140 assert_eq!(out.shape().dims(), &[1, 1, 6]);
12141 assert_eq!(out.realize_f32(), vec![1.0, 1.0, 2.0, 2.0, 3.0, 3.0]);
12142 }
12143
12144 #[test]
12145 fn interpolate2d_integer_multiple() {
12146 let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[1, 1, 2, 2]);
12147 let out = x.interpolate2d(4, 4).unwrap();
12148 assert_eq!(out.shape().dims(), &[1, 1, 4, 4]);
12149 }
12150
12151 #[test]
12152 fn interpolate2d_accepts_non_integer_ratio() {
12153 let x = cpu_f32(vec![1.0; 4], &[1, 1, 2, 2]);
12158 let out = x.interpolate2d(3, 4).unwrap();
12159 assert_eq!(out.shape().dims(), &[1, 1, 3, 4]);
12160 }
12161
12162 #[test]
12163 fn interpolate1d_integer_multiple() {
12164 let x = cpu_f32(vec![1.0, 2.0], &[1, 1, 2]);
12165 let out = x.interpolate1d(6).unwrap();
12166 assert_eq!(out.shape().dims(), &[1, 1, 6]);
12167 assert_eq!(out.realize_f32(), vec![1.0, 1.0, 1.0, 2.0, 2.0, 2.0]);
12168 }
12169
12170 #[test]
12171 fn pool_rejects_bad_rank() {
12172 let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
12173 assert!(x.avg_pool2d((2, 2), (2, 2), (0, 0), true).is_err());
12174 assert!(x.max_pool2d((2, 2), (2, 2), (0, 0)).is_err());
12175 }
12176
12177 #[test]
12178 fn pool_rejects_zero_kernel() {
12179 let x = cpu_f32(vec![1.0; 16], &[1, 1, 4, 4]);
12180 assert!(x.avg_pool2d((0, 2), (1, 1), (0, 0), true).is_err());
12181 assert!(x.max_pool2d((2, 0), (1, 1), (0, 0)).is_err());
12182 }
12183
12184 #[test]
12187 fn numel_matches_elem_count() {
12188 let t = cpu_f32(vec![1.0; 12], &[3, 4]);
12189 assert_eq!(t.numel(), t.elem_count());
12190 assert_eq!(t.numel(), 12);
12191 }
12192
12193 #[test]
12194 fn dim_returns_specific_axis_size() {
12195 let t = cpu_f32(vec![0.0; 24], &[2, 3, 4]);
12196 assert_eq!(t.dim(0).unwrap(), 2);
12197 assert_eq!(t.dim(1).unwrap(), 3);
12198 assert_eq!(t.dim(2).unwrap(), 4);
12199 assert!(t.dim(3).is_err());
12200 }
12201
12202 #[test]
12203 fn to_dtype_switches_dtype() {
12204 let t = cpu_f32(vec![1.0, 2.0], &[2]);
12205 let b = t.to_dtype(DType::F64).unwrap();
12206 assert_eq!(b.dtype(), DType::F64);
12207 assert_eq!(b.realize_f64(), vec![1.0, 2.0]);
12208 }
12209
12210 #[test]
12211 fn to_dtype_same_dtype_is_noop() {
12212 let t = cpu_f32(vec![1.0_f32], &[1]);
12213 let b = t.to_dtype(DType::F32).unwrap();
12214 assert_eq!(b.dtype(), DType::F32);
12215 }
12216
12217 #[test]
12218 fn detach_is_identity_on_lazy() {
12219 let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
12220 let d = t.detach();
12221 assert_eq!(d.realize_f32(), t.realize_f32());
12222 }
12223
12224 #[test]
12225 fn track_op_is_true_on_lazy() {
12226 let t = cpu_f32(vec![0.0], &[1]);
12227 assert!(t.track_op());
12228 }
12229
12230 #[test]
12233 fn try_permute_accepts_tuple_syntax() {
12234 let t = cpu_f32(vec![0.0; 24], &[2, 3, 4]);
12235 let out = t.permute((2_usize, 0_usize, 1_usize)).unwrap();
12237 assert_eq!(out.shape().dims(), &[4, 2, 3]);
12238 }
12239
12240 #[test]
12241 fn dim_arg_methods_accept_negative_indexing() {
12242 use fuel_ir::D;
12243 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
12244 let sum_last = t.shape().dims().to_vec(); assert_eq!(sum_last, vec![2, 3]);
12247 let cumsum_last = t.cumsum(D::Minus1).unwrap();
12250 assert_eq!(cumsum_last.shape().dims(), &[2, 3]);
12251 }
12252
12253 #[test]
12254 fn unsqueeze_accepts_dim_trait() {
12255 use fuel_ir::D;
12256 let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
12257 let out = t.unsqueeze(D::Minus1).unwrap();
12259 assert_eq!(out.shape().dims().len(), 2);
12262 }
12263}
12264pub struct TokenDataHost {
12265 pub token_ids: fuel_ir::HostBuffer,
12266 pub rope_cos: fuel_ir::HostBuffer,
12267 pub rope_sin: fuel_ir::HostBuffer,
12268 pub mask: fuel_ir::HostBuffer,
12269 pub offset: Option<fuel_ir::HostBuffer>,
12270}
12271
12272#[cfg(feature = "cuda")]
12277pub struct TokenDataBytes {
12278 pub token_ids: Vec<u8>,
12279 pub rope_cos: Vec<u8>,
12280 pub rope_sin: Vec<u8>,
12281 pub mask: Vec<u8>,
12282 pub offset: Option<Vec<u8>>,
12283}
12284
12285#[cfg(feature = "cuda")]
12298pub fn captured_output_to_f32(
12299 output: &Arc<std::sync::RwLock<fuel_memory::Storage>>,
12300) -> fuel_ir::error::Result<Vec<f32>> {
12301 use fuel_memory::BackendStorage;
12302 let guard = output.read().map_err(|_| {
12303 fuel_ir::Error::Msg("captured decode output storage lock poisoned".into()).bt()
12304 })?;
12305 let bytes: Vec<u8> = match &guard.inner {
12306 BackendStorage::Cpu(c) => c.bytes().to_vec(),
12307 BackendStorage::Cuda(c) => c.to_cpu_bytes()?,
12308 #[allow(unreachable_patterns)]
12309 other => {
12310 return Err(fuel_ir::Error::Msg(format!(
12311 "captured decode output is BackendStorage::{:?}, expected Cpu or Cuda",
12312 std::mem::discriminant(other),
12313 ))
12314 .bt());
12315 }
12316 };
12317 Ok(bytemuck::cast_slice::<u8, f32>(&bytes).to_vec())
12318}