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 Q4_0 {
8625 words: Arc<[u32]>,
8626 bytes_len: usize,
8627 in_features: usize,
8628 out_features: usize,
8629 },
8630 Ggml {
8636 qtype: fuel_graph::QuantType,
8637 words: Arc<[u32]>,
8638 bytes_len: usize,
8639 in_features: usize,
8640 out_features: usize,
8641 },
8642 Awq(Arc<crate::awq::AwqHostWeight>),
8647 WithLoRA {
8658 base: Box<WeightStorage>,
8659 lora_a: Arc<[f32]>,
8661 lora_b: Arc<[f32]>,
8663 rank: usize,
8664 alpha: f32,
8666 in_features: usize,
8667 out_features: usize,
8668 },
8669}
8670
8671impl WeightStorage {
8672 pub fn from_ggml_bytes(
8687 dtype: fuel_ir::quantized::GgmlDType,
8688 bytes: &[u8],
8689 in_features: usize,
8690 out_features: usize,
8691 ) -> Option<Self> {
8692 use fuel_ir::quantized::GgmlDType;
8693 let qtype = match dtype {
8694 GgmlDType::Q8_0 => fuel_graph::QuantType::Q8_0,
8695 GgmlDType::Q4K => fuel_graph::QuantType::Q4_K_M,
8696 GgmlDType::Q6K => fuel_graph::QuantType::Q6K,
8697 GgmlDType::Q3K => fuel_graph::QuantType::Q3K,
8698 GgmlDType::Q5K => fuel_graph::QuantType::Q5K,
8699 GgmlDType::Iq4Nl => fuel_graph::QuantType::Iq4Nl,
8700 GgmlDType::Iq4Xs => fuel_graph::QuantType::Iq4Xs,
8701 GgmlDType::Iq3S => fuel_graph::QuantType::Iq3S,
8702 GgmlDType::F32
8705 | GgmlDType::F16
8706 | GgmlDType::BF16
8707 | GgmlDType::Q4_0
8708 | GgmlDType::Q4_1
8709 | GgmlDType::Q5_0
8710 | GgmlDType::Q5_1
8711 | GgmlDType::Q8_1
8712 | GgmlDType::Q2K
8713 | GgmlDType::Q8K
8714 | GgmlDType::Iq2Xxs
8715 | GgmlDType::Iq2Xs
8716 | GgmlDType::Iq3Xxs
8717 | GgmlDType::Iq1S
8718 | GgmlDType::Iq2S
8719 | GgmlDType::Iq1M
8720 | GgmlDType::Tq1_0
8721 | GgmlDType::Tq2_0
8722 | GgmlDType::Mxfp4
8723 | GgmlDType::Nvfp4 => return None,
8724 };
8725 let block = qtype.elements_per_block();
8726 if in_features == 0 || !in_features.is_multiple_of(block) {
8727 return None;
8728 }
8729 if bytes.len() != out_features * (in_features / block) * qtype.bytes_per_block() {
8730 return None;
8731 }
8732 let mut padded = bytes.to_vec();
8734 padded.resize(bytes.len().div_ceil(4) * 4, 0);
8735 let words: Vec<u32> = padded
8736 .as_chunks::<4>()
8737 .0
8738 .iter()
8739 .map(|c| u32::from_le_bytes(*c))
8740 .collect();
8741 Some(Self::Ggml {
8742 qtype,
8743 words: Arc::from(words),
8744 bytes_len: bytes.len(),
8745 in_features,
8746 out_features,
8747 })
8748 }
8749
8750 pub fn resident_bytes(&self) -> usize {
8754 match self {
8755 Self::F32(a) => a.len() * std::mem::size_of::<f32>(),
8756 Self::BF16(a) => a.len() * std::mem::size_of::<half::bf16>(),
8757 Self::Q4_0 { bytes_len, .. } | Self::Ggml { bytes_len, .. } => *bytes_len,
8758 Self::Awq(w) => {
8759 w.weight.len() * std::mem::size_of::<u32>()
8760 + w.zeros.len() * std::mem::size_of::<u32>()
8761 + w.scales.len() * std::mem::size_of::<half::f16>()
8762 }
8763 Self::WithLoRA {
8764 base,
8765 lora_a,
8766 lora_b,
8767 ..
8768 } => base.resident_bytes() + (lora_a.len() + lora_b.len()) * std::mem::size_of::<f32>(),
8769 }
8770 }
8771
8772 pub fn elem_count(&self) -> usize {
8773 match self {
8774 Self::F32(a) => a.len(),
8775 Self::BF16(a) => a.len(),
8776 Self::Q4_0 {
8778 in_features,
8779 out_features,
8780 ..
8781 }
8782 | Self::Ggml {
8783 in_features,
8784 out_features,
8785 ..
8786 } => *in_features * *out_features,
8787 Self::Awq(w) => w.ic * w.oc,
8788 Self::WithLoRA {
8789 in_features,
8790 out_features,
8791 ..
8792 } => *in_features * *out_features,
8793 }
8794 }
8795
8796 pub fn dtype(&self) -> fuel_ir::DType {
8797 match self {
8798 Self::F32(_) => fuel_ir::DType::F32,
8799 Self::BF16(_) => fuel_ir::DType::BF16,
8800 Self::Q4_0 { .. } | Self::Ggml { .. } => fuel_ir::DType::U32,
8804 Self::Awq(_) => fuel_ir::DType::U32,
8806 Self::WithLoRA { base, .. } => base.dtype(),
8809 }
8810 }
8811
8812 pub fn const_like(
8823 &self,
8824 anchor: &Tensor,
8825 shape: Shape,
8826 ) -> std::result::Result<Tensor, fuel_ir::Error> {
8827 match self {
8828 Self::F32(a) => anchor.const_f32_like(a.clone(), shape),
8829 Self::BF16(a) => anchor.const_bf16_like(a.clone(), shape),
8830 Self::Q4_0 { words, .. } | Self::Ggml { words, .. } => {
8831 let _ = shape; anchor.const_u32_like(Arc::clone(words), Shape::from_dims(&[words.len()]))
8834 }
8835 Self::Awq(_) => Err(fuel_ir::Error::Msg(
8836 "WeightStorage::Awq::const_like is not supported — an AWQ weight is three operands \
8837 (weight, zeros, scales), applied via apply_linear."
8838 .into(),
8839 )
8840 .bt()),
8841 Self::WithLoRA { .. } => Err(fuel_ir::Error::Msg(
8842 "WeightStorage::WithLoRA::const_like is not supported \
8843 — the base + LoRA update must be applied via \
8844 apply_linear to produce the right graph structure."
8845 .into(),
8846 )
8847 .bt()),
8848 }
8849 }
8850
8851 pub fn apply_linear_with_bias(
8860 &self,
8861 x: &Tensor,
8862 in_features: usize,
8863 out_features: usize,
8864 bias: std::sync::Arc<[f32]>,
8865 ) -> std::result::Result<Tensor, fuel_ir::Error> {
8866 if bias.len() != out_features {
8867 return Err(fuel_ir::Error::Msg(format!(
8872 "apply_linear_with_bias: bias len ({}) != out_features ({out_features})",
8873 bias.len(),
8874 ))
8875 .bt());
8876 }
8877 let projected = self.apply_linear(x, in_features, out_features)?;
8878 let bias_t = projected.const_f32_like(bias, Shape::from_dims(&[out_features]))?;
8879 projected.broadcast_add(&bias_t)
8880 }
8881
8882 pub fn apply_linear(
8900 &self,
8901 x: &Tensor,
8902 in_features: usize,
8903 out_features: usize,
8904 ) -> std::result::Result<Tensor, fuel_ir::Error> {
8905 let x_dims = x.shape().dims().to_vec();
8911 match x_dims.last() {
8912 Some(&k) if k == in_features => {}
8913 _ => {
8914 return Err(fuel_ir::Error::Msg(format!(
8915 "apply_linear({in_features} -> {out_features}): input shape {x_dims:?} \
8916 must have trailing dim {in_features}",
8917 ))
8918 .bt());
8919 }
8920 }
8921 match self {
8922 Self::F32(_) | Self::BF16(_) => {
8923 let w = self.const_like(x, Shape::from_dims(&[in_features, out_features]))?;
8924 x.matmul(&w)
8925 }
8926 Self::Q4_0 {
8927 in_features: expected_in,
8928 out_features: expected_out,
8929 ..
8930 } => {
8931 if *expected_in != in_features || *expected_out != out_features {
8932 return Err(fuel_ir::Error::Msg(format!(
8933 "WeightStorage::Q4_0 shape mismatch: stored \
8934 [{expected_in}, {expected_out}], requested \
8935 [{in_features}, {out_features}]",
8936 ))
8937 .bt());
8938 }
8939 let w_bytes = self.const_like(x, Shape::from_dims(&[in_features, out_features]))?;
8940 x.qmatmul(
8941 &w_bytes,
8942 fuel_graph::QuantType::Q4_0,
8943 in_features,
8944 out_features,
8945 )
8946 }
8947 Self::Ggml {
8948 qtype,
8949 in_features: expected_in,
8950 out_features: expected_out,
8951 ..
8952 } => {
8953 if *expected_in != in_features || *expected_out != out_features {
8954 return Err(fuel_ir::Error::Msg(format!(
8955 "WeightStorage::Ggml({qtype:?}) shape mismatch: stored [{expected_in}, {expected_out}], requested [{in_features}, {out_features}]",
8956 ))
8957 .bt());
8958 }
8959 let w_bytes = self.const_like(x, Shape::from_dims(&[in_features, out_features]))?;
8960 x.qmatmul(&w_bytes, *qtype, in_features, out_features)
8961 }
8962 Self::Awq(w) => {
8963 if w.ic != in_features || w.oc != out_features {
8964 return Err(fuel_ir::Error::Msg(format!(
8965 "WeightStorage::Awq shape mismatch: stored [{}, {}], requested [{in_features}, {out_features}]",
8966 w.ic, w.oc,
8967 ))
8968 .bt());
8969 }
8970 w.matmul(x, 8)
8973 }
8974 Self::WithLoRA {
8975 base,
8976 lora_a,
8977 lora_b,
8978 rank,
8979 alpha,
8980 in_features: expected_in,
8981 out_features: expected_out,
8982 } => {
8983 if *expected_in != in_features || *expected_out != out_features {
8984 return Err(fuel_ir::Error::Msg(format!(
8985 "WeightStorage::WithLoRA shape mismatch: stored \
8986 [{expected_in}, {expected_out}], requested \
8987 [{in_features}, {out_features}]",
8988 ))
8989 .bt());
8990 }
8991 let base_out = base.apply_linear(x, in_features, out_features)?;
8993 let a_t =
8995 x.const_f32_like(Arc::clone(lora_a), Shape::from_dims(&[in_features, *rank]))?;
8996 let b_t =
8997 x.const_f32_like(Arc::clone(lora_b), Shape::from_dims(&[*rank, out_features]))?;
8998 let scale = *alpha as f64 / *rank as f64;
8999 let lora_path = Tensor {
9001 inner: x.matmul(&a_t)?.matmul(&b_t)?.inner.mul_scalar(scale),
9002 };
9003 base_out.add(&lora_path)
9004 }
9005 }
9006 }
9007
9008 pub fn apply_linear_dyn_m(
9021 &self,
9022 x: &Tensor,
9023 in_features: usize,
9024 out_features: usize,
9025 row_count: fuel_ir::DynScalar,
9026 ) -> std::result::Result<Tensor, fuel_ir::Error> {
9027 match self {
9028 Self::F32(_) => {
9029 let w = self
9031 .const_like(x, Shape::from_dims(&[in_features, out_features]))
9032 .expect("apply_linear_dyn_m F32 arm: const_like cannot fail for F32");
9033 x.matmul_dyn_m(&w, row_count)
9034 }
9035 other => Err(fuel_ir::Error::Msg(format!(
9036 "apply_linear_dyn_m: sparse-MoE dispatch is F32-only today, got {:?} \
9037 weight (cast the expert weights to F32)",
9038 other.dtype(),
9039 ))
9040 .bt()),
9041 }
9042 }
9043
9044 pub fn with_lora(
9049 self,
9050 lora_a: Arc<[f32]>,
9051 lora_b: Arc<[f32]>,
9052 rank: usize,
9053 alpha: f32,
9054 in_features: usize,
9055 out_features: usize,
9056 ) -> Self {
9057 assert_eq!(
9058 lora_a.len(),
9059 in_features * rank,
9060 "lora_a length {} does not match in_features ({in_features}) × rank ({rank}) = {}",
9061 lora_a.len(),
9062 in_features * rank,
9063 );
9064 assert_eq!(
9065 lora_b.len(),
9066 rank * out_features,
9067 "lora_b length {} does not match rank ({rank}) × out_features ({out_features}) = {}",
9068 lora_b.len(),
9069 rank * out_features,
9070 );
9071 assert!(
9072 !matches!(self, Self::WithLoRA { .. }),
9073 "with_lora: base is already WithLoRA (nested adapters unsupported)",
9074 );
9075 Self::WithLoRA {
9076 base: Box::new(self),
9077 lora_a,
9078 lora_b,
9079 rank,
9080 alpha,
9081 in_features,
9082 out_features,
9083 }
9084 }
9085}
9086
9087impl From<Arc<[f32]>> for WeightStorage {
9091 fn from(a: Arc<[f32]>) -> Self {
9092 Self::F32(a)
9093 }
9094}
9095impl From<Vec<f32>> for WeightStorage {
9096 fn from(v: Vec<f32>) -> Self {
9097 Self::F32(Arc::from(v))
9098 }
9099}
9100impl From<Arc<[half::bf16]>> for WeightStorage {
9101 fn from(a: Arc<[half::bf16]>) -> Self {
9102 Self::BF16(a)
9103 }
9104}
9105impl From<Vec<half::bf16>> for WeightStorage {
9106 fn from(v: Vec<half::bf16>) -> Self {
9107 Self::BF16(Arc::from(v))
9108 }
9109}
9110
9111#[derive(Debug, Clone)]
9123pub struct LayerWeights {
9124 pub attn_q: WeightStorage,
9126 pub attn_q_bias: Option<Arc<[f32]>>,
9128 pub attn_k: WeightStorage,
9130 pub attn_k_bias: Option<Arc<[f32]>>,
9132 pub attn_v: WeightStorage,
9134 pub attn_v_bias: Option<Arc<[f32]>>,
9136 pub attn_o: WeightStorage,
9138 pub ffn_gate: WeightStorage,
9140 pub ffn_up: WeightStorage,
9142 pub ffn_down: WeightStorage,
9144 pub attn_norm_gain: Arc<[f32]>,
9147 pub ffn_norm_gain: Arc<[f32]>,
9149}
9150
9151pub fn invalidate_decode_pair_if_stale<C>(
9152 session: &mut Option<crate::inference_context::DecodeSession>,
9153 captured: &mut Option<C>,
9154 ctx: &mut InferenceContext,
9155 seq: usize,
9156 max_seq_len: Option<usize>,
9157 cache_dtype: DType,
9158 n_layers: usize,
9159 shape_key: u64,
9160 kv: &dyn crate::inference_context::KvRebindSource,
9161 drop_session: impl FnOnce(
9162 &mut Option<crate::inference_context::DecodeSession>,
9163 &mut InferenceContext,
9164 ),
9165) -> SessionDisposition {
9166 refresh_decode_session(
9167 session,
9168 ctx,
9169 seq,
9170 max_seq_len,
9171 cache_dtype,
9172 n_layers,
9173 shape_key,
9174 kv,
9175 || *captured = None,
9179 drop_session,
9180 )
9181}
9182
9183#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9185pub enum SessionDisposition {
9186 Absent,
9188 Kept,
9190 Rebound,
9193 Dropped(Option<crate::inference_context::RebindRefusal>),
9197}
9198
9199pub fn refresh_decode_session(
9224 session: &mut Option<crate::inference_context::DecodeSession>,
9225 ctx: &mut InferenceContext,
9226 seq: usize,
9227 max_seq_len: Option<usize>,
9228 cache_dtype: DType,
9229 n_layers: usize,
9230 shape_key: u64,
9231 kv: &dyn crate::inference_context::KvRebindSource,
9232 on_invalidate: impl FnOnce(),
9233 drop_session: impl FnOnce(
9234 &mut Option<crate::inference_context::DecodeSession>,
9235 &mut InferenceContext,
9236 ),
9237) -> SessionDisposition {
9238 use crate::inference_context::PlanValidity;
9239
9240 let verdict = match (session.as_ref(), max_seq_len) {
9241 (None, _) => return SessionDisposition::Absent,
9242 (Some(s), Some(msl)) => {
9243 s.validity_for(seq, msl, n_layers, cache_dtype, shape_key, kv.alloc_id())
9244 }
9245 (Some(_), None) => PlanValidity::Stale,
9248 };
9249 if verdict == PlanValidity::Valid {
9250 return SessionDisposition::Kept;
9251 }
9252
9253 on_invalidate();
9254
9255 let refusal = if verdict == PlanValidity::AllocationChanged {
9256 match session.as_mut().map(|s| s.rebind_kv(kv)) {
9257 Some(Ok(())) => return SessionDisposition::Rebound,
9258 Some(Err(r)) => Some(r),
9259 None => None,
9263 }
9264 } else {
9265 None
9266 };
9267
9268 drop_session(session, ctx);
9269 SessionDisposition::Dropped(refusal)
9270}
9271
9272pub fn build_decode_causal_mask(cached_len: usize, seq: usize, max_seq_len: usize) -> Vec<f32> {
9273 let mut mask_data = vec![0.0_f32; seq * max_seq_len];
9274 for q_idx in 0..seq {
9275 let abs_q = cached_len + q_idx;
9276 for k_idx in (abs_q + 1)..max_seq_len {
9277 mask_data[q_idx * max_seq_len + k_idx] = f32::NEG_INFINITY;
9278 }
9279 }
9280 mask_data
9281}
9282
9283pub fn build_decode_causal_mask_windowed(
9323 cached_len: usize,
9324 seq: usize,
9325 max_seq_len: usize,
9326 window: usize,
9327) -> Vec<f32> {
9328 let mut mask_data = vec![0.0_f32; seq * max_seq_len];
9329 for q_idx in 0..seq {
9330 let abs_q = cached_len + q_idx;
9331 for k_idx in 0..max_seq_len {
9332 if k_idx > abs_q || k_idx + window <= abs_q {
9334 mask_data[q_idx * max_seq_len + k_idx] = f32::NEG_INFINITY;
9335 }
9336 }
9337 }
9338 mask_data
9339}
9340
9341#[cfg(test)]
9342mod decode_mask_tests {
9343 use super::{build_decode_causal_mask, build_decode_causal_mask_windowed};
9344
9345 fn attendable(row: &[f32]) -> Vec<u8> {
9348 row.iter().map(|&v| u8::from(v == 0.0)).collect()
9349 }
9350
9351 #[test]
9358 fn windowed_mask_excludes_positions_older_than_the_window() {
9359 let m = build_decode_causal_mask_windowed(3, 1, 6, 2);
9360 assert_eq!(
9361 attendable(&m),
9362 vec![0, 0, 1, 1, 0, 0],
9363 "window=2 at absolute position 3 must attend to exactly {{2, 3}}",
9364 );
9365 }
9366
9367 #[test]
9372 fn windowed_mask_offsets_each_row_by_cached_len() {
9373 let m = build_decode_causal_mask_windowed(1, 2, 5, 2);
9374 assert_eq!(
9375 attendable(&m[0..5]),
9376 vec![1, 1, 0, 0, 0],
9377 "row 0 = abs pos 1"
9378 );
9379 assert_eq!(
9380 attendable(&m[5..10]),
9381 vec![0, 1, 1, 0, 0],
9382 "row 1 = abs pos 2"
9383 );
9384 }
9385
9386 #[test]
9395 fn window_wider_than_capacity_is_byte_identical_to_the_dense_mask() {
9396 for (cached_len, seq, max_seq_len) in [(0, 1, 8), (3, 1, 8), (0, 4, 8), (2, 3, 8)] {
9397 let dense = build_decode_causal_mask(cached_len, seq, max_seq_len);
9398 let windowed =
9399 build_decode_causal_mask_windowed(cached_len, seq, max_seq_len, max_seq_len);
9400 assert_eq!(
9401 dense, windowed,
9402 "window == max_seq_len must equal dense at \
9403 (cached_len={cached_len}, seq={seq}, max_seq_len={max_seq_len})",
9404 );
9405 }
9406 }
9407
9408 #[test]
9417 fn decode_row_matches_the_prefill_mask_row_at_the_same_position() {
9418 let (n, window, max_seq_len) = (6_usize, 3_usize, 10_usize);
9419
9420 let mut prefill = vec![0.0_f32; n * n];
9422 for i in 0..n {
9423 for j in 0..n {
9424 if j > i || j + window <= i {
9425 prefill[i * n + j] = f32::NEG_INFINITY;
9426 }
9427 }
9428 }
9429
9430 for p in 0..n {
9431 let decode = build_decode_causal_mask_windowed(p, 1, max_seq_len, window);
9432 assert_eq!(
9433 attendable(&decode[0..n]),
9434 attendable(&prefill[p * n..(p + 1) * n]),
9435 "decode at cached_len={p} must match prefill row {p}",
9436 );
9437 assert!(
9438 decode[n..].iter().all(|&v| v == f32::NEG_INFINITY),
9439 "the unwritten tail beyond position {n} must stay masked",
9440 );
9441 }
9442 }
9443
9444 }
9485
9486pub fn flash_window_bounds(window: Option<usize>) -> (Option<usize>, Option<usize>) {
9524 match window {
9525 None => (None, None),
9526 Some(w) => (Some(w.saturating_sub(1)), Some(0)),
9527 }
9528}
9529
9530pub fn offer_flash_decode_arm_for_region(
9535 graph: &fuel_graph::SharedGraph,
9536 q: fuel_graph::NodeId,
9537 k: fuel_graph::NodeId,
9538 v: fuel_graph::NodeId,
9539 decomposed_out: fuel_graph::NodeId,
9540 reconverge: fuel_graph::NodeId,
9541 softmax_scale: f32,
9542 attended_len_sym: fuel_ir::SymId,
9543 attn_window: Option<usize>,
9544 softcap: Option<f32>,
9545 cap: fuel_dispatch::decode_flash::FlashArmCapability,
9546) -> crate::Result<Option<fuel_graph::NodeId>> {
9547 use fuel_dispatch::decode_flash::{DecodeFlashSpec, offer_decode_flash_arm};
9548 let (window_size_left, window_size_right) = flash_window_bounds(attn_window);
9549 let spec = DecodeFlashSpec {
9550 q,
9551 k,
9552 v,
9553 alibi: None,
9554 softmax_scale,
9555 causal: true,
9556 window_size_left,
9563 window_size_right,
9564 softcap,
9565 k_len: fuel_ir::DynScalar::Sym(attended_len_sym),
9566 decomposed_out,
9567 reconverge,
9568 };
9569 let mut g = graph.write().map_err(|_| {
9570 fuel_ir::Error::Msg("graph lock poisoned during flash-arm offer".into()).bt()
9571 })?;
9572 offer_decode_flash_arm(&mut g, &spec, cap)
9573}
9574
9575pub fn apply_affine_rms_norm(x: &Tensor, gain: &Arc<[f32]>, dim: usize, eps: f64) -> Tensor {
9576 assert_eq!(
9577 gain.len(),
9578 dim,
9579 "apply_affine_rms_norm: gain length must equal dim"
9580 );
9581 let normalized = x.rms_norm_last_dim(eps).unwrap();
9582 let gain_t = x
9588 .const_like_dtype(gain, Shape::from_dims(&[dim]), x.dtype())
9589 .expect("apply_affine_rms_norm: activation dtype must be F32 or BF16");
9590 normalized.broadcast_mul(&gain_t).unwrap()
9591}
9592
9593pub fn load_tensor_as_f32(
9600 st: &fuel_formats::safetensors::MmapedSafetensors,
9601 name: &str,
9602) -> crate::Result<Vec<f32>> {
9603 use safetensors::Dtype;
9604 let view = st.get(name)?;
9605 let bytes = view.data();
9606 match view.dtype() {
9607 Dtype::F32 => {
9608 let mut out = Vec::with_capacity(bytes.len() / 4);
9609 for chunk in bytes.as_chunks::<4>().0.iter() {
9610 out.push(f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
9611 }
9612 Ok(out)
9613 }
9614 Dtype::F64 => {
9615 let mut out = Vec::with_capacity(bytes.len() / 8);
9616 for chunk in bytes.as_chunks::<8>().0.iter() {
9617 let arr: [u8; 8] = *chunk;
9618 out.push(f64::from_le_bytes(arr) as f32);
9619 }
9620 Ok(out)
9621 }
9622 Dtype::BF16 => {
9623 let mut out = Vec::with_capacity(bytes.len() / 2);
9624 for chunk in bytes.as_chunks::<2>().0.iter() {
9625 let raw = u16::from_le_bytes([chunk[0], chunk[1]]);
9626 out.push(half::bf16::from_bits(raw).to_f32());
9627 }
9628 Ok(out)
9629 }
9630 Dtype::F16 => {
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::f16::from_bits(raw).to_f32());
9635 }
9636 Ok(out)
9637 }
9638 other => {
9639 crate::bail!("load_tensor_as_f32: unsupported dtype {other:?} for tensor {name:?}",)
9640 }
9641 }
9642}
9643
9644pub fn load_transposed_matrix(
9651 st: &fuel_formats::safetensors::MmapedSafetensors,
9652 name: &str,
9653 out_features: usize,
9654 in_features: usize,
9655) -> crate::Result<Vec<f32>> {
9656 let flat = load_tensor_as_f32(st, name)?;
9657 if flat.len() != out_features * in_features {
9658 crate::bail!(
9659 "load_transposed_matrix: tensor {name:?} has {} elements, expected {} ({out_features} × {in_features})",
9660 flat.len(),
9661 out_features * in_features,
9662 );
9663 }
9664 let mut out = vec![0.0_f32; out_features * in_features];
9668 for i in 0..out_features {
9669 for j in 0..in_features {
9670 out[j * out_features + i] = flat[i * in_features + j];
9671 }
9672 }
9673 Ok(out)
9674}
9675
9676pub fn load_transposed_matrix_preserve_dtype(
9688 st: &fuel_formats::safetensors::MmapedSafetensors,
9689 name: &str,
9690 out_features: usize,
9691 in_features: usize,
9692) -> crate::Result<WeightStorage> {
9693 use safetensors::Dtype;
9694 let view = st.get(name)?;
9695 let bytes = view.data();
9696 let expected = out_features * in_features;
9697 match view.dtype() {
9698 Dtype::BF16 => {
9699 if bytes.len() != expected * 2 {
9700 crate::bail!(
9701 "load_transposed_matrix_preserve_dtype: bf16 tensor {name:?} has {} bytes, expected {}",
9702 bytes.len(),
9703 expected * 2,
9704 );
9705 }
9706 let mut out = vec![half::bf16::ZERO; expected];
9709 for i in 0..out_features {
9710 for j in 0..in_features {
9711 let src_off = (i * in_features + j) * 2;
9712 let bits = u16::from_le_bytes([bytes[src_off], bytes[src_off + 1]]);
9713 out[j * out_features + i] = half::bf16::from_bits(bits);
9714 }
9715 }
9716 Ok(WeightStorage::BF16(Arc::from(out)))
9717 }
9718 _ => {
9719 let flat = load_transposed_matrix(st, name, out_features, in_features)?;
9723 Ok(WeightStorage::F32(Arc::from(flat)))
9724 }
9725 }
9726}
9727
9728#[derive(Debug, Clone, Copy, Default)]
9730pub enum SamplingStrategy {
9731 #[default]
9733 Greedy,
9734 Temperature { temp: f32, seed: u64 },
9739}
9740
9741fn argmax_logits(logits: &[f32]) -> fuel_ir::Result<u32> {
9750 if logits.is_empty() {
9751 return Err(fuel_ir::error::Error::Msg(
9752 "sample_logits: empty logits".into(),
9753 ));
9754 }
9755 if let Some(at) = logits.iter().position(|v| v.is_nan()) {
9756 return Err(fuel_ir::error::Error::Msg(format!(
9757 "sample_logits: logit {at} of {} is NaN (the model produced NaN); refusing to pick a token",
9758 logits.len()
9759 )));
9760 }
9761 let mut best = 0usize;
9762 for (i, &v) in logits.iter().enumerate() {
9763 if v > logits[best] {
9764 best = i;
9765 }
9766 }
9767 Ok(best as u32)
9768}
9769
9770pub fn sample_logits(
9778 logits: &[f32],
9779 strategy: SamplingStrategy,
9780 rng_state: &mut u64,
9781) -> fuel_ir::Result<u32> {
9782 match strategy {
9783 SamplingStrategy::Greedy => argmax_logits(logits),
9784 SamplingStrategy::Temperature { temp, .. } if temp.is_nan() || temp <= 0.0 => {
9787 argmax_logits(logits)
9788 }
9789 SamplingStrategy::Temperature { temp, .. } => {
9790 if let Some(at) = logits.iter().position(|v| !v.is_finite()) {
9791 return Err(fuel_ir::error::Error::Msg(format!(
9792 "sample_logits: logit {at} of {} is not finite; refusing to sample",
9793 logits.len()
9794 )));
9795 }
9796 if logits.is_empty() {
9797 return Err(fuel_ir::error::Error::Msg(
9798 "sample_logits: empty logits".into(),
9799 ));
9800 }
9801 let inv_temp = 1.0 / temp;
9804 let scaled: Vec<f32> = logits.iter().map(|&x| x * inv_temp).collect();
9805 let max = scaled.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
9806 let exp: Vec<f32> = scaled.iter().map(|&x| (x - max).exp()).collect();
9807 let sum: f32 = exp.iter().sum();
9808 let probs: Vec<f32> = exp.iter().map(|&x| x / sum).collect();
9809 Ok(sample_multinomial(&probs, rng_state))
9810 }
9811 }
9812}
9813
9814pub fn spec_argmax(logits: &[f32]) -> fuel_ir::Result<u32> {
9824 argmax_logits(logits)
9825}
9826
9827pub fn spec_softmax_temp(logits: &[f32], temp: f32) -> Vec<f32> {
9829 let inv_t = if temp == 0.0 { 1.0 } else { 1.0 / temp };
9830 let max = logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
9831 let exp: Vec<f32> = logits.iter().map(|&x| ((x - max) * inv_t).exp()).collect();
9832 let sum: f32 = exp.iter().sum();
9833 exp.iter().map(|&x| x / sum).collect()
9834}
9835
9836pub fn spec_next_u01(state: &mut u64) -> f32 {
9838 *state = state
9839 .wrapping_mul(6364136223846793005)
9840 .wrapping_add(1442695040888963407);
9841 (*state >> 32) as f32 / u32::MAX as f32
9842}
9843
9844pub fn spec_sample_cat(probs: &[f32], state: &mut u64) -> u32 {
9846 let u = spec_next_u01(state);
9847 let mut cum = 0.0_f32;
9848 for (i, &p) in probs.iter().enumerate() {
9849 cum += p;
9850 if u <= cum {
9851 return i as u32;
9852 }
9853 }
9854 (probs.len() - 1) as u32
9855}
9856
9857pub fn sample_multinomial(probs: &[f32], rng_state: &mut u64) -> u32 {
9861 *rng_state = rng_state
9863 .wrapping_mul(6364136223846793005)
9864 .wrapping_add(1442695040888963407);
9865 let u = (*rng_state >> 32) as f32 / u32::MAX as f32;
9866 let mut cumulative = 0.0_f32;
9867 for (i, &p) in probs.iter().enumerate() {
9868 cumulative += p;
9869 if u <= cumulative {
9870 return i as u32;
9871 }
9872 }
9873 (probs.len() - 1) as u32
9875}
9876
9877#[cfg(test)]
9878mod lora_tests {
9879 use super::*;
9880 use crate::Shape;
9881
9882 #[test]
9883 fn with_lora_matches_manual_base_plus_lora() {
9884 let in_f = 4;
9886 let out_f = 3;
9887 let rank = 2;
9888 let alpha = 8.0_f32;
9889
9890 let anchor =
9891 Tensor::from_f32(vec![0.0_f32; 1], Shape::from_dims(&[1]), &Device::cpu()).unwrap();
9892 let base_vec: Vec<f32> = (0..in_f * out_f).map(|i| (i as f32) * 0.1).collect();
9894 let lora_a_vec: Vec<f32> = (0..in_f * rank).map(|i| (i as f32) * 0.05).collect();
9895 let lora_b_vec: Vec<f32> = (0..rank * out_f).map(|i| (i as f32) * 0.02).collect();
9896
9897 let ws = WeightStorage::F32(Arc::from(base_vec.clone())).with_lora(
9898 Arc::from(lora_a_vec.clone()),
9899 Arc::from(lora_b_vec.clone()),
9900 rank,
9901 alpha,
9902 in_f,
9903 out_f,
9904 );
9905
9906 let batch = 2;
9908 let x_data: Vec<f32> = (0..batch * in_f).map(|i| (i as f32) * 0.1 + 0.5).collect();
9909 let x = anchor
9910 .const_f32_like(x_data.clone(), Shape::from_dims(&[batch, in_f]))
9911 .unwrap();
9912 let y = ws.apply_linear(&x, in_f, out_f).unwrap();
9913 let got = y.realize_f32().to_vec();
9914
9915 let mut expected = vec![0.0_f32; batch * out_f];
9917 for b in 0..batch {
9918 for j in 0..out_f {
9919 let mut acc = 0.0_f32;
9920 for k in 0..in_f {
9922 acc += x_data[b * in_f + k] * base_vec[k * out_f + j];
9923 }
9924 let scale = alpha as f64 / rank as f64;
9926 for r in 0..rank {
9927 let mut xar = 0.0_f32;
9928 for k in 0..in_f {
9929 xar += x_data[b * in_f + k] * lora_a_vec[k * rank + r];
9930 }
9931 acc += (xar * lora_b_vec[r * out_f + j]) * scale as f32;
9932 }
9933 expected[b * out_f + j] = acc;
9934 }
9935 }
9936
9937 for (i, (&e, &g)) in expected.iter().zip(got.iter()).enumerate() {
9938 let diff = (e - g).abs();
9939 assert!(
9940 diff <= 1e-4,
9941 "LoRA mismatch at {i}: expected {e}, got {g} (diff {diff})",
9942 );
9943 }
9944 }
9945
9946 #[test]
9947 #[should_panic(expected = "lora_a length")]
9948 fn with_lora_rejects_mismatched_a_shape() {
9949 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);
9953 }
9954
9955 #[test]
9967 fn apply_linear_errors_on_trailing_dim_mismatch() {
9968 let ws = WeightStorage::F32(Arc::from(vec![0.0_f32; 12])); let x = Tensor::from_f32(
9970 vec![0.0_f32; 10],
9971 Shape::from_dims(&[2, 5]), &Device::cpu(),
9973 )
9974 .unwrap();
9975 let err = ws
9976 .apply_linear(&x, 4, 3)
9977 .expect_err("must not panic, must Err");
9978 let msg = err.to_string();
9979 assert!(
9980 msg.contains("trailing dim 4"),
9981 "error should name the expected trailing dim, got: {msg}",
9982 );
9983 }
9984
9985 #[test]
9986 fn apply_linear_errors_on_q4_0_stored_shape_mismatch() {
9987 let ws = WeightStorage::Q4_0 {
9990 words: Arc::from(vec![0_u32; 8]),
9991 bytes_len: 18, in_features: 4,
9993 out_features: 4,
9994 };
9995 let x =
9996 Tensor::from_f32(vec![0.0_f32; 8], Shape::from_dims(&[2, 4]), &Device::cpu()).unwrap();
9997 let err = ws
10000 .apply_linear(&x, 4, 7)
10001 .expect_err("must not panic, must Err");
10002 let msg = err.to_string();
10003 assert!(
10004 msg.contains("Q4_0 shape mismatch"),
10005 "error should name the stored/requested disagreement, got: {msg}",
10006 );
10007 }
10008
10009 #[test]
10010 fn apply_linear_with_bias_errors_on_wrong_bias_length() {
10011 let ws = WeightStorage::F32(Arc::from(vec![0.0_f32; 12])); let x =
10013 Tensor::from_f32(vec![0.0_f32; 8], Shape::from_dims(&[2, 4]), &Device::cpu()).unwrap();
10014 let bias: Arc<[f32]> = Arc::from(vec![0.0_f32; 2]); let err = ws
10016 .apply_linear_with_bias(&x, 4, 3, bias)
10017 .expect_err("wrong-length bias must Err in EVERY profile, not just debug");
10018 assert!(
10019 err.to_string().contains("bias len"),
10020 "error should name the bias length, got: {err}",
10021 );
10022 }
10023}
10024
10025#[cfg(test)]
10026mod safetensors_bridge_tests {
10027 use super::*;
10028
10029 #[test]
10030 fn from_safetensors_bytes_round_trip_f32() {
10031 let original: Vec<f32> = vec![1.0, -2.5, 3.25, 0.0];
10035 let mut bytes = Vec::with_capacity(original.len() * 4);
10036 for &v in &original {
10037 bytes.extend_from_slice(&v.to_le_bytes());
10038 }
10039 let t =
10040 Tensor::from_safetensors_bytes(&bytes, safetensors::Dtype::F32, &[4], &Device::cpu())
10041 .unwrap();
10042 assert_eq!(t.shape().dims(), &[4]);
10043 assert_eq!(t.dtype(), DType::F32);
10044 assert_eq!(t.realize_f32(), original);
10045 }
10046
10047 #[test]
10048 fn from_safetensors_bytes_round_trip_bf16() {
10049 let original_f32: Vec<f32> = vec![0.5, -1.0, 2.0, 4.0];
10050 let bf16_vec: Vec<half::bf16> = original_f32
10051 .iter()
10052 .map(|&v| half::bf16::from_f32(v))
10053 .collect();
10054 let mut bytes = Vec::with_capacity(bf16_vec.len() * 2);
10055 for b in &bf16_vec {
10056 bytes.extend_from_slice(&b.to_bits().to_le_bytes());
10057 }
10058 let t =
10059 Tensor::from_safetensors_bytes(&bytes, safetensors::Dtype::BF16, &[4], &Device::cpu())
10060 .unwrap();
10061 assert_eq!(t.dtype(), DType::BF16);
10062 let realized = t.realize_bf16();
10065 assert_eq!(realized, bf16_vec);
10066 }
10067
10068 #[test]
10069 fn from_safetensors_bytes_rejects_wrong_byte_count() {
10070 let bad_bytes = vec![0_u8; 4];
10073 let result = Tensor::from_safetensors_bytes(
10074 &bad_bytes,
10075 safetensors::Dtype::F32,
10076 &[3],
10077 &Device::cpu(),
10078 );
10079 assert!(result.is_err());
10080 }
10081}
10082
10083#[cfg(test)]
10092mod phase_a1_wrapper_tests {
10093 use super::*;
10094
10095 fn cpu_f32(data: Vec<f32>, shape: &[usize]) -> Tensor {
10096 Tensor::from_f32(data, shape.to_vec(), &Device::cpu()).unwrap()
10097 }
10098
10099 #[test]
10100 fn unsqueeze_adds_size_one_dim() {
10101 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
10102 let out = t.unsqueeze(0_usize).unwrap();
10103 assert_eq!(out.shape().dims(), &[1, 2, 2]);
10104 assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0, 4.0]);
10105 }
10106
10107 #[test]
10108 fn unsqueeze_errors_out_of_bounds() {
10109 let t = cpu_f32(vec![1.0, 2.0], &[2]);
10110 assert!(t.unsqueeze(0_usize).is_ok());
10112 assert!(t.unsqueeze(1_usize).is_ok());
10113 assert!(t.unsqueeze(2_usize).is_err());
10114 }
10115
10116 #[test]
10117 fn try_reshape_errors_on_size_mismatch() {
10118 let t = cpu_f32(vec![1.0; 6], &[2, 3]);
10119 assert!(t.reshape(vec![3, 2]).is_ok());
10120 assert!(t.reshape(vec![2, 2]).is_err());
10121 }
10122
10123 #[test]
10124 fn try_permute_validates_axes() {
10125 let t = cpu_f32(vec![0.0; 24], &[2, 3, 4]);
10126 assert!(t.permute((2_usize, 0_usize, 1_usize)).is_ok());
10128 assert!(t.permute([2_usize, 0, 1]).is_ok());
10129 assert!(t.permute([0_usize, 1]).is_err()); assert!(t.permute([0_usize, 0, 1]).is_err()); }
10132
10133 #[test]
10134 fn try_transpose_requires_rank_two_plus() {
10135 let scalar = cpu_f32(vec![1.0], &[1]);
10136 let _ = scalar.transpose();
10138 }
10139
10140 #[test]
10141 fn triu_tril_shape_preserved() {
10142 let t = cpu_f32(vec![1.0; 9], &[3, 3]);
10143 let upper = t.triu(0).unwrap();
10144 let lower = t.tril(0).unwrap();
10145 assert_eq!(upper.shape().dims(), &[3, 3]);
10146 assert_eq!(lower.shape().dims(), &[3, 3]);
10147 assert_eq!(
10149 lower.realize_f32(),
10150 vec![1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0]
10151 );
10152 }
10153
10154 #[test]
10155 fn triu_rejects_rank_one() {
10156 let t = cpu_f32(vec![1.0, 2.0], &[2]);
10157 assert!(t.triu(0).is_err());
10158 }
10159
10160 #[test]
10161 fn log_softmax_last_dim_shape_preserved() {
10162 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
10163 let out = t.log_softmax_last_dim().unwrap();
10164 assert_eq!(out.shape().dims(), &[2, 2]);
10165 for v in out.realize_f32() {
10167 assert!(v <= 0.0 + 1e-6, "log_softmax produced positive value: {v}");
10168 }
10169 }
10170
10171 #[test]
10172 fn softmax_general_axis_matches_hand_computed_rank3_middle_axis() {
10173 let data: Vec<f32> = vec![
10182 -1.0, 0.0, 0.0, -3.0, -2.0, -1.0, -2.0, -1.0, -1.0, -1.0, 0.0, 0.0, ];
10191 let t = cpu_f32(data, &[2, 3, 2]);
10192 let out = t.softmax(1_usize).unwrap();
10193 assert_eq!(out.shape().dims(), &[2, 3, 2]);
10194 let v = out.realize_f32();
10195
10196 let lane_softmax = |xs: [f32; 3]| -> [f32; 3] {
10198 let m = xs.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
10199 let exps = [(xs[0] - m).exp(), (xs[1] - m).exp(), (xs[2] - m).exp()];
10200 let s = exps[0] + exps[1] + exps[2];
10201 [exps[0] / s, exps[1] / s, exps[2] / s]
10202 };
10203 let lanes: [[f32; 3]; 4] = [
10205 [-1.0, 0.0, -2.0], [0.0, -3.0, -1.0], [-2.0, -1.0, 0.0], [-1.0, -1.0, 0.0], ];
10210 let refs: Vec<[f32; 3]> = lanes.iter().map(|l| lane_softmax(*l)).collect();
10211
10212 for b in 0..2 {
10214 for c in 0..2 {
10215 let lane_ix = b * 2 + c;
10216 for r in 0..3 {
10217 let got = v[b * 6 + r * 2 + c];
10218 let want = refs[lane_ix][r];
10219 assert!(
10220 (got - want).abs() < 1e-6,
10221 "softmax mismatch at (b={b}, r={r}, c={c}): got {got}, want {want}",
10222 );
10223 }
10224 let sum: f32 = (0..3).map(|r| v[b * 6 + r * 2 + c]).sum();
10226 assert!((sum - 1.0).abs() < 1e-6, "lane (b={b},c={c}) sums to {sum}");
10227 }
10228 }
10229 }
10230
10231 #[test]
10232 fn softmax_last_axis_matches_softmax_last_dim() {
10233 let data: Vec<f32> = vec![
10234 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,
10236 ];
10237 let t = cpu_f32(data, &[2, 2, 4]);
10238 let via_general = t.softmax(2_usize).unwrap();
10239 let via_fused = t.softmax_last_dim().unwrap();
10240 assert_eq!(via_general.shape().dims(), via_fused.shape().dims());
10241 let g = via_general.realize_f32();
10242 let f = via_fused.realize_f32();
10243 assert_eq!(g.len(), f.len());
10244 for (i, (a, b)) in g.iter().zip(f.iter()).enumerate() {
10245 assert!(
10246 (a - b).abs() < 1e-6,
10247 "softmax (general axis=2) vs softmax_last_dim diverge at {i}: {a} vs {b}",
10248 );
10249 }
10250 }
10251
10252 #[test]
10253 fn log_softmax_general_axis_matches_hand_computed_rank3_middle_axis() {
10254 let data: Vec<f32> = vec![
10257 -1.0, 0.0, 0.0, -3.0, -2.0, -1.0, -2.0, -1.0, -1.0, -1.0, 0.0, 0.0,
10258 ];
10259 let t = cpu_f32(data, &[2, 3, 2]);
10260 let out = t.log_softmax(1_usize).unwrap();
10261 assert_eq!(out.shape().dims(), &[2, 3, 2]);
10262 let v = out.realize_f32();
10263
10264 let lane_log_softmax = |xs: [f32; 3]| -> [f32; 3] {
10265 let m = xs.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
10266 let shifted = [xs[0] - m, xs[1] - m, xs[2] - m];
10267 let lse = (shifted[0].exp() + shifted[1].exp() + shifted[2].exp()).ln();
10268 [shifted[0] - lse, shifted[1] - lse, shifted[2] - lse]
10269 };
10270 let lanes: [[f32; 3]; 4] = [
10271 [-1.0, 0.0, -2.0],
10272 [0.0, -3.0, -1.0],
10273 [-2.0, -1.0, 0.0],
10274 [-1.0, -1.0, 0.0],
10275 ];
10276 let refs: Vec<[f32; 3]> = lanes.iter().map(|l| lane_log_softmax(*l)).collect();
10277
10278 for b in 0..2 {
10279 for c in 0..2 {
10280 let lane_ix = b * 2 + c;
10281 for r in 0..3 {
10282 let got = v[b * 6 + r * 2 + c];
10283 let want = refs[lane_ix][r];
10284 assert!(
10285 (got - want).abs() < 1e-6,
10286 "log_softmax mismatch at (b={b}, r={r}, c={c}): got {got}, want {want}",
10287 );
10288 assert!(got <= 1e-6, "log_softmax produced positive value: {got}");
10290 }
10291 }
10292 }
10293 }
10294
10295 #[test]
10296 fn log_softmax_last_axis_matches_log_softmax_last_dim() {
10297 let data: Vec<f32> = vec![
10298 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,
10299 ];
10300 let t = cpu_f32(data, &[2, 2, 4]);
10301 let via_general = t.log_softmax(2_usize).unwrap();
10302 let via_fused = t.log_softmax_last_dim().unwrap();
10303 assert_eq!(via_general.shape().dims(), via_fused.shape().dims());
10304 let g = via_general.realize_f32();
10305 let f = via_fused.realize_f32();
10306 assert_eq!(g.len(), f.len());
10307 for (i, (a, b)) in g.iter().zip(f.iter()).enumerate() {
10308 assert!(
10309 (a - b).abs() < 1e-6,
10310 "log_softmax (general axis=2) vs log_softmax_last_dim diverge at {i}: {a} vs {b}",
10311 );
10312 }
10313 }
10314
10315 #[test]
10316 fn argmin_dim_drops_reduced_axis() {
10317 let t = cpu_f32(vec![3.0, 1.0, 2.0, 0.5, 5.0, 4.0], &[2, 3]);
10318 let out = t.argmin_dim(1_usize).unwrap();
10319 assert_eq!(out.shape().dims(), &[2]);
10320 assert_eq!(out.dtype(), DType::U32);
10321 assert_eq!(out.realize_u32(), vec![1, 0]);
10322 }
10323
10324 #[test]
10325 fn masked_fill_smoke() {
10326 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
10327 let probe = t
10330 .const_f32_like(vec![0.0, 1.0, 1.0, 0.0], vec![2, 2])
10331 .unwrap();
10332 let threshold = t.const_f32_like(vec![0.5; 4], vec![2, 2]).unwrap();
10333 let mask = probe.gt(&threshold).unwrap(); let out = t.masked_fill(&mask, fuel_ir::Scalar::F32(-9.0)).unwrap();
10335 assert_eq!(out.realize_f32(), vec![1.0, -9.0, -9.0, 4.0]);
10336 }
10337
10338 #[test]
10344 fn bool_is_distinguishable_from_u8_end_to_end() {
10345 let t = cpu_f32(vec![0.0, 5.0, 3.0, 0.0], &[4]);
10350 let thr = t.const_f32_like(vec![0.5; 4], vec![4]).unwrap();
10351 let mask = t.gt(&thr).unwrap();
10352 assert_eq!(mask.dtype(), DType::Bool, "gt yields Bool, not U8");
10353 assert_eq!(mask.realize_u8(), vec![0, 1, 1, 0], "mask bytes are 0/1");
10354
10355 let u8_vals = t
10362 .const_f32_like(vec![0.0, 5.0, 3.0, 0.0], vec![4])
10363 .unwrap()
10364 .to_dtype(DType::U8)
10365 .unwrap();
10366 assert_eq!(u8_vals.dtype(), DType::U8);
10367 assert_eq!(
10368 u8_vals.realize_u8(),
10369 vec![0, 5, 3, 0],
10370 "negative control: the U8 source must really hold 5 and 3, else the \
10371 conversion assertion below cannot discriminate"
10372 );
10373
10374 let as_bool = u8_vals.to_dtype(DType::Bool).unwrap();
10378 assert_eq!(as_bool.dtype(), DType::Bool);
10379 assert_eq!(
10380 as_bool.realize_u8(),
10381 vec![0, 1, 1, 0],
10382 "U8->Bool must CONVERT (5 -> 1), not reinterpret (5 -> 5)"
10383 );
10384
10385 assert_eq!(
10387 as_bool.to_dtype(DType::F32).unwrap().realize_f32(),
10388 vec![0.0, 1.0, 1.0, 0.0],
10389 "Bool->F32 yields 0.0/1.0"
10390 );
10391 assert_eq!(
10394 mask.to_dtype(DType::U8).unwrap().realize_u8(),
10395 vec![0, 1, 1, 0]
10396 );
10397
10398 let err = t.masked_fill(&u8_vals, fuel_ir::Scalar::F32(-9.0));
10403 assert!(
10404 err.is_err(),
10405 "a U8 mask must be REJECTED by masked_fill — Bool and U8 are \
10406 byte-identical, so accepting it would 'work' and erase the distinction"
10407 );
10408 }
10409
10410 #[test]
10424 fn float_to_bool_lowering_preserves_ieee_semantics() {
10425 let t = cpu_f32(
10426 vec![
10427 0.0,
10428 -0.0,
10429 5.0,
10430 -3.0,
10431 f32::NAN,
10432 f32::INFINITY,
10433 f32::NEG_INFINITY,
10434 ],
10435 &[7],
10436 );
10437 let b = t.to_dtype(DType::Bool).unwrap();
10438 assert_eq!(b.dtype(), DType::Bool, "to_dtype(Bool) still yields Bool");
10439 assert_eq!(
10440 b.realize_u8(),
10441 vec![0, 0, 1, 1, 1, 1, 1],
10442 "0 and -0.0 are false; every other value including NaN and both \
10443 infinities is true",
10444 );
10445 }
10446
10447 #[test]
10448 fn index_add_smoke() {
10449 let base = cpu_f32(vec![1.0, 1.0, 1.0, 1.0], &[2, 2]);
10450 let src = base
10451 .const_f32_like(vec![10.0, 20.0, 30.0, 40.0], vec![2, 2])
10452 .unwrap();
10453 let indices = base.const_u32_like(vec![0_u32, 0_u32], vec![2]).unwrap();
10454 let out = base.index_add(0, &indices, &src).unwrap();
10455 assert_eq!(out.shape().dims(), &[2, 2]);
10456 let v = out.realize_f32();
10458 assert_eq!(v[0], 41.0); assert_eq!(v[1], 61.0); assert_eq!(v[2], 1.0);
10461 assert_eq!(v[3], 1.0);
10462 }
10463
10464 #[test]
10465 fn scatter_add_smoke() {
10466 let base = cpu_f32(vec![0.0, 0.0, 0.0, 0.0], &[2, 2]);
10467 let src = base
10468 .const_f32_like(vec![5.0, 6.0, 7.0, 8.0], vec![2, 2])
10469 .unwrap();
10470 let indices = base
10471 .const_u32_like(vec![0_u32, 1_u32, 1_u32, 0_u32], vec![2, 2])
10472 .unwrap();
10473 let out = base.scatter_add(0, &indices, &src).unwrap();
10474 assert_eq!(out.shape().dims(), &[2, 2]);
10475 }
10476
10477 #[test]
10478 fn inplace_activations_compile_and_run() {
10479 let t = cpu_f32(vec![-1.0, 0.5, -3.0, 2.0], &[4]);
10480 let r = cpu_f32(vec![-1.0, 0.5, -3.0, 2.0], &[4]).relu_inplace();
10482 let _ = cpu_f32(vec![-1.0, 0.5, -3.0, 2.0], &[4]).silu_inplace();
10483 let _ = cpu_f32(vec![-1.0, 0.5, -3.0, 2.0], &[4]).gelu_tanh_inplace();
10484 let _ = cpu_f32(vec![-1.0, 0.5, -3.0, 2.0], &[4]).tanh_inplace();
10485 let _ = cpu_f32(vec![-1.0, 0.5, -3.0, 2.0], &[4]).sigmoid_inplace();
10486 let _ = t.affine_inplace(2.0, 1.0);
10487 let v = r.realize_f32();
10489 assert_eq!(v, vec![0.0, 0.5, 0.0, 2.0]);
10490 }
10491
10492 #[test]
10493 fn const_f64_like_round_trips() {
10494 let anchor = cpu_f32(vec![0.0], &[1]);
10495 let t = anchor.const_f64_like(vec![1.5, 2.5, 3.5], vec![3]).unwrap();
10496 assert_eq!(t.shape().dims(), &[3]);
10497 assert_eq!(t.dtype(), DType::F64);
10498 assert_eq!(t.realize_f64(), vec![1.5, 2.5, 3.5]);
10499 }
10500
10501 #[test]
10502 fn const_i64_like_round_trips() {
10503 let anchor = cpu_f32(vec![0.0], &[1]);
10504 let t = anchor.const_i64_like(vec![-1_i64, 2, -3], vec![3]).unwrap();
10505 assert_eq!(t.shape().dims(), &[3]);
10506 assert_eq!(t.dtype(), DType::I64);
10507 }
10508
10509 #[test]
10510 fn on_device_smoke_cpu() {
10511 let t = cpu_f32(vec![1.0, 2.0], &[2]);
10512 let pinned = t.on_device(&Device::cpu());
10513 assert_eq!(pinned.realize_f32(), vec![1.0, 2.0]);
10514 }
10515
10516 #[test]
10517 fn copy_to_device_same_device_round_trips() {
10518 let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
10519 let copied = t.copy_to_device(&Device::cpu());
10520 assert_eq!(copied.realize_f32(), vec![1.0, 2.0, 3.0]);
10521 }
10522}
10523
10524#[cfg(test)]
10528mod phase_a2_composite_tests {
10529 use super::*;
10530
10531 fn cpu_f32(data: Vec<f32>, shape: &[usize]) -> Tensor {
10532 Tensor::from_f32(data, shape.to_vec(), &Device::cpu()).unwrap()
10533 }
10534
10535 #[test]
10536 fn transpose_last_two_swaps_last_two_dims() {
10537 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
10538 let out = t.transpose_last_two().unwrap();
10539 assert_eq!(out.shape().dims(), &[3, 2]);
10540 assert_eq!(out.realize_f32(), vec![1.0, 4.0, 2.0, 5.0, 3.0, 6.0]);
10541 }
10542
10543 #[test]
10544 fn t_is_alias_of_transpose_last_two() {
10545 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
10546 assert_eq!(
10547 t.t().unwrap().realize_f32(),
10548 t.transpose_last_two().unwrap().realize_f32()
10549 );
10550 }
10551
10552 #[test]
10553 fn transpose_dims_swaps_arbitrary_axes() {
10554 let t = cpu_f32((0..24).map(|i| i as f32).collect(), &[2, 3, 4]);
10555 let out = t.transpose_dims(0, 2).unwrap();
10556 assert_eq!(out.shape().dims(), &[4, 3, 2]);
10557 }
10558
10559 #[test]
10560 fn transpose_dims_identity_when_same_axis() {
10561 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
10562 let out = t.transpose_dims(0, 0).unwrap();
10563 assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0, 4.0]);
10564 }
10565
10566 #[test]
10567 fn transpose_dims_errors_out_of_bounds() {
10568 let t = cpu_f32(vec![0.0; 6], &[2, 3]);
10569 assert!(t.transpose_dims(0, 2).is_err());
10570 assert!(t.transpose_dims(5, 0).is_err());
10571 }
10572
10573 #[test]
10574 fn flatten_merges_middle_dims() {
10575 let t = cpu_f32(vec![0.0; 24], &[2, 3, 4]);
10576 let out = t.flatten(0, 1).unwrap();
10577 assert_eq!(out.shape().dims(), &[6, 4]);
10578 }
10579
10580 #[test]
10581 fn flatten_to_merges_leading_dims() {
10582 let t = cpu_f32(vec![0.0; 24], &[2, 3, 4]);
10583 let out = t.flatten_to(1).unwrap();
10584 assert_eq!(out.shape().dims(), &[6, 4]);
10585 }
10586
10587 #[test]
10588 fn flatten_from_merges_trailing_dims() {
10589 let t = cpu_f32(vec![0.0; 24], &[2, 3, 4]);
10590 let out = t.flatten_from(1).unwrap();
10591 assert_eq!(out.shape().dims(), &[2, 12]);
10592 }
10593
10594 #[test]
10595 fn flatten_all_produces_rank_one() {
10596 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
10597 let out = t.flatten_all().unwrap();
10598 assert_eq!(out.shape().dims(), &[6]);
10599 assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
10600 }
10601
10602 #[test]
10612 fn rope_batched_matches_single_position_rope_row_by_row() {
10613 let lcg = |n: usize, seed: u32| -> Vec<f32> {
10614 let mut s = seed;
10615 (0..n)
10616 .map(|_| {
10617 s = s.wrapping_mul(1103515245).wrapping_add(12345);
10618 ((s >> 16) as u16 as f32 / 65535.0 - 0.5) * 0.5
10619 })
10620 .collect()
10621 };
10622 let (b, heads, hd) = (3usize, 4usize, 8usize);
10623 let base = 10000.0f64;
10624 let positions = [0usize, 7, 3];
10625
10626 let x_data = lcg(b * heads * hd, 11);
10627 let x = cpu_f32(x_data.clone(), &[b, heads, 1, hd]);
10628 let (cos, sin) = x.rope_tables_const_batched(base, &positions, hd);
10629 let got = x.rope_batched(&cos, &sin).unwrap().realize_f32();
10630
10631 let per_row = heads * hd;
10632 for (row, &pos) in positions.iter().enumerate() {
10633 let row_data = x_data[row * per_row..(row + 1) * per_row].to_vec();
10634 let xr = cpu_f32(row_data, &[1, heads, 1, hd]);
10635 let (c, s) = xr.rope_tables_const(base, pos, 1, hd);
10636 let want = xr
10637 .rope_with_tables_decomposed(&c, &s)
10638 .unwrap()
10639 .realize_f32();
10640 assert_eq!(
10641 &got[row * per_row..(row + 1) * per_row],
10642 &want[..],
10643 "row {row} (position {pos}) != decomposed RoPE at that position",
10644 );
10645 }
10646
10647 let shared = [positions[0]; 3];
10652 let (c0, s0) = x.rope_tables_const_batched(base, &shared, hd);
10653 let wrong = x.rope_batched(&c0, &s0).unwrap().realize_f32();
10654 for (row, &pos) in positions.iter().enumerate().skip(1) {
10655 assert_ne!(
10656 &wrong[row * per_row..(row + 1) * per_row],
10657 &got[row * per_row..(row + 1) * per_row],
10658 "CONTROL: row {row} at shared position 0 matched its own position \
10659 {pos} — per-row RoPE not applied, or comparison blind to it",
10660 );
10661 }
10662 }
10663
10664 #[test]
10665 fn flatten_errors_on_bad_range() {
10666 let t = cpu_f32(vec![0.0; 6], &[2, 3]);
10667 assert!(t.flatten(0, 5).is_err());
10668 assert!(t.flatten(2, 1).is_err()); }
10670
10671 #[test]
10672 fn split_heads_then_merge_heads_round_trip() {
10673 let x = cpu_f32((0..12).map(|i| i as f32).collect(), &[1, 2, 6]);
10675 let split = x.split_heads(2, 3).unwrap();
10676 assert_eq!(split.shape().dims(), &[1, 2, 2, 3]);
10677 let merged = split.merge_heads().unwrap();
10678 assert_eq!(merged.shape().dims(), &[1, 2, 6]);
10679 let m = merged.realize_f32();
10680 let original = x.realize_f32();
10681 for (a, b) in m.iter().zip(original.iter()) {
10682 assert!((a - b).abs() < 1e-7, "{a} vs {b}");
10683 }
10684 }
10685
10686 #[test]
10687 fn rope_tables_const_shapes_and_anchoring() {
10688 let anchor = cpu_f32(vec![0.0_f32; 8], &[1, 4, 2]);
10689 let (cos, sin) = anchor.rope_tables_const(10_000.0, 0, 4, 8);
10690 assert_eq!(cos.shape().dims(), &[4, 8]);
10691 assert_eq!(sin.shape().dims(), &[4, 8]);
10692 let cv = cos.realize_f32();
10694 let sv = sin.realize_f32();
10695 for i in 0..8 {
10697 assert!((cv[i] - 1.0).abs() < 1e-5, "cos[0,{i}] = {}", cv[i]);
10698 assert!(sv[i].abs() < 1e-5, "sin[0,{i}] = {}", sv[i]);
10699 }
10700 }
10701
10702 #[test]
10703 fn embed_tokens_shape_and_lookup() {
10704 let vocab_size = 5;
10707 let hidden = 3;
10708 let table: Vec<f32> = (0..vocab_size)
10709 .flat_map(|i| vec![i as f32, i as f32 + 0.5, i as f32 + 1.0])
10710 .collect();
10711 let tokens = vec![1_u32, 3, 0];
10712 let out = Tensor::embed_tokens(
10713 std::sync::Arc::from(table),
10714 vocab_size,
10715 hidden,
10716 &tokens,
10717 &crate::Device::cpu(),
10718 )
10719 .unwrap();
10720 assert_eq!(out.shape().dims(), &[1, 3, hidden]);
10721 let v = out.realize_f32();
10722 let want = [
10723 1.0_f32, 1.5, 2.0, 3.0, 3.5, 4.0, 0.0, 0.5, 1.0, ];
10727 for (i, (&got, &exp)) in v.iter().zip(want.iter()).enumerate() {
10728 assert!((got - exp).abs() < 1e-5, "row {i}: got={got} want={exp}");
10729 }
10730 }
10731
10732 #[test]
10733 fn embed_tokens_anchored_lives_on_receiver_graph() {
10734 let vocab_size = 4;
10738 let hidden = 2;
10739 let table: Vec<f32> = (0..vocab_size)
10740 .flat_map(|i| vec![i as f32, i as f32 * 2.0])
10741 .collect();
10742 let table_arc: std::sync::Arc<[f32]> = std::sync::Arc::from(table);
10743 let tokens = vec![2_u32, 1];
10744
10745 let anchor = cpu_f32(vec![0.0_f32], &[1]);
10746 let embedded = anchor
10747 .embed_tokens_anchored(
10748 std::sync::Arc::clone(&table_arc),
10749 vocab_size,
10750 hidden,
10751 &tokens,
10752 )
10753 .unwrap();
10754 assert_eq!(embedded.shape().dims(), &[1, 2, hidden]);
10755
10756 let one_scaled = anchor
10758 .const_f32_like(std::sync::Arc::from(vec![1.0_f32]), Shape::from_dims(&[1]))
10759 .unwrap();
10760 let _ = embedded
10761 .add(
10762 &one_scaled
10763 .reshape(Shape::from_dims(&[1, 1, 1]))
10764 .unwrap()
10765 .broadcast_to(Shape::from_dims(&[1, 2, hidden]))
10766 .unwrap(),
10767 )
10768 .unwrap();
10769 let v = embedded.realize_f32();
10770 let want = [
10771 2.0_f32, 4.0, 1.0, 2.0, ];
10774 for (i, (&got, &exp)) in v.iter().zip(want.iter()).enumerate() {
10775 assert!((got - exp).abs() < 1e-5, "row {i}: got={got} want={exp}");
10776 }
10777 }
10778
10779 #[test]
10780 fn embed_tokens_empty_returns_error() {
10781 let r = Tensor::embed_tokens(
10782 std::sync::Arc::from(vec![0.0_f32]),
10783 1,
10784 1,
10785 &[],
10786 &crate::Device::cpu(),
10787 );
10788 assert!(r.is_err());
10789 }
10790
10791 #[test]
10792 fn softcap_matches_tanh_form() {
10793 let x = cpu_f32(vec![0.0_f32, 5.0, -5.0, 30.0], &[1, 4]);
10795 let capped = x.softcap(10.0).realize_f32();
10796 let expect = [0.0_f32, 4.6212, -4.6212, 9.9505];
10798 for (i, (&got, &want)) in capped.iter().zip(expect.iter()).enumerate() {
10799 assert!(
10800 (got - want).abs() < 1e-3,
10801 "softcap[{i}] got={got} want={want}"
10802 );
10803 }
10804 }
10805
10806 #[test]
10807 fn softcap_optional_none_returns_input_unchanged() {
10808 let x = cpu_f32(vec![1.0_f32, -2.0, 30.0], &[1, 3]);
10809 let out = x.softcap_optional(None).realize_f32();
10810 let expect = [1.0_f32, -2.0, 30.0];
10811 for (g, w) in out.iter().zip(expect.iter()) {
10812 assert!((g - w).abs() < 1e-6);
10813 }
10814 let out = x.softcap_optional(Some(0.0)).realize_f32();
10816 for (g, w) in out.iter().zip(expect.iter()) {
10817 assert!((g - w).abs() < 1e-6);
10818 }
10819 }
10820
10821 #[test]
10822 fn rope_partial_full_dim_matches_rope_with_tables() {
10823 let qk = cpu_f32(vec![1.0_f32; 1 * 1 * 2 * 4], &[1, 1, 2, 4]);
10825 let (cos, sin) = qk.rope_tables_const(10_000.0, 0, 2, 4);
10826 let via_partial = qk.rope_partial(&cos, &sin, 4).unwrap();
10827 let via_full = qk.rope_with_tables(&cos, &sin).unwrap();
10828 let a = via_partial.realize_f32();
10829 let b = via_full.realize_f32();
10830 for (i, (av, bv)) in a.iter().zip(b.iter()).enumerate() {
10831 assert!((av - bv).abs() < 1e-6, "{i}: {av} vs {bv}");
10832 }
10833 }
10834
10835 #[test]
10836 fn rope_partial_pass_through_suffix_unchanged() {
10837 let qk = cpu_f32(
10841 vec![
10842 1.0_f32, 2.0, 3.0, 4.0,
10844 ],
10845 &[1, 1, 1, 4],
10846 );
10847 let (cos, sin) = qk.rope_tables_const(10_000.0, 0, 1, 2);
10848 let out = qk.rope_partial(&cos, &sin, 2).unwrap().realize_f32();
10849 for (i, &v) in out.iter().enumerate() {
10850 let expect = [1.0_f32, 2.0, 3.0, 4.0][i];
10851 assert!((v - expect).abs() < 1e-6, "{i}: {v} != {expect}");
10852 }
10853 }
10854
10855 #[test]
10856 fn add_optional_trailing_bias_none_returns_input_unchanged() {
10857 let a = cpu_f32(vec![1.0_f32, 2.0, 3.0], &[1, 3]);
10858 let original = a.realize_f32();
10859 let out = a.add_optional_trailing_bias(None).unwrap();
10860 assert_eq!(out.realize_f32(), original);
10861 }
10862
10863 #[test]
10864 fn add_optional_trailing_bias_some_applies_add() {
10865 let a = cpu_f32(vec![1.0_f32, 2.0, 3.0], &[1, 3]);
10866 let bias = std::sync::Arc::<[f32]>::from(vec![10.0_f32, 20.0, 30.0]);
10867 let out = a.add_optional_trailing_bias(Some(&bias)).unwrap();
10868 assert_eq!(out.realize_f32(), vec![11.0, 22.0, 33.0]);
10869 }
10870
10871 #[test]
10872 fn add_trailing_bias_broadcasts_across_leading_dims() {
10873 let x = cpu_f32(vec![1.0_f32, 2.0, 3.0, 10.0, 20.0, 30.0], &[2, 3]);
10875 let bias = std::sync::Arc::<[f32]>::from(vec![100.0_f32, 200.0, 300.0]);
10876 let out = x.add_trailing_bias(bias).unwrap();
10877 assert_eq!(out.shape().dims(), &[2, 3]);
10878 let v = out.realize_f32();
10879 assert_eq!(v, vec![101.0, 202.0, 303.0, 110.0, 220.0, 330.0]);
10880 }
10881
10882 #[test]
10883 fn rms_norm_affine_with_offset_adds_offset_to_each_gain() {
10884 let x = cpu_f32(vec![1.0_f32, 2.0, 3.0], &[1, 3]);
10885 let gain_raw: [f32; 3] = [-0.5, 0.0, 0.5];
10886 let via_offset = x.rms_norm_affine_with_offset(&gain_raw, 1.0, 1e-6).unwrap();
10887 let gain_shifted = std::sync::Arc::<[f32]>::from(vec![0.5_f32, 1.0, 1.5]);
10888 let via_plain = x.rms_norm_affine(gain_shifted, 1e-6).unwrap();
10889 let a = via_offset.realize_f32();
10890 let b = via_plain.realize_f32();
10891 for (x, y) in a.iter().zip(b.iter()) {
10892 assert!((x - y).abs() < 1e-6, "{x} vs {y}");
10893 }
10894 }
10895
10896 #[test]
10897 fn global_avg_pool_2d_averages_spatial_dims() {
10898 let x = cpu_f32(
10902 vec![
10903 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,
10904 ],
10905 &[1, 2, 2, 3],
10906 );
10907 let out = x.global_avg_pool_2d().unwrap();
10908 assert_eq!(out.shape().dims(), &[1, 2]);
10909 let v = out.realize_f32();
10910 assert!((v[0] - 3.5).abs() < 1e-5);
10911 assert!((v[1] - 35.0).abs() < 1e-4);
10912 }
10913
10914 #[test]
10915 fn channel_affine_4d_applies_per_channel_gain_and_bias() {
10916 let x = cpu_f32(
10918 vec![
10919 1.0_f32, 2.0, 3.0, 4.0, 10.0, 20.0, 30.0, 40.0, ],
10922 &[1, 2, 2, 2],
10923 );
10924 let gain = std::sync::Arc::<[f32]>::from(vec![2.0_f32, 0.5]);
10925 let bias = std::sync::Arc::<[f32]>::from(vec![1.0_f32, -10.0]);
10926 let out = x.channel_affine_4d(gain, bias).unwrap();
10927 let v = out.realize_f32();
10928 assert_eq!(&v[0..4], &[3.0, 5.0, 7.0, 9.0]);
10930 assert_eq!(&v[4..8], &[-5.0, 0.0, 5.0, 10.0]);
10932 }
10933
10934 #[test]
10935 fn additive_causal_mask_has_strict_lower_triangle() {
10936 let anchor = cpu_f32(vec![0.0_f32], &[1]);
10937 let mask = Tensor::additive_causal_mask_like(&anchor, 4);
10938 assert_eq!(mask.shape().dims(), &[4, 4]);
10939 let v = mask.realize_f32();
10940 for i in 0..4 {
10946 for j in 0..4 {
10947 let got = v[i * 4 + j];
10948 if j > i {
10949 assert!(
10950 got.is_infinite() && got.is_sign_negative(),
10951 "above-diag (i={i}, j={j}) should be -inf, got {got}"
10952 );
10953 } else {
10954 assert_eq!(
10955 got, 0.0,
10956 "on/below-diag (i={i}, j={j}) should be 0, got {got}"
10957 );
10958 }
10959 }
10960 }
10961 }
10962
10963 #[test]
10964 fn layer_norm_affine_unit_gain_zero_bias_matches_layer_norm_last_dim() {
10965 let a = cpu_f32(vec![1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
10966 let gain = std::sync::Arc::<[f32]>::from(vec![1.0_f32; 3]);
10967 let bias = std::sync::Arc::<[f32]>::from(vec![0.0_f32; 3]);
10968 let out_affine = a.layer_norm_affine(gain, bias, 1e-5).unwrap();
10969 let out_plain = a.layer_norm_last_dim(1e-5).unwrap();
10970 let va = out_affine.realize_f32();
10971 let vp = out_plain.realize_f32();
10972 for (a, b) in va.iter().zip(vp.iter()) {
10973 assert!((a - b).abs() < 1e-5, "{a} vs {b}");
10974 }
10975 }
10976
10977 #[test]
10978 fn layer_norm_affine_applies_gain_and_bias() {
10979 let a = cpu_f32(vec![1.0_f32, 2.0, 3.0], &[1, 3]);
10980 let gain = std::sync::Arc::<[f32]>::from(vec![2.0_f32, 0.5, 1.5]);
10981 let bias = std::sync::Arc::<[f32]>::from(vec![10.0_f32, -5.0, 0.0]);
10982 let out = a.layer_norm_affine(gain, bias, 1e-5).unwrap();
10983 let v = out.realize_f32();
10984 let mean = 2.0_f32;
10986 let var = ((1.0 - mean).powi(2) + (2.0 - mean).powi(2) + (3.0 - mean).powi(2)) / 3.0;
10987 let den = (var + 1e-5_f32).sqrt();
10988 let expected = [
10989 ((1.0 - mean) / den) * 2.0 + 10.0,
10990 ((2.0 - mean) / den) * 0.5 + (-5.0),
10991 ((3.0 - mean) / den) * 1.5 + 0.0,
10992 ];
10993 for (got, want) in v.iter().zip(expected.iter()) {
10994 assert!((got - want).abs() < 1e-4, "{got} vs {want}");
10995 }
10996 }
10997
10998 #[test]
10999 fn l2_normalize_last_dim_unit_norm_per_row() {
11000 let a = cpu_f32(vec![3.0, 4.0, 0.0, 1.0, 2.0, 2.0], &[2, 3]);
11002 let out = a.l2_normalize(1_usize, 1e-12).unwrap();
11003 assert_eq!(out.shape().dims(), &[2, 3]);
11004 let v = out.realize_f32();
11005 let row0_norm = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
11006 let row1_norm = (v[3] * v[3] + v[4] * v[4] + v[5] * v[5]).sqrt();
11007 assert!((row0_norm - 1.0).abs() < 1e-5, "row 0 norm = {row0_norm}");
11008 assert!((row1_norm - 1.0).abs() < 1e-5, "row 1 norm = {row1_norm}");
11009 assert!((v[0] - 0.6).abs() < 1e-5);
11011 assert!((v[1] - 0.8).abs() < 1e-5);
11012 assert!(v[2].abs() < 1e-5);
11013 }
11014
11015 #[test]
11016 fn l2_normalize_eps_zero_works_when_nonzero() {
11017 let a = cpu_f32(vec![1.0_f32, 0.0], &[2]);
11018 let out = a.l2_normalize(0_usize, 0.0).unwrap();
11019 let v = out.realize_f32();
11020 assert!((v[0] - 1.0).abs() < 1e-6);
11021 assert!(v[1].abs() < 1e-6);
11022 }
11023
11024 #[test]
11025 fn repeat_interleave_last_dim_matches_torch_semantics() {
11026 let a = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
11030 let out = a.repeat_interleave(1_usize, 2).unwrap();
11031 assert_eq!(out.shape().dims(), &[2, 6]);
11032 assert_eq!(
11033 out.realize_f32(),
11034 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]
11035 );
11036 }
11037
11038 #[test]
11039 fn repeat_interleave_middle_dim() {
11040 let a = cpu_f32((0..8).map(|i| i as f32).collect(), &[2, 2, 2]);
11042 let out = a.repeat_interleave(1_usize, 3).unwrap();
11043 assert_eq!(out.shape().dims(), &[2, 6, 2]);
11044 let v = out.realize_f32();
11046 assert_eq!(&v[0..6], &[0.0, 1.0, 0.0, 1.0, 0.0, 1.0]);
11047 assert_eq!(&v[6..12], &[2.0, 3.0, 2.0, 3.0, 2.0, 3.0]);
11048 }
11049
11050 #[test]
11051 fn repeat_interleave_repeats_one_is_noop() {
11052 let a = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11053 let out = a.repeat_interleave(0_usize, 1).unwrap();
11054 assert_eq!(out.shape().dims(), &[3]);
11055 assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0]);
11056 }
11057
11058 #[test]
11059 fn repeat_interleave_repeats_zero_errors() {
11060 let a = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11061 assert!(a.repeat_interleave(0_usize, 0).is_err());
11062 }
11063
11064 #[test]
11065 fn stack_adds_leading_dim() {
11066 let a = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11067 let b = a.const_f32_like(vec![4.0, 5.0, 6.0], vec![3]).unwrap();
11068 let out = Tensor::stack(&[&a, &b], 0).unwrap();
11069 assert_eq!(out.shape().dims(), &[2, 3]);
11070 assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
11071 }
11072
11073 #[test]
11074 fn stack_adds_trailing_dim() {
11075 let a = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11076 let b = a.const_f32_like(vec![4.0, 5.0, 6.0], vec![3]).unwrap();
11077 let out = Tensor::stack(&[&a, &b], 1).unwrap();
11078 assert_eq!(out.shape().dims(), &[3, 2]);
11079 assert_eq!(out.realize_f32(), vec![1.0, 4.0, 2.0, 5.0, 3.0, 6.0]);
11080 }
11081
11082 #[test]
11083 fn stack_rejects_mismatched_shapes() {
11084 let a = cpu_f32(vec![1.0, 2.0], &[2]);
11085 let b = a.const_f32_like(vec![3.0, 4.0, 5.0], vec![3]).unwrap();
11086 assert!(Tensor::stack(&[&a, &b], 0).is_err());
11087 }
11088
11089 #[test]
11090 fn stack_rejects_empty_input() {
11091 let result = Tensor::stack(&[], 0);
11092 assert!(result.is_err());
11093 }
11094
11095 #[test]
11096 fn repeat_tiles_along_each_dim() {
11097 let t = cpu_f32(vec![1.0, 2.0], &[2]);
11098 let out = t.repeat(vec![3]).unwrap();
11099 assert_eq!(out.shape().dims(), &[6]);
11100 assert_eq!(out.realize_f32(), vec![1.0, 2.0, 1.0, 2.0, 1.0, 2.0]);
11101 }
11102
11103 #[test]
11104 fn repeat_extends_rank_when_needed() {
11105 let t = cpu_f32(vec![1.0, 2.0], &[2]);
11106 let out = t.repeat(vec![3, 2]).unwrap();
11108 assert_eq!(out.shape().dims(), &[3, 4]);
11109 }
11110
11111 #[test]
11112 fn repeat_identity_with_all_ones() {
11113 let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11114 let out = t.repeat(vec![1]).unwrap();
11115 assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0]);
11116 }
11117}
11118
11119#[cfg(test)]
11123mod phase_a3_keepdim_tests {
11124 use super::*;
11125
11126 fn cpu_f32(data: Vec<f32>, shape: &[usize]) -> Tensor {
11127 Tensor::from_f32(data, shape.to_vec(), &Device::cpu()).unwrap()
11128 }
11129
11130 #[test]
11131 fn sum_keepdim_preserves_dim_as_one() {
11132 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11133 let out = t.sum_keepdim(1_usize).unwrap();
11134 assert_eq!(out.shape().dims(), &[2, 1]);
11135 assert_eq!(out.realize_f32(), vec![3.0, 7.0]);
11136 }
11137
11138 #[test]
11139 fn mean_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.mean_keepdim(0_usize).unwrap();
11142 assert_eq!(out.shape().dims(), &[1, 2]);
11143 assert_eq!(out.realize_f32(), vec![2.0, 3.0]);
11144 }
11145
11146 #[test]
11147 fn max_keepdim_preserves_dim_as_one() {
11148 let t = cpu_f32(vec![1.0, 3.0, 2.0, 4.0], &[2, 2]);
11149 let out = t.max_keepdim(1_usize).unwrap();
11150 assert_eq!(out.shape().dims(), &[2, 1]);
11151 assert_eq!(out.realize_f32(), vec![3.0, 4.0]);
11152 }
11153
11154 #[test]
11155 fn min_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.min_keepdim(1_usize).unwrap();
11158 assert_eq!(out.shape().dims(), &[2, 1]);
11159 assert_eq!(out.realize_f32(), vec![1.0, 2.0]);
11160 }
11161
11162 fn var_in(dtype: &str, data: &[f64], shape: &[usize], dim: usize, correction: f64) -> Vec<f64> {
11169 let dev = Device::cpu();
11170 let s = Shape::from_dims(shape);
11171 match dtype {
11172 "f32" => Tensor::from_f32(data.iter().map(|&x| x as f32).collect::<Vec<_>>(), s, &dev)
11173 .unwrap()
11174 .var(dim, correction)
11175 .unwrap()
11176 .realize_f32()
11177 .iter()
11178 .map(|&x| x as f64)
11179 .collect(),
11180 "f64" => Tensor::from_f64(data.to_vec(), s, &dev)
11181 .unwrap()
11182 .var(dim, correction)
11183 .unwrap()
11184 .realize_f64(),
11185 "f16" => Tensor::from_f16(
11186 data.iter()
11187 .map(|&x| half::f16::from_f64(x))
11188 .collect::<Vec<_>>(),
11189 s,
11190 &dev,
11191 )
11192 .unwrap()
11193 .var(dim, correction)
11194 .unwrap()
11195 .realize_f16()
11196 .iter()
11197 .map(|x| x.to_f64())
11198 .collect(),
11199 "bf16" => Tensor::from_bf16(
11200 data.iter()
11201 .map(|&x| half::bf16::from_f64(x))
11202 .collect::<Vec<_>>(),
11203 s,
11204 &dev,
11205 )
11206 .unwrap()
11207 .var(dim, correction)
11208 .unwrap()
11209 .realize_bf16()
11210 .iter()
11211 .map(|x| x.to_f64())
11212 .collect(),
11213 other => panic!("dtype {other}"),
11214 }
11215 }
11216
11217 #[test]
11219 fn var_rejects_a_nan_correction() {
11220 let dev = Device::cpu();
11221 let x = Tensor::from_f32(vec![1.0, 3.0], Shape::from_dims(&[2]), &dev).unwrap();
11222 assert!(x.var_keepdim(0, f64::NAN).is_err());
11223 assert!(x.var_keepdim(0, 1.0).is_ok());
11225 }
11226
11227 #[test]
11228 fn var_divisor_is_clamped_at_zero_in_every_dtype() {
11229 for dt in ["f32", "f64", "f16", "bf16"] {
11230 assert!(var_in(dt, &[5.0], &[1], 0, 1.0)[0].is_nan(), "{dt} [5] c=1");
11232 let v = var_in(dt, &[5.0, 7.0], &[2, 1], 1, 1.0);
11233 assert!(v[0].is_nan() && v[1].is_nan(), "{dt} [[5],[7]] c=1: {v:?}");
11234 assert_eq!(
11236 var_in(dt, &[1.0, 3.0], &[2], 0, 2.0)[0],
11237 f64::INFINITY,
11238 "{dt} [1,3] c=2"
11239 );
11240 assert!(var_in(dt, &[5.0], &[1], 0, 2.0)[0].is_nan(), "{dt} [5] c=2");
11242 assert_eq!(
11243 var_in(dt, &[1.0, 3.0], &[2], 0, 3.0)[0],
11244 f64::INFINITY,
11245 "{dt} [1,3] c=3"
11246 );
11247 assert_eq!(var_in(dt, &[5.0], &[1], 0, 0.0)[0], 0.0, "{dt} [5] c=0");
11249 assert_eq!(
11250 var_in(dt, &[1.0, 3.0], &[2], 0, 1.0)[0],
11251 2.0,
11252 "{dt} [1,3] c=1"
11253 );
11254 }
11255 }
11256
11257 #[test]
11258 fn var_matches_unbiased_formula_with_correction_1() {
11259 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
11261 let out = t.var(1, 1.0).unwrap();
11262 assert_eq!(out.shape().dims(), &[2]);
11263 let v = out.realize_f32();
11264 assert!((v[0] - 1.0).abs() < 1e-5, "var row 0 = {} != 1.0", v[0]);
11265 assert!((v[1] - 1.0).abs() < 1e-5, "var row 1 = {} != 1.0", v[1]);
11266 }
11267
11268 #[test]
11273 fn var_population_with_correction_0() {
11274 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
11276 let out = t.var(1, 0.0).unwrap();
11277 let v = out.realize_f32();
11278 let want = 2.0 / 3.0;
11279 assert!(
11280 (v[0] - want).abs() < 1e-5,
11281 "population var row 0 = {} != {want}",
11282 v[0]
11283 );
11284 assert!(
11285 (v[1] - want).abs() < 1e-5,
11286 "population var row 1 = {} != {want}",
11287 v[1]
11288 );
11289 }
11290
11291 #[test]
11292 fn var_keepdim_preserves_dim() {
11293 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
11294 let out = t.var_keepdim(1, 1.0).unwrap();
11295 assert_eq!(out.shape().dims(), &[2, 1]);
11296 }
11297
11298 #[test]
11299 fn var_errors_out_of_bounds() {
11300 let t = cpu_f32(vec![1.0, 2.0], &[2]);
11301 assert!(t.var(3, 1.0).is_err());
11302 assert!(t.var_keepdim(3, 1.0).is_err());
11303 }
11304}
11305
11306#[cfg(test)]
11310mod phase_a4_composite_tests {
11311 use super::*;
11312
11313 fn cpu_f32(data: Vec<f32>, shape: &[usize]) -> Tensor {
11314 Tensor::from_f32(data, shape.to_vec(), &Device::cpu()).unwrap()
11315 }
11316
11317 #[test]
11318 fn affine_applies_mul_then_add() {
11319 let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11320 let out = t.affine(2.0, 10.0);
11321 assert_eq!(out.realize_f32(), vec![12.0, 14.0, 16.0]);
11322 }
11323
11324 #[test]
11325 fn scale_and_shift_alias_of_affine() {
11326 let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11327 assert_eq!(
11328 t.scale_and_shift(2.0, 10.0).realize_f32(),
11329 t.affine(2.0, 10.0).realize_f32(),
11330 );
11331 }
11332
11333 #[test]
11334 fn elu_matches_reference_values() {
11335 let t = cpu_f32(vec![1.0, 0.0, -1.0, -2.0], &[4]);
11336 let out = t.elu(1.0);
11337 let v = out.realize_f32();
11338 assert!((v[0] - 1.0).abs() < 1e-5);
11341 assert!(v[1].abs() < 1e-5);
11342 assert!((v[2] - ((-1.0_f32).exp() - 1.0)).abs() < 1e-5);
11343 assert!((v[3] - ((-2.0_f32).exp() - 1.0)).abs() < 1e-5);
11344 }
11345
11346 #[test]
11347 fn dot_of_rank_one_vectors() {
11348 let a = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11349 let b = a.const_f32_like(vec![4.0, 5.0, 6.0], vec![3]).unwrap();
11350 let out = a.dot(&b).unwrap();
11351 assert_eq!(out.shape().elem_count(), 1);
11352 let v = out.realize_f32();
11353 assert_eq!(v[0], 32.0); }
11355
11356 #[test]
11357 fn dot_rejects_non_rank_one() {
11358 let a = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11359 let b = a
11360 .const_f32_like(vec![1.0, 2.0, 3.0, 4.0], vec![2, 2])
11361 .unwrap();
11362 assert!(a.dot(&b).is_err());
11363 }
11364
11365 #[test]
11366 fn dot_rejects_length_mismatch() {
11367 let a = cpu_f32(vec![1.0, 2.0], &[2]);
11368 let b = a.const_f32_like(vec![1.0, 2.0, 3.0], vec![3]).unwrap();
11369 assert!(a.dot(&b).is_err());
11370 }
11371
11372 #[test]
11373 fn mv_matrix_times_vector() {
11374 let m = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
11375 let v = m.const_f32_like(vec![1.0, 1.0, 1.0], vec![3]).unwrap();
11376 let out = m.mv(&v).unwrap();
11377 assert_eq!(out.shape().dims(), &[2]);
11378 assert_eq!(out.realize_f32(), vec![6.0, 15.0]);
11379 }
11380
11381 #[test]
11382 fn matvec_is_mv_alias() {
11383 let m = cpu_f32(vec![1.0, 0.0, 0.0, 1.0], &[2, 2]);
11384 let v = m.const_f32_like(vec![3.0, 4.0], vec![2]).unwrap();
11385 let a = m.mv(&v).unwrap().realize_f32();
11386 let b = m.matvec(&v).unwrap().realize_f32();
11387 assert_eq!(a, b);
11388 }
11389
11390 #[test]
11391 fn mv_rejects_shape_mismatch() {
11392 let m = cpu_f32(vec![1.0; 6], &[2, 3]);
11393 let v = m.const_f32_like(vec![1.0, 1.0], vec![2]).unwrap();
11394 assert!(m.mv(&v).is_err());
11395 }
11396
11397 #[test]
11398 fn broadcast_matmul_passes_through_to_matmul() {
11399 let a = cpu_f32(vec![1.0, 0.0, 0.0, 1.0], &[2, 2]);
11400 let b = a
11401 .const_f32_like(vec![5.0, 6.0, 7.0, 8.0], vec![2, 2])
11402 .unwrap();
11403 let out = a.broadcast_matmul(&b).unwrap();
11404 assert_eq!(out.realize_f32(), vec![5.0, 6.0, 7.0, 8.0]);
11405 }
11406}
11407
11408#[cfg(test)]
11412mod phase_a5_factory_tests {
11413 use super::*;
11414
11415 fn cpu_f32(data: Vec<f32>, shape: &[usize]) -> Tensor {
11416 Tensor::from_f32(data, shape.to_vec(), &Device::cpu()).unwrap()
11417 }
11418
11419 #[test]
11420 fn ones_like_matches_shape_dtype_graph() {
11421 let t = cpu_f32(vec![5.0, 6.0, 7.0, 8.0], &[2, 2]);
11422 let ones = t.ones_like().unwrap();
11423 assert_eq!(ones.shape().dims(), t.shape().dims());
11424 assert_eq!(ones.dtype(), t.dtype());
11425 assert_eq!(ones.realize_f32(), vec![1.0; 4]);
11426 }
11427
11428 #[test]
11429 fn zeros_like_matches_shape_dtype_graph() {
11430 let t = cpu_f32(vec![5.0, 6.0, 7.0], &[3]);
11431 let zeros = t.zeros_like().unwrap();
11432 assert_eq!(zeros.realize_f32(), vec![0.0; 3]);
11433 }
11434
11435 #[test]
11436 fn static_ones_f32() {
11437 let t = Tensor::ones(vec![2, 3], DType::F32, &Device::cpu()).unwrap();
11438 assert_eq!(t.shape().dims(), &[2, 3]);
11439 assert_eq!(t.realize_f32(), vec![1.0; 6]);
11440 }
11441
11442 #[test]
11443 fn static_zeros_f64() {
11444 let t = Tensor::zeros(vec![4], DType::F64, &Device::cpu()).unwrap();
11445 assert_eq!(t.dtype(), DType::F64);
11446 assert_eq!(t.realize_f64(), vec![0.0; 4]);
11447 }
11448
11449 #[test]
11450 fn full_with_f32_scalar() {
11451 let t = Tensor::full(vec![5], fuel_ir::Scalar::F32(2.5), &Device::cpu()).unwrap();
11452 assert_eq!(t.realize_f32(), vec![2.5; 5]);
11453 }
11454
11455 #[test]
11456 fn eye_identity_matrix() {
11457 let t = Tensor::eye(3, DType::F32, &Device::cpu());
11458 assert_eq!(t.shape().dims(), &[3, 3]);
11459 assert_eq!(
11460 t.realize_f32(),
11461 vec![1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0],
11462 );
11463 }
11464
11465 #[test]
11466 fn tril2_lower_triangular_ones() {
11467 let t = Tensor::tril2(3, DType::F32, &Device::cpu());
11468 assert_eq!(
11469 t.realize_f32(),
11470 vec![1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0],
11471 );
11472 }
11473
11474 #[test]
11475 fn triu2_upper_triangular_ones() {
11476 let t = Tensor::triu2(3, DType::F32, &Device::cpu());
11477 assert_eq!(
11478 t.realize_f32(),
11479 vec![1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0],
11480 );
11481 }
11482
11483 #[test]
11484 fn meshgrid_ij_indexing_two_inputs() {
11485 let x = Tensor::from_f32(vec![1.0_f32, 2.0, 3.0], vec![3], &Device::cpu()).unwrap();
11486 let y = x.const_f32_like(vec![4.0_f32, 5.0], vec![2]).unwrap();
11487 let grids = Tensor::meshgrid(&[&x, &y], false).unwrap();
11488 assert_eq!(grids.len(), 2);
11489 assert_eq!(grids[0].shape().dims(), &[3, 2]);
11491 assert_eq!(grids[1].shape().dims(), &[3, 2]);
11492 assert_eq!(grids[0].realize_f32(), vec![1.0, 1.0, 2.0, 2.0, 3.0, 3.0]);
11494 assert_eq!(grids[1].realize_f32(), vec![4.0, 5.0, 4.0, 5.0, 4.0, 5.0]);
11496 }
11497
11498 #[test]
11499 fn meshgrid_xy_indexing_swaps_first_two() {
11500 let x = Tensor::from_f32(vec![1.0_f32, 2.0, 3.0], vec![3], &Device::cpu()).unwrap();
11501 let y = x.const_f32_like(vec![4.0_f32, 5.0], vec![2]).unwrap();
11502 let grids = Tensor::meshgrid(&[&x, &y], true).unwrap();
11503 assert_eq!(grids[0].shape().dims(), &[2, 3]);
11505 assert_eq!(grids[1].shape().dims(), &[2, 3]);
11506 assert_eq!(grids[0].realize_f32(), vec![1.0, 2.0, 3.0, 1.0, 2.0, 3.0]);
11508 assert_eq!(grids[1].realize_f32(), vec![4.0, 4.0, 4.0, 5.0, 5.0, 5.0]);
11510 }
11511
11512 #[test]
11513 fn meshgrid_rejects_single_input() {
11514 let x = Tensor::from_f32(vec![1.0_f32, 2.0], vec![2], &Device::cpu()).unwrap();
11515 assert!(Tensor::meshgrid(&[&x], false).is_err());
11516 }
11517
11518 #[test]
11519 fn meshgrid_rejects_non_rank_one() {
11520 let x = Tensor::from_f32(vec![1.0; 4], vec![2, 2], &Device::cpu()).unwrap();
11521 let y = x.const_f32_like(vec![1.0, 2.0], vec![2]).unwrap();
11522 assert!(Tensor::meshgrid(&[&x, &y], false).is_err());
11523 }
11524
11525 #[test]
11528 fn narrow_is_slice_alias() {
11529 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0], &[5]);
11530 let a = t.narrow(0, 1, 3).unwrap().realize_f32();
11531 let b = t.slice(0, 1, 3).unwrap().realize_f32();
11532 assert_eq!(a, b);
11533 assert_eq!(a, vec![2.0, 3.0, 4.0]);
11534 }
11535
11536 #[test]
11537 fn chunk_splits_evenly() {
11538 let t = cpu_f32((1..=6).map(|i| i as f32).collect(), &[6]);
11539 let parts = t.chunk(3, 0).unwrap();
11540 assert_eq!(parts.len(), 3);
11541 assert_eq!(parts[0].realize_f32(), vec![1.0, 2.0]);
11542 assert_eq!(parts[1].realize_f32(), vec![3.0, 4.0]);
11543 assert_eq!(parts[2].realize_f32(), vec![5.0, 6.0]);
11544 }
11545
11546 #[test]
11547 fn chunk_distributes_remainder_to_leading() {
11548 let t = cpu_f32((1..=7).map(|i| i as f32).collect(), &[7]);
11550 let parts = t.chunk(3, 0).unwrap();
11551 assert_eq!(parts.len(), 3);
11552 assert_eq!(parts[0].realize_f32(), vec![1.0, 2.0, 3.0]);
11553 assert_eq!(parts[1].realize_f32(), vec![4.0, 5.0]);
11554 assert_eq!(parts[2].realize_f32(), vec![6.0, 7.0]);
11555 }
11556
11557 #[test]
11558 fn chunk_returns_singletons_when_size_less_than_chunks() {
11559 let t = cpu_f32(vec![1.0, 2.0], &[2]);
11560 let parts = t.chunk(5, 0).unwrap();
11561 assert_eq!(parts.len(), 2);
11562 assert_eq!(parts[0].realize_f32(), vec![1.0]);
11563 assert_eq!(parts[1].realize_f32(), vec![2.0]);
11564 }
11565
11566 #[test]
11567 fn get_at_first_dim() {
11568 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[3, 2]);
11569 let row1 = t.get(1).unwrap();
11570 assert_eq!(row1.shape().dims(), &[2]);
11571 assert_eq!(row1.realize_f32(), vec![3.0, 4.0]);
11572 }
11573
11574 #[test]
11575 fn get_on_dim_arbitrary_axis() {
11576 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[3, 2]);
11577 let col0 = t.get_on_dim(1, 0).unwrap();
11578 assert_eq!(col0.shape().dims(), &[3]);
11579 assert_eq!(col0.realize_f32(), vec![1.0, 3.0, 5.0]);
11580 }
11581
11582 #[test]
11583 fn sum_dims_multi_dim_reduces_to_smaller() {
11584 let t = cpu_f32(vec![1.0; 24], &[2, 3, 4]);
11586 let s = t.sum_dims([0, 2_usize]).unwrap();
11587 assert_eq!(s.shape().dims(), &[3]);
11588 assert_eq!(s.realize_f32(), vec![8.0; 3]);
11590 }
11591
11592 #[test]
11593 fn mean_dims_multi_dim() {
11594 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11595 let m = t.mean_dims([0, 1_usize]).unwrap();
11596 assert_eq!(m.shape().dims(), &[] as &[usize]);
11597 assert_eq!(m.realize_f32(), vec![2.5]);
11598 }
11599
11600 #[test]
11601 fn sum_dims_keepdim_preserves_rank() {
11602 let t = cpu_f32(vec![1.0; 24], &[2, 3, 4]);
11603 let s = t.sum_dims_keepdim(&[0, 2]).unwrap();
11604 assert_eq!(s.shape().dims(), &[1, 3, 1]);
11605 }
11606
11607 #[test]
11608 fn mean_dims_keepdim_preserves_rank() {
11609 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11610 let m = t.mean_dims_keepdim(&[0, 1]).unwrap();
11611 assert_eq!(m.shape().dims(), &[1, 1]);
11612 assert_eq!(m.realize_f32(), vec![2.5]);
11613 }
11614
11615 #[test]
11616 fn rand_like_matches_shape_dtype() {
11617 let t = cpu_f32(vec![0.0; 6], &[2, 3]);
11618 let r = t.rand_like(-1.0, 1.0).unwrap();
11619 assert_eq!(r.shape().dims(), t.shape().dims());
11620 assert_eq!(r.dtype(), t.dtype());
11621 for v in r.realize_f32() {
11623 assert!((-1.0..1.0).contains(&v), "sample {v} out of [-1, 1)");
11624 }
11625 }
11626
11627 #[test]
11628 fn randn_like_matches_shape_dtype() {
11629 let t = cpu_f32(vec![0.0; 4], &[4]);
11630 let r = t.randn_like(0.0, 1.0).unwrap();
11631 assert_eq!(r.shape().dims(), &[4]);
11632 assert_eq!(r.dtype(), DType::F32);
11633 for v in r.realize_f32() {
11635 assert!(v.is_finite());
11636 }
11637 }
11638
11639 #[test]
11640 fn static_rand_f32() {
11641 let t = Tensor::rand(vec![100], 0.0, 1.0, DType::F32, &Device::cpu()).unwrap();
11642 let v = t.realize_f32();
11643 let mean: f32 = v.iter().sum::<f32>() / v.len() as f32;
11645 assert!((0.3..0.7).contains(&mean), "mean {mean} too far from 0.5");
11646 }
11647
11648 #[test]
11649 fn static_randn_f64() {
11650 let t = Tensor::randn(vec![1000], 0.0, 1.0, DType::F64, &Device::cpu()).unwrap();
11651 let v = t.realize_f64();
11652 let mean: f64 = v.iter().sum::<f64>() / v.len() as f64;
11653 assert!(mean.abs() < 0.2, "mean {mean} too far from 0");
11655 }
11656
11657 #[test]
11658 fn arange_int_step() {
11659 let t = Tensor::arange(0.0, 5.0, &Device::cpu());
11660 assert_eq!(t.shape().dims(), &[5]);
11661 assert_eq!(t.realize_f32(), vec![0.0, 1.0, 2.0, 3.0, 4.0]);
11662 }
11663
11664 #[test]
11665 fn arange_step_fractional() {
11666 let t = Tensor::arange_step(2.0, 4.0, 0.5, &Device::cpu());
11667 assert_eq!(t.realize_f32(), vec![2.0, 2.5, 3.0, 3.5]);
11668 }
11669
11670 #[test]
11671 fn arange_step_negative_descends() {
11672 let t = Tensor::arange_step(5.0, 0.0, -1.0, &Device::cpu());
11673 assert_eq!(t.realize_f32(), vec![5.0, 4.0, 3.0, 2.0, 1.0]);
11674 }
11675
11676 #[test]
11677 fn linspace_includes_endpoints() {
11678 let t = Tensor::linspace(0.0, 1.0, 5, &Device::cpu());
11679 assert_eq!(t.shape().dims(), &[5]);
11680 let v = t.realize_f32();
11681 assert!((v[0] - 0.0).abs() < 1e-6);
11682 assert!((v[4] - 1.0).abs() < 1e-6);
11683 assert!((v[2] - 0.5).abs() < 1e-6);
11684 }
11685
11686 #[test]
11687 fn linspace_n_one_returns_start() {
11688 let t = Tensor::linspace(7.0, 99.0, 1, &Device::cpu());
11689 assert_eq!(t.realize_f32(), vec![7.0]);
11690 }
11691
11692 #[test]
11693 fn norm_is_sqrt_sum_sq() {
11694 let t = Tensor::from_f32(vec![3.0_f32, 4.0], vec![2], &Device::cpu()).unwrap();
11695 let n = t.norm();
11696 assert!((n.realize_f32()[0] - 5.0).abs() < 1e-6);
11697 }
11698
11699 #[test]
11700 fn pad_with_zeros_left_and_right() {
11701 let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11702 let p = t.pad_with_zeros(0, 2, 1).unwrap();
11703 assert_eq!(p.shape().dims(), &[6]);
11704 assert_eq!(p.realize_f32(), vec![0.0, 0.0, 1.0, 2.0, 3.0, 0.0]);
11705 }
11706
11707 #[test]
11708 fn pad_with_zeros_identity_when_both_zero() {
11709 let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11710 let p = t.pad_with_zeros(0, 0, 0).unwrap();
11711 assert_eq!(p.realize_f32(), vec![1.0, 2.0, 3.0]);
11712 }
11713
11714 #[test]
11715 fn pad_with_zeros_rejects_bad_dim() {
11716 let t = cpu_f32(vec![1.0, 2.0], &[2]);
11717 assert!(t.pad_with_zeros(3, 1, 1).is_err());
11718 }
11719
11720 #[test]
11721 fn pad_with_value_zero_matches_pad_with_zeros() {
11722 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11725 let via_zeros = t.pad_with_zeros(0, 1, 2).unwrap();
11726 let via_value = t.pad_with_value(0, 1, 2, 0.0).unwrap();
11727 assert_eq!(via_zeros.shape().dims(), via_value.shape().dims());
11728 assert_eq!(via_zeros.shape().dims(), &[5, 2]);
11729 assert_eq!(via_zeros.realize_f32(), via_value.realize_f32());
11730 assert_eq!(
11731 via_value.realize_f32(),
11732 vec![0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 0.0, 0.0, 0.0, 0.0],
11733 );
11734 }
11735
11736 #[test]
11737 fn pad_with_value_neg_inf_then_max_reduce_ignores_pad() {
11738 let t = cpu_f32(vec![-1.0, -2.0, -3.0], &[3]);
11742 let padded = t.pad_with_value(0, 2, 2, f32::NEG_INFINITY).unwrap();
11743 assert_eq!(padded.shape().dims(), &[7]);
11744 let v = padded.realize_f32();
11745 assert!(v[0].is_infinite() && v[0].is_sign_negative());
11747 assert!(v[1].is_infinite() && v[1].is_sign_negative());
11748 assert_eq!(v[2], -1.0);
11749 assert_eq!(v[3], -2.0);
11750 assert_eq!(v[4], -3.0);
11751 assert!(v[5].is_infinite() && v[5].is_sign_negative());
11752 assert!(v[6].is_infinite() && v[6].is_sign_negative());
11753 let m = padded.max_all().realize_f32();
11755 assert_eq!(m, vec![-1.0]);
11756 }
11757
11758 #[test]
11759 fn pad_with_value_identity_when_both_zero() {
11760 let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11763 let p = t.pad_with_value(0, 0, 0, f32::NEG_INFINITY).unwrap();
11764 assert_eq!(p.realize_f32(), vec![1.0, 2.0, 3.0]);
11765 }
11766
11767 #[test]
11768 fn pad_with_value_rejects_bad_dim() {
11769 let t = cpu_f32(vec![1.0, 2.0], &[2]);
11770 assert!(t.pad_with_value(3, 1, 1, 0.0).is_err());
11771 }
11772
11773 #[test]
11774 fn max_pool2d_with_pad_value_neg_inf_on_negative_interior() {
11775 let x = cpu_f32(
11786 vec![-1.0, -2.0, -3.0, -4.0, -5.0, -6.0, -7.0, -8.0, -9.0],
11787 &[1, 1, 3, 3],
11788 );
11789 let out = x
11790 .max_pool2d_with_pad_value((3, 3), (1, 1), (1, 1), f32::NEG_INFINITY)
11791 .unwrap();
11792 assert_eq!(out.shape().dims(), &[1, 1, 3, 3]);
11793 let v = out.realize_f32();
11794 assert_eq!(v[0], -1.0);
11797 assert_eq!(v[4], -1.0);
11799 assert_eq!(v[8], -5.0);
11802
11803 let default_pad = x.max_pool2d((3, 3), (1, 1), (1, 1)).unwrap();
11813 let vd = default_pad.realize_f32();
11814 assert_eq!(
11815 vd[0], -1.0,
11816 "max_pool2d's default must now match NEG_INFINITY padding, not 0.0"
11817 );
11818 assert_eq!(vd[8], -5.0);
11819
11820 let explicit_zero_pad = x
11821 .max_pool2d_with_pad_value((3, 3), (1, 1), (1, 1), 0.0)
11822 .unwrap();
11823 let vz = explicit_zero_pad.realize_f32();
11824 assert_eq!(
11825 vz[0], 0.0,
11826 "explicit 0.0 padding must still be reachable via max_pool2d_with_pad_value"
11827 );
11828 assert_eq!(vz[8], 0.0);
11829 }
11830
11831 #[test]
11832 fn max_pool2d_with_pad_value_zero_matches_max_pool2d() {
11833 let data: Vec<f32> = (0..16).map(|i| i as f32).collect();
11836 let x = cpu_f32(data, &[1, 1, 4, 4]);
11837 let a = x.max_pool2d((2, 2), (2, 2), (0, 0)).unwrap();
11838 let b = x
11839 .max_pool2d_with_pad_value((2, 2), (2, 2), (0, 0), 0.0)
11840 .unwrap();
11841 assert_eq!(a.shape().dims(), b.shape().dims());
11842 assert_eq!(a.realize_f32(), b.realize_f32());
11843 }
11844
11845 #[test]
11848 fn conv1d_identity_kernel_passes_input_through() {
11849 let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0], &[1, 1, 5]);
11851 let w = x.const_f32_like(vec![1.0], vec![1, 1, 1]).unwrap();
11852 let out = x.conv1d(&w, None, 1, 0, 1).unwrap();
11853 assert_eq!(out.shape().dims(), &[1, 1, 5]);
11854 assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0, 4.0, 5.0]);
11855 }
11856
11857 #[test]
11858 fn conv1d_sum_kernel_two_wide() {
11859 let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[1, 1, 4]);
11861 let w = x.const_f32_like(vec![1.0, 1.0], vec![1, 1, 2]).unwrap();
11862 let out = x.conv1d(&w, None, 1, 0, 1).unwrap();
11863 assert_eq!(out.shape().dims(), &[1, 1, 3]);
11864 assert_eq!(out.realize_f32(), vec![3.0, 5.0, 7.0]);
11865 }
11866
11867 #[test]
11868 fn conv1d_with_bias_applies_correctly() {
11869 let x = cpu_f32(vec![1.0, 1.0, 1.0], &[1, 1, 3]);
11870 let w = x.const_f32_like(vec![1.0], vec![1, 1, 1]).unwrap();
11871 let bias = x.const_f32_like(vec![10.0], vec![1]).unwrap();
11872 let out = x.conv1d(&w, Some(&bias), 1, 0, 1).unwrap();
11873 assert_eq!(out.realize_f32(), vec![11.0, 11.0, 11.0]);
11874 }
11875
11876 #[test]
11877 fn conv1d_stride_two_halves_output() {
11878 let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[1, 1, 6]);
11880 let w = x.const_f32_like(vec![1.0, 1.0], vec![1, 1, 2]).unwrap();
11881 let out = x.conv1d(&w, None, 2, 0, 1).unwrap();
11882 assert_eq!(out.shape().dims(), &[1, 1, 3]);
11883 assert_eq!(out.realize_f32(), vec![3.0, 7.0, 11.0]);
11884 }
11885
11886 #[test]
11887 fn conv1d_padding_one_preserves_length() {
11888 let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[1, 1, 4]);
11890 let w = x
11891 .const_f32_like(vec![1.0, 1.0, 1.0], vec![1, 1, 3])
11892 .unwrap();
11893 let out = x.conv1d(&w, None, 1, 1, 1).unwrap();
11894 assert_eq!(out.shape().dims(), &[1, 1, 4]);
11895 assert_eq!(out.realize_f32(), vec![3.0, 6.0, 9.0, 7.0]);
11898 }
11899
11900 #[test]
11901 fn conv1d_multi_channel_output() {
11902 let x = cpu_f32(vec![1.0, 2.0, 3.0], &[1, 1, 3]);
11904 let w = x.const_f32_like(vec![2.0, -1.0], vec![2, 1, 1]).unwrap();
11906 let out = x.conv1d(&w, None, 1, 0, 1).unwrap();
11907 assert_eq!(out.shape().dims(), &[1, 2, 3]);
11908 assert_eq!(out.realize_f32(), vec![2.0, 4.0, 6.0, -1.0, -2.0, -3.0]);
11910 }
11911
11912 #[test]
11913 fn conv1d_rejects_rank_two_input() {
11914 let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11915 let w = x.const_f32_like(vec![1.0], vec![1, 1, 1]).unwrap();
11916 assert!(x.conv1d(&w, None, 1, 0, 1).is_err());
11917 }
11918
11919 #[test]
11920 fn conv1d_rejects_rank_two_weight() {
11921 let x = cpu_f32(vec![1.0; 4], &[1, 1, 4]);
11922 let w = x.const_f32_like(vec![1.0], vec![1, 1]).unwrap();
11923 assert!(x.conv1d(&w, None, 1, 0, 1).is_err());
11924 }
11925
11926 #[test]
11927 fn conv1d_rejects_zero_groups_or_stride() {
11928 let x = cpu_f32(vec![1.0; 4], &[1, 1, 4]);
11929 let w = x.const_f32_like(vec![1.0], vec![1, 1, 1]).unwrap();
11930 assert!(x.conv1d(&w, None, 0, 0, 1).is_err());
11931 assert!(x.conv1d(&w, None, 1, 0, 0).is_err());
11932 }
11933
11934 #[test]
11935 fn conv1d_with_algo_ignores_algo_param() {
11936 let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[1, 1, 4]);
11937 let w = x.const_f32_like(vec![1.0, 1.0], vec![1, 1, 2]).unwrap();
11938 let a = x.conv1d_with_algo(&w, None, 1, 0, 1, "unused").unwrap();
11940 let b = x.conv1d(&w, None, 1, 0, 1).unwrap();
11941 assert_eq!(a.realize_f32(), b.realize_f32());
11942 }
11943
11944 #[test]
11947 fn avg_pool2d_2x2_stride2() {
11948 let data: Vec<f32> = (0..16).map(|i| i as f32).collect();
11950 let x = cpu_f32(data, &[1, 1, 4, 4]);
11951 let out = x.avg_pool2d((2, 2), (2, 2), (0, 0), true).unwrap();
11952 assert_eq!(out.shape().dims(), &[1, 1, 2, 2]);
11953 let v = out.realize_f32();
11957 assert!((v[0] - 2.5).abs() < 1e-5);
11958 assert!((v[1] - 4.5).abs() < 1e-5);
11959 assert!((v[2] - 10.5).abs() < 1e-5);
11960 assert!((v[3] - 12.5).abs() < 1e-5);
11961 }
11962
11963 #[test]
11964 fn avg_pool2d_3x3_stride1_padding1_preserves_size() {
11965 let x = cpu_f32(vec![1.0; 16], &[1, 1, 4, 4]);
11966 let out = x.avg_pool2d((3, 3), (1, 1), (1, 1), true).unwrap();
11967 assert_eq!(out.shape().dims(), &[1, 1, 4, 4]);
11968 }
11969
11970 #[test]
11988 fn avg_pool2d_excludes_padding_keeps_uniform_data_exactly_at_its_true_value() {
11989 let x = cpu_f32(vec![1.0; 16], &[1, 1, 4, 4]);
11990 let included = x.avg_pool2d((3, 3), (1, 1), (1, 1), true).unwrap();
11991 let excluded = x.avg_pool2d((3, 3), (1, 1), (1, 1), false).unwrap();
11992 assert_eq!(included.shape().dims(), excluded.shape().dims());
11993
11994 let ve = excluded.realize_f32();
11995 for (i, &v) in ve.iter().enumerate() {
11996 assert!(
11997 (v - 1.0).abs() < 1e-5,
11998 "count_include_pad=false must be exactly 1.0 at every position \
11999 (all real taps are 1.0) — position {i} got {v}",
12000 );
12001 }
12002
12003 let vi = included.realize_f32();
12004 assert!(
12005 (vi[0] - 1.0).abs() > 0.1,
12006 "count_include_pad=true must NOT match at a corner (4 of 9 taps \
12007 real → 4/9, far from 1.0) — got {}, modes should disagree here",
12008 vi[0]
12009 );
12010 }
12011
12012 #[test]
12021 fn avg_pool2d_excludes_padding_from_divisor_discriminating() {
12022 let x = cpu_f32(vec![10.0, 10.0, 10.0, 10.0], &[1, 1, 2, 2]);
12023 let included = x.avg_pool2d((2, 2), (1, 1), (1, 1), true).unwrap();
12024 let excluded = x.avg_pool2d((2, 2), (1, 1), (1, 1), false).unwrap();
12025 let vi = included.realize_f32();
12026 let ve = excluded.realize_f32();
12027 assert!(
12028 (vi[0] - 2.5).abs() < 1e-5,
12029 "count_include_pad=true: top-left = 10/4 = 2.5, got {}",
12030 vi[0]
12031 );
12032 assert!(
12033 (ve[0] - 10.0).abs() < 1e-5,
12034 "count_include_pad=false: top-left = 10/1 (ONE real tap) = 10.0, got {}",
12035 ve[0]
12036 );
12037 }
12038
12039 #[test]
12044 fn avg_pool2d_rejects_zero_valid_tap_window() {
12045 let x = cpu_f32(vec![5.0], &[1, 1, 1, 1]);
12046 let err = x
12047 .avg_pool2d((1, 1), (1, 1), (2, 2), false)
12048 .expect_err("a window with zero real taps must be rejected, not silently NaN");
12049 let msg = err.to_string();
12050 assert!(
12051 msg.contains("divide by zero") || msg.contains("no valid"),
12052 "error should explain the zero-valid-tap cause, got: {msg}"
12053 );
12054
12055 let ok = x.avg_pool2d((1, 1), (1, 1), (2, 2), true);
12060 assert!(
12061 ok.is_ok(),
12062 "count_include_pad=true must still accept this shape (uniform divisor, never zero)"
12063 );
12064 }
12065
12066 #[test]
12067 fn avg_pool2d_multi_channel() {
12068 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]);
12070 let out = x.avg_pool2d((2, 2), (2, 2), (0, 0), true).unwrap();
12071 assert_eq!(out.shape().dims(), &[1, 2, 1, 1]);
12072 assert_eq!(out.realize_f32(), vec![0.0, 1.0]);
12073 }
12074
12075 #[test]
12076 fn max_pool2d_2x2_stride2() {
12077 let data: Vec<f32> = (0..16).map(|i| i as f32).collect();
12078 let x = cpu_f32(data, &[1, 1, 4, 4]);
12079 let out = x.max_pool2d((2, 2), (2, 2), (0, 0)).unwrap();
12080 assert_eq!(out.shape().dims(), &[1, 1, 2, 2]);
12081 assert_eq!(out.realize_f32(), vec![5.0, 7.0, 13.0, 15.0]);
12083 }
12084
12085 #[test]
12086 fn max_pool2d_3x3_stride1_padding1() {
12087 let x = cpu_f32(
12088 vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0],
12089 &[1, 1, 3, 3],
12090 );
12091 let out = x.max_pool2d((3, 3), (1, 1), (1, 1)).unwrap();
12092 assert_eq!(out.shape().dims(), &[1, 1, 3, 3]);
12093 let v = out.realize_f32();
12095 assert!((v[4] - 9.0).abs() < 1e-5);
12097 }
12098
12099 #[test]
12100 fn upsample_nearest2d_2x() {
12101 let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[1, 1, 2, 2]);
12102 let out = x.upsample_nearest2d(2).unwrap();
12103 assert_eq!(out.shape().dims(), &[1, 1, 4, 4]);
12104 assert_eq!(
12106 out.realize_f32(),
12107 vec![
12108 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,
12109 ],
12110 );
12111 }
12112
12113 #[test]
12114 fn upsample_nearest2d_3x() {
12115 let x = cpu_f32(vec![5.0], &[1, 1, 1, 1]);
12116 let out = x.upsample_nearest2d(3).unwrap();
12117 assert_eq!(out.shape().dims(), &[1, 1, 3, 3]);
12118 assert_eq!(out.realize_f32(), vec![5.0; 9]);
12119 }
12120
12121 #[test]
12122 fn upsample_nearest2d_identity_scale_one() {
12123 let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[1, 1, 2, 2]);
12124 let out = x.upsample_nearest2d(1).unwrap();
12125 assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0, 4.0]);
12126 }
12127
12128 #[test]
12129 fn upsample_nearest1d_2x() {
12130 let x = cpu_f32(vec![1.0, 2.0, 3.0], &[1, 1, 3]);
12131 let out = x.upsample_nearest1d(2).unwrap();
12132 assert_eq!(out.shape().dims(), &[1, 1, 6]);
12133 assert_eq!(out.realize_f32(), vec![1.0, 1.0, 2.0, 2.0, 3.0, 3.0]);
12134 }
12135
12136 #[test]
12137 fn interpolate2d_integer_multiple() {
12138 let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[1, 1, 2, 2]);
12139 let out = x.interpolate2d(4, 4).unwrap();
12140 assert_eq!(out.shape().dims(), &[1, 1, 4, 4]);
12141 }
12142
12143 #[test]
12144 fn interpolate2d_accepts_non_integer_ratio() {
12145 let x = cpu_f32(vec![1.0; 4], &[1, 1, 2, 2]);
12150 let out = x.interpolate2d(3, 4).unwrap();
12151 assert_eq!(out.shape().dims(), &[1, 1, 3, 4]);
12152 }
12153
12154 #[test]
12155 fn interpolate1d_integer_multiple() {
12156 let x = cpu_f32(vec![1.0, 2.0], &[1, 1, 2]);
12157 let out = x.interpolate1d(6).unwrap();
12158 assert_eq!(out.shape().dims(), &[1, 1, 6]);
12159 assert_eq!(out.realize_f32(), vec![1.0, 1.0, 1.0, 2.0, 2.0, 2.0]);
12160 }
12161
12162 #[test]
12163 fn pool_rejects_bad_rank() {
12164 let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
12165 assert!(x.avg_pool2d((2, 2), (2, 2), (0, 0), true).is_err());
12166 assert!(x.max_pool2d((2, 2), (2, 2), (0, 0)).is_err());
12167 }
12168
12169 #[test]
12170 fn pool_rejects_zero_kernel() {
12171 let x = cpu_f32(vec![1.0; 16], &[1, 1, 4, 4]);
12172 assert!(x.avg_pool2d((0, 2), (1, 1), (0, 0), true).is_err());
12173 assert!(x.max_pool2d((2, 0), (1, 1), (0, 0)).is_err());
12174 }
12175
12176 #[test]
12179 fn numel_matches_elem_count() {
12180 let t = cpu_f32(vec![1.0; 12], &[3, 4]);
12181 assert_eq!(t.numel(), t.elem_count());
12182 assert_eq!(t.numel(), 12);
12183 }
12184
12185 #[test]
12186 fn dim_returns_specific_axis_size() {
12187 let t = cpu_f32(vec![0.0; 24], &[2, 3, 4]);
12188 assert_eq!(t.dim(0).unwrap(), 2);
12189 assert_eq!(t.dim(1).unwrap(), 3);
12190 assert_eq!(t.dim(2).unwrap(), 4);
12191 assert!(t.dim(3).is_err());
12192 }
12193
12194 #[test]
12195 fn to_dtype_switches_dtype() {
12196 let t = cpu_f32(vec![1.0, 2.0], &[2]);
12197 let b = t.to_dtype(DType::F64).unwrap();
12198 assert_eq!(b.dtype(), DType::F64);
12199 assert_eq!(b.realize_f64(), vec![1.0, 2.0]);
12200 }
12201
12202 #[test]
12203 fn to_dtype_same_dtype_is_noop() {
12204 let t = cpu_f32(vec![1.0_f32], &[1]);
12205 let b = t.to_dtype(DType::F32).unwrap();
12206 assert_eq!(b.dtype(), DType::F32);
12207 }
12208
12209 #[test]
12210 fn detach_is_identity_on_lazy() {
12211 let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
12212 let d = t.detach();
12213 assert_eq!(d.realize_f32(), t.realize_f32());
12214 }
12215
12216 #[test]
12217 fn track_op_is_true_on_lazy() {
12218 let t = cpu_f32(vec![0.0], &[1]);
12219 assert!(t.track_op());
12220 }
12221
12222 #[test]
12225 fn try_permute_accepts_tuple_syntax() {
12226 let t = cpu_f32(vec![0.0; 24], &[2, 3, 4]);
12227 let out = t.permute((2_usize, 0_usize, 1_usize)).unwrap();
12229 assert_eq!(out.shape().dims(), &[4, 2, 3]);
12230 }
12231
12232 #[test]
12233 fn dim_arg_methods_accept_negative_indexing() {
12234 use fuel_ir::D;
12235 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
12236 let sum_last = t.shape().dims().to_vec(); assert_eq!(sum_last, vec![2, 3]);
12239 let cumsum_last = t.cumsum(D::Minus1).unwrap();
12242 assert_eq!(cumsum_last.shape().dims(), &[2, 3]);
12243 }
12244
12245 #[test]
12246 fn unsqueeze_accepts_dim_trait() {
12247 use fuel_ir::D;
12248 let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
12249 let out = t.unsqueeze(D::Minus1).unwrap();
12251 assert_eq!(out.shape().dims().len(), 2);
12254 }
12255}
12256pub struct TokenDataHost {
12257 pub token_ids: fuel_ir::HostBuffer,
12258 pub rope_cos: fuel_ir::HostBuffer,
12259 pub rope_sin: fuel_ir::HostBuffer,
12260 pub mask: fuel_ir::HostBuffer,
12261 pub offset: Option<fuel_ir::HostBuffer>,
12262}
12263
12264#[cfg(feature = "cuda")]
12269pub struct TokenDataBytes {
12270 pub token_ids: Vec<u8>,
12271 pub rope_cos: Vec<u8>,
12272 pub rope_sin: Vec<u8>,
12273 pub mask: Vec<u8>,
12274 pub offset: Option<Vec<u8>>,
12275}
12276
12277#[cfg(feature = "cuda")]
12290pub fn captured_output_to_f32(
12291 output: &Arc<std::sync::RwLock<fuel_memory::Storage>>,
12292) -> fuel_ir::error::Result<Vec<f32>> {
12293 use fuel_memory::BackendStorage;
12294 let guard = output.read().map_err(|_| {
12295 fuel_ir::Error::Msg("captured decode output storage lock poisoned".into()).bt()
12296 })?;
12297 let bytes: Vec<u8> = match &guard.inner {
12298 BackendStorage::Cpu(c) => c.bytes().to_vec(),
12299 BackendStorage::Cuda(c) => c.to_cpu_bytes()?,
12300 #[allow(unreachable_patterns)]
12301 other => {
12302 return Err(fuel_ir::Error::Msg(format!(
12303 "captured decode output is BackendStorage::{:?}, expected Cpu or Cuda",
12304 std::mem::discriminant(other),
12305 ))
12306 .bt());
12307 }
12308 };
12309 Ok(bytemuck::cast_slice::<u8, f32>(&bytes).to_vec())
12310}