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")]
2009 pub fn realize_f32_cuda(&self, device: &fuel_cuda_backend::CudaDevice) -> Vec<f32> {
2010 let graph = self.inner.graph().clone();
2011 let target = self.inner.id();
2012 let fc_device: crate::Device = device.clone().into();
2013 crate::pipelined_bridge::realize_one_as::<f32>(&graph, target, &fc_device)
2014 .expect("realize_f32_cuda via PipelinedExecutor")
2015 }
2016
2017 #[cfg(feature = "vulkan")]
2025 pub fn realize_f32_vulkan(
2026 &self,
2027 backend: &std::sync::Arc<fuel_vulkan_backend::VulkanBackend>,
2028 ) -> Vec<f32> {
2029 let graph = self.inner.graph().clone();
2030 let target = self.inner.id();
2031 let fc_device: crate::Device = backend.clone().into();
2032 crate::pipelined_bridge::realize_one_as::<f32>(&graph, target, &fc_device)
2033 .expect("realize_f32_vulkan via PipelinedExecutor")
2034 }
2035}
2036
2037pub fn realize_many_f32(tensors: &[&Tensor]) -> Vec<Vec<f32>> {
2039 if tensors.is_empty() {
2040 return Vec::new();
2041 }
2042 let graph = tensors[0].inner.graph().clone();
2043 let targets: Vec<fuel_graph::NodeId> = tensors.iter().map(|t| t.inner.id()).collect();
2044 let device = crate::Device::cpu();
2045 crate::pipelined_bridge::realize_many_as::<f32>(&graph, &targets, &device)
2046 .expect("realize_many_f32 via PipelinedExecutor")
2047}
2048
2049#[cfg(feature = "cuda")]
2052pub fn realize_many_f32_cuda(
2053 tensors: &[&Tensor],
2054 device: &fuel_cuda_backend::CudaDevice,
2055) -> Vec<Vec<f32>> {
2056 if tensors.is_empty() {
2057 return Vec::new();
2058 }
2059 let graph = tensors[0].inner.graph().clone();
2060 let targets: Vec<fuel_graph::NodeId> = tensors.iter().map(|t| t.inner.id()).collect();
2061 let fc_device: crate::Device = device.clone().into();
2062 crate::pipelined_bridge::realize_many_as::<f32>(&graph, &targets, &fc_device)
2063 .expect("realize_many_f32_cuda via PipelinedExecutor")
2064}
2065
2066#[cfg(test)]
2067mod tests {
2068 use super::*;
2069 use crate::Shape;
2070
2071 #[test]
2072 fn constructors_wrap_graph_tensor_correctly() {
2073 let t =
2074 Tensor::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), &Device::cpu()).unwrap();
2075 assert_eq!(t.dtype(), DType::F32);
2076 assert_eq!(t.shape().dims(), &[3]);
2077 assert_eq!(t.rank(), 1);
2078 assert_eq!(t.elem_count(), 3);
2079 }
2080
2081 #[test]
2082 fn add_builds_add_node_in_underlying_graph() {
2083 let a =
2084 Tensor::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), &Device::cpu()).unwrap();
2085 let b = a
2086 .const_f32_like(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]))
2087 .unwrap();
2088 let c = a.add(&b).unwrap();
2089 assert_eq!(c.shape().dims(), &[3]);
2090 assert!(std::sync::Arc::ptr_eq(
2093 c.graph_tensor().graph(),
2094 a.graph_tensor().graph(),
2095 ));
2096 }
2097
2098 #[test]
2099 fn chained_lazy_method_call_builds_sensible_graph() {
2100 let x = Tensor::from_f32(
2105 vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
2106 Shape::from_dims(&[2, 3]),
2107 &Device::cpu(),
2108 )
2109 .unwrap();
2110 let w = x
2111 .const_f32_like(
2112 vec![1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0],
2113 Shape::from_dims(&[3, 3]),
2114 )
2115 .unwrap();
2116 let y = x
2117 .rms_norm_last_dim(1e-6)
2118 .unwrap()
2119 .matmul(&w)
2120 .unwrap()
2121 .relu();
2122 assert_eq!(y.shape().dims(), &[2, 3]);
2123 assert_eq!(y.dtype(), DType::F32);
2124 }
2125
2126 #[test]
2127 fn rope_through_lazy_wrapper() {
2128 let x = Tensor::from_f32(
2130 vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0],
2131 Shape::from_dims(&[2, 4]),
2132 &Device::cpu(),
2133 )
2134 .unwrap();
2135 let y = x.rope(10000.0, 0).unwrap();
2136 assert_eq!(y.shape().dims(), &[2, 4]);
2137 assert_eq!(y.dtype(), DType::F32);
2138 }
2139
2140 #[test]
2141 fn rope_delta_rotate_equals_direct_shift() {
2142 let dev = Device::cpu();
2148 let (n_kv_heads, head_dim, bs) = (2usize, 4usize, 4usize);
2149 let theta = 10000.0;
2150 let (p0, m) = (0usize, 8usize); let raw: Vec<f32> = (0..bs * n_kv_heads * head_dim)
2152 .map(|i| (i as f32 * 0.017).sin())
2153 .collect();
2154 let rope_pool_at = |data: &[f32], start_pos: usize| -> Vec<f32> {
2158 let k = Tensor::from_f32(
2159 data.to_vec(),
2160 Shape::from_dims(&[bs, n_kv_heads, head_dim]),
2161 &dev,
2162 )
2163 .unwrap();
2164 let k4 = k
2165 .permute([1, 0, 2])
2166 .unwrap()
2167 .reshape(Shape::from_dims(&[1, n_kv_heads, bs, head_dim]))
2168 .unwrap();
2169 let (c, s) = k4.rope_tables_const(theta, start_pos, bs, head_dim);
2170 k4.rope_with_tables_decomposed(&c, &s)
2171 .unwrap()
2172 .reshape(Shape::from_dims(&[n_kv_heads, bs, head_dim]))
2173 .unwrap()
2174 .permute([1, 0, 2])
2175 .unwrap()
2176 .realize_f32()
2177 };
2178 let direct = rope_pool_at(&raw, p0 + m); let at_p0 = rope_pool_at(&raw, p0); let shifted =
2181 Tensor::rope_delta_rotate_block_f32(&dev, &at_p0, theta, m, bs, n_kv_heads, head_dim);
2182 let maxdiff = direct
2183 .iter()
2184 .zip(&shifted)
2185 .map(|(a, b)| (a - b).abs())
2186 .fold(0.0f32, f32::max);
2187 assert!(
2188 maxdiff < 1e-5,
2189 "delta-rotate == direct shift (maxdiff {maxdiff})"
2190 );
2191 }
2192
2193 #[test]
2194 fn cast_switches_dtype_through_wrapper() {
2195 let x =
2196 Tensor::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), &Device::cpu()).unwrap();
2197 let y = x.to_dtype(DType::F64).unwrap();
2198 assert_eq!(y.dtype(), DType::F64);
2199 assert_eq!(y.shape().dims(), &[3]);
2200 }
2201
2202 #[test]
2203 fn indexing_builds_correct_output_shape() {
2204 let data =
2205 Tensor::from_f32(vec![1.0; 12], Shape::from_dims(&[3, 4]), &Device::cpu()).unwrap();
2206 let idx = data
2207 .const_u32_like(vec![0, 2, 1], Shape::from_dims(&[3]))
2208 .unwrap();
2209 let out = data.index_select(0, &idx).unwrap();
2210 assert_eq!(out.shape().dims(), &[3, 4]);
2211 }
2212
2213 #[test]
2216 fn realize_f32_executes_the_underlying_graph() {
2217 let a =
2221 Tensor::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), &Device::cpu()).unwrap();
2222 let b = a
2223 .const_f32_like(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]))
2224 .unwrap();
2225 let c = a.add(&b).unwrap().mul(&a).unwrap();
2226 let result = c.realize_f32();
2227 assert_eq!(result, vec![5.0, 14.0, 27.0]);
2228 }
2229
2230 #[test]
2231 fn realize_f32_relu_and_maximum_propagate_nan_end_to_end() {
2232 let a = Tensor::from_f32(
2238 vec![f32::NAN, -2.0, 3.0],
2239 Shape::from_dims(&[3]),
2240 &Device::cpu(),
2241 )
2242 .unwrap();
2243 let relu_result = a.relu().realize_f32();
2244 assert!(
2245 relu_result[0].is_nan(),
2246 "relu(NaN) must propagate NaN through realize, got {}",
2247 relu_result[0]
2248 );
2249 assert_eq!(relu_result[1], 0.0, "relu(-2) must clip to 0");
2250 assert_eq!(relu_result[2], 3.0, "relu(3) must pass through");
2251
2252 let b = a
2253 .const_f32_like(vec![1.0, f32::NAN, 2.0], Shape::from_dims(&[3]))
2254 .unwrap();
2255 let max_result = a.maximum(&b).unwrap().realize_f32();
2256 assert!(
2257 max_result[0].is_nan(),
2258 "maximum(NaN, 1) must propagate NaN through realize, got {}",
2259 max_result[0]
2260 );
2261 assert!(
2262 max_result[1].is_nan(),
2263 "maximum(-2, NaN) must propagate NaN through realize, got {}",
2264 max_result[1]
2265 );
2266 assert_eq!(max_result[2], 3.0, "maximum(3, 2) non-NaN sanity");
2267 }
2268
2269 #[test]
2275 fn fmax_fmin_ieee_suppress_nan_where_prop_propagates() {
2276 let a = Tensor::from_f32(
2280 vec![f32::NAN, 2.0, 5.0],
2281 Shape::from_dims(&[3]),
2282 &Device::cpu(),
2283 )
2284 .unwrap();
2285 let b = a
2286 .const_f32_like(vec![3.0, f32::NAN, 4.0], Shape::from_dims(&[3]))
2287 .unwrap();
2288
2289 let fmax = a.fmax_ieee(&b).unwrap().realize_f32();
2290 assert_eq!(fmax[0], 3.0, "fmax_ieee(NaN,3) suppresses NaN → 3");
2291 assert_eq!(fmax[1], 2.0, "fmax_ieee(2,NaN) suppresses NaN → 2");
2292 assert_eq!(fmax[2], 5.0, "fmax_ieee(5,4) → 5");
2293 let max = a.maximum(&b).unwrap().realize_f32();
2294 assert!(
2295 max[0].is_nan() && max[1].is_nan(),
2296 "maximum PROPAGATES NaN — the divergence that makes fmax_ieee distinct"
2297 );
2298
2299 let fmin = a.fmin_ieee(&b).unwrap().realize_f32();
2300 assert_eq!(fmin[0], 3.0, "fmin_ieee(NaN,3) suppresses NaN → 3");
2301 assert_eq!(fmin[1], 2.0, "fmin_ieee(2,NaN) suppresses NaN → 2");
2302 assert_eq!(fmin[2], 4.0, "fmin_ieee(5,4) → 4");
2303 let min = a.minimum(&b).unwrap().realize_f32();
2304 assert!(
2305 min[0].is_nan() && min[1].is_nan(),
2306 "minimum PROPAGATES NaN — the divergence that makes fmin_ieee distinct"
2307 );
2308 }
2309
2310 #[test]
2311 fn fmax_fmin_ieee_signed_zero_tie_operand_a_wins_bitwise() {
2312 let a = Tensor::from_f32(vec![-0.0, 0.0], Shape::from_dims(&[2]), &Device::cpu()).unwrap();
2330 let b = a
2331 .const_f32_like(vec![0.0, -0.0], Shape::from_dims(&[2]))
2332 .unwrap();
2333
2334 let fmax = a.fmax_ieee(&b).unwrap().realize_f32();
2335 assert_eq!(
2336 fmax[0].to_bits(),
2337 (-0.0f32).to_bits(),
2338 "fmax_ieee(-0.0,+0.0): operand a wins the tie → -0.0 (bitwise)"
2339 );
2340 assert_eq!(
2341 fmax[1].to_bits(),
2342 (0.0f32).to_bits(),
2343 "fmax_ieee(+0.0,-0.0): operand a wins the tie → +0.0 (bitwise)"
2344 );
2345
2346 let fmin = a.fmin_ieee(&b).unwrap().realize_f32();
2347 assert_eq!(
2348 fmin[0].to_bits(),
2349 (-0.0f32).to_bits(),
2350 "fmin_ieee(-0.0,+0.0): operand a wins the tie → -0.0 (bitwise)"
2351 );
2352 assert_eq!(
2353 fmin[1].to_bits(),
2354 (0.0f32).to_bits(),
2355 "fmin_ieee(+0.0,-0.0): operand a wins the tie → +0.0 (bitwise)"
2356 );
2357 }
2358
2359 #[test]
2360 fn rem_trunc_diverges_from_floored_rem_on_opposite_signs() {
2361 let a = Tensor::from_f32(
2365 vec![-7.0, 7.0, -7.0],
2366 Shape::from_dims(&[3]),
2367 &Device::cpu(),
2368 )
2369 .unwrap();
2370 let b = a
2371 .const_f32_like(vec![3.0, -3.0, -3.0], Shape::from_dims(&[3]))
2372 .unwrap();
2373
2374 let rt = a.rem_trunc(&b).unwrap().realize_f32();
2375 assert_eq!(rt[0], -1.0, "-7 rem_trunc 3 = -1 (sign of dividend)");
2376 assert_eq!(rt[1], 1.0, "7 rem_trunc -3 = 1 (sign of dividend)");
2377 assert_eq!(rt[2], -1.0, "-7 rem_trunc -3 = -1");
2378 let rf = a.rem(&b).unwrap().realize_f32();
2379 assert_eq!(
2380 rf[0], 2.0,
2381 "-7 rem 3 = 2 (floored, sign of divisor) — the divergence from rem_trunc"
2382 );
2383 }
2384
2385 #[test]
2386 fn trunc_edges_signed_zero_nan_inf_bitwise() {
2387 let q = Tensor::from_f32(
2391 vec![
2392 2.7,
2393 -2.7,
2394 -0.0,
2395 0.0,
2396 f32::NAN,
2397 f32::INFINITY,
2398 f32::NEG_INFINITY,
2399 ],
2400 Shape::from_dims(&[7]),
2401 &Device::cpu(),
2402 )
2403 .unwrap();
2404 let t = q.trunc().realize_f32();
2405 assert_eq!(t[0], 2.0, "trunc(2.7) = 2 (toward zero)");
2406 assert_eq!(t[1], -2.0, "trunc(-2.7) = -2 (toward zero, NOT -3)");
2407 assert_eq!(
2408 t[2].to_bits(),
2409 (-0.0f32).to_bits(),
2410 "trunc(-0.0) must PRESERVE -0.0 (bitwise, not +0.0)"
2411 );
2412 assert_eq!(
2413 t[3].to_bits(),
2414 (0.0f32).to_bits(),
2415 "trunc(+0.0) = +0.0 (bitwise)"
2416 );
2417 assert!(t[4].is_nan(), "trunc(NaN) = NaN");
2418 assert_eq!(t[5], f32::INFINITY, "trunc(+inf) = +inf");
2419 assert_eq!(t[6], f32::NEG_INFINITY, "trunc(-inf) = -inf");
2420 }
2421
2422 #[test]
2423 fn realize_f32_matmul_hand_computed() {
2424 let a = Tensor::from_f32(
2426 vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
2427 Shape::from_dims(&[2, 3]),
2428 &Device::cpu(),
2429 )
2430 .unwrap();
2431 let b = a
2432 .const_f32_like(
2433 vec![7.0, 8.0, 9.0, 10.0, 11.0, 12.0],
2434 Shape::from_dims(&[3, 2]),
2435 )
2436 .unwrap();
2437 let c = a.matmul(&b).unwrap();
2438 assert_eq!(c.shape().dims(), &[2, 2]);
2439 assert_eq!(c.realize_f32(), vec![58.0, 64.0, 139.0, 154.0]);
2440 }
2441
2442 #[test]
2443 fn fast_and_reference_agree_on_medium_matmul() {
2444 let m = 64;
2449 let k = 96;
2450 let n = 32;
2451 let a_data: Vec<f32> = (0..m * k).map(|i| (i as f32 * 0.01).sin()).collect();
2452 let b_data: Vec<f32> = (0..k * n).map(|i| (i as f32 * 0.013).cos()).collect();
2453 let a = Tensor::from_f32(a_data, Shape::from_dims(&[m, k]), &Device::cpu()).unwrap();
2454 let b = a.const_f32_like(b_data, Shape::from_dims(&[k, n])).unwrap();
2455 let c = a.matmul(&b).unwrap();
2456 let fast = c.realize_f32();
2457 let reference = c.realize_f32();
2458 assert_eq!(fast.len(), reference.len());
2459 for (i, (&f, &r)) in fast.iter().zip(&reference).enumerate() {
2460 let diff = (f - r).abs();
2466 let rel = if r.abs() > 1e-6 { diff / r.abs() } else { 0.0 };
2467 assert!(
2468 diff < 1e-4 || rel < 1e-3,
2469 "at index {i}: fast={f}, reference={r}, diff={diff}, rel={rel}",
2470 );
2471 }
2472 }
2473
2474 fn ref_attention(
2479 q: &[f32],
2480 k: &[f32],
2481 v: &[f32],
2482 hq: usize,
2483 hkv: usize,
2484 sq: usize,
2485 sk: usize,
2486 d: usize,
2487 scale: f32,
2488 causal: bool,
2489 softcap: Option<f32>,
2490 alibi: Option<&[f32]>,
2491 ) -> Vec<f32> {
2492 let g = hq / hkv;
2493 let mut out = vec![0.0f32; hq * sq * d];
2494 for h in 0..hq {
2495 let hk = h / g;
2496 let qh = &q[h * sq * d..(h + 1) * sq * d];
2497 let kh = &k[hk * sk * d..(hk + 1) * sk * d];
2498 let vh = &v[hk * sk * d..(hk + 1) * sk * d];
2499 for i in 0..sq {
2500 let mut scores = vec![0.0f32; sk];
2501 for j in 0..sk {
2502 let mut s = 0.0f32;
2503 for l in 0..d {
2504 s += qh[i * d + l] * kh[j * d + l];
2505 }
2506 let mut sc = scale * s;
2507 if let Some(cap) = softcap {
2508 sc = cap * (sc / cap).tanh();
2509 }
2510 if let Some(slopes) = alibi {
2511 sc += slopes[h] * (j as f32 - i as f32);
2513 }
2514 scores[j] = if causal && j > i {
2515 f32::NEG_INFINITY
2516 } else {
2517 sc
2518 };
2519 }
2520 let m = scores.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
2521 let mut sum = 0.0f32;
2522 let exps: Vec<f32> = scores
2523 .iter()
2524 .map(|&s| {
2525 let e = (s - m).exp();
2526 sum += e;
2527 e
2528 })
2529 .collect();
2530 for l in 0..d {
2531 let mut o = 0.0f32;
2532 for j in 0..sk {
2533 o += (exps[j] / sum) * vh[j * d + l];
2534 }
2535 out[(h * sq + i) * d + l] = o;
2536 }
2537 }
2538 }
2539 out
2540 }
2541
2542 fn flash_decompose_vs_reference(
2548 hq: usize,
2549 hkv: usize,
2550 causal: bool,
2551 softcap: Option<f32>,
2552 alibi: bool,
2553 ) {
2554 let dev = Device::cpu();
2555 let (sq, sk, d) = (2usize, 2usize, 2usize);
2556 let q_data: Vec<f32> = (0..hq * sq * d).map(|i| (i as f32 * 0.1).sin()).collect();
2558 let k_data: Vec<f32> = (0..hkv * sk * d).map(|i| (i as f32 * 0.13).cos()).collect();
2559 let v_data: Vec<f32> = (0..hkv * sk * d).map(|i| i as f32 * 0.07 + 1.0).collect();
2560 #[allow(clippy::approx_constant)]
2563 let scale = 0.7071f32;
2564 let q = Tensor::from_f32(q_data.clone(), Shape::from_dims(&[1, hq, sq, d]), &dev).unwrap();
2565 let k = q
2566 .const_f32_like(k_data.clone(), Shape::from_dims(&[1, hkv, sk, d]))
2567 .unwrap();
2568 let v = q
2569 .const_f32_like(v_data.clone(), Shape::from_dims(&[1, hkv, sk, d]))
2570 .unwrap();
2571 let alibi_slopes: Option<Vec<f32>> = if alibi {
2573 Some((0..hq).map(|h| 0.5f32.powi(h as i32 + 1)).collect())
2574 } else {
2575 None
2576 };
2577 let alibi_t = alibi_slopes.as_ref().map(|s| {
2578 q.const_f32_like(s.clone(), Shape::from_dims(&[hq]))
2579 .unwrap()
2580 });
2581 let attn = q
2582 .flash_attn(&k, &v, alibi_t.as_ref(), scale, causal, None, None, softcap)
2583 .unwrap();
2584
2585 let graph = attn.inner.graph().clone();
2587 let id = attn.inner.id();
2588 let roots =
2589 fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
2590 assert_eq!(roots.len(), 1, "lowering should keep a single root");
2591 let got = crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &dev)
2592 .expect("realize decomposed FlashAttn on CPU");
2593
2594 let expected = ref_attention(
2595 &q_data,
2596 &k_data,
2597 &v_data,
2598 hq,
2599 hkv,
2600 sq,
2601 sk,
2602 d,
2603 scale,
2604 causal,
2605 softcap,
2606 alibi_slopes.as_deref(),
2607 );
2608 assert_eq!(got.len(), expected.len());
2609 for (i, (&g, &e)) in got.iter().zip(&expected).enumerate() {
2610 assert!(
2611 (g - e).abs() < 1e-4,
2612 "FlashAttn decompose mismatch (hq={hq} hkv={hkv} causal={causal} \
2613 softcap={softcap:?} alibi={alibi}) at {i}: got {g}, expected {e}",
2614 );
2615 }
2616 }
2617
2618 struct AttnCase {
2627 name: &'static str,
2628 q: Vec<f32>,
2629 k: Vec<f32>,
2630 v: Vec<f32>,
2631 sq: usize,
2632 sk: usize,
2633 causal: bool,
2634 wl: Option<usize>,
2635 }
2636
2637 fn attn_cases() -> Vec<AttnCase> {
2638 let nan = f32::NAN;
2639 let bq = vec![0.5f32, -0.25, 0.1, 0.9, -0.4, 0.3];
2640 let bk = vec![0.3f32, 0.2, -0.1, 0.6];
2641 let bv = vec![1.0f32, 2.0, 3.0, 4.0];
2642 let c = |name, q: Vec<f32>, k: Vec<f32>, v: Vec<f32>, sq, sk, causal, wl| AttnCase {
2643 name,
2644 q,
2645 k,
2646 v,
2647 sq,
2648 sk,
2649 causal,
2650 wl,
2651 };
2652 vec![
2653 c(
2654 "control",
2655 bq[..4].to_vec(),
2656 bk.clone(),
2657 bv.clone(),
2658 2,
2659 2,
2660 false,
2661 None,
2662 ),
2663 c(
2665 "fully-masked-row-mixed",
2666 bq.clone(),
2667 bk.clone(),
2668 bv.clone(),
2669 3,
2670 2,
2671 true,
2672 Some(0),
2673 ),
2674 c(
2675 "nan-q-row1",
2676 vec![0.5, -0.25, nan, 0.9],
2677 bk.clone(),
2678 bv.clone(),
2679 2,
2680 2,
2681 false,
2682 None,
2683 ),
2684 c(
2685 "nan-k-row1",
2686 bq[..4].to_vec(),
2687 vec![0.3, 0.2, nan, 0.6],
2688 bv.clone(),
2689 2,
2690 2,
2691 false,
2692 None,
2693 ),
2694 c(
2695 "nan-v-row1",
2696 bq[..4].to_vec(),
2697 bk.clone(),
2698 vec![1.0, 2.0, nan, 4.0],
2699 2,
2700 2,
2701 false,
2702 None,
2703 ),
2704 c(
2709 "nan-q-fully-masked-row",
2710 vec![0.5, -0.25, 0.1, 0.9, nan, 0.3],
2711 bk.clone(),
2712 bv.clone(),
2713 3,
2714 2,
2715 true,
2716 Some(0),
2717 ),
2718 c(
2720 "nan-k-masked-key",
2721 bq[..4].to_vec(),
2722 vec![0.3, 0.2, nan, nan],
2723 bv.clone(),
2724 2,
2725 2,
2726 true,
2727 None,
2728 ),
2729 c(
2730 "inf-k-masked-key",
2731 bq[..4].to_vec(),
2732 vec![0.3, 0.2, f32::INFINITY, f32::INFINITY],
2733 bv.clone(),
2734 2,
2735 2,
2736 true,
2737 None,
2738 ),
2739 c(
2740 "nan-v-masked-key",
2741 bq[..4].to_vec(),
2742 bk.clone(),
2743 vec![1.0, 2.0, nan, 4.0],
2744 2,
2745 2,
2746 true,
2747 None,
2748 ),
2749 ]
2750 }
2751
2752 #[derive(Debug, Clone, Copy)]
2754 enum Want {
2755 Nan,
2757 Val(f32),
2759 NanOrVal(f32),
2761 Any,
2763 }
2764
2765 fn attn_expected(name: &str) -> Vec<Want> {
2766 use Want::{Any as a, Nan as n, NanOrVal as o, Val as s};
2767 match name {
2768 "control" => vec![s(1.8943309), s(2.894331), s(2.1126559), s(3.1126556)],
2769 "fully-masked-row-mixed" => vec![s(1.0), s(2.0), s(3.0), s(4.0), s(0.0), s(0.0)],
2770 "nan-q-row1" => vec![s(1.8943309), s(2.894331), n, n],
2771 "nan-k-row1" => vec![n, n, n, n],
2772 "nan-v-row1" => vec![n, s(2.894331), n, s(3.1126556)],
2773 "nan-v-masked-key" => vec![o(1.0), o(2.0), n, s(3.1126556)],
2776 "nan-q-fully-masked-row" => vec![s(1.0), s(2.0), s(3.0), s(4.0), s(0.0), s(0.0)],
2777 "nan-k-masked-key" => vec![s(1.0), s(2.0), n, n],
2778 "inf-k-masked-key" => vec![s(1.0), s(2.0), a, a],
2779 other => panic!("no expectation for {other}"),
2780 }
2781 }
2782
2783 fn attn_check(name: &str, path: &str, got: &[f32], want: &[Want]) -> Option<String> {
2784 assert_eq!(got.len(), want.len(), "{name}/{path}");
2785 let bad: Vec<String> = got
2786 .iter()
2787 .zip(want)
2788 .enumerate()
2789 .filter(|(_, (g, w))| match w {
2790 Want::Nan => !g.is_nan(),
2791 Want::Val(x) => g.is_nan() || (**g - *x).abs() > 1e-4,
2792 Want::NanOrVal(x) => !g.is_nan() && (**g - *x).abs() > 1e-4,
2793 Want::Any => false,
2794 })
2795 .map(|(i, (g, w))| format!("[{i}] got {g} want {w:?}"))
2796 .collect();
2797 (!bad.is_empty()).then(|| format!("{name}/{path}: {}", bad.join("; ")))
2798 }
2799
2800 #[allow(clippy::approx_constant)]
2803 fn attn_tensor(c: &AttnCase) -> Tensor {
2804 let dev = Device::cpu();
2805 let q = Tensor::from_f32(c.q.clone(), Shape::from_dims(&[1, 1, c.sq, 2]), &dev).unwrap();
2806 let k = q
2807 .const_f32_like(c.k.clone(), Shape::from_dims(&[1, 1, c.sk, 2]))
2808 .unwrap();
2809 let v = q
2810 .const_f32_like(c.v.clone(), Shape::from_dims(&[1, 1, c.sk, 2]))
2811 .unwrap();
2812 q.flash_attn(&k, &v, None, 0.7071, c.causal, c.wl, None, None)
2813 .unwrap()
2814 }
2815
2816 #[test]
2817 fn flash_attn_fused_cpu_follows_the_masked_and_nan_row_contract() {
2818 let mut bad = Vec::new();
2819 for c in attn_cases() {
2820 let got = attn_tensor(&c).realize_f32();
2821 bad.extend(attn_check(c.name, "fused", &got, &attn_expected(c.name)));
2822 }
2823 assert!(bad.is_empty(), "{bad:#?}");
2824 }
2825
2826 #[test]
2827 fn flash_attn_decomposed_cpu_follows_the_masked_and_nan_row_contract() {
2828 let mut bad = Vec::new();
2829 for c in attn_cases() {
2830 let attn = attn_tensor(&c);
2831 let graph = attn.inner.graph().clone();
2832 let id = attn.inner.id();
2833 let roots =
2834 fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
2835 let got =
2836 crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &Device::cpu())
2837 .expect("realize decomposed FlashAttn on CPU");
2838 bad.extend(attn_check(
2839 c.name,
2840 "decomposed",
2841 &got,
2842 &attn_expected(c.name),
2843 ));
2844 }
2845 assert!(bad.is_empty(), "{bad:#?}");
2846 }
2847
2848 #[test]
2849 fn flash_attn_decompose_vanilla() {
2850 flash_decompose_vs_reference(1, 1, false, None, false);
2851 }
2852
2853 #[test]
2854 fn flash_attn_decompose_causal() {
2855 flash_decompose_vs_reference(1, 1, true, None, false);
2856 }
2857
2858 #[test]
2859 fn flash_attn_decompose_gqa_causal() {
2860 flash_decompose_vs_reference(2, 1, true, None, false); }
2862
2863 #[test]
2864 fn flash_attn_decompose_softcap() {
2865 flash_decompose_vs_reference(1, 1, false, Some(0.5), false); }
2867
2868 #[test]
2869 fn flash_attn_decompose_alibi() {
2870 flash_decompose_vs_reference(2, 2, false, None, true);
2873 }
2874
2875 #[test]
2876 fn flash_attn_decompose_alibi_causal() {
2877 flash_decompose_vs_reference(2, 2, true, None, true);
2878 }
2879
2880 fn ref_decode_attn(
2886 q: &[f32],
2887 k: &[f32],
2888 v: &[f32],
2889 hq: usize,
2890 hkv: usize,
2891 sq: usize,
2892 cap: usize,
2893 kl: usize,
2894 d: usize,
2895 scale: f32,
2896 causal: bool,
2897 ) -> Vec<f32> {
2898 let g = hq / hkv;
2899 let offset = kl - sq;
2900 let mut out = vec![0f32; hq * sq * d];
2901 for h in 0..hq {
2902 let hk = h / g;
2903 for i in 0..sq {
2904 let qh = &q[((h * sq) + i) * d..][..d];
2905 let mut scores = vec![f32::NEG_INFINITY; kl];
2906 for j in 0..kl {
2907 if causal && j > offset + i {
2908 continue;
2909 }
2910 let kh = &k[((hk * cap) + j) * d..][..d];
2911 let s: f32 = (0..d).map(|l| qh[l] * kh[l]).sum();
2912 scores[j] = scale * s;
2913 }
2914 let m = scores.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
2915 let mut sum = 0f32;
2916 let exps: Vec<f32> = scores
2917 .iter()
2918 .map(|&s| {
2919 let e = (s - m).exp();
2920 sum += e;
2921 e
2922 })
2923 .collect();
2924 for l in 0..d {
2925 let mut o = 0f32;
2926 for j in 0..kl {
2927 o += (exps[j] / sum) * v[((hk * cap) + j) * d + l];
2928 }
2929 out[(h * sq + i) * d + l] = o;
2930 }
2931 }
2932 }
2933 out
2934 }
2935
2936 #[test]
2944 fn flash_attn_decompose_concrete_klen() {
2945 use fuel_graph::Op;
2946 use fuel_graph::registry::FusedOps;
2947 use fuel_ir::DynScalar;
2948 let dev = Device::cpu();
2949 let (hq, hkv, sq, cap, kl, d) = (2usize, 1usize, 2usize, 4usize, 3usize, 2usize);
2950 #[allow(clippy::approx_constant)]
2953 let scale = 0.7071f32;
2954 let causal = true;
2955 let q_data: Vec<f32> = (0..hq * sq * d).map(|i| (i as f32 * 0.1).sin()).collect();
2956 let k_data: Vec<f32> = (0..hkv * cap * d)
2957 .map(|i| (i as f32 * 0.13).cos())
2958 .collect();
2959 let v_data: Vec<f32> = (0..hkv * cap * d).map(|i| i as f32 * 0.07 + 1.0).collect();
2960 let q = Tensor::from_f32(q_data.clone(), Shape::from_dims(&[1, hq, sq, d]), &dev).unwrap();
2961 let k = q
2962 .inner
2963 .const_f32_like(k_data.clone(), Shape::from_dims(&[1, hkv, cap, d]))
2964 .unwrap();
2965 let v = q
2966 .inner
2967 .const_f32_like(v_data.clone(), Shape::from_dims(&[1, hkv, cap, d]))
2968 .unwrap();
2969 let attn = q.inner.flash_attn_dyn(
2971 &k,
2972 &v,
2973 None,
2974 scale,
2975 causal,
2976 None,
2977 None,
2978 None,
2979 DynScalar::Concrete(kl),
2980 );
2981
2982 let graph = attn.graph().clone();
2983 let id = attn.id();
2984 let roots =
2985 fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
2986 assert_eq!(roots.len(), 1, "lowering should keep a single root");
2987
2988 {
2990 let g = graph.read().unwrap();
2991 let mut stack = vec![roots[0]];
2992 let mut seen = std::collections::HashSet::new();
2993 while let Some(nid) = stack.pop() {
2994 if !seen.insert(nid) {
2995 continue;
2996 }
2997 let node = g.node(nid);
2998 assert!(
2999 !matches!(node.op, Op::Fused(fid, _) if fid == FusedOps::FLASH_ATTN),
3000 "concrete-k_len FlashAttn still fused after lowering (self-return)",
3001 );
3002 for &inp in &node.inputs {
3003 stack.push(inp);
3004 }
3005 }
3006 }
3007
3008 let got = crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &dev)
3009 .expect("realize decomposed concrete-k_len FlashAttn on CPU");
3010 let expected = ref_decode_attn(
3011 &q_data, &k_data, &v_data, hq, hkv, sq, cap, kl, d, scale, causal,
3012 );
3013 assert_eq!(got.len(), expected.len());
3014 for (i, (&gv, &ev)) in got.iter().zip(&expected).enumerate() {
3015 assert!(
3016 (gv - ev).abs() < 1e-4,
3017 "concrete-k_len decode mismatch at {i}: got {gv}, expected {ev}",
3018 );
3019 }
3020 }
3021
3022 fn assert_f32_bits_eq(got: &[f32], want: &[f32], ctx: &str) {
3025 assert_eq!(got.len(), want.len(), "{ctx}: length mismatch");
3026 for (i, (&g, &w)) in got.iter().zip(want).enumerate() {
3027 assert_eq!(
3028 g.to_bits(),
3029 w.to_bits(),
3030 "{ctx}: bit mismatch at {i}: got {g} (0x{:08x}), want {w} (0x{:08x})",
3031 g.to_bits(),
3032 w.to_bits(),
3033 );
3034 }
3035 }
3036
3037 fn assert_f32_within_ulp(got: &[f32], want: &[f32], max_ulp: i64, ctx: &str) {
3041 assert_eq!(got.len(), want.len(), "{ctx}: length mismatch");
3042 for (i, (&g, &w)) in got.iter().zip(want).enumerate() {
3043 let d = (g.to_bits() as i64 - w.to_bits() as i64).abs();
3044 assert!(
3045 d <= max_ulp,
3046 "{ctx}: {d} ULP at {i} (> {max_ulp}): got {g} (0x{:08x}), want {w} (0x{:08x})",
3047 g.to_bits(),
3048 w.to_bits(),
3049 );
3050 }
3051 }
3052
3053 #[test]
3078 fn reduce_swap_sumdim_vs_reducesumto_bit_exact_on_cpu_backend() {
3079 let dev = Device::cpu();
3080 let (rows, cols) = (2usize, 4usize);
3081 let data: Vec<f32> = vec![1e8, 1.0, -1e8, 1.0, 3.0e7, 2.0, -3.0e7, -1.0];
3086
3087 let mut left_fold = vec![0.0f32; rows];
3090 let mut right_fold = vec![0.0f32; rows];
3091 for r in 0..rows {
3092 let row = &data[r * cols..(r + 1) * cols];
3093 let mut acc = 0.0f32;
3094 for &v in row.iter() {
3095 acc += v;
3096 }
3097 left_fold[r] = acc;
3098 let mut acc_r = 0.0f32;
3099 for &v in row.iter().rev() {
3100 acc_r += v;
3101 }
3102 right_fold[r] = acc_r;
3103 }
3104 assert_ne!(
3105 left_fold, right_fold,
3106 "test data must be accumulation-order-sensitive so the parity has teeth",
3107 );
3108
3109 let x = Tensor::from_f32(data.clone(), Shape::from_dims(&[rows, cols]), &dev).unwrap();
3110 let sumdim = x.inner.sum_dim(1);
3112 let got_sumdim = crate::pipelined_bridge::realize_one_as::<f32>(
3113 &sumdim.graph().clone(),
3114 sumdim.id(),
3115 &dev,
3116 )
3117 .expect("realize SumDim(last) on CPU");
3118 let reducesumto = x.inner.reduce_sum_to(Shape::from_dims(&[rows, 1]));
3120 let got_reducesumto = crate::pipelined_bridge::realize_one_as::<f32>(
3121 &reducesumto.graph().clone(),
3122 reducesumto.id(),
3123 &dev,
3124 )
3125 .expect("realize ReduceSumTo(keepdim) on CPU");
3126
3127 assert_f32_bits_eq(&got_sumdim, &got_reducesumto, "SumDim vs ReduceSumTo");
3129 assert_f32_bits_eq(&got_sumdim, &left_fold, "SumDim vs left-fold");
3132
3133 let maxdim = x.inner.max_dim(1);
3138 let got_maxdim = crate::pipelined_bridge::realize_one_as::<f32>(
3139 &maxdim.graph().clone(),
3140 maxdim.id(),
3141 &dev,
3142 )
3143 .expect("realize MaxDim(last) on CPU");
3144 let reducemaxto = x.inner.reduce_max_to(Shape::from_dims(&[rows, 1]));
3145 let got_reducemaxto = crate::pipelined_bridge::realize_one_as::<f32>(
3146 &reducemaxto.graph().clone(),
3147 reducemaxto.id(),
3148 &dev,
3149 )
3150 .expect("realize ReduceMaxTo(keepdim) on CPU");
3151 let row_max: Vec<f32> = (0..rows)
3152 .map(|r| {
3153 data[r * cols..(r + 1) * cols]
3154 .iter()
3155 .cloned()
3156 .fold(f32::NEG_INFINITY, f32::max)
3157 })
3158 .collect();
3159 assert_f32_bits_eq(&got_maxdim, &got_reducemaxto, "MaxDim vs ReduceMaxTo");
3160 assert_f32_bits_eq(&got_maxdim, &row_max, "MaxDim vs per-row max");
3161 }
3162
3163 #[test]
3183 fn softmax_last_dim_recipe_decompose_matches_legacy_on_cpu() {
3184 let dev = Device::cpu();
3185 let (rows, cols) = (3usize, 5usize);
3186 let data: Vec<f32> = (0..rows * cols)
3187 .map(|i| ((i as f32) * 0.37).sin() * 4.0 - (i as f32) * 0.11)
3188 .collect();
3189 let shape = || Shape::from_dims(&[rows, cols]);
3190 let keepdim = || Shape::from_dims(&[rows, 1]);
3191
3192 let recipe = Tensor::from_f32(data.clone(), shape(), &dev)
3194 .unwrap()
3195 .softmax_last_dim()
3196 .expect("softmax recipe build");
3197 let graph = recipe.inner.graph().clone();
3198 let id = recipe.inner.id();
3199 let roots =
3200 fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
3201 assert_eq!(roots.len(), 1, "lowering keeps a single root");
3202 let recipe_out = crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &dev)
3203 .expect("realize recipe-decomposed softmax on CPU");
3204
3205 let x = Tensor::from_f32(data.clone(), shape(), &dev).unwrap().inner;
3208 let m = x.reduce_max_to(keepdim());
3209 let mb = m.broadcast_to(shape());
3210 let s = x.sub(&mb);
3211 let e = s.exp();
3212 let d = e.reduce_sum_to(keepdim());
3213 let db = d.broadcast_to(shape());
3214 let legacy = e.div(&db);
3215 let legacy_out = crate::pipelined_bridge::realize_one_as::<f32>(
3216 &legacy.graph().clone(),
3217 legacy.id(),
3218 &dev,
3219 )
3220 .expect("realize legacy softmax on CPU");
3221
3222 assert_f32_bits_eq(&recipe_out, &legacy_out, "softmax recipe vs legacy");
3224 for r in 0..rows {
3226 let sum: f32 = recipe_out[r * cols..(r + 1) * cols].iter().sum();
3227 assert!((sum - 1.0).abs() < 1e-5, "row {r} softmax sum = {sum}");
3228 }
3229
3230 let fused_out = Tensor::from_f32(data.clone(), shape(), &dev)
3234 .unwrap()
3235 .softmax_last_dim()
3236 .expect("softmax fused build")
3237 .realize_f32();
3238 assert_f32_within_ulp(&recipe_out, &fused_out, 1, "softmax recipe vs fused kernel");
3239 }
3240
3241 #[test]
3249 fn rms_norm_last_dim_recipe_decompose_matches_legacy_on_cpu() {
3250 let dev = Device::cpu();
3251 let (rows, cols) = (3usize, 6usize);
3252 let eps = 1e-6f64;
3253 let data: Vec<f32> = (0..rows * cols)
3254 .map(|i| ((i as f32) * 0.29).cos() * 2.5 + 0.5)
3255 .collect();
3256 let shape = || Shape::from_dims(&[rows, cols]);
3257 let keepdim = || Shape::from_dims(&[rows, 1]);
3258
3259 let recipe = Tensor::from_f32(data.clone(), shape(), &dev)
3261 .unwrap()
3262 .rms_norm_last_dim(eps)
3263 .expect("rms_norm recipe build");
3264 let graph = recipe.inner.graph().clone();
3265 let id = recipe.inner.id();
3266 let roots =
3267 fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
3268 assert_eq!(roots.len(), 1, "lowering keeps a single root");
3269 let recipe_out = crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &dev)
3270 .expect("realize recipe-decomposed rms_norm on CPU");
3271
3272 let x = Tensor::from_f32(data.clone(), shape(), &dev).unwrap().inner;
3275 let sq = x.sqr();
3276 let mean = sq.mean_dim(1);
3277 let mean_kd = mean.reshape(keepdim());
3278 let denom_sq = mean_kd.add_scalar(eps);
3279 let denom = denom_sq.sqrt();
3280 let denom_b = denom.broadcast_to(shape());
3281 let legacy = x.div(&denom_b);
3282 let legacy_out = crate::pipelined_bridge::realize_one_as::<f32>(
3283 &legacy.graph().clone(),
3284 legacy.id(),
3285 &dev,
3286 )
3287 .expect("realize legacy rms_norm on CPU");
3288
3289 assert_f32_bits_eq(&recipe_out, &legacy_out, "rms_norm recipe vs legacy");
3291
3292 let fused_out = Tensor::from_f32(data.clone(), shape(), &dev)
3295 .unwrap()
3296 .rms_norm_last_dim(eps)
3297 .expect("rms_norm fused build")
3298 .realize_f32();
3299 assert_f32_within_ulp(
3300 &recipe_out,
3301 &fused_out,
3302 1,
3303 "rms_norm recipe vs fused kernel",
3304 );
3305 }
3306
3307 #[test]
3318 fn selective_scan_decompose_lowers_to_scan_and_matches() {
3319 use fuel_graph::Op;
3320 use fuel_graph::registry::FusedOps;
3321 let dev = Device::cpu();
3322 let u = Tensor::from_f32(vec![2.0f32], Shape::from_dims(&[1, 1, 1]), &dev).unwrap();
3323 let delta = u
3324 .const_f32_like(vec![0.5f32], Shape::from_dims(&[1, 1, 1]))
3325 .unwrap();
3326 let a = u
3327 .const_f32_like(vec![-1.0f32], Shape::from_dims(&[1, 1]))
3328 .unwrap();
3329 let b = u
3330 .const_f32_like(vec![3.0f32], Shape::from_dims(&[1, 1, 1]))
3331 .unwrap();
3332 let c = u
3333 .const_f32_like(vec![4.0f32], Shape::from_dims(&[1, 1, 1]))
3334 .unwrap();
3335 let y = u.selective_scan(&delta, &a, &b, &c, false);
3336
3337 let got = y.realize_f32();
3339 assert_eq!(got.len(), 1);
3340 assert!((got[0] - 12.0).abs() < 1e-4, "fused kernel y: {}", got[0]);
3341
3342 let graph = y.inner.graph().clone();
3345 let id = y.inner.id();
3346 let roots =
3347 fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
3348 assert_eq!(roots.len(), 1);
3349 let scan_id = {
3350 let g = graph.read().unwrap();
3351 let mut stack = vec![roots[0]];
3352 let mut seen = std::collections::HashSet::new();
3353 let mut scan_id = None;
3354 while let Some(nid) = stack.pop() {
3355 if !seen.insert(nid) {
3356 continue;
3357 }
3358 let node = g.node(nid);
3359 assert!(
3360 !matches!(node.op, Op::Fused(fid, _) if fid == FusedOps::SELECTIVE_SCAN),
3361 "SelectiveScan must lower to Op::Scan, not remain fused"
3362 );
3363 if matches!(node.op, Op::Scan { .. }) {
3364 scan_id = Some(nid);
3365 }
3366 for &inp in &node.inputs {
3367 stack.push(inp);
3368 }
3369 }
3370 scan_id.expect("an Op::Scan terminal must be present after lowering")
3371 };
3372 let ys = {
3374 let mut g = graph.write().unwrap();
3375 fuel_graph::scan::unroll_scan(&mut g, scan_id, 1)
3376 .expect("unroll")
3377 .0[0] };
3379 let oracle = crate::pipelined_bridge::realize_one_as::<f32>(&graph, ys, &dev)
3380 .expect("realize unrolled selective_scan oracle on CPU");
3381 assert!(
3382 oracle.iter().any(|&v| (v - 12.0).abs() < 1e-4),
3383 "unroll oracle must contain y = 12, got {oracle:?}"
3384 );
3385 }
3386
3387 #[test]
3400 fn ssd_chunk_scan_decompose_lowers_to_scan_and_matches() {
3401 use fuel_graph::Op;
3402 use fuel_graph::registry::FusedOps;
3403 let dev = Device::cpu();
3404 let x = Tensor::from_f32(vec![2.0f32], Shape::from_dims(&[1, 1, 1, 1]), &dev).unwrap();
3407 let dt = x
3408 .const_f32_like(vec![0.5f32], Shape::from_dims(&[1, 1, 1]))
3409 .unwrap();
3410 let a = x
3411 .const_f32_like(vec![-1.0f32], Shape::from_dims(&[1]))
3412 .unwrap();
3413 let b = x
3414 .const_f32_like(vec![3.0f32], Shape::from_dims(&[1, 1, 1, 1]))
3415 .unwrap();
3416 let c = x
3417 .const_f32_like(vec![4.0f32], Shape::from_dims(&[1, 1, 1, 1]))
3418 .unwrap();
3419 let y = x.ssd_chunk_scan(&dt, &a, &b, &c, 1);
3420
3421 let got = y.realize_f32();
3423 assert!(
3424 (got[0] - 12.0).abs() < 1e-4,
3425 "fused ssd kernel y: {}",
3426 got[0]
3427 );
3428
3429 let graph = y.inner.graph().clone();
3432 let id = y.inner.id();
3433 let roots =
3434 fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
3435 let scan_id = {
3436 let g = graph.read().unwrap();
3437 let mut stack = vec![roots[0]];
3438 let mut seen = std::collections::HashSet::new();
3439 let mut scan_id = None;
3440 while let Some(nid) = stack.pop() {
3441 if !seen.insert(nid) {
3442 continue;
3443 }
3444 let node = g.node(nid);
3445 assert!(
3446 !matches!(node.op, Op::Fused(fid, _) if fid == FusedOps::SSD_CHUNK_SCAN),
3447 "SsdChunkScan must lower to Op::Scan, not remain fused"
3448 );
3449 if matches!(node.op, Op::Scan { .. }) {
3450 scan_id = Some(nid);
3451 }
3452 for &inp in &node.inputs {
3453 stack.push(inp);
3454 }
3455 }
3456 scan_id.expect("an Op::Scan terminal must be present after lowering")
3457 };
3458 let ys = {
3459 let mut g = graph.write().unwrap();
3460 fuel_graph::scan::unroll_scan(&mut g, scan_id, 1)
3461 .expect("unroll")
3462 .0[0] };
3464 let oracle = crate::pipelined_bridge::realize_one_as::<f32>(&graph, ys, &dev)
3465 .expect("realize unrolled ssd_chunk_scan oracle on CPU");
3466 assert!(
3467 oracle.iter().any(|&v| (v - 12.0).abs() < 1e-4),
3468 "oracle y=12, got {oracle:?}"
3469 );
3470 }
3471
3472 #[test]
3479 fn affine_scan_bptt_matches_finite_difference() {
3480 use fuel_graph::{Node, NodeHandle, Op, ScanEmit, ScanRole};
3481 use fuel_ir::{DType, Shape};
3482 let dev = Device::cpu();
3483 let build = |init_v: f32,
3486 a_v: f32,
3487 b_v: f32|
3488 -> (
3489 std::sync::Arc<std::sync::RwLock<fuel_graph::Graph>>,
3490 fuel_graph::NodeId,
3491 fuel_graph::NodeHandle,
3492 fuel_graph::NodeHandle,
3493 fuel_graph::NodeHandle,
3494 ) {
3495 let init =
3496 NodeHandle::from_f32(vec![init_v], Shape::from_dims(&[1]), dev.as_dyn()).unwrap();
3497 let g = init.graph().clone();
3498 let a = NodeHandle::from_existing(g.clone(), init.id())
3499 .const_f32_like(vec![a_v], Shape::from_dims(&[1]))
3500 .unwrap();
3501 let b = NodeHandle::from_existing(g.clone(), init.id())
3502 .const_f32_like(vec![b_v], Shape::from_dims(&[1]))
3503 .unwrap();
3504 let nc = {
3505 let mut gw = g.write().unwrap();
3506 let s = Shape::from_dims(&[1]);
3507 let hole = gw.push(Node {
3508 op: Op::ScanPlaceholder {
3509 role: ScanRole::Carry,
3510 index: 0,
3511 },
3512 inputs: vec![],
3513 shape: s.clone(),
3514 dtype: DType::F32,
3515 });
3516 let ac = gw.push(Node {
3517 op: Op::Mul,
3518 inputs: vec![a.id(), hole],
3519 shape: s.clone(),
3520 dtype: DType::F32,
3521 });
3522 gw.push(Node {
3523 op: Op::Add,
3524 inputs: vec![ac, b.id()],
3525 shape: s.clone(),
3526 dtype: DType::F32,
3527 })
3528 };
3529 let nc_t = NodeHandle::from_existing(g.clone(), nc);
3530 let out = init
3531 .scan(
3532 &[],
3533 &[a.clone(), b.clone()],
3534 &nc_t,
3535 &nc_t,
3536 3,
3537 ScanEmit::Final,
3538 )
3539 .expect("scan");
3540 (g, out.id(), init, a, b)
3541 };
3542 let fwd = |init_v: f32, a_v: f32, b_v: f32| -> f32 {
3544 let (g, out_id, _i, _a, _b) = build(init_v, a_v, b_v);
3545 let scan_id = {
3546 let gr = g.read().unwrap();
3547 gr.node(out_id).inputs[0]
3548 };
3549 let carry = {
3550 let mut gw = g.write().unwrap();
3551 fuel_graph::scan::unroll_scan(&mut gw, scan_id, 3)
3552 .expect("unroll")
3553 .0[0] }; crate::pipelined_bridge::realize_one_as::<f32>(&g, carry, &dev).expect("realize")[0]
3556 };
3557 let (g, out_id, init, a, b) = build(1.0, 0.5, 0.1);
3559 let out = fuel_graph::NodeHandle::from_existing(g.clone(), out_id);
3560 let grads = out.backward();
3561 let realize_grad = |t: &fuel_graph::NodeHandle| {
3562 crate::pipelined_bridge::realize_one_as::<f32>(
3563 &g,
3564 grads.get(t).expect("grad").id(),
3565 &dev,
3566 )
3567 .expect("realize grad")[0]
3568 };
3569 let g_init = realize_grad(&init);
3570 let g_a = realize_grad(&a);
3571 let g_b = realize_grad(&b);
3572 let h = 1e-3f32;
3574 let fd = |dinit: f32, da: f32, db: f32| {
3575 (fwd(1.0 + dinit, 0.5 + da, 0.1 + db) - fwd(1.0 - dinit, 0.5 - da, 0.1 - db))
3576 / (2.0 * h)
3577 };
3578 assert!(
3579 (g_init - fd(h, 0.0, 0.0)).abs() < 2e-2,
3580 "d/dinit: autograd {g_init} vs FD {}",
3581 fd(h, 0.0, 0.0)
3582 );
3583 assert!(
3584 (g_a - fd(0.0, h, 0.0)).abs() < 2e-2,
3585 "d/da: autograd {g_a} vs FD {}",
3586 fd(0.0, h, 0.0)
3587 );
3588 assert!(
3589 (g_b - fd(0.0, 0.0, h)).abs() < 2e-2,
3590 "d/db: autograd {g_b} vs FD {}",
3591 fd(0.0, 0.0, h)
3592 );
3593 }
3594
3595 #[test]
3596 fn selective_scan_is_differentiable_backward_matches_fd() {
3597 let dev = Device::cpu();
3598 let fwd = |u_v: f32| -> f32 {
3599 let u = Tensor::from_f32(vec![u_v], Shape::from_dims(&[1, 1, 1]), &dev).unwrap();
3600 let delta = u
3601 .const_f32_like(vec![0.5f32], Shape::from_dims(&[1, 1, 1]))
3602 .unwrap();
3603 let a = u
3604 .const_f32_like(vec![-1.0f32], Shape::from_dims(&[1, 1]))
3605 .unwrap();
3606 let b = u
3607 .const_f32_like(vec![3.0f32], Shape::from_dims(&[1, 1, 1]))
3608 .unwrap();
3609 let c = u
3610 .const_f32_like(vec![4.0f32], Shape::from_dims(&[1, 1, 1]))
3611 .unwrap();
3612 u.selective_scan(&delta, &a, &b, &c, false).realize_f32()[0]
3613 };
3614 let u = Tensor::from_f32(vec![2.0f32], Shape::from_dims(&[1, 1, 1]), &dev).unwrap();
3616 let delta = u
3617 .const_f32_like(vec![0.5f32], Shape::from_dims(&[1, 1, 1]))
3618 .unwrap();
3619 let a = u
3620 .const_f32_like(vec![-1.0f32], Shape::from_dims(&[1, 1]))
3621 .unwrap();
3622 let b = u
3623 .const_f32_like(vec![3.0f32], Shape::from_dims(&[1, 1, 1]))
3624 .unwrap();
3625 let c = u
3626 .const_f32_like(vec![4.0f32], Shape::from_dims(&[1, 1, 1]))
3627 .unwrap();
3628 let y = u.selective_scan(&delta, &a, &b, &c, false);
3629 let grads = y.inner.backward();
3630 let g_u_id = grads.get(u.graph_tensor()).expect("grad u").id();
3631 let g_u =
3632 crate::pipelined_bridge::realize_one_as::<f32>(&u.inner.graph().clone(), g_u_id, &dev)
3633 .expect("realize")[0];
3634 let h = 1e-3;
3635 let fd = (fwd(2.0 + h) - fwd(2.0 - h)) / (2.0 * h);
3636 assert!(
3637 (g_u - fd).abs() < 5e-2,
3638 "selective_scan d/du: autograd {g_u} vs FD {fd}"
3639 );
3640 }
3641
3642 #[test]
3643 fn ssd_chunk_scan_is_differentiable_backward_matches_fd() {
3644 let dev = Device::cpu();
3645 let fwd = |x_v: f32| -> f32 {
3648 let x = Tensor::from_f32(vec![x_v], Shape::from_dims(&[1, 1, 1, 1]), &dev).unwrap();
3649 let dt = x
3650 .const_f32_like(vec![0.5f32], Shape::from_dims(&[1, 1, 1]))
3651 .unwrap();
3652 let a = x
3653 .const_f32_like(vec![-1.0f32], Shape::from_dims(&[1]))
3654 .unwrap();
3655 let b = x
3656 .const_f32_like(vec![3.0f32], Shape::from_dims(&[1, 1, 1, 1]))
3657 .unwrap();
3658 let c = x
3659 .const_f32_like(vec![4.0f32], Shape::from_dims(&[1, 1, 1, 1]))
3660 .unwrap();
3661 x.ssd_chunk_scan(&dt, &a, &b, &c, 1).realize_f32()[0]
3662 };
3663 let x = Tensor::from_f32(vec![2.0f32], Shape::from_dims(&[1, 1, 1, 1]), &dev).unwrap();
3665 let dt = x
3666 .const_f32_like(vec![0.5f32], Shape::from_dims(&[1, 1, 1]))
3667 .unwrap();
3668 let a = x
3669 .const_f32_like(vec![-1.0f32], Shape::from_dims(&[1]))
3670 .unwrap();
3671 let b = x
3672 .const_f32_like(vec![3.0f32], Shape::from_dims(&[1, 1, 1, 1]))
3673 .unwrap();
3674 let c = x
3675 .const_f32_like(vec![4.0f32], Shape::from_dims(&[1, 1, 1, 1]))
3676 .unwrap();
3677 let y = x.ssd_chunk_scan(&dt, &a, &b, &c, 1);
3678 let grads = y.inner.backward();
3679 let g_x_id = grads.get(x.graph_tensor()).expect("grad x").id();
3680 let g_x =
3681 crate::pipelined_bridge::realize_one_as::<f32>(&x.inner.graph().clone(), g_x_id, &dev)
3682 .expect("realize")[0];
3683 let h = 1e-3;
3684 let fd = (fwd(2.0 + h) - fwd(2.0 - h)) / (2.0 * h);
3685 assert!(
3686 (g_x - fd).abs() < 5e-2,
3687 "ssd_chunk_scan d/dx: autograd {g_x} vs FD {fd}"
3688 );
3689 }
3690
3691 fn act_grad_and_fd(
3694 x_v: f32,
3695 act: impl Fn(&Tensor) -> Tensor,
3696 fd_act: impl Fn(&Tensor) -> Tensor,
3697 ) -> (f32, f32) {
3698 let dev = Device::cpu();
3699 let x = Tensor::from_f32(vec![x_v], Shape::from_dims(&[1]), &dev).unwrap();
3700 let y = act(&x);
3701 let grads = y.inner.backward();
3702 let g_id = grads.get(x.graph_tensor()).expect("grad x").id();
3703 let g =
3704 crate::pipelined_bridge::realize_one_as::<f32>(&x.inner.graph().clone(), g_id, &dev)
3705 .expect("realize")[0];
3706 let fwd = |v: f32| -> f32 {
3707 let t = Tensor::from_f32(vec![v], Shape::from_dims(&[1]), &dev).unwrap();
3708 fd_act(&t).realize_f32()[0]
3709 };
3710 let h = 1e-2f32;
3711 (g, (fwd(x_v + h) - fwd(x_v - h)) / (2.0 * h))
3712 }
3713
3714 #[test]
3718 fn gelu_tanh_backward_matches_finite_difference() {
3719 for x_v in [-3.0f32, -1.5, -0.5, 0.0, 0.3, 1.0, 2.5] {
3720 let (g, fd) = act_grad_and_fd(x_v, |x| x.gelu_tanh(), |x| x.gelu_tanh());
3721 assert!(
3722 (g - fd).abs() < 2e-3,
3723 "gelu_tanh d/dx at {x_v}: autograd {g} vs FD {fd}"
3724 );
3725 }
3726 }
3727
3728 #[test]
3730 fn gelu_tanh_inplace_backward_matches_finite_difference() {
3731 for x_v in [-3.0f32, -1.5, -0.5, 0.0, 0.3, 1.0, 2.5] {
3732 let (g, fd) = act_grad_and_fd(x_v, |x| x.gelu_tanh_inplace(), |x| x.gelu_tanh());
3733 assert!(
3734 (g - fd).abs() < 2e-3,
3735 "gelu_tanh_inplace d/dx at {x_v}: autograd {g} vs FD {fd}"
3736 );
3737 }
3738 }
3739
3740 #[test]
3746 fn finite_difference_harness_rejects_a_wrong_activation_gradient() {
3747 let (g_silu, fd_gelu) = act_grad_and_fd(-1.5, |x| x.silu(), |x| x.gelu_tanh());
3748 assert!(
3749 (g_silu - fd_gelu).abs() > 2e-2,
3750 "silu grad {g_silu} too close to gelu_tanh FD {fd_gelu}: harness cannot discriminate"
3751 );
3752 }
3753
3754 fn grad_vs_fd(
3758 x_vals: &[f32],
3759 x_shape: &[usize],
3760 build: impl Fn(&Tensor) -> Tensor,
3761 ) -> (Vec<f32>, Vec<f32>) {
3762 grad_vs_fd_impl(x_vals, x_shape, build, false)
3763 }
3764
3765 fn grad_vs_fd_lowered(
3768 x_vals: &[f32],
3769 x_shape: &[usize],
3770 build: impl Fn(&Tensor) -> Tensor,
3771 ) -> (Vec<f32>, Vec<f32>) {
3772 grad_vs_fd_impl(x_vals, x_shape, build, true)
3773 }
3774
3775 fn grad_vs_fd_impl(
3776 x_vals: &[f32],
3777 x_shape: &[usize],
3778 build: impl Fn(&Tensor) -> Tensor,
3779 lower_forward: bool,
3780 ) -> (Vec<f32>, Vec<f32>) {
3781 let dev = Device::cpu();
3782 let x = Tensor::from_f32(x_vals.to_vec(), Shape::from_dims(x_shape), &dev).unwrap();
3783 let y = build(&x);
3784 let grads = y.inner.backward();
3785 let g_id = grads.get(x.graph_tensor()).expect("grad x").id();
3786 let g =
3787 crate::pipelined_bridge::realize_one_as::<f32>(&x.inner.graph().clone(), g_id, &dev)
3788 .expect("realize");
3789 let fwd_sum = |vals: &[f32]| -> f32 {
3790 let t = Tensor::from_f32(vals.to_vec(), Shape::from_dims(x_shape), &dev).unwrap();
3791 let y = build(&t);
3792 if lower_forward {
3793 let graph = y.inner.graph().clone();
3794 let roots = fuel_graph::opt::RuleRegistry::lowering_only()
3795 .optimize_to_fixpoint(&graph, &[y.inner.id()]);
3796 crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &dev)
3797 .expect("realize lowered forward")
3798 .iter()
3799 .sum()
3800 } else {
3801 y.realize_f32().iter().sum()
3802 }
3803 };
3804 let h = 1e-2f32;
3805 let fd = (0..x_vals.len())
3806 .map(|i| {
3807 let (mut p, mut m) = (x_vals.to_vec(), x_vals.to_vec());
3808 p[i] += h;
3809 m[i] -= h;
3810 (fwd_sum(&p) - fwd_sum(&m)) / (2.0 * h)
3811 })
3812 .collect();
3813 (g, fd)
3814 }
3815
3816 fn assert_grad_close(label: &str, g: &[f32], fd: &[f32]) {
3817 assert_eq!(g.len(), fd.len(), "{label}: length");
3818 for (i, (a, b)) in g.iter().zip(fd).enumerate() {
3819 assert!(
3820 (a - b).abs() < 5e-3 + 5e-3 * b.abs(),
3821 "{label}[{i}]: autograd {a} vs FD {b}"
3822 );
3823 }
3824 }
3825
3826 #[test]
3830 fn nf4_matmul_activation_gradient_matches_finite_difference() {
3831 let (g, fd) = grad_vs_fd(&[1.0, 2.0, 2.0, 4.0], &[1, 4], |act| {
3832 let w_packed = Tensor::from_graph_tensor(
3833 act.graph_tensor()
3834 .const_u8_like(vec![247_u8, 247, 127, 127], Shape::from_dims(&[2, 2]))
3835 .unwrap(),
3836 );
3837 let absmax = act
3838 .const_f32_like(vec![1.0_f32, 2.0, 10.0, 20.0], Shape::from_dims(&[2, 2]))
3839 .unwrap();
3840 act.nf4_matmul(&w_packed, &absmax, 2)
3841 });
3842 assert_grad_close("nf4_matmul d/dact", &g, &fd);
3843 }
3844
3845 #[test]
3850 fn awq_matmul_activation_gradient_matches_finite_difference() {
3851 let x_vals: Vec<f32> = (0..64).map(|k| ((k * 7) % 13) as f32 * 0.1 - 0.6).collect();
3852 let (g, fd) = grad_vs_fd_lowered(&x_vals, &[1, 64], |act| {
3853 let words: Vec<u32> = (0..64u32)
3854 .map(|i| i.wrapping_mul(0x9E37_79B1) ^ 0x1234_5678)
3855 .collect();
3856 let weight = act
3857 .graph_tensor()
3858 .const_u32_like(words, Shape::from_dims(&[8, 8]))
3859 .unwrap();
3860 let zeros = act
3861 .graph_tensor()
3862 .const_u32_like(vec![0x7777_7777; 16], Shape::from_dims(&[8, 2]))
3863 .unwrap();
3864 let scales: Vec<half::f16> = (0..128)
3865 .map(|i| half::f16::from_f32(0.05 + 0.01 * (i % 7) as f32))
3866 .collect();
3867 let scales = act
3868 .const_f16_like(scales, Shape::from_dims(&[8, 16]))
3869 .unwrap();
3870 Tensor::from_graph_tensor(act.graph_tensor().awq_matmul(
3871 &weight,
3872 &zeros,
3873 scales.graph_tensor(),
3874 64,
3875 8,
3876 ))
3877 });
3878 assert_grad_close("awq_matmul d/dact", &g, &fd);
3879 }
3880
3881 #[test]
3882 fn causal_conv1d_weight_and_bias_gradients_match_finite_difference() {
3883 let x_data = vec![0.3, -0.5, 0.8, 0.1, -0.2, 0.6, 0.4, -0.7];
3884 for use_silu in [false, true] {
3885 let (g, fd) = grad_vs_fd(&[0.5, -0.25, 0.75, 0.1, 0.9, -0.4], &[2, 1, 3], |w| {
3887 let x = w
3888 .const_f32_like(x_data.clone(), Shape::from_dims(&[1, 2, 4]))
3889 .unwrap();
3890 let b = w
3891 .const_f32_like(vec![0.05, -0.05], Shape::from_dims(&[2]))
3892 .unwrap();
3893 x.causal_conv1d(w, &b, use_silu)
3894 });
3895 assert_grad_close(&format!("causal_conv1d(silu={use_silu}) d/dw"), &g, &fd);
3896 let (g, fd) = grad_vs_fd(&[0.05, -0.05], &[2], |b| {
3898 let x = b
3899 .const_f32_like(x_data.clone(), Shape::from_dims(&[1, 2, 4]))
3900 .unwrap();
3901 let w = b
3902 .const_f32_like(
3903 vec![0.5, -0.25, 0.75, 0.1, 0.9, -0.4],
3904 Shape::from_dims(&[2, 1, 3]),
3905 )
3906 .unwrap();
3907 x.causal_conv1d(&w, b, use_silu)
3908 });
3909 assert_grad_close(&format!("causal_conv1d(silu={use_silu}) d/dbias"), &g, &fd);
3910 }
3911 }
3912
3913 #[test]
3914 fn causal_conv1d_input_gradient_matches_finite_difference() {
3915 for use_silu in [false, true] {
3917 let (g, fd) = grad_vs_fd(
3918 &[0.3, -0.5, 0.8, 0.1, -0.2, 0.6, 0.4, -0.7],
3919 &[1, 2, 4],
3920 |x| {
3921 let w = x
3922 .const_f32_like(
3923 vec![0.5, -0.25, 0.75, 0.1, 0.9, -0.4],
3924 Shape::from_dims(&[2, 1, 3]),
3925 )
3926 .unwrap();
3927 let b = x
3928 .const_f32_like(vec![0.05, -0.05], Shape::from_dims(&[2]))
3929 .unwrap();
3930 x.causal_conv1d(&w, &b, use_silu)
3931 },
3932 );
3933 assert_grad_close(&format!("causal_conv1d(silu={use_silu}) d/dx"), &g, &fd);
3934 }
3935 }
3936
3937 #[test]
3944 fn selective_scan_seqlen2_bptt_matches_finite_difference() {
3945 let dev = Device::cpu();
3946 let fwd = |u_vals: &[f32]| -> f32 {
3949 let u = Tensor::from_f32(u_vals.to_vec(), Shape::from_dims(&[1, 2, 1]), &dev).unwrap();
3950 let delta = u
3951 .const_f32_like(vec![0.7f32, 0.7], Shape::from_dims(&[1, 2, 1]))
3952 .unwrap();
3953 let a = u
3954 .const_f32_like(vec![-0.5f32], Shape::from_dims(&[1, 1]))
3955 .unwrap();
3956 let b = u
3957 .const_f32_like(vec![1.0f32, 1.0], Shape::from_dims(&[1, 2, 1]))
3958 .unwrap();
3959 let c = u
3960 .const_f32_like(vec![1.0f32, 1.0], Shape::from_dims(&[1, 2, 1]))
3961 .unwrap();
3962 u.selective_scan(&delta, &a, &b, &c, false)
3963 .realize_f32()
3964 .iter()
3965 .sum()
3966 };
3967 let u0 = vec![1.0f32, 2.0];
3968 let u = Tensor::from_f32(u0.clone(), Shape::from_dims(&[1, 2, 1]), &dev).unwrap();
3969 let delta = u
3970 .const_f32_like(vec![0.7f32, 0.7], Shape::from_dims(&[1, 2, 1]))
3971 .unwrap();
3972 let a = u
3973 .const_f32_like(vec![-0.5f32], Shape::from_dims(&[1, 1]))
3974 .unwrap();
3975 let b = u
3976 .const_f32_like(vec![1.0f32, 1.0], Shape::from_dims(&[1, 2, 1]))
3977 .unwrap();
3978 let c = u
3979 .const_f32_like(vec![1.0f32, 1.0], Shape::from_dims(&[1, 2, 1]))
3980 .unwrap();
3981 let y = u.selective_scan(&delta, &a, &b, &c, false);
3982 let grads = y.inner.backward(); let g_u_id = grads.get(u.graph_tensor()).expect("grad u").id();
3984 let g_u =
3985 crate::pipelined_bridge::realize_one_as::<f32>(&u.inner.graph().clone(), g_u_id, &dev)
3986 .expect("realize");
3987 let h = 1e-3f32;
3990 let mut up = u0.clone();
3991 up[0] += h;
3992 let mut um = u0.clone();
3993 um[0] -= h;
3994 let fd0 = (fwd(&up) - fwd(&um)) / (2.0 * h);
3995 assert!(
3996 (g_u[0] - fd0).abs() < 5e-2,
3997 "selective_scan seqlen2 dL/du_1: autograd {} vs FD {fd0}",
3998 g_u[0]
3999 );
4000 assert!(
4003 g_u[0].abs() > 0.5,
4004 "recurrent-gate grad must be non-trivial, got {g_u:?}"
4005 );
4006 }
4007
4008 #[test]
4009 fn ssd_chunk_scan_seqlen4_chunk2_bptt_matches_finite_difference() {
4010 let dev = Device::cpu();
4011 let fwd = |x_vals: &[f32]| -> f32 {
4015 let x =
4016 Tensor::from_f32(x_vals.to_vec(), Shape::from_dims(&[1, 4, 1, 1]), &dev).unwrap();
4017 let dt = x
4018 .const_f32_like(vec![0.6f32, 0.6, 0.6, 0.6], Shape::from_dims(&[1, 4, 1]))
4019 .unwrap();
4020 let a = x
4021 .const_f32_like(vec![-0.5f32], Shape::from_dims(&[1]))
4022 .unwrap();
4023 let b = x
4024 .const_f32_like(vec![1.0f32, 1.0, 1.0, 1.0], Shape::from_dims(&[1, 4, 1, 1]))
4025 .unwrap();
4026 let c = x
4027 .const_f32_like(vec![1.0f32, 1.0, 1.0, 1.0], Shape::from_dims(&[1, 4, 1, 1]))
4028 .unwrap();
4029 x.ssd_chunk_scan(&dt, &a, &b, &c, 2)
4030 .realize_f32()
4031 .iter()
4032 .sum()
4033 };
4034 let x0 = vec![1.0f32, 2.0, 3.0, 4.0];
4035 let x = Tensor::from_f32(x0.clone(), Shape::from_dims(&[1, 4, 1, 1]), &dev).unwrap();
4036 let dt = x
4037 .const_f32_like(vec![0.6f32, 0.6, 0.6, 0.6], Shape::from_dims(&[1, 4, 1]))
4038 .unwrap();
4039 let a = x
4040 .const_f32_like(vec![-0.5f32], Shape::from_dims(&[1]))
4041 .unwrap();
4042 let b = x
4043 .const_f32_like(vec![1.0f32, 1.0, 1.0, 1.0], Shape::from_dims(&[1, 4, 1, 1]))
4044 .unwrap();
4045 let c = x
4046 .const_f32_like(vec![1.0f32, 1.0, 1.0, 1.0], Shape::from_dims(&[1, 4, 1, 1]))
4047 .unwrap();
4048 let y = x.ssd_chunk_scan(&dt, &a, &b, &c, 2);
4049 let grads = y.inner.backward();
4050 let g_x_id = grads.get(x.graph_tensor()).expect("grad x").id();
4051 let g_x =
4052 crate::pipelined_bridge::realize_one_as::<f32>(&x.inner.graph().clone(), g_x_id, &dev)
4053 .expect("realize");
4054 let h = 1e-3f32;
4057 let mut xp = x0.clone();
4058 xp[0] += h;
4059 let mut xm = x0.clone();
4060 xm[0] -= h;
4061 let fd0 = (fwd(&xp) - fwd(&xm)) / (2.0 * h);
4062 assert!(
4063 (g_x[0] - fd0).abs() < 5e-2,
4064 "ssd_chunk_scan seqlen4 dL/dx_0: autograd {} vs FD {fd0}",
4065 g_x[0]
4066 );
4067 assert!(
4068 g_x[0].abs() > 0.5,
4069 "cross-chunk-gate grad must be non-trivial, got {g_x:?}"
4070 );
4071 }
4072
4073 fn find_scan_terminal(
4087 graph: &std::sync::Arc<std::sync::RwLock<fuel_graph::Graph>>,
4088 root: fuel_graph::NodeId,
4089 fused_id: fuel_graph::registry::FusedOpId,
4090 ) -> fuel_graph::NodeId {
4091 use fuel_graph::Op;
4092 let g = graph.read().unwrap();
4093 let mut stack = vec![root];
4094 let mut seen = std::collections::HashSet::new();
4095 let mut scan_id = None;
4096 while let Some(nid) = stack.pop() {
4097 if !seen.insert(nid) {
4098 continue;
4099 }
4100 let node = g.node(nid);
4101 assert!(
4102 !matches!(node.op, Op::Fused(fid, _) if fid == fused_id),
4103 "SSM op must lower to Op::Scan, not remain fused",
4104 );
4105 if matches!(node.op, Op::Scan { .. }) {
4106 scan_id = Some(nid);
4107 }
4108 for &inp in &node.inputs {
4109 stack.push(inp);
4110 }
4111 }
4112 scan_id.expect("an Op::Scan terminal must be present after lowering")
4113 }
4114
4115 fn scan_ys_to_fused_layout(ys: &[f32], seqlen: usize, batch: usize, tail: usize) -> Vec<f32> {
4128 assert_eq!(ys.len(), seqlen * batch * tail, "ys layout mismatch");
4129 let mut out = vec![0f32; ys.len()];
4130 for s in 0..seqlen {
4131 for bb in 0..batch {
4132 for t in 0..tail {
4133 out[(bb * seqlen + s) * tail + t] = ys[(s * batch + bb) * tail + t];
4134 }
4135 }
4136 }
4137 out
4138 }
4139
4140 #[test]
4156 fn selective_scan_multidim_unroll_matches_fused_kernel() {
4157 use fuel_graph::registry::FusedOps;
4158 let dev = Device::cpu();
4159 let (batch, seqlen, dim, dstate) = (2usize, 3usize, 2usize, 2usize);
4160 let u = Tensor::from_f32(
4162 vec![
4163 0.5, -0.3, 1.0, 0.2, -0.5, 0.7, 0.25, 0.9, -0.8, 0.4, 0.6, -0.1,
4164 ],
4165 Shape::from_dims(&[batch, seqlen, dim]),
4166 &dev,
4167 )
4168 .unwrap();
4169 let delta = u
4171 .const_f32_like(
4172 vec![
4173 0.1, 0.2, 0.3, 0.15, 0.25, 0.4, 0.35, 0.05, 0.2, 0.3, 0.12, 0.28,
4174 ],
4175 Shape::from_dims(&[batch, seqlen, dim]),
4176 )
4177 .unwrap();
4178 let a = u
4180 .const_f32_like(
4181 vec![-0.7, -0.3, -0.5, -0.9],
4182 Shape::from_dims(&[dim, dstate]),
4183 )
4184 .unwrap();
4185 let b = u
4187 .const_f32_like(
4188 vec![
4189 1.0, 0.5, 0.25, 0.75, 0.6, 0.2, 0.8, 0.4, 0.3, 0.9, 0.55, 0.15,
4190 ],
4191 Shape::from_dims(&[batch, seqlen, dstate]),
4192 )
4193 .unwrap();
4194 let c = u
4196 .const_f32_like(
4197 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],
4198 Shape::from_dims(&[batch, seqlen, dstate]),
4199 )
4200 .unwrap();
4201 let y = u.selective_scan(&delta, &a, &b, &c, false);
4202
4203 let fused = y.realize_f32();
4205 assert_eq!(fused.len(), batch * seqlen * dim);
4206
4207 let graph = y.inner.graph().clone();
4209 let roots = fuel_graph::opt::RuleRegistry::lowering_only()
4210 .optimize_to_fixpoint(&graph, &[y.inner.id()]);
4211 assert_eq!(roots.len(), 1);
4212 let scan_id = find_scan_terminal(&graph, roots[0], FusedOps::SELECTIVE_SCAN);
4213 let ys = {
4214 let mut g = graph.write().unwrap();
4215 fuel_graph::scan::unroll_scan(&mut g, scan_id, seqlen)
4216 .expect("unroll")
4217 .0[0] };
4219 let ys_flat = crate::pipelined_bridge::realize_one_as::<f32>(&graph, ys, &dev)
4220 .expect("realize selective_scan unroll oracle on CPU");
4221 let oracle = scan_ys_to_fused_layout(&ys_flat, seqlen, batch, dim);
4223 assert_eq!(oracle.len(), fused.len());
4224 let mut max_drift = 0f32;
4225 for (i, (o, f)) in oracle.iter().zip(fused.iter()).enumerate() {
4226 let d = (o - f).abs();
4227 max_drift = max_drift.max(d);
4228 assert!(
4232 d < 1e-3,
4233 "selective_scan multidim mismatch at {i}: oracle {o} vs fused {f} (drift {d})",
4234 );
4235 }
4236 eprintln!("selective_scan multidim: max honest drift = {max_drift:e}");
4237 }
4238
4239 #[test]
4245 fn selective_scan_softplus_multitoken_unroll_matches_fused_kernel() {
4246 use fuel_graph::registry::FusedOps;
4247 let dev = Device::cpu();
4248 let (batch, seqlen, dim, dstate) = (1usize, 3usize, 2usize, 2usize);
4249 let u = Tensor::from_f32(
4250 vec![0.5, -0.3, 1.0, 0.2, -0.5, 0.7],
4251 Shape::from_dims(&[batch, seqlen, dim]),
4252 &dev,
4253 )
4254 .unwrap();
4255 let delta = u
4257 .const_f32_like(
4258 vec![-0.5, 0.2, 0.8, -1.0, 0.3, -0.2],
4259 Shape::from_dims(&[batch, seqlen, dim]),
4260 )
4261 .unwrap();
4262 let a = u
4263 .const_f32_like(
4264 vec![-0.7, -0.3, -0.5, -0.9],
4265 Shape::from_dims(&[dim, dstate]),
4266 )
4267 .unwrap();
4268 let b = u
4269 .const_f32_like(
4270 vec![1.0, 0.5, 0.25, 0.75, 0.6, 0.2],
4271 Shape::from_dims(&[batch, seqlen, dstate]),
4272 )
4273 .unwrap();
4274 let c = u
4275 .const_f32_like(
4276 vec![2.0, 1.0, 0.5, 1.5, 0.8, 0.3],
4277 Shape::from_dims(&[batch, seqlen, dstate]),
4278 )
4279 .unwrap();
4280 let y = u.selective_scan(&delta, &a, &b, &c, true);
4281
4282 let fused = y.realize_f32();
4283 assert_eq!(fused.len(), batch * seqlen * dim);
4284
4285 let graph = y.inner.graph().clone();
4286 let roots = fuel_graph::opt::RuleRegistry::lowering_only()
4287 .optimize_to_fixpoint(&graph, &[y.inner.id()]);
4288 let scan_id = find_scan_terminal(&graph, roots[0], FusedOps::SELECTIVE_SCAN);
4289 let ys = {
4290 let mut g = graph.write().unwrap();
4291 fuel_graph::scan::unroll_scan(&mut g, scan_id, seqlen)
4292 .expect("unroll")
4293 .0[0] };
4295 let ys_flat = crate::pipelined_bridge::realize_one_as::<f32>(&graph, ys, &dev)
4296 .expect("realize selective_scan softplus oracle on CPU");
4297 let oracle = scan_ys_to_fused_layout(&ys_flat, seqlen, batch, dim);
4298 let mut max_drift = 0f32;
4299 for (i, (o, f)) in oracle.iter().zip(fused.iter()).enumerate() {
4300 let d = (o - f).abs();
4301 max_drift = max_drift.max(d);
4302 assert!(
4303 d < 1e-3,
4304 "selective_scan softplus mismatch at {i}: oracle {o} vs fused {f} (drift {d})",
4305 );
4306 }
4307 eprintln!("selective_scan softplus: max honest drift = {max_drift:e}");
4308 }
4309
4310 #[test]
4324 fn ssd_chunk_scan_multidim_unroll_matches_fused_kernel() {
4325 use fuel_graph::registry::FusedOps;
4326 let dev = Device::cpu();
4327 let (batch, seqlen, heads, head_dim, state_dim, chunk) =
4328 (2usize, 4usize, 2usize, 2usize, 2usize, 2usize);
4329 let x_data: Vec<f32> = (0..batch * seqlen * heads * head_dim)
4332 .map(|i| 0.20 + 0.05 * i as f32)
4333 .collect();
4334 let dt_data: Vec<f32> = (0..batch * seqlen * heads)
4335 .map(|i| 0.10 + 0.04 * i as f32)
4336 .collect();
4337 let b_data: Vec<f32> = (0..batch * seqlen * heads * state_dim)
4338 .map(|i| 0.15 + 0.03 * i as f32)
4339 .collect();
4340 let c_data: Vec<f32> = (0..batch * seqlen * heads * state_dim)
4341 .map(|i| 0.25 + 0.035 * i as f32)
4342 .collect();
4343 let x = Tensor::from_f32(
4344 x_data,
4345 Shape::from_dims(&[batch, seqlen, heads, head_dim]),
4346 &dev,
4347 )
4348 .unwrap();
4349 let dt = x
4350 .const_f32_like(dt_data, Shape::from_dims(&[batch, seqlen, heads]))
4351 .unwrap();
4352 let a = x
4353 .const_f32_like(vec![-0.6f32, -1.0], Shape::from_dims(&[heads]))
4354 .unwrap();
4355 let b = x
4356 .const_f32_like(b_data, Shape::from_dims(&[batch, seqlen, heads, state_dim]))
4357 .unwrap();
4358 let c = x
4359 .const_f32_like(c_data, Shape::from_dims(&[batch, seqlen, heads, state_dim]))
4360 .unwrap();
4361 let y = x.ssd_chunk_scan(&dt, &a, &b, &c, chunk);
4362
4363 let fused = y.realize_f32();
4365 assert_eq!(fused.len(), batch * seqlen * heads * head_dim);
4366
4367 let graph = y.inner.graph().clone();
4369 let roots = fuel_graph::opt::RuleRegistry::lowering_only()
4370 .optimize_to_fixpoint(&graph, &[y.inner.id()]);
4371 assert_eq!(roots.len(), 1);
4372 let scan_id = find_scan_terminal(&graph, roots[0], FusedOps::SSD_CHUNK_SCAN);
4373 let ys = {
4374 let mut g = graph.write().unwrap();
4375 fuel_graph::scan::unroll_scan(&mut g, scan_id, seqlen)
4376 .expect("unroll")
4377 .0[0] };
4379 let ys_flat = crate::pipelined_bridge::realize_one_as::<f32>(&graph, ys, &dev)
4380 .expect("realize ssd_chunk_scan unroll oracle on CPU");
4381 let oracle = scan_ys_to_fused_layout(&ys_flat, seqlen, batch, heads * head_dim);
4384 assert_eq!(oracle.len(), fused.len());
4385 let mut max_drift = 0f32;
4386 for (i, (o, f)) in oracle.iter().zip(fused.iter()).enumerate() {
4387 let d = (o - f).abs();
4388 max_drift = max_drift.max(d);
4389 assert!(
4390 d < 1e-3,
4391 "ssd_chunk_scan multidim mismatch at {i}: oracle {o} vs fused {f} (drift {d})",
4392 );
4393 }
4394 eprintln!("ssd_chunk_scan multidim: max honest drift = {max_drift:e}");
4395 }
4396
4397 #[test]
4406 fn nf4_matmul_decompose_matches_kernel() {
4407 use fuel_graph::Op;
4408 use fuel_graph::registry::FusedOps;
4409 let dev = Device::cpu();
4410 let weight = crate::nf4::nf4_from_bytes(
4412 vec![247_u8, 247, 127, 127],
4413 vec![1.0_f32, 2.0, 10.0, 20.0],
4414 2,
4415 4,
4416 2,
4417 &dev,
4418 )
4419 .expect("nf4_from_bytes");
4420 let act = Tensor::from_graph_tensor(
4421 weight
4422 .w_packed
4423 .graph_tensor()
4424 .const_f32_like(vec![1.0_f32, 2.0, 2.0, 4.0], Shape::from_dims(&[1, 4]))
4425 .unwrap(),
4426 );
4427 let y = weight.matmul(&act);
4428
4429 let graph = y.inner.graph().clone();
4431 let id = y.inner.id();
4432 let roots =
4433 fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
4434 assert_eq!(roots.len(), 1, "lowering should keep a single root");
4435
4436 {
4439 let g = graph.read().unwrap();
4440 let mut stack = vec![roots[0]];
4441 let mut seen = std::collections::HashSet::new();
4442 while let Some(nid) = stack.pop() {
4443 if !seen.insert(nid) {
4444 continue;
4445 }
4446 let node = g.node(nid);
4447 assert!(
4448 !matches!(node.op, Op::Fused(fid, _) if fid == FusedOps::NF4_MATMUL),
4449 "decomposed graph still contains an Op::Fused(NF4_MATMUL) island",
4450 );
4451 for &inp in &node.inputs {
4452 stack.push(inp);
4453 }
4454 }
4455 }
4456
4457 let got = crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &dev)
4458 .expect("realize decomposed Nf4Matmul on CPU");
4459 assert_eq!(got.len(), 2);
4460 assert!((got[0] - 10.0).abs() < 1e-4, "out 0: {}", got[0]);
4461 assert!((got[1] - 50.0).abs() < 1e-4, "out 1: {}", got[1]);
4462 }
4463
4464 fn lower_realize_fused(
4470 anchor: &Tensor,
4471 op: fuel_graph::Op,
4472 inputs: Vec<fuel_graph::NodeId>,
4473 shape: Shape,
4474 ) -> Vec<f32> {
4475 let graph = anchor.inner.graph().clone();
4476 let fused_id = {
4477 let mut g = graph.write().unwrap();
4478 g.push(fuel_graph::Node {
4479 op,
4480 inputs,
4481 shape,
4482 dtype: DType::F32,
4483 })
4484 };
4485 let roots = fuel_graph::opt::RuleRegistry::lowering_only()
4486 .optimize_to_fixpoint(&graph, &[fused_id]);
4487 assert_eq!(roots.len(), 1, "lowering keeps a single root");
4488 crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &Device::cpu())
4489 .expect("realize decomposed fused op on CPU")
4490 }
4491
4492 #[test]
4493 fn powi_backward_decompose_matches_reference() {
4494 use fuel_graph::registry::{FusedOpParams, FusedOps};
4495 let dev = Device::cpu();
4496 let exp = 3i32;
4497 let x_data = vec![1.5f32, -2.0, 0.5, 3.0];
4498 let up_data = vec![1.0f32, 0.5, 2.0, -1.0];
4499 let shape = Shape::from_dims(&[4]);
4500 let x = Tensor::from_f32(x_data.clone(), shape.clone(), &dev).unwrap();
4501 let up = x.const_f32_like(up_data.clone(), shape.clone()).unwrap();
4502 let got = lower_realize_fused(
4503 &x,
4504 fuel_graph::Op::Fused(FusedOps::POWI_BACKWARD, FusedOpParams::PowIBackward { exp }),
4505 vec![x.inner.id(), up.inner.id()],
4506 shape,
4507 );
4508 let expected: Vec<f32> = x_data
4510 .iter()
4511 .zip(&up_data)
4512 .map(|(&x, &u)| exp as f32 * x.powi(exp - 1) * u)
4513 .collect();
4514 assert_eq!(got.len(), expected.len());
4515 for (i, (&g, &e)) in got.iter().zip(&expected).enumerate() {
4516 assert!(
4517 (g - e).abs() < 1e-4,
4518 "powi_backward at {i}: got {g}, expected {e}"
4519 );
4520 }
4521 }
4522
4523 #[test]
4531 fn inplace_affine_decompose_matches_affine_reference() {
4532 use fuel_graph::registry::{FusedOpParams, FusedOps};
4533 let dev = Device::cpu();
4534 let (mul, add) = (2.5f64, -1.0f64);
4535 let x_data = vec![1.5f32, -2.0, 0.5, 3.0];
4536 let shape = Shape::from_dims(&[4]);
4537 let x = Tensor::from_f32(x_data.clone(), shape.clone(), &dev).unwrap();
4538 let got = lower_realize_fused(
4539 &x,
4540 fuel_graph::Op::Fused(
4541 FusedOps::INPLACE_AFFINE,
4542 FusedOpParams::InplaceAffine { mul, add },
4543 ),
4544 vec![x.inner.id()],
4545 shape,
4546 );
4547 let expected: Vec<f32> = x_data
4549 .iter()
4550 .map(|&v| (mul as f32) * v + add as f32)
4551 .collect();
4552 assert_eq!(got.len(), expected.len());
4553 for (i, (&g, &e)) in got.iter().zip(&expected).enumerate() {
4554 assert_eq!(g, e, "inplace_affine at {i}: got {g}, expected {e}");
4555 }
4556 }
4557
4558 #[test]
4559 fn softmax_last_dim_backward_decompose_matches_reference() {
4560 use fuel_graph::registry::{FusedOpParams, FusedOps};
4561 let dev = Device::cpu();
4562 let (rows, cols) = (2usize, 3usize);
4563 let logits = [[0.5f32, -1.0, 2.0], [1.0, 0.0, -0.5]];
4565 let mut s_data = Vec::new();
4566 for row in &logits {
4567 let m = row.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
4568 let exps: Vec<f32> = row.iter().map(|&v| (v - m).exp()).collect();
4569 let sum: f32 = exps.iter().sum();
4570 s_data.extend(exps.iter().map(|&e| e / sum));
4571 }
4572 let g_data = vec![1.0f32, -0.5, 0.3, 0.2, 1.5, -1.0];
4573 let shape = Shape::from_dims(&[rows, cols]);
4574 let s = Tensor::from_f32(s_data.clone(), shape.clone(), &dev).unwrap();
4575 let g = s.const_f32_like(g_data.clone(), shape.clone()).unwrap();
4576 let got = lower_realize_fused(
4577 &s,
4578 fuel_graph::Op::Fused(
4579 FusedOps::SOFTMAX_LAST_DIM_BACKWARD,
4580 FusedOpParams::SoftmaxLastDimBackward,
4581 ),
4582 vec![s.inner.id(), g.inner.id()],
4583 shape,
4584 );
4585 let mut expected = vec![0.0f32; rows * cols];
4587 for r in 0..rows {
4588 let dot: f32 = (0..cols)
4589 .map(|c| g_data[r * cols + c] * s_data[r * cols + c])
4590 .sum();
4591 for c in 0..cols {
4592 expected[r * cols + c] = s_data[r * cols + c] * (g_data[r * cols + c] - dot);
4593 }
4594 }
4595 for (i, (&gv, &ev)) in got.iter().zip(&expected).enumerate() {
4596 assert!(
4597 (gv - ev).abs() < 1e-5,
4598 "softmax_bwd at {i}: got {gv}, expected {ev}"
4599 );
4600 }
4601 }
4602
4603 #[test]
4604 fn rms_norm_last_dim_backward_decompose_matches_reference() {
4605 use fuel_graph::registry::{FusedOpParams, FusedOps};
4606 let dev = Device::cpu();
4607 let (rows, cols) = (2usize, 3usize);
4608 let eps = 1e-5f64;
4609 let x_data = vec![1.0f32, -2.0, 0.5, 3.0, 0.25, -1.5];
4610 let g_data = vec![0.5f32, 1.0, -0.3, 0.2, -1.0, 0.7];
4611 let shape = Shape::from_dims(&[rows, cols]);
4612 let x = Tensor::from_f32(x_data.clone(), shape.clone(), &dev).unwrap();
4613 let g = x.const_f32_like(g_data.clone(), shape.clone()).unwrap();
4614 let got = lower_realize_fused(
4615 &x,
4616 fuel_graph::Op::Fused(
4617 FusedOps::RMS_NORM_LAST_DIM_BACKWARD,
4618 FusedOpParams::RmsNormLastDimBackward { eps },
4619 ),
4620 vec![x.inner.id(), g.inner.id()],
4621 shape,
4622 );
4623 let n = cols as f32;
4625 let mut expected = vec![0.0f32; rows * cols];
4626 for r in 0..rows {
4627 let meansq: f32 = (0..cols).map(|c| x_data[r * cols + c].powi(2)).sum::<f32>() / n;
4628 let denom = meansq + eps as f32;
4629 let rrms = 1.0 / denom.sqrt();
4630 let s: f32 = (0..cols)
4631 .map(|c| g_data[r * cols + c] * x_data[r * cols + c])
4632 .sum();
4633 for c in 0..cols {
4634 let term = x_data[r * cols + c] * s / (n * denom);
4635 expected[r * cols + c] = rrms * (g_data[r * cols + c] - term);
4636 }
4637 }
4638 for (i, (&gv, &ev)) in got.iter().zip(&expected).enumerate() {
4639 assert!(
4640 (gv - ev).abs() < 1e-4,
4641 "rms_norm_bwd at {i}: got {gv}, expected {ev}"
4642 );
4643 }
4644 }
4645
4646 #[test]
4647 fn layer_norm_last_dim_backward_decompose_matches_reference() {
4648 use fuel_graph::registry::{FusedOpParams, FusedOps};
4649 let dev = Device::cpu();
4650 let (rows, cols) = (2usize, 3usize);
4651 let eps = 1e-5f64;
4652 let x_data = vec![1.0f32, -2.0, 0.5, 3.0, 0.25, -1.5];
4653 let g_data = vec![0.5f32, 1.0, -0.3, 0.2, -1.0, 0.7];
4654 let shape = Shape::from_dims(&[rows, cols]);
4655 let x = Tensor::from_f32(x_data.clone(), shape.clone(), &dev).unwrap();
4656 let g = x.const_f32_like(g_data.clone(), shape.clone()).unwrap();
4657 let got = lower_realize_fused(
4658 &x,
4659 fuel_graph::Op::Fused(
4660 FusedOps::LAYER_NORM_LAST_DIM_BACKWARD,
4661 FusedOpParams::LayerNormLastDimBackward { eps },
4662 ),
4663 vec![x.inner.id(), g.inner.id()],
4664 shape,
4665 );
4666 let n = cols as f32;
4668 let mut expected = vec![0.0f32; rows * cols];
4669 for r in 0..rows {
4670 let mean_x: f32 = (0..cols).map(|c| x_data[r * cols + c]).sum::<f32>() / n;
4671 let var: f32 = (0..cols)
4672 .map(|c| (x_data[r * cols + c] - mean_x).powi(2))
4673 .sum::<f32>()
4674 / n;
4675 let istd = 1.0 / (var + eps as f32).sqrt();
4676 let xhat: Vec<f32> = (0..cols)
4677 .map(|c| (x_data[r * cols + c] - mean_x) * istd)
4678 .collect();
4679 let mean_g: f32 = (0..cols).map(|c| g_data[r * cols + c]).sum::<f32>() / n;
4680 let mean_gxh: f32 = (0..cols)
4681 .map(|c| g_data[r * cols + c] * xhat[c])
4682 .sum::<f32>()
4683 / n;
4684 for c in 0..cols {
4685 expected[r * cols + c] =
4686 istd * (g_data[r * cols + c] - mean_g - xhat[c] * mean_gxh);
4687 }
4688 }
4689 for (i, (&gv, &ev)) in got.iter().zip(&expected).enumerate() {
4690 assert!(
4691 (gv - ev).abs() < 1e-4,
4692 "layer_norm_bwd at {i}: got {gv}, expected {ev}"
4693 );
4694 }
4695 }
4696
4697 #[test]
4698 fn reduce_max_to_backward_decompose_matches_reference() {
4699 use fuel_graph::registry::{FusedOpParams, FusedOps};
4700 let dev = Device::cpu();
4701 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]);
4705 let up_shape = Shape::from_dims(&[2, 1]);
4706 let x = Tensor::from_f32(x_data.clone(), x_shape.clone(), &dev).unwrap();
4707 let up = x.const_f32_like(up_data.clone(), up_shape).unwrap();
4708 let got = lower_realize_fused(
4709 &x,
4710 fuel_graph::Op::Fused(
4711 FusedOps::REDUCE_MAX_TO_BACKWARD,
4712 FusedOpParams::ReduceMaxToBackward,
4713 ),
4714 vec![x.inner.id(), up.inner.id()],
4715 x_shape,
4716 );
4717 let expected = vec![0.0f32, 5.0, 5.0, 5.0, 0.0, 0.0];
4719 for (i, (&gv, &ev)) in got.iter().zip(&expected).enumerate() {
4720 assert!(
4721 (gv - ev).abs() < 1e-5,
4722 "reduce_max_bwd at {i}: got {gv}, expected {ev}"
4723 );
4724 }
4725 }
4726
4727 fn causal_conv1d_check(use_silu: bool) {
4728 use fuel_graph::registry::{FusedOpParams, FusedOps};
4729 let dev = Device::cpu();
4730 let (b, c, k, seq) = (1usize, 2usize, 3usize, 2usize);
4731 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];
4734 let w_data = vec![0.5f32, 1.0, -0.5, 1.0, 0.0, 2.0];
4735 let bias_data = vec![0.1f32, -0.2];
4736 let x = Tensor::from_f32(x_data.clone(), Shape::from_dims(&[b, c, x_seq]), &dev).unwrap();
4737 let w = x
4738 .const_f32_like(w_data.clone(), Shape::from_dims(&[c, 1, k]))
4739 .unwrap();
4740 let bias = x
4741 .const_f32_like(bias_data.clone(), Shape::from_dims(&[c]))
4742 .unwrap();
4743 let got = lower_realize_fused(
4744 &x,
4745 fuel_graph::Op::Fused(
4746 FusedOps::CAUSAL_CONV1D,
4747 FusedOpParams::CausalConv1d { use_silu },
4748 ),
4749 vec![x.inner.id(), w.inner.id(), bias.inner.id()],
4750 Shape::from_dims(&[b, c, seq]),
4751 );
4752 let mut expected = vec![0.0f32; b * c * seq];
4754 for ch in 0..c {
4755 for t in 0..seq {
4756 let mut acc = 0.0f32;
4757 for kk in 0..k {
4758 acc += w_data[ch * k + kk] * x_data[ch * x_seq + t + kk];
4759 }
4760 acc += bias_data[ch];
4761 if use_silu {
4762 acc *= 1.0 / (1.0 + (-acc).exp());
4763 }
4764 expected[ch * seq + t] = acc;
4765 }
4766 }
4767 for (i, (&gv, &ev)) in got.iter().zip(&expected).enumerate() {
4768 assert!(
4769 (gv - ev).abs() < 1e-4,
4770 "causal_conv1d (silu={use_silu}) at {i}: got {gv}, expected {ev}",
4771 );
4772 }
4773 }
4774
4775 #[test]
4776 fn causal_conv1d_decompose_matches_reference() {
4777 causal_conv1d_check(false);
4778 causal_conv1d_check(true);
4779 }
4780
4781 #[test]
4782 fn flash_attn_backward_decompose_matches_reference() {
4783 use fuel_graph::registry::{FusedOpParams, FusedOps};
4784 let dev = Device::cpu();
4785 let (sq, sk, d) = (2usize, 2usize, 2usize);
4786 #[allow(clippy::approx_constant)]
4789 let scale = 0.7071f32;
4790 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]);
4795 let kshape = Shape::from_dims(&[1, 1, sk, d]);
4796 let q = Tensor::from_f32(q_data.clone(), qshape.clone(), &dev).unwrap();
4797 let k = q.const_f32_like(k_data.clone(), kshape.clone()).unwrap();
4798 let v = q.const_f32_like(v_data.clone(), kshape.clone()).unwrap();
4799 let dout = q.const_f32_like(do_data.clone(), qshape.clone()).unwrap();
4800 let params = FusedOpParams::FlashAttnBackward {
4801 softmax_scale: scale,
4802 causal: false,
4803 window_size_left: None,
4804 window_size_right: None,
4805 softcap: None,
4806 };
4807 let inputs = vec![q.inner.id(), k.inner.id(), v.inner.id(), dout.inner.id()];
4808 let dq = lower_realize_fused(
4809 &q,
4810 fuel_graph::Op::Fused(FusedOps::FLASH_ATTN_BACKWARD_Q, params.clone()),
4811 inputs.clone(),
4812 qshape.clone(),
4813 );
4814 let dk = lower_realize_fused(
4815 &q,
4816 fuel_graph::Op::Fused(FusedOps::FLASH_ATTN_BACKWARD_K, params.clone()),
4817 inputs.clone(),
4818 kshape.clone(),
4819 );
4820 let dv = lower_realize_fused(
4821 &q,
4822 fuel_graph::Op::Fused(FusedOps::FLASH_ATTN_BACKWARD_V, params),
4823 inputs,
4824 kshape,
4825 );
4826
4827 let mut p = vec![0.0f32; sq * sk];
4829 for i in 0..sq {
4830 let mut scores = vec![0.0f32; sk];
4831 for j in 0..sk {
4832 let mut s = 0.0f32;
4833 for l in 0..d {
4834 s += q_data[i * d + l] * k_data[j * d + l];
4835 }
4836 scores[j] = scale * s;
4837 }
4838 let m = scores.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
4839 let mut sum = 0.0f32;
4840 let e: Vec<f32> = scores
4841 .iter()
4842 .map(|&s| {
4843 let x = (s - m).exp();
4844 sum += x;
4845 x
4846 })
4847 .collect();
4848 for j in 0..sk {
4849 p[i * sk + j] = e[j] / sum;
4850 }
4851 }
4852 let mut ref_dv = vec![0.0f32; sk * d];
4854 for j in 0..sk {
4855 for l in 0..d {
4856 ref_dv[j * d + l] = (0..sq).map(|i| p[i * sk + j] * do_data[i * d + l]).sum();
4857 }
4858 }
4859 let mut dp = vec![0.0f32; sq * sk];
4861 for i in 0..sq {
4862 for j in 0..sk {
4863 dp[i * sk + j] = (0..d).map(|l| do_data[i * d + l] * v_data[j * d + l]).sum();
4864 }
4865 }
4866 let mut dsr = vec![0.0f32; sq * sk];
4868 for i in 0..sq {
4869 let rowdot: f32 = (0..sk).map(|j| dp[i * sk + j] * p[i * sk + j]).sum();
4870 for j in 0..sk {
4871 dsr[i * sk + j] = scale * p[i * sk + j] * (dp[i * sk + j] - rowdot);
4872 }
4873 }
4874 let mut ref_dq = vec![0.0f32; sq * d];
4876 for i in 0..sq {
4877 for l in 0..d {
4878 ref_dq[i * d + l] = (0..sk).map(|j| dsr[i * sk + j] * k_data[j * d + l]).sum();
4879 }
4880 }
4881 let mut ref_dk = vec![0.0f32; sk * d];
4882 for j in 0..sk {
4883 for l in 0..d {
4884 ref_dk[j * d + l] = (0..sq).map(|i| dsr[i * sk + j] * q_data[i * d + l]).sum();
4885 }
4886 }
4887 let check = |name: &str, got: &[f32], exp: &[f32]| {
4888 assert_eq!(got.len(), exp.len(), "{name} length");
4889 for (i, (&gv, &ev)) in got.iter().zip(exp).enumerate() {
4890 assert!(
4891 (gv - ev).abs() < 1e-4,
4892 "{name} at {i}: got {gv}, expected {ev}"
4893 );
4894 }
4895 };
4896 check("dQ", &dq, &ref_dq);
4897 check("dK", &dk, &ref_dk);
4898 check("dV", &dv, &ref_dv);
4899 }
4900
4901 #[test]
4902 fn paged_attn_decompose_matches_reference() {
4903 use fuel_graph::registry::{FusedOpParams, FusedOps};
4904 let dev = Device::cpu();
4905 let block_size = 2usize;
4907 let scale = 1.0f32;
4908 let kc = vec![
4911 1.0f32, 0.0, 0.0, 1.0, 9.0, 9.0, 9.0, 9.0, 1.0, 1.0, 2.0, 0.0,
4912 ];
4913 let vc = vec![
4914 1.0f32, 2.0, 3.0, 4.0, 0.0, 0.0, 0.0, 0.0, 5.0, 6.0, 7.0, 8.0,
4915 ];
4916 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();
4921 let kcache = q
4922 .const_f32_like(kc.clone(), Shape::from_dims(&[3, 2, 1, 2]))
4923 .unwrap();
4924 let vcache = q
4925 .const_f32_like(vc.clone(), Shape::from_dims(&[3, 2, 1, 2]))
4926 .unwrap();
4927 let block_table = q.const_u32_like(bt, Shape::from_dims(&[1, 2])).unwrap();
4928 let context_lens = q.const_u32_like(cl, Shape::from_dims(&[1])).unwrap();
4929 let params = FusedOpParams::PagedAttn {
4930 softmax_scale: scale,
4931 block_size,
4932 softcap: None,
4933 };
4934 let inputs = vec![
4935 q.inner.id(),
4936 kcache.inner.id(),
4937 vcache.inner.id(),
4938 block_table.inner.id(),
4939 context_lens.inner.id(),
4940 ];
4941 let got = lower_realize_fused(
4942 &q,
4943 fuel_graph::Op::Fused(FusedOps::PAGED_ATTN, params),
4944 inputs,
4945 Shape::from_dims(&[1, 1, 1, 2]),
4946 );
4947
4948 let (kv_len, ctx) = (4usize, 3usize);
4951 let mut k_seq = vec![];
4952 let mut v_seq = vec![];
4953 for &blk in &[0usize, 2usize] {
4954 for p in 0..block_size {
4955 let base = (blk * block_size + p) * 2; k_seq.push([kc[base], kc[base + 1]]);
4957 v_seq.push([vc[base], vc[base + 1]]);
4958 }
4959 }
4960 let mut scores = vec![0.0f32; kv_len];
4961 for j in 0..kv_len {
4962 let s = q_data[0] * k_seq[j][0] + q_data[1] * k_seq[j][1];
4963 scores[j] = if j >= ctx {
4964 f32::NEG_INFINITY
4965 } else {
4966 scale * s
4967 };
4968 }
4969 let m = scores.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
4970 let mut sum = 0.0f32;
4971 let e: Vec<f32> = scores
4972 .iter()
4973 .map(|&s| {
4974 let x = (s - m).exp();
4975 sum += x;
4976 x
4977 })
4978 .collect();
4979 let mut expected = vec![0.0f32; 2];
4980 for j in 0..kv_len {
4981 for l in 0..2 {
4982 expected[l] += (e[j] / sum) * v_seq[j][l];
4983 }
4984 }
4985 for (i, (&gv, &ev)) in got.iter().zip(&expected).enumerate() {
4986 assert!(
4987 (gv - ev).abs() < 1e-4,
4988 "paged_attn at {i}: got {gv}, expected {ev}"
4989 );
4990 }
4991 }
4992
4993 #[test]
4994 #[cfg(feature = "cuda")]
4995 fn cuda_executor_matches_cpu_on_add_mul() {
4996 let a =
4997 Tensor::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), &Device::cpu()).unwrap();
4998 let b = a
4999 .const_f32_like(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]))
5000 .unwrap();
5001 let c = a.add(&b).unwrap().mul(&a).unwrap();
5002 let cpu_result = c.realize_f32();
5003 let executor = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5004 let cuda_result = c.realize_f32_cuda(&executor);
5005 assert_eq!(cpu_result, cuda_result);
5006 }
5007
5008 #[test]
5026 #[cfg(feature = "cuda")]
5027 #[ignore = "requires a live CUDA device"]
5028 fn maximum_minimum_nan_convention_lazy_realize_smoke() {
5029 let cuda = match fuel_cuda_backend::CudaDevice::new(0) {
5030 Ok(d) => d,
5031 Err(e) => {
5032 return fuel_test_support::hardware::skip(
5033 fuel_test_support::hardware::Hardware::Cuda,
5034 fuel_test_support::hardware::Missing::device(format!(
5035 "CudaDevice::new(0): {e:?}"
5036 )),
5037 );
5038 }
5039 };
5040 let a = Tensor::from_f32(
5041 vec![f32::NAN, -2.0, 3.0, f32::NAN],
5042 Shape::from_dims(&[4]),
5043 &Device::cpu(),
5044 )
5045 .unwrap();
5046 let b = a
5047 .const_f32_like(vec![1.0, f32::NAN, 2.0, f32::NAN], Shape::from_dims(&[4]))
5048 .unwrap();
5049
5050 let max_lazy = a.maximum(&b).unwrap();
5051 let cpu_max = max_lazy.realize_f32();
5052 let cuda_max = max_lazy.realize_f32_cuda(&cuda);
5053 for i in 0..4 {
5054 assert_eq!(
5055 cpu_max[i].is_nan(),
5056 cuda_max[i].is_nan(),
5057 "maximum[{i}] NaN-ness must match: cpu={}, cuda={}",
5058 cpu_max[i],
5059 cuda_max[i],
5060 );
5061 if !cpu_max[i].is_nan() {
5062 assert_eq!(cpu_max[i], cuda_max[i], "maximum[{i}]");
5063 }
5064 }
5065
5066 let min_lazy = a.minimum(&b).unwrap();
5067 let cpu_min = min_lazy.realize_f32();
5068 let cuda_min = min_lazy.realize_f32_cuda(&cuda);
5069 for i in 0..4 {
5070 assert_eq!(
5071 cpu_min[i].is_nan(),
5072 cuda_min[i].is_nan(),
5073 "minimum[{i}] NaN-ness must match: cpu={}, cuda={}",
5074 cpu_min[i],
5075 cuda_min[i],
5076 );
5077 if !cpu_min[i].is_nan() {
5078 assert_eq!(cpu_min[i], cuda_min[i], "minimum[{i}]");
5079 }
5080 }
5081 }
5082
5083 #[test]
5106 #[cfg(feature = "cuda")]
5107 #[ignore = "requires a live CUDA device"]
5108 fn relu_nan_convention_lazy_realize_smoke() {
5109 let cuda = match fuel_cuda_backend::CudaDevice::new(0) {
5110 Ok(d) => d,
5111 Err(e) => {
5112 return fuel_test_support::hardware::skip(
5113 fuel_test_support::hardware::Hardware::Cuda,
5114 fuel_test_support::hardware::Missing::device(format!(
5115 "CudaDevice::new(0): {e:?}"
5116 )),
5117 );
5118 }
5119 };
5120 let a = Tensor::from_f32(
5121 vec![f32::NAN, -2.0, 3.0],
5122 Shape::from_dims(&[3]),
5123 &Device::cpu(),
5124 )
5125 .unwrap();
5126 let relu_lazy = a.relu();
5127 let cpu_result = relu_lazy.realize_f32();
5128 let cuda_result = relu_lazy.realize_f32_cuda(&cuda);
5129
5130 for i in 0..3 {
5131 assert_eq!(
5132 cpu_result[i].is_nan(),
5133 cuda_result[i].is_nan(),
5134 "relu[{i}] NaN-ness must match: cpu={}, cuda={}",
5135 cpu_result[i],
5136 cuda_result[i],
5137 );
5138 if !cpu_result[i].is_nan() {
5139 assert_eq!(cpu_result[i], cuda_result[i], "relu[{i}]");
5140 }
5141 }
5142 }
5143
5144 #[test]
5145 #[cfg(feature = "cuda")]
5146 fn cuda_executor_matches_cpu_on_matmul() {
5147 let a = Tensor::from_f32(
5148 vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
5149 Shape::from_dims(&[2, 3]),
5150 &Device::cpu(),
5151 )
5152 .unwrap();
5153 let b = a
5154 .const_f32_like(
5155 vec![7.0, 8.0, 9.0, 10.0, 11.0, 12.0],
5156 Shape::from_dims(&[3, 2]),
5157 )
5158 .unwrap();
5159 let c = a.matmul(&b).unwrap();
5160 let cpu = c.realize_f32();
5161 let exe = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5162 let cuda = c.realize_f32_cuda(&exe);
5163 assert_eq!(cpu.len(), cuda.len());
5164 for (i, (a, b)) in cpu.iter().zip(cuda.iter()).enumerate() {
5165 assert!((a - b).abs() < 1e-3, "matmul[{i}]: cpu={a}, cuda={b}",);
5166 }
5167 }
5168
5169 #[test]
5170 #[cfg(feature = "cuda")]
5171 fn cuda_executor_matches_cpu_on_broadcast_matmul() {
5172 let x = Tensor::from_f32(
5175 (0..12).map(|i| i as f32 * 0.1).collect::<Vec<_>>(),
5176 Shape::from_dims(&[1, 3, 4]),
5177 &Device::cpu(),
5178 )
5179 .unwrap();
5180 let w = x
5181 .const_f32_like(
5182 (0..8).map(|i| i as f32 * 0.2).collect::<Vec<_>>(),
5183 Shape::from_dims(&[4, 2]),
5184 )
5185 .unwrap();
5186 let y = x.matmul(&w).unwrap();
5187 let cpu = y.realize_f32();
5188 let exe = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5189 let cuda = y.realize_f32_cuda(&exe);
5190 assert_eq!(cpu.len(), cuda.len());
5191 for (i, (&a, &b)) in cpu.iter().zip(cuda.iter()).enumerate() {
5192 assert!((a - b).abs() < 1e-3, "bcast_mm[{i}]: cpu={a}, cuda={b}");
5193 }
5194 }
5195
5196 #[test]
5197 #[cfg(feature = "cuda")]
5198 fn cuda_executor_matches_cpu_on_permute() {
5199 let x = Tensor::from_f32(
5200 (0..24).map(|i| i as f32).collect::<Vec<_>>(),
5201 Shape::from_dims(&[1, 2, 3, 4]),
5202 &Device::cpu(),
5203 )
5204 .unwrap();
5205 let y = x.permute([0, 2, 1, 3_usize]).unwrap();
5206 let cpu = y.realize_f32();
5207 let exe = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5208 let cuda = y.realize_f32_cuda(&exe);
5209 assert_eq!(cpu, cuda, "permute mismatch");
5210 }
5211
5212 #[test]
5213 #[cfg(feature = "cuda")]
5214 fn cuda_executor_matches_cpu_on_softmax() {
5215 let x = Tensor::from_f32(
5216 vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
5217 Shape::from_dims(&[2, 3]),
5218 &Device::cpu(),
5219 )
5220 .unwrap();
5221 let y = x.softmax_last_dim().unwrap();
5222 let cpu = y.realize_f32();
5223 let exe = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5224 let cuda = y.realize_f32_cuda(&exe);
5225 assert_eq!(cpu.len(), cuda.len());
5226 for (i, (&a, &b)) in cpu.iter().zip(cuda.iter()).enumerate() {
5227 assert!((a - b).abs() < 1e-4, "softmax[{i}]: cpu={a}, cuda={b}");
5228 }
5229 }
5230
5231 #[test]
5246 #[cfg(feature = "cuda")]
5247 fn cuda_executor_matches_cpu_on_softmax_via_lowering() {
5248 let n = 24;
5251 let last = 5;
5252 let data: Vec<f32> = (0..n * last)
5253 .map(|i| ((i as f32) * 0.13).sin() * 2.0 - 0.7)
5254 .collect();
5255 let x = Tensor::from_f32(data, Shape::from_dims(&[n, last]), &Device::cpu()).unwrap();
5256 let y = x.softmax_last_dim().unwrap();
5257
5258 let cpu = y.realize_f32();
5261
5262 let graph = y.inner.graph().clone();
5268 let registry = fuel_graph::opt::RuleRegistry::lowering_only();
5269 let remapped = registry.optimize_to_fixpoint(&graph, &[y.inner.id()]);
5270 let dev = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5271 let fc_device: crate::Device = dev.clone().into();
5272 let cuda = crate::pipelined_bridge::realize_one_as::<f32>(&graph, remapped[0], &fc_device)
5273 .expect("realize lowered softmax on CUDA");
5274
5275 assert_eq!(cpu.len(), cuda.len());
5276 let mut max_abs_err = 0.0_f32;
5277 for (i, (&a, &b)) in cpu.iter().zip(cuda.iter()).enumerate() {
5278 let err = (a - b).abs();
5279 if err > max_abs_err {
5280 max_abs_err = err;
5281 }
5282 assert!(
5283 err < 1e-5,
5284 "lowered softmax[{i}]: cpu={a} (fused), cuda={b} (composed), err={err}",
5285 );
5286 }
5287 eprintln!("max_abs_err over lowered-vs-fused softmax: {max_abs_err:.3e}");
5288 }
5289
5290 #[test]
5291 #[cfg(feature = "cuda")]
5292 fn cuda_executor_matches_cpu_on_concat_slice() {
5293 let a = Tensor::from_f32(
5294 vec![1.0, 2.0, 3.0, 4.0],
5295 Shape::from_dims(&[2, 2]),
5296 &Device::cpu(),
5297 )
5298 .unwrap();
5299 let b = a
5300 .const_f32_like(vec![5.0, 6.0, 7.0, 8.0], Shape::from_dims(&[2, 2]))
5301 .unwrap();
5302 let cat = a.concat(&b, 1).unwrap(); let sliced = cat.slice(1, 1, 2).unwrap(); let cpu = sliced.realize_f32();
5305 let exe = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5306 let cuda = sliced.realize_f32_cuda(&exe);
5307 assert_eq!(cpu, cuda, "concat+slice mismatch");
5308 }
5309
5310 #[test]
5311 #[cfg(feature = "cuda")]
5312 fn cuda_executor_matches_cpu_on_rms_norm() {
5313 let x = Tensor::from_f32(
5314 (0..8).map(|i| i as f32 * 0.5 - 1.5).collect::<Vec<_>>(),
5315 Shape::from_dims(&[2, 4]),
5316 &Device::cpu(),
5317 )
5318 .unwrap();
5319 let y = x.rms_norm_last_dim(1e-5).unwrap();
5320 let cpu = y.realize_f32();
5321 let exe = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5322 let cuda = y.realize_f32_cuda(&exe);
5323 assert_eq!(cpu.len(), cuda.len());
5324 for (i, (&a, &b)) in cpu.iter().zip(cuda.iter()).enumerate() {
5325 assert!((a - b).abs() < 1e-3, "rms_norm[{i}]: cpu={a}, cuda={b}");
5326 }
5327 }
5328
5329 #[test]
5330 fn realize_f64_through_bridge() {
5331 let a =
5332 Tensor::from_f64(vec![1.5, 2.5, 3.5], Shape::from_dims(&[3]), &Device::cpu()).unwrap();
5333 let b = a.mul(&a).unwrap();
5334 assert_eq!(b.realize_f64(), vec![2.25, 6.25, 12.25]);
5335 }
5336
5337 #[test]
5348 fn gap327_realize_f32_on_f64_root_must_reject_not_reinterpret() {
5349 let t =
5350 Tensor::from_f64(vec![1.0_f64, 2.0], Shape::from_dims(&[2]), &Device::cpu()).unwrap();
5351 let graph = t.inner.graph().clone();
5352 let target = t.inner.id();
5353 let device = Device::cpu();
5354
5355 let prev_hook = std::panic::take_hook();
5358 std::panic::set_hook(Box::new(|_| {}));
5359 let ctl_f64 = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| t.realize_f64()));
5361 let ctl_f16 = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| t.realize_f16()));
5364 let subj_method =
5366 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| t.realize_f32()));
5367 std::panic::set_hook(prev_hook);
5368
5369 let subj_raw = crate::pipelined_bridge::realize_one_as::<f32>(&graph, target, &device);
5371 let bytes_view = crate::pipelined_bridge::realize_one_bytes(&graph, target, &device);
5374
5375 assert!(
5376 ctl_f64.is_ok(),
5377 "control: realize_f64 on an F64 root must succeed; got {ctl_f64:?}"
5378 );
5379 assert!(
5380 ctl_f16.is_err(),
5381 "positive control: realize_f16() on an F64 root must panic (guard fires); if it \
5382 does not, the harness is not observing panics and the subject asserts are vacuous"
5383 );
5384 assert!(
5385 subj_method.is_err(),
5386 "realize_f32() on an F64 root must REJECT (panic), not silently reinterpret bytes"
5387 );
5388 assert!(
5389 matches!(subj_raw, Err(fuel_ir::Error::UnexpectedDType { .. })),
5390 "realize_one_as::<f32> on an F64 root must return Err(UnexpectedDType), not \
5391 Ok(reinterpreted bytes); got {subj_raw:?}"
5392 );
5393 assert!(
5394 matches!(&bytes_view, Ok(b) if b.len() == 16),
5395 "byte view realize_one_bytes on an F64 [1.0, 2.0] root must return 16 raw bytes \
5396 (unguarded), not an error; got {bytes_view:?}"
5397 );
5398 }
5399
5400 #[test]
5401 fn lazy_tensor_mini_llama_block_forward() {
5402 let seq = 3;
5411 let d_head = 4; let num_heads = 2;
5413 let d_model = num_heads * d_head; let x_data: Vec<f32> = (0..seq * d_model).map(|i| i as f32 * 0.01).collect();
5417 let x =
5418 Tensor::from_f32(x_data, Shape::from_dims(&[1, seq, d_model]), &Device::cpu()).unwrap();
5419
5420 let w_q = x
5424 .const_f32_like(
5425 identity_matrix(d_model),
5426 Shape::from_dims(&[d_model, d_model]),
5427 )
5428 .unwrap();
5429 let w_k = x
5430 .const_f32_like(
5431 identity_matrix(d_model),
5432 Shape::from_dims(&[d_model, d_model]),
5433 )
5434 .unwrap();
5435 let w_v = x
5436 .const_f32_like(
5437 identity_matrix(d_model),
5438 Shape::from_dims(&[d_model, d_model]),
5439 )
5440 .unwrap();
5441 let w_o = x
5442 .const_f32_like(
5443 identity_matrix(d_model),
5444 Shape::from_dims(&[d_model, d_model]),
5445 )
5446 .unwrap();
5447
5448 let x_norm = x.rms_norm_last_dim(1e-6).unwrap();
5450 let q = x_norm.matmul(&w_q).unwrap();
5451 let k = x_norm.matmul(&w_k).unwrap();
5452 let v = x_norm.matmul(&w_v).unwrap();
5453
5454 let q_h = q
5456 .reshape(Shape::from_dims(&[1, seq, num_heads, d_head]))
5457 .unwrap()
5458 .permute([0, 2, 1, 3_usize])
5459 .unwrap();
5460 let k_h = k
5461 .reshape(Shape::from_dims(&[1, seq, num_heads, d_head]))
5462 .unwrap()
5463 .permute([0, 2, 1, 3_usize])
5464 .unwrap();
5465 let v_h = v
5466 .reshape(Shape::from_dims(&[1, seq, num_heads, d_head]))
5467 .unwrap()
5468 .permute([0, 2, 1, 3_usize])
5469 .unwrap();
5470
5471 let q_r = q_h.rope(10000.0, 0).unwrap();
5473 let k_r = k_h.rope(10000.0, 0).unwrap();
5474
5475 let k_t = k_r.transpose().unwrap();
5477 let scores = q_r.matmul(&k_t).unwrap();
5478 let attn = scores.softmax_last_dim().unwrap();
5479 let attn_v = attn.matmul(&v_h).unwrap();
5480
5481 let merged = attn_v
5483 .permute([0, 2, 1, 3_usize])
5484 .unwrap()
5485 .reshape(Shape::from_dims(&[1, seq, d_model]))
5486 .unwrap();
5487 let attn_out = merged.matmul(&w_o).unwrap();
5488 let h = x.add(&attn_out).unwrap();
5489
5490 let result = h.realize_f32();
5492 assert_eq!(result.len(), seq * d_model);
5493 for &v in &result {
5494 assert!(
5495 v.is_finite(),
5496 "bridge-based LLaMA block output non-finite: {v}"
5497 );
5498 }
5499 }
5500
5501 fn identity_matrix(n: usize) -> Vec<f32> {
5503 let mut out = vec![0.0_f32; n * n];
5504 for i in 0..n {
5505 out[i * n + i] = 1.0;
5506 }
5507 out
5508 }
5509}
5510
5511impl Tensor {
5515 pub fn const_u32_like(
5517 &self,
5518 data: impl Into<Arc<[u32]>>,
5519 shape: impl Into<Shape>,
5520 ) -> std::result::Result<Self, fuel_ir::Error> {
5521 Ok(Self {
5522 inner: self.inner.const_u32_like(data, shape)?,
5523 })
5524 }
5525
5526 pub fn const_placeholder_like(&self, shape: impl Into<Shape>, dtype: fuel_ir::DType) -> Self {
5537 Self {
5538 inner: self.inner.const_placeholder_like(shape, dtype),
5539 }
5540 }
5541
5542 pub fn write_slice(&self, source: &Self, ranges: Vec<(usize, usize)>) -> crate::Result<Self> {
5554 let inner = self.inner.write_slice(&source.inner, ranges)?;
5555 Ok(Self { inner })
5556 }
5557
5558 pub fn write_slice_dyn(
5566 &self,
5567 source: &Self,
5568 ranges: Vec<(usize, usize)>,
5569 dyn_axis: usize,
5570 offset: fuel_ir::DynScalar,
5571 ) -> crate::Result<Self> {
5572 let inner = self
5573 .inner
5574 .write_slice_dyn(&source.inner, ranges, dyn_axis, offset)?;
5575 Ok(Self { inner })
5576 }
5577
5578 pub fn write_slice_rotating(
5593 &self,
5594 source: &Self,
5595 position: &Self,
5596 axis: usize,
5597 modulus: usize,
5598 ranges: Vec<(usize, usize)>,
5599 ) -> crate::Result<Self> {
5600 let inner = self.inner.write_slice_rotating(
5601 &source.inner,
5602 &position.inner,
5603 axis,
5604 modulus,
5605 ranges,
5606 )?;
5607 Ok(Self { inner })
5608 }
5609
5610 pub fn write_slice_doff(
5623 &self,
5624 source: &Self,
5625 offset: &Self,
5626 axis: usize,
5627 ranges: Vec<(usize, usize)>,
5628 ) -> crate::Result<Self> {
5629 let inner = self
5630 .inner
5631 .write_slice_doff(&source.inner, &offset.inner, axis, ranges)?;
5632 Ok(Self { inner })
5633 }
5634
5635 pub fn conv2d(
5646 &self,
5647 weight: &Self,
5648 bias: Option<&Self>,
5649 stride: (usize, usize),
5650 padding: (usize, usize),
5651 groups: usize,
5652 ) -> std::result::Result<Self, fuel_ir::Error> {
5653 if groups < 1 {
5654 return Err(
5655 fuel_ir::Error::Msg(format!("conv2d: groups must be >= 1, got {groups}",)).bt(),
5656 );
5657 }
5658 let x_shape = self.inner.shape();
5659 let x_dims = x_shape.dims();
5660 let w_shape = weight.inner.shape();
5661 let w_dims = w_shape.dims();
5662 if x_dims.len() != 4 {
5663 return Err(fuel_ir::Error::Msg(format!(
5664 "conv2d: x must be rank 4 [N, Cin, H, W], got {x_dims:?}",
5665 ))
5666 .bt());
5667 }
5668 if w_dims.len() != 4 {
5669 return Err(fuel_ir::Error::Msg(format!(
5670 "conv2d: weight must be rank 4 [Cout, Cin/groups, Kh, Kw], got {w_dims:?}",
5671 ))
5672 .bt());
5673 }
5674 let (cin, h_in, w_in) = (x_dims[1], x_dims[2], x_dims[3]);
5675 let (cout, cin_per_g, kh, kw) = (w_dims[0], w_dims[1], w_dims[2], w_dims[3]);
5676 if cin != cin_per_g * groups {
5677 return Err(fuel_ir::Error::Msg(format!(
5678 "conv2d: x has {cin} in-channels but weight expects {} ({cin_per_g}*{groups})",
5679 cin_per_g * groups,
5680 ))
5681 .bt());
5682 }
5683 if cout % groups != 0 {
5684 return Err(fuel_ir::Error::Msg(format!(
5685 "conv2d: Cout={cout} must be divisible by groups={groups}",
5686 ))
5687 .bt());
5688 }
5689 if let Some(b) = bias {
5690 let b_shape = b.inner.shape();
5691 let b_dims = b_shape.dims();
5692 if b_dims != [cout] {
5693 return Err(fuel_ir::Error::Msg(format!(
5694 "conv2d: bias shape {b_dims:?} must match [Cout={cout}]",
5695 ))
5696 .bt());
5697 }
5698 }
5699 let (stride_h, stride_w) = stride;
5700 let (pad_h, pad_w) = padding;
5701 if stride_h < 1 || stride_w < 1 {
5702 return Err(fuel_ir::Error::Msg(format!(
5703 "conv2d: stride must be >= 1, got ({stride_h}, {stride_w})",
5704 ))
5705 .bt());
5706 }
5707 let h_padded = h_in + 2 * pad_h;
5708 let w_padded = w_in + 2 * pad_w;
5709 if h_padded < kh || w_padded < kw {
5710 return Err(fuel_ir::Error::Msg(format!(
5711 "conv2d: padded input ({h_padded}x{w_padded}) smaller than kernel ({kh}x{kw})",
5712 ))
5713 .bt());
5714 }
5715 Ok(Self {
5716 inner: self.inner.conv2d(
5717 &weight.inner,
5718 bias.map(|b| &b.inner),
5719 stride,
5720 padding,
5721 groups,
5722 ),
5723 })
5724 }
5725
5726 pub fn flash_attn(
5736 &self,
5737 k: &Self,
5738 v: &Self,
5739 alibi_slopes: Option<&Self>,
5740 softmax_scale: f32,
5741 causal: bool,
5742 window_size_left: Option<usize>,
5743 window_size_right: Option<usize>,
5744 softcap: Option<f32>,
5745 ) -> std::result::Result<Self, fuel_ir::Error> {
5746 let q_shape = self.inner.shape();
5747 let q_dims = q_shape.dims();
5748 let k_shape = k.inner.shape();
5749 let k_dims = k_shape.dims();
5750 let v_shape = v.inner.shape();
5751 let v_dims = v_shape.dims();
5752 if q_dims.len() != 4 {
5753 return Err(fuel_ir::Error::Msg(format!(
5754 "flash_attn: q must be rank 4 [B, Hq, Sq, D], got {q_dims:?}",
5755 ))
5756 .bt());
5757 }
5758 if k_dims.len() != 4 {
5759 return Err(fuel_ir::Error::Msg(format!(
5760 "flash_attn: k must be rank 4 [B, Hkv, Sk, D], got {k_dims:?}",
5761 ))
5762 .bt());
5763 }
5764 if v_dims.len() != 4 {
5765 return Err(fuel_ir::Error::Msg(format!(
5766 "flash_attn: v must be rank 4 [B, Hkv, Sk, D], got {v_dims:?}",
5767 ))
5768 .bt());
5769 }
5770 let (b, hq, _sq, d) = (q_dims[0], q_dims[1], q_dims[2], q_dims[3]);
5771 let (bk, hkv, sk, dk) = (k_dims[0], k_dims[1], k_dims[2], k_dims[3]);
5772 let (bv, hkv_v, sk_v, dv) = (v_dims[0], v_dims[1], v_dims[2], v_dims[3]);
5773 if b != bk || b != bv {
5774 return Err(fuel_ir::Error::Msg(
5775 format!("flash_attn: B mismatch q={b} k={bk} v={bv}",),
5776 )
5777 .bt());
5778 }
5779 if hkv != hkv_v {
5780 return Err(fuel_ir::Error::Msg(format!(
5781 "flash_attn: Hkv mismatch k={hkv} vs v={hkv_v}",
5782 ))
5783 .bt());
5784 }
5785 if sk != sk_v {
5786 return Err(fuel_ir::Error::Msg(
5787 format!("flash_attn: Sk mismatch k={sk} vs v={sk_v}",),
5788 )
5789 .bt());
5790 }
5791 if d != dk || d != dv {
5792 return Err(fuel_ir::Error::Msg(format!(
5793 "flash_attn: head_dim mismatch q={d} k={dk} v={dv}",
5794 ))
5795 .bt());
5796 }
5797 if hkv == 0 || hq % hkv != 0 {
5798 return Err(fuel_ir::Error::Msg(format!(
5799 "flash_attn: Hq={hq} must be a positive multiple of Hkv={hkv}",
5800 ))
5801 .bt());
5802 }
5803 if let Some(a) = alibi_slopes {
5804 let a_shape = a.inner.shape();
5805 let a_dims = a_shape.dims();
5806 if a_dims != [hq] {
5807 return Err(fuel_ir::Error::Msg(format!(
5808 "flash_attn: alibi_slopes must be [Hq={hq}], got {a_dims:?}",
5809 ))
5810 .bt());
5811 }
5812 }
5813 Ok(Self {
5814 inner: self.inner.flash_attn(
5815 &k.inner,
5816 &v.inner,
5817 alibi_slopes.map(|t| &t.inner),
5818 softmax_scale,
5819 causal,
5820 window_size_left,
5821 window_size_right,
5822 softcap,
5823 ),
5824 })
5825 }
5826
5827 pub fn paged_attn(
5837 &self,
5838 k_cache: &Self,
5839 v_cache: &Self,
5840 block_table: &Self,
5841 context_lens: &Self,
5842 alibi_slopes: Option<&Self>,
5843 softmax_scale: f32,
5844 block_size: usize,
5845 softcap: Option<f32>,
5846 ) -> std::result::Result<Self, fuel_ir::Error> {
5847 if block_size < 1 {
5848 return Err(fuel_ir::Error::Msg("paged_attn: block_size must be >= 1".into()).bt());
5849 }
5850 let q_shape = self.inner.shape();
5851 let q_dims = q_shape.dims();
5852 let kc_shape = k_cache.inner.shape();
5853 let kc_dims = kc_shape.dims();
5854 let vc_shape = v_cache.inner.shape();
5855 let vc_dims = vc_shape.dims();
5856 let bt_shape = block_table.inner.shape();
5857 let bt_dims = bt_shape.dims();
5858 let cl_shape = context_lens.inner.shape();
5859 let cl_dims = cl_shape.dims();
5860 if q_dims.len() != 4 {
5861 return Err(fuel_ir::Error::Msg(format!(
5862 "paged_attn: q must be rank 4 [B, Hq, Sq, D], got {q_dims:?}",
5863 ))
5864 .bt());
5865 }
5866 if kc_dims.len() != 4 {
5867 return Err(fuel_ir::Error::Msg(format!(
5868 "paged_attn: k_cache must be rank 4 [num_blocks, block_size, Hkv, D], got {kc_dims:?}",
5869 )).bt());
5870 }
5871 if vc_dims.len() != 4 {
5872 return Err(fuel_ir::Error::Msg(format!(
5873 "paged_attn: v_cache must be rank 4 [num_blocks, block_size, Hkv, D], got {vc_dims:?}",
5874 )).bt());
5875 }
5876 if bt_dims.len() != 2 {
5877 return Err(fuel_ir::Error::Msg(format!(
5878 "paged_attn: block_table must be rank 2 [B, max_blocks], got {bt_dims:?}",
5879 ))
5880 .bt());
5881 }
5882 if cl_dims.len() != 1 {
5883 return Err(fuel_ir::Error::Msg(format!(
5884 "paged_attn: context_lens must be rank 1 [B], got {cl_dims:?}",
5885 ))
5886 .bt());
5887 }
5888 let (b, hq, _sq, d) = (q_dims[0], q_dims[1], q_dims[2], q_dims[3]);
5889 if kc_dims[1] != block_size {
5890 return Err(fuel_ir::Error::Msg(format!(
5891 "paged_attn: k_cache block dim {} != block_size {block_size}",
5892 kc_dims[1],
5893 ))
5894 .bt());
5895 }
5896 if vc_dims[1] != block_size {
5897 return Err(fuel_ir::Error::Msg(format!(
5898 "paged_attn: v_cache block dim {} != block_size {block_size}",
5899 vc_dims[1],
5900 ))
5901 .bt());
5902 }
5903 let hkv = kc_dims[2];
5904 if vc_dims[2] != hkv {
5905 return Err(fuel_ir::Error::Msg(format!(
5906 "paged_attn: Hkv mismatch k_cache={hkv} vs v_cache={}",
5907 vc_dims[2],
5908 ))
5909 .bt());
5910 }
5911 if kc_dims[3] != d || vc_dims[3] != d {
5912 return Err(fuel_ir::Error::Msg(format!(
5913 "paged_attn: D mismatch q={d} k={} v={}",
5914 kc_dims[3], vc_dims[3],
5915 ))
5916 .bt());
5917 }
5918 if hkv == 0 || hq % hkv != 0 {
5919 return Err(fuel_ir::Error::Msg(format!(
5920 "paged_attn: Hq={hq} must be a positive multiple of Hkv={hkv}",
5921 ))
5922 .bt());
5923 }
5924 if bt_dims[0] != b {
5925 return Err(fuel_ir::Error::Msg(format!(
5926 "paged_attn: block_table batch dim {} != B={b}",
5927 bt_dims[0],
5928 ))
5929 .bt());
5930 }
5931 if cl_dims[0] != b {
5932 return Err(fuel_ir::Error::Msg(format!(
5933 "paged_attn: context_lens len {} != B={b}",
5934 cl_dims[0],
5935 ))
5936 .bt());
5937 }
5938 if block_table.inner.dtype() != fuel_ir::DType::U32 {
5939 return Err(fuel_ir::Error::Msg(format!(
5940 "paged_attn: block_table must be U32, got {:?}",
5941 block_table.inner.dtype(),
5942 ))
5943 .bt());
5944 }
5945 if context_lens.inner.dtype() != fuel_ir::DType::U32 {
5946 return Err(fuel_ir::Error::Msg(format!(
5947 "paged_attn: context_lens must be U32, got {:?}",
5948 context_lens.inner.dtype(),
5949 ))
5950 .bt());
5951 }
5952 if let Some(a) = alibi_slopes {
5953 let a_shape = a.inner.shape();
5954 let a_dims = a_shape.dims();
5955 if a_dims != [hq] {
5956 return Err(fuel_ir::Error::Msg(format!(
5957 "paged_attn: alibi_slopes must be [Hq={hq}], got {a_dims:?}",
5958 ))
5959 .bt());
5960 }
5961 }
5962 Ok(Self {
5963 inner: self.inner.paged_attn(
5964 &k_cache.inner,
5965 &v_cache.inner,
5966 &block_table.inner,
5967 &context_lens.inner,
5968 alibi_slopes.map(|t| &t.inner),
5969 softmax_scale,
5970 block_size,
5971 softcap,
5972 ),
5973 })
5974 }
5975
5976 pub fn conv_transpose2d(
5986 &self,
5987 weight: &Self,
5988 stride: (usize, usize),
5989 padding: (usize, usize),
5990 output_padding: (usize, usize),
5991 dilation: (usize, usize),
5992 groups: usize,
5993 ) -> std::result::Result<Self, fuel_ir::Error> {
5994 if groups < 1 {
5995 return Err(fuel_ir::Error::Msg(format!(
5996 "conv_transpose2d: groups must be >= 1, got {groups}",
5997 ))
5998 .bt());
5999 }
6000 let x_shape = self.inner.shape();
6001 let x_dims = x_shape.dims();
6002 let w_shape = weight.inner.shape();
6003 let w_dims = w_shape.dims();
6004 if x_dims.len() != 4 {
6005 return Err(fuel_ir::Error::Msg(format!(
6006 "conv_transpose2d: x must be rank 4 [N, Cin, H, W], got {x_dims:?}",
6007 ))
6008 .bt());
6009 }
6010 if w_dims.len() != 4 {
6011 return Err(fuel_ir::Error::Msg(format!(
6012 "conv_transpose2d: weight must be rank 4 [Cin, Cout/groups, Kh, Kw], got {w_dims:?}",
6013 )).bt());
6014 }
6015 let (cin, h_in, w_in) = (x_dims[1], x_dims[2], x_dims[3]);
6016 let (cin_w, cout_per_g, kh, kw) = (w_dims[0], w_dims[1], w_dims[2], w_dims[3]);
6017 if cin != cin_w {
6018 return Err(fuel_ir::Error::Msg(format!(
6019 "conv_transpose2d: x has {cin} in-channels but weight has {cin_w}",
6020 ))
6021 .bt());
6022 }
6023 if cin % groups != 0 {
6024 return Err(fuel_ir::Error::Msg(format!(
6025 "conv_transpose2d: Cin={cin} must be divisible by groups={groups}",
6026 ))
6027 .bt());
6028 }
6029 let (stride_h, stride_w) = stride;
6030 let (pad_h, pad_w) = padding;
6031 let (out_pad_h, out_pad_w) = output_padding;
6032 let (dil_h, dil_w) = dilation;
6033 if stride_h < 1 || stride_w < 1 {
6034 return Err(fuel_ir::Error::Msg(format!(
6035 "conv_transpose2d: stride must be >= 1, got ({stride_h}, {stride_w})",
6036 ))
6037 .bt());
6038 }
6039 if dil_h < 1 || dil_w < 1 {
6040 return Err(fuel_ir::Error::Msg(format!(
6041 "conv_transpose2d: dilation must be >= 1, got ({dil_h}, {dil_w})",
6042 ))
6043 .bt());
6044 }
6045 let h_out = h_in.saturating_sub(1) * stride_h + dil_h * (kh - 1) + out_pad_h + 1;
6046 let w_out = w_in.saturating_sub(1) * stride_w + dil_w * (kw - 1) + out_pad_w + 1;
6047 if h_out <= 2 * pad_h || w_out <= 2 * pad_w {
6048 return Err(fuel_ir::Error::Msg(format!(
6049 "conv_transpose2d: padding ({pad_h}x{pad_w}) is larger than the produced output dims ({h_out}x{w_out})",
6050 )).bt());
6051 }
6052 let _ = cout_per_g;
6053 Ok(Self {
6054 inner: self.inner.conv_transpose2d(
6055 &weight.inner,
6056 stride,
6057 padding,
6058 output_padding,
6059 dilation,
6060 groups,
6061 ),
6062 })
6063 }
6064
6065 pub fn conv_transpose1d(
6079 &self,
6080 weight: &Self,
6081 stride: usize,
6082 padding: usize,
6083 output_padding: usize,
6084 dilation: usize,
6085 groups: usize,
6086 ) -> std::result::Result<Self, fuel_ir::Error> {
6087 if groups < 1 {
6088 return Err(fuel_ir::Error::Msg(format!(
6089 "conv_transpose1d: groups must be >= 1, got {groups}",
6090 ))
6091 .bt());
6092 }
6093 let x_shape = self.inner.shape();
6094 let x_dims = x_shape.dims();
6095 let w_shape = weight.inner.shape();
6096 let w_dims = w_shape.dims();
6097 if x_dims.len() != 3 {
6098 return Err(fuel_ir::Error::Msg(format!(
6099 "conv_transpose1d: x must be rank 3 [N, Cin, Lin], got {x_dims:?}",
6100 ))
6101 .bt());
6102 }
6103 if w_dims.len() != 3 {
6104 return Err(fuel_ir::Error::Msg(format!(
6105 "conv_transpose1d: weight must be rank 3 [Cin, Cout/groups, K], got {w_dims:?}",
6106 ))
6107 .bt());
6108 }
6109 if stride < 1 {
6110 return Err(fuel_ir::Error::Msg(format!(
6111 "conv_transpose1d: stride must be >= 1, got {stride}",
6112 ))
6113 .bt());
6114 }
6115 if dilation < 1 {
6116 return Err(fuel_ir::Error::Msg(format!(
6117 "conv_transpose1d: dilation must be >= 1, got {dilation}",
6118 ))
6119 .bt());
6120 }
6121 let cin = x_dims[1];
6122 let cin_w = w_dims[0];
6123 if cin != cin_w {
6124 return Err(fuel_ir::Error::Msg(format!(
6125 "conv_transpose1d: x has {cin} in-channels but weight has {cin_w}",
6126 ))
6127 .bt());
6128 }
6129 if !cin.is_multiple_of(groups) {
6130 return Err(fuel_ir::Error::Msg(format!(
6131 "conv_transpose1d: Cin={cin} must be divisible by groups={groups}",
6132 ))
6133 .bt());
6134 }
6135 Ok(Self {
6136 inner: self.inner.conv_transpose1d(
6137 &weight.inner,
6138 stride,
6139 padding,
6140 output_padding,
6141 dilation,
6142 groups,
6143 ),
6144 })
6145 }
6146}
6147
6148impl Tensor {
6157 pub fn unsqueeze<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6163 let shape = self.inner.shape();
6164 let dim = dim.to_index_plus_one(&shape, "unsqueeze")?;
6165 Ok(Self {
6166 inner: self.inner.try_unsqueeze(dim)?,
6167 })
6168 }
6169
6170 pub fn triu(&self, diagonal: i64) -> std::result::Result<Self, fuel_ir::Error> {
6175 Ok(Self {
6176 inner: self.inner.triu(diagonal)?,
6177 })
6178 }
6179
6180 pub fn tril(&self, diagonal: i64) -> std::result::Result<Self, fuel_ir::Error> {
6183 Ok(Self {
6184 inner: self.inner.tril(diagonal)?,
6185 })
6186 }
6187
6188 pub fn log_softmax_last_dim(&self) -> std::result::Result<Self, fuel_ir::Error> {
6192 Ok(Self {
6193 inner: self.inner.log_softmax_last_dim()?,
6194 })
6195 }
6196
6197 pub fn softmax<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6206 let shape = self.inner.shape();
6207 let axis: usize = dim.to_index(&shape, "softmax")?;
6211 let m = self.max_keepdim(axis)?;
6212 let shifted = self.broadcast_sub(&m)?;
6213 let e = shifted.exp();
6214 let s = e.sum_keepdim(axis)?;
6215 e.broadcast_div(&s)
6216 }
6217
6218 pub fn log_softmax<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6228 let shape = self.inner.shape();
6229 let axis: usize = dim.to_index(&shape, "log_softmax")?;
6230 let m = self.max_keepdim(axis)?;
6231 let shifted = self.broadcast_sub(&m)?;
6232 let lse = shifted.exp().sum_keepdim(axis)?.log();
6233 shifted.broadcast_sub(&lse)
6234 }
6235
6236 pub fn argmin_dim<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6240 let shape = self.inner.shape();
6241 let dim = dim.to_index(&shape, "argmin_dim")?;
6242 Ok(Self {
6243 inner: self.inner.argmin_dim(dim),
6244 })
6245 }
6246
6247 pub fn masked_fill(
6253 &self,
6254 mask: &Self,
6255 value: fuel_ir::Scalar,
6256 ) -> std::result::Result<Self, fuel_ir::Error> {
6257 Ok(Self {
6258 inner: self.inner.masked_fill(&mask.inner, value)?,
6259 })
6260 }
6261
6262 pub fn index_add<D: Dim>(
6268 &self,
6269 dim: D,
6270 indices: &Self,
6271 src: &Self,
6272 ) -> std::result::Result<Self, fuel_ir::Error> {
6273 let shape = self.inner.shape();
6274 let dim = dim.to_index(&shape, "index_add")?;
6275 if indices.inner.dtype() != fuel_ir::DType::U32 {
6276 return Err(fuel_ir::Error::Msg(format!(
6277 "index_add: index must be U32, got {:?}",
6278 indices.inner.dtype(),
6279 ))
6280 .bt());
6281 }
6282 if self.inner.dtype() != src.inner.dtype() {
6283 return Err(fuel_ir::Error::Msg(format!(
6284 "index_add: base and src dtypes must match, got {:?} vs {:?}",
6285 self.inner.dtype(),
6286 src.inner.dtype(),
6287 ))
6288 .bt());
6289 }
6290 let base_dims = shape.dims();
6291 let src_shape = src.inner.shape();
6292 let src_dims = src_shape.dims();
6293 if base_dims.len() != src_dims.len() {
6294 return Err(fuel_ir::Error::Msg(format!(
6295 "index_add: base and src must have the same rank, got {} vs {}",
6296 base_dims.len(),
6297 src_dims.len(),
6298 ))
6299 .bt());
6300 }
6301 let idx_shape = indices.inner.shape();
6302 let idx_dims = idx_shape.dims();
6303 if idx_dims.len() != 1 {
6304 return Err(fuel_ir::Error::Msg(format!(
6305 "index_add: index must be rank 1, got {idx_dims:?}",
6306 ))
6307 .bt());
6308 }
6309 if src_dims[dim] != idx_dims[0] {
6310 return Err(fuel_ir::Error::Msg(format!(
6311 "index_add: src dim {dim} ({}) must match index length ({})",
6312 src_dims[dim], idx_dims[0],
6313 ))
6314 .bt());
6315 }
6316 Ok(Self {
6317 inner: self.inner.index_add(dim, &indices.inner, &src.inner),
6318 })
6319 }
6320
6321 pub fn scatter_add<D: Dim>(
6326 &self,
6327 dim: D,
6328 indices: &Self,
6329 src: &Self,
6330 ) -> std::result::Result<Self, fuel_ir::Error> {
6331 let shape = self.inner.shape();
6332 let dim = dim.to_index(&shape, "scatter_add")?;
6333 if indices.inner.dtype() != fuel_ir::DType::U32 {
6334 return Err(fuel_ir::Error::Msg(format!(
6335 "scatter_add: index must be U32, got {:?}",
6336 indices.inner.dtype(),
6337 ))
6338 .bt());
6339 }
6340 if self.inner.dtype() != src.inner.dtype() {
6341 return Err(fuel_ir::Error::Msg(format!(
6342 "scatter_add: base and src dtypes must match, got {:?} vs {:?}",
6343 self.inner.dtype(),
6344 src.inner.dtype(),
6345 ))
6346 .bt());
6347 }
6348 let idx_shape = indices.inner.shape();
6349 let src_shape = src.inner.shape();
6350 if idx_shape.dims() != src_shape.dims() {
6351 return Err(fuel_ir::Error::Msg(format!(
6352 "scatter_add: index and src must have the same shape, got {:?} vs {:?}",
6353 idx_shape.dims(),
6354 src_shape.dims(),
6355 ))
6356 .bt());
6357 }
6358 Ok(Self {
6359 inner: self.inner.scatter_add(dim, &indices.inner, &src.inner),
6360 })
6361 }
6362
6363 pub fn relu_inplace(&self) -> Self {
6373 Self {
6374 inner: self.inner.relu_inplace(),
6375 }
6376 }
6377
6378 pub fn silu_inplace(&self) -> Self {
6381 Self {
6382 inner: self.inner.silu_inplace(),
6383 }
6384 }
6385
6386 pub fn gelu_tanh_inplace(&self) -> Self {
6389 Self {
6390 inner: self.inner.gelu_tanh_inplace(),
6391 }
6392 }
6393
6394 pub fn tanh_inplace(&self) -> Self {
6397 Self {
6398 inner: self.inner.tanh_inplace(),
6399 }
6400 }
6401
6402 pub fn sigmoid_inplace(&self) -> Self {
6405 Self {
6406 inner: self.inner.sigmoid_inplace(),
6407 }
6408 }
6409
6410 pub fn affine_inplace(&self, mul: f64, add: f64) -> Self {
6413 Self {
6414 inner: self.inner.affine_inplace(mul, add),
6415 }
6416 }
6417
6418 pub fn const_f64_like(
6422 &self,
6423 data: impl Into<Arc<[f64]>>,
6424 shape: impl Into<Shape>,
6425 ) -> std::result::Result<Self, fuel_ir::Error> {
6426 Ok(Self {
6427 inner: self.inner.const_f64_like(data, shape)?,
6428 })
6429 }
6430
6431 pub fn const_i64_like(
6435 &self,
6436 data: impl Into<Arc<[i64]>>,
6437 shape: impl Into<Shape>,
6438 ) -> std::result::Result<Self, fuel_ir::Error> {
6439 Ok(Self {
6440 inner: self.inner.const_i64_like(data, shape)?,
6441 })
6442 }
6443
6444 pub fn on_device(self, device: &Device) -> Self {
6450 Self {
6451 inner: self.inner.on_device(device.location()),
6452 }
6453 }
6454
6455 pub fn release(&self) -> Self {
6459 Self {
6460 inner: self.inner.release(),
6461 }
6462 }
6463
6464 pub fn move_to_device(&self, device: &Device) -> Self {
6467 Self {
6468 inner: self.inner.move_to_device(device.location()),
6469 }
6470 }
6471
6472 pub fn copy_to_device(&self, device: &Device) -> Self {
6475 Self {
6476 inner: self.inner.copy_to_device(device.location()),
6477 }
6478 }
6479
6480 pub fn backward(&self) -> fuel_graph::GradMap {
6487 self.inner.backward()
6488 }
6489}
6490
6491impl Tensor {
6499 pub fn transpose_last_two(&self) -> std::result::Result<Self, fuel_ir::Error> {
6504 self.transpose()
6505 }
6506
6507 pub fn t(&self) -> std::result::Result<Self, fuel_ir::Error> {
6510 self.transpose()
6511 }
6512
6513 pub fn transpose_dims<D1: Dim, D2: Dim>(
6518 &self,
6519 dim1: D1,
6520 dim2: D2,
6521 ) -> std::result::Result<Self, fuel_ir::Error> {
6522 let shape = self.shape();
6523 let dim1 = dim1.to_index(&shape, "transpose_dims")?;
6524 let dim2 = dim2.to_index(&shape, "transpose_dims")?;
6525 if dim1 == dim2 {
6526 return Ok(self.clone());
6527 }
6528 let rank = shape.dims().len();
6529 let mut axes: Vec<usize> = (0..rank).collect();
6530 axes.swap(dim1, dim2);
6531 self.permute(axes.as_slice())
6532 }
6533
6534 pub fn flatten<D1: Dim, D2: Dim>(
6539 &self,
6540 start_dim: D1,
6541 end_dim: D2,
6542 ) -> std::result::Result<Self, fuel_ir::Error> {
6543 let shape = self.shape();
6544 let rank = shape.dims().len();
6545 if rank == 0 {
6546 return Ok(self.clone());
6547 }
6548 let start_dim = start_dim.to_index(&shape, "flatten")?;
6549 let end_dim = end_dim.to_index(&shape, "flatten")?;
6550 if start_dim > end_dim {
6551 return Err(fuel_ir::Error::Msg(format!(
6552 "flatten: start_dim={start_dim} > end_dim={end_dim}",
6553 ))
6554 .bt());
6555 }
6556 let dims = shape.dims();
6557 let merged: usize = dims[start_dim..=end_dim].iter().product();
6558 let mut new_dims: Vec<usize> = Vec::with_capacity(rank - (end_dim - start_dim));
6559 new_dims.extend_from_slice(&dims[..start_dim]);
6560 new_dims.push(merged);
6561 new_dims.extend_from_slice(&dims[end_dim + 1..]);
6562 self.reshape(new_dims)
6563 }
6564
6565 pub fn flatten_to<D: Dim>(&self, end_dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6567 self.flatten(0_usize, end_dim)
6568 }
6569
6570 pub fn flatten_from<D: Dim>(&self, start_dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6572 let rank = self.shape().dims().len();
6573 if rank == 0 {
6574 return Ok(self.clone());
6575 }
6576 self.flatten(start_dim, rank - 1)
6577 }
6578
6579 pub fn flatten_all(&self) -> std::result::Result<Self, fuel_ir::Error> {
6581 let rank = self.shape().dims().len();
6582 if rank == 0 {
6583 return Ok(self.clone());
6584 }
6585 self.flatten(0, rank - 1)
6586 }
6587
6588 pub fn stack<D: Dim>(args: &[&Self], dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6593 if args.is_empty() {
6594 return Err(fuel_ir::Error::Msg("stack: requires at least one tensor".into()).bt());
6595 }
6596 let reference_shape = args[0].shape();
6597 let reference_dims = reference_shape.dims().to_vec();
6598 let dim = dim.to_index_plus_one(&reference_shape, "stack")?;
6599 for (idx, t) in args.iter().enumerate().skip(1) {
6600 if t.shape().dims() != reference_dims.as_slice() {
6601 return Err(fuel_ir::Error::Msg(format!(
6602 "stack: tensor {idx} shape {:?} != reference shape {:?}",
6603 t.shape().dims(),
6604 reference_dims,
6605 ))
6606 .bt());
6607 }
6608 }
6609 let mut iter = args.iter();
6611 let first = iter.next().unwrap().unsqueeze(dim)?;
6612 let mut acc = first;
6613 for t in iter {
6614 let u = t.unsqueeze(dim)?;
6615 acc = acc.concat(&u, dim)?;
6616 }
6617 Ok(acc)
6618 }
6619
6620 pub fn sum_keepdim<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6630 let shape = self.shape();
6631 let dim = dim.to_index(&shape, "sum_keepdim")?;
6632 self.sum_dim(dim).unwrap().unsqueeze(dim)
6633 }
6634
6635 pub fn mean_keepdim<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6637 let shape = self.shape();
6638 let dim = dim.to_index(&shape, "mean_keepdim")?;
6639 self.mean_dim(dim).unwrap().unsqueeze(dim)
6640 }
6641
6642 pub fn max_keepdim<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6644 let shape = self.shape();
6645 let dim = dim.to_index(&shape, "max_keepdim")?;
6646 self.max_dim(dim).unwrap().unsqueeze(dim)
6647 }
6648
6649 pub fn min_keepdim<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6651 let shape = self.shape();
6652 let dim = dim.to_index(&shape, "min_keepdim")?;
6653 self.min_dim(dim).unwrap().unsqueeze(dim)
6657 }
6658
6659 pub fn var_keepdim<D: Dim>(
6677 &self,
6678 dim: D,
6679 correction: f64,
6680 ) -> std::result::Result<Self, fuel_ir::Error> {
6681 if correction.is_nan() {
6684 return Err(fuel_ir::Error::Msg(
6685 "var_keepdim: correction must not be NaN".to_string(),
6686 ));
6687 }
6688 let shape = self.shape();
6689 let dim = dim.to_index(&shape, "var_keepdim")?;
6690 let dims = shape.dims();
6691 let n = dims[dim];
6692 let mean = self.mean_keepdim(dim)?;
6693 let deviation = self.broadcast_sub(&mean).unwrap();
6694 let squares = deviation.sqr();
6695 let summed = squares.sum_keepdim(dim)?;
6697 let divisor = (n as f64 - correction).max(0.0);
6698 Ok(summed.mul_scalar(1.0 / divisor))
6699 }
6700
6701 pub fn var<D: Dim>(
6704 &self,
6705 dim: D,
6706 correction: f64,
6707 ) -> std::result::Result<Self, fuel_ir::Error> {
6708 let shape = self.shape();
6709 let dim = dim.to_index(&shape, "var")?;
6710 self.var_keepdim(dim, correction)?.squeeze(dim)
6711 }
6712
6713 pub fn affine(&self, mul: f64, add: f64) -> Self {
6720 self.mul_scalar(mul).add_scalar(add)
6721 }
6722
6723 pub fn scale_and_shift(&self, scale: f64, shift: f64) -> Self {
6727 self.affine(scale, shift)
6728 }
6729
6730 pub fn elu(&self, alpha: f64) -> Self {
6734 let neg_branch = self.exp().affine(alpha, -alpha);
6736 let zero = self
6741 .const_f32_like(vec![0.0; self.elem_count()], self.shape())
6742 .expect("elu: vec![_; self.elem_count()] against self.shape() -- same source");
6743 let mask = self.gt(&zero).unwrap();
6744 mask.where_cond(self, &neg_branch).unwrap()
6745 }
6746
6747 pub fn dot(&self, rhs: &Self) -> std::result::Result<Self, fuel_ir::Error> {
6750 let a = self.shape().dims().to_vec();
6751 let b = rhs.shape().dims().to_vec();
6752 if a.len() != 1 || b.len() != 1 {
6753 return Err(fuel_ir::Error::Msg(format!(
6754 "dot: requires rank-1 inputs, got lhs={a:?} rhs={b:?}",
6755 ))
6756 .bt());
6757 }
6758 if a[0] != b[0] {
6759 return Err(fuel_ir::Error::Msg(format!(
6760 "dot: length mismatch lhs={} rhs={}",
6761 a[0], b[0],
6762 ))
6763 .bt());
6764 }
6765 Ok(self.mul(rhs).unwrap().sum_all())
6766 }
6767
6768 pub fn mv(&self, rhs: &Self) -> std::result::Result<Self, fuel_ir::Error> {
6772 let a = self.shape().dims().to_vec();
6773 let b = rhs.shape().dims().to_vec();
6774 if a.len() != 2 || b.len() != 1 || a[1] != b[0] {
6775 return Err(fuel_ir::Error::Msg(format!(
6776 "mv: shape mismatch lhs={a:?} rhs={b:?} (need [m,n] · [n])",
6777 ))
6778 .bt());
6779 }
6780 let rhs_col = rhs.unsqueeze(1_usize)?;
6782 let prod = self.matmul(&rhs_col).unwrap();
6783 prod.squeeze(1_usize)
6784 }
6785
6786 pub fn matvec(&self, rhs: &Self) -> std::result::Result<Self, fuel_ir::Error> {
6789 self.mv(rhs)
6790 }
6791
6792 pub fn broadcast_matmul(&self, rhs: &Self) -> std::result::Result<Self, fuel_ir::Error> {
6796 self.matmul(rhs)
6797 }
6798
6799 pub fn ones_like(&self) -> std::result::Result<Self, fuel_ir::Error> {
6809 let n = self.elem_count();
6810 let shape = self.shape();
6811 match self.dtype() {
6812 DType::F32 => self.const_f32_like(vec![1.0_f32; n], shape),
6813 DType::F64 => self.const_f64_like(vec![1.0_f64; n], shape),
6814 DType::BF16 => self.const_bf16_like(vec![half::bf16::ONE; n], shape),
6815 DType::F16 => self.const_f16_like(vec![half::f16::ONE; n], shape),
6816 DType::U32 => self.const_u32_like(vec![1_u32; n], shape),
6817 DType::I64 => self.const_i64_like(vec![1_i64; n], shape),
6818 other => {
6819 Err(fuel_ir::Error::Msg(format!("ones_like: unsupported dtype {other:?}",)).bt())
6820 }
6821 }
6822 }
6823
6824 pub fn zeros_like(&self) -> std::result::Result<Self, fuel_ir::Error> {
6828 let n = self.elem_count();
6829 let shape = self.shape();
6830 match self.dtype() {
6831 DType::F32 => self.const_f32_like(vec![0.0_f32; n], shape),
6832 DType::F64 => self.const_f64_like(vec![0.0_f64; n], shape),
6833 DType::BF16 => self.const_bf16_like(vec![half::bf16::ZERO; n], shape),
6834 DType::F16 => self.const_f16_like(vec![half::f16::ZERO; n], shape),
6835 DType::U32 => self.const_u32_like(vec![0_u32; n], shape),
6836 DType::I64 => self.const_i64_like(vec![0_i64; n], shape),
6837 other => {
6838 Err(fuel_ir::Error::Msg(format!("zeros_like: unsupported dtype {other:?}",)).bt())
6839 }
6840 }
6841 }
6842
6843 pub fn ones(
6847 shape: impl Into<Shape>,
6848 dtype: DType,
6849 device: &Device,
6850 ) -> std::result::Result<Self, fuel_ir::Error> {
6851 let shape = shape.into();
6852 let n = shape.elem_count();
6853 match dtype {
6854 DType::F32 => Self::from_f32(vec![1.0_f32; n], shape, device),
6855 DType::F64 => Self::from_f64(vec![1.0_f64; n], shape, device),
6856 DType::BF16 => Self::from_bf16(vec![half::bf16::ONE; n], shape, device),
6857 DType::F16 => Self::from_f16(vec![half::f16::ONE; n], shape, device),
6858 DType::U32 => Self::from_u32(vec![1_u32; n], shape, device),
6859 other => Err(fuel_ir::Error::Msg(format!("ones: unsupported dtype {other:?}",)).bt()),
6860 }
6861 }
6862
6863 pub fn zeros(
6873 shape: impl Into<Shape>,
6874 dtype: DType,
6875 device: &Device,
6876 ) -> std::result::Result<Self, fuel_ir::Error> {
6877 let shape = shape.into();
6878 let n = shape.elem_count();
6879 match dtype {
6880 DType::F32 => Self::from_f32(vec![0.0_f32; n], shape, device),
6881 DType::F64 => Self::from_f64(vec![0.0_f64; n], shape, device),
6882 DType::BF16 => Self::from_bf16(vec![half::bf16::ZERO; n], shape, device),
6883 DType::F16 => Self::from_f16(vec![half::f16::ZERO; n], shape, device),
6884 DType::U32 => Self::from_u32(vec![0_u32; n], shape, device),
6885 other => Err(fuel_ir::Error::Msg(format!("zeros: unsupported dtype {other:?}",)).bt()),
6886 }
6887 }
6888
6889 pub fn full(
6898 shape: impl Into<Shape>,
6899 value: fuel_ir::Scalar,
6900 device: &Device,
6901 ) -> std::result::Result<Self, fuel_ir::Error> {
6902 let shape = shape.into();
6903 let n = shape.elem_count();
6904 match value {
6905 fuel_ir::Scalar::F32(v) => Self::from_f32(vec![v; n], shape, device),
6906 fuel_ir::Scalar::F64(v) => Self::from_f64(vec![v; n], shape, device),
6907 fuel_ir::Scalar::BF16(v) => Self::from_bf16(vec![v; n], shape, device),
6908 fuel_ir::Scalar::F16(v) => Self::from_f16(vec![v; n], shape, device),
6909 fuel_ir::Scalar::U32(v) => Self::from_u32(vec![v; n], shape, device),
6910 other => Err(fuel_ir::Error::Msg(format!(
6911 "full: unsupported scalar dtype {:?}",
6912 other.dtype(),
6913 ))
6914 .bt()),
6915 }
6916 }
6917
6918 pub fn eye(n: usize, dtype: DType, device: &Device) -> Self {
6921 let mut data = vec![0.0_f32; n * n];
6922 for i in 0..n {
6923 data[i * n + i] = 1.0;
6924 }
6925 let base = Self::from_f32(data, vec![n, n], device).expect(
6934 "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",
6935 );
6936 if dtype == DType::F32 {
6937 base
6938 } else {
6939 base.to_dtype(dtype).unwrap()
6940 }
6941 }
6942
6943 pub fn split_heads(
6949 &self,
6950 num_heads: usize,
6951 head_dim: usize,
6952 ) -> std::result::Result<Self, fuel_ir::Error> {
6953 let dims = self.inner.shape().dims().to_vec();
6954 debug_assert_eq!(
6955 dims.len(),
6956 3,
6957 "split_heads: input must be rank 3 (B, N, embed), got {dims:?}"
6958 );
6959 debug_assert_eq!(
6960 dims[2],
6961 num_heads * head_dim,
6962 "split_heads: trailing dim ({}) != num_heads * head_dim ({} * {} = {})",
6963 dims[2],
6964 num_heads,
6965 head_dim,
6966 num_heads * head_dim
6967 );
6968 let b = dims[0];
6969 let n = dims[1];
6970 self.reshape(Shape::from_dims(&[b, n, num_heads, head_dim]))?
6971 .permute([0, 2, 1, 3_usize])
6972 }
6973
6974 pub fn merge_heads(&self) -> std::result::Result<Self, fuel_ir::Error> {
6978 let dims = self.inner.shape().dims().to_vec();
6979 debug_assert_eq!(
6980 dims.len(),
6981 4,
6982 "merge_heads: input must be rank 4 (B, heads, N, head_dim), got {dims:?}"
6983 );
6984 let b = dims[0];
6985 let num_heads = dims[1];
6986 let n = dims[2];
6987 let head_dim = dims[3];
6988 self.permute([0, 2, 1, 3_usize])?
6989 .reshape(Shape::from_dims(&[b, n, num_heads * head_dim]))
6990 }
6991
6992 pub fn add_trailing_bias(
7003 &self,
7004 bias: std::sync::Arc<[f32]>,
7005 ) -> std::result::Result<Self, fuel_ir::Error> {
7006 let n = bias.len();
7007 let bias_t = self.const_like_dtype(&bias, Shape::from_dims(&[n]), self.dtype())?;
7013 self.broadcast_add(&bias_t)
7014 }
7015
7016 pub fn embed_tokens(
7028 embed_table: std::sync::Arc<[f32]>,
7029 vocab_size: usize,
7030 hidden: usize,
7031 tokens: &[u32],
7032 device: &crate::Device,
7033 ) -> std::result::Result<Self, fuel_ir::Error> {
7034 let seq = tokens.len();
7035 if seq == 0 {
7036 return Err(fuel_ir::Error::Msg("embed_tokens: tokens must be non-empty".into()).bt());
7037 }
7038 let embed = Self::from_f32(embed_table, Shape::from_dims(&[vocab_size, hidden]), device)?;
7039 let token_ids = embed.const_u32_like(tokens.to_vec(), Shape::from_dims(&[seq]))?;
7040 embed
7041 .index_select(0_usize, &token_ids)?
7042 .reshape(Shape::from_dims(&[1, seq, hidden]))
7043 }
7044
7045 pub fn embed_tokens_anchored(
7053 &self,
7054 embed_table: std::sync::Arc<[f32]>,
7055 vocab_size: usize,
7056 hidden: usize,
7057 tokens: &[u32],
7058 ) -> std::result::Result<Self, fuel_ir::Error> {
7059 let seq = tokens.len();
7060 if seq == 0 {
7061 return Err(fuel_ir::Error::Msg(
7062 "embed_tokens_anchored: tokens must be non-empty".into(),
7063 )
7064 .bt());
7065 }
7066 let embed = self.const_f32_like(embed_table, Shape::from_dims(&[vocab_size, hidden]))?;
7067 let token_ids = self.const_u32_like(tokens.to_vec(), Shape::from_dims(&[seq]))?;
7068 embed
7069 .index_select(0_usize, &token_ids)?
7070 .reshape(Shape::from_dims(&[1, seq, hidden]))
7071 }
7072
7073 pub fn rope_tables_const(
7084 &self,
7085 theta: f64,
7086 start_pos: usize,
7087 seq: usize,
7088 head_dim: usize,
7089 ) -> (Self, Self) {
7090 let (cos_data, sin_data) = fuel_graph::build_rope_tables(theta, start_pos, seq, head_dim);
7091 let rope_shape = Shape::from_dims(&[seq, head_dim]);
7092 let rope_cos = self
7098 .const_f32_like(cos_data, rope_shape.clone())
7099 .expect("rope tables: build_rope_tables must return seq*head_dim elements");
7100 let rope_sin = self
7101 .const_f32_like(sin_data, rope_shape)
7102 .expect("rope tables: build_rope_tables must return seq*head_dim elements");
7103 (rope_cos, rope_sin)
7104 }
7105
7106 pub fn rope_delta_tables_const(
7118 &self,
7119 theta: f64,
7120 delta: usize,
7121 rows: usize,
7122 head_dim: usize,
7123 ) -> (Self, Self) {
7124 let (c1, s1) = fuel_graph::build_rope_tables(theta, delta, 1, head_dim);
7125 let mut cos = Vec::with_capacity(rows * head_dim);
7126 let mut sin = Vec::with_capacity(rows * head_dim);
7127 for _ in 0..rows {
7128 cos.extend_from_slice(&c1);
7129 sin.extend_from_slice(&s1);
7130 }
7131 let shape = Shape::from_dims(&[rows, head_dim]);
7132 (
7136 self.const_f32_like(cos, shape.clone()).expect(
7137 "rope tables: rows appends of c1 (local); c1 has head_dim elements (not local)",
7138 ),
7139 self.const_f32_like(sin, shape).expect(
7140 "rope tables: rows appends of s1 (local); s1 has head_dim elements (not local)",
7141 ),
7142 )
7143 }
7144
7145 pub fn rope_delta_rotate_block_f32(
7160 dev: &crate::Device,
7161 k_block: &[f32],
7162 theta: f64,
7163 delta: usize,
7164 block_size: usize,
7165 n_kv_heads: usize,
7166 head_dim: usize,
7167 ) -> Vec<f32> {
7168 let pool_shape = Shape::from_dims(&[block_size, n_kv_heads, head_dim]);
7169 let k = Tensor::from_f32(k_block.to_vec(), pool_shape, dev).expect(
7180 "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)",
7181 );
7182 let k4 = k
7183 .permute([1, 0, 2])
7184 .expect("rope_delta_rotate_block_f32: permute [bs,Hkv,D]->[Hkv,bs,D]")
7185 .reshape(Shape::from_dims(&[1, n_kv_heads, block_size, head_dim]))
7186 .expect("rope_delta_rotate_block_f32: reshape to [1,Hkv,bs,D]");
7187 let (cos, sin) = k4.rope_delta_tables_const(theta, delta, block_size, head_dim);
7188 k4.rope_with_tables_decomposed(&cos, &sin)
7189 .expect("rope_delta_rotate_block_f32: rope_with_tables_decomposed")
7190 .reshape(Shape::from_dims(&[n_kv_heads, block_size, head_dim]))
7191 .expect("rope_delta_rotate_block_f32: reshape back to [Hkv,bs,D]")
7192 .permute([1, 0, 2])
7193 .expect("rope_delta_rotate_block_f32: permute [Hkv,bs,D]->[bs,Hkv,D]")
7194 .realize_f32()
7195 }
7196
7197 pub fn rope_tables_const_batched(
7210 &self,
7211 theta: f64,
7212 positions: &[usize],
7213 head_dim: usize,
7214 ) -> (Self, Self) {
7215 let b = positions.len();
7216 let mut cos_data = Vec::with_capacity(b * head_dim);
7217 let mut sin_data = Vec::with_capacity(b * head_dim);
7218 for &pos in positions {
7219 let (c, s) = fuel_graph::build_rope_tables(theta, pos, 1, head_dim);
7220 cos_data.extend_from_slice(&c);
7221 sin_data.extend_from_slice(&s);
7222 }
7223 let shape = Shape::from_dims(&[b, 1, 1, head_dim]);
7224 let rope_cos = self
7231 .const_f32_like(cos_data, shape.clone())
7232 .expect("batched rope tables: b IS positions.len() (local); build_rope_tables must yield head_dim per position (not local)");
7233 let rope_sin = self
7234 .const_f32_like(sin_data, shape)
7235 .expect("batched rope tables: b IS positions.len() (local); build_rope_tables must yield head_dim per position (not local)");
7236 (rope_cos, rope_sin)
7237 }
7238
7239 pub fn rope_tables_const_with_inv_freq(
7244 &self,
7245 inv_freq: &[f64],
7246 start_pos: usize,
7247 seq: usize,
7248 head_dim: usize,
7249 ) -> (Self, Self) {
7250 let (cos_data, sin_data) =
7251 fuel_graph::build_rope_tables_with_inv_freq(inv_freq, start_pos, seq, head_dim);
7252 let rope_shape = Shape::from_dims(&[seq, head_dim]);
7253 let rope_cos = self.const_f32_like(cos_data, rope_shape.clone()).expect(
7256 "rope tables: build_rope_tables_with_inv_freq must return seq*head_dim elements",
7257 );
7258 let rope_sin = self.const_f32_like(sin_data, rope_shape).expect(
7259 "rope tables: build_rope_tables_with_inv_freq must return seq*head_dim elements",
7260 );
7261 (rope_cos, rope_sin)
7262 }
7263
7264 pub fn rope_tables_const_batched_with_inv_freq(
7267 &self,
7268 inv_freq: &[f64],
7269 positions: &[usize],
7270 head_dim: usize,
7271 ) -> (Self, Self) {
7272 let b = positions.len();
7273 let mut cos_data = Vec::with_capacity(b * head_dim);
7274 let mut sin_data = Vec::with_capacity(b * head_dim);
7275 for &pos in positions {
7276 let (c, s) = fuel_graph::build_rope_tables_with_inv_freq(inv_freq, pos, 1, head_dim);
7277 cos_data.extend_from_slice(&c);
7278 sin_data.extend_from_slice(&s);
7279 }
7280 let shape = Shape::from_dims(&[b, 1, 1, head_dim]);
7281 let rope_cos = self
7284 .const_f32_like(cos_data, shape.clone())
7285 .expect("batched rope tables: b IS positions.len() (local); build_rope_tables_with_inv_freq must yield head_dim per position (not local)");
7286 let rope_sin = self
7287 .const_f32_like(sin_data, shape)
7288 .expect("batched rope tables: b IS positions.len() (local); build_rope_tables_with_inv_freq must yield head_dim per position (not local)");
7289 (rope_cos, rope_sin)
7290 }
7291
7292 pub fn rope_batched(
7312 &self,
7313 cos: &Self,
7314 sin: &Self,
7315 ) -> std::result::Result<Self, fuel_ir::Error> {
7316 let dims: Vec<usize> = self.inner.shape().dims().to_vec();
7317 let rank = dims.len();
7318 if rank < 2 {
7319 return Err(fuel_ir::Error::Msg(format!(
7320 "rope_batched: expected rank >= 2, got {dims:?}",
7321 ))
7322 .bt());
7323 }
7324 let d = dims[rank - 1];
7325 if !d.is_multiple_of(2) {
7326 return Err(
7327 fuel_ir::Error::Msg(format!("rope_batched: head_dim {d} must be even",)).bt(),
7328 );
7329 }
7330 let half = d / 2;
7331 let target = Shape::from_dims(&dims);
7332
7333 let cos_b = cos.broadcast_to(target.clone())?;
7334 let sin_b = sin.broadcast_to(target)?;
7335
7336 let first = self.slice(rank - 1, 0, half)?;
7337 let second = self.slice(rank - 1, half, half)?;
7338 let rotated = second.neg().concat(&first, rank - 1)?;
7339
7340 let left = self.mul(&cos_b)?;
7341 let right = rotated.mul(&sin_b)?;
7342 left.add(&right)
7343 }
7344
7345 pub fn rope_partial(
7356 &self,
7357 rope_cos: &Self,
7358 rope_sin: &Self,
7359 rope_dim: usize,
7360 ) -> std::result::Result<Self, fuel_ir::Error> {
7361 let dims = self.inner.shape();
7362 let dims = dims.dims();
7363 let head_dim = *dims.last().ok_or_else(|| {
7364 fuel_ir::Error::Msg("rope_partial: receiver must have at least one dimension".into())
7365 .bt()
7366 })?;
7367 if rope_dim == head_dim {
7368 return self.rope_with_tables(rope_cos, rope_sin);
7369 }
7370 if rope_dim > head_dim {
7371 return Err(fuel_ir::Error::Msg(format!(
7372 "rope_partial: rope_dim={rope_dim} exceeds head_dim={head_dim}",
7373 ))
7374 .bt());
7375 }
7376 let last = dims.len() - 1;
7377 let pass_dim = head_dim - rope_dim;
7378 let rot = self.slice(last, 0, rope_dim)?;
7379 let pass = self.slice(last, rope_dim, pass_dim)?;
7380 let rot_rotated = rot.rope_with_tables(rope_cos, rope_sin)?;
7381 rot_rotated.concat(&pass, last)
7382 }
7383
7384 pub fn add_optional_trailing_bias(
7389 &self,
7390 bias: Option<&std::sync::Arc<[f32]>>,
7391 ) -> std::result::Result<Self, fuel_ir::Error> {
7392 match bias {
7393 None => Ok(self.clone()),
7394 Some(b) => self.add_trailing_bias(std::sync::Arc::clone(b)),
7395 }
7396 }
7397
7398 pub fn softcap(&self, cap: f64) -> Self {
7404 self.mul_scalar(1.0 / cap).tanh().mul_scalar(cap)
7405 }
7406
7407 pub fn softcap_optional(&self, cap: Option<f64>) -> Self {
7411 match cap {
7412 Some(c) if c > 0.0 => self.softcap(c),
7413 _ => self.clone(),
7414 }
7415 }
7416
7417 pub fn rms_norm_affine_with_offset(
7426 &self,
7427 gain: &[f32],
7428 offset: f32,
7429 eps: f64,
7430 ) -> std::result::Result<Self, fuel_ir::Error> {
7431 let shifted: std::sync::Arc<[f32]> =
7432 std::sync::Arc::from(gain.iter().map(|g| *g + offset).collect::<Vec<_>>());
7433 self.rms_norm_affine(shifted, eps)
7434 }
7435
7436 pub fn rms_norm_affine(
7441 &self,
7442 gain: std::sync::Arc<[f32]>,
7443 eps: f64,
7444 ) -> std::result::Result<Self, fuel_ir::Error> {
7445 let hidden = gain.len();
7446 let normed = self.rms_norm_last_dim(eps)?;
7447 let gain_t = self.const_f32_like(gain, Shape::from_dims(&[hidden]))?;
7448 normed.broadcast_mul(&gain_t)
7449 }
7450
7451 pub fn global_avg_pool_2d(&self) -> std::result::Result<Self, fuel_ir::Error> {
7461 let dims = self.inner.shape().dims().to_vec();
7462 debug_assert_eq!(
7463 dims.len(),
7464 4,
7465 "global_avg_pool_2d: input must be rank 4 (B, C, H, W), got {dims:?}"
7466 );
7467 self.mean_dim(3_usize)?.mean_dim(2_usize)
7469 }
7470
7471 pub fn channel_affine_4d(
7483 &self,
7484 gain: std::sync::Arc<[f32]>,
7485 bias: std::sync::Arc<[f32]>,
7486 ) -> std::result::Result<Self, fuel_ir::Error> {
7487 let dims = self.inner.shape().dims().to_vec();
7488 debug_assert_eq!(
7489 dims.len(),
7490 4,
7491 "channel_affine_4d: input must be rank 4 (B, C, H, W), got {dims:?}"
7492 );
7493 let channels = dims[1];
7494 debug_assert_eq!(
7495 gain.len(),
7496 channels,
7497 "channel_affine_4d: gain len ({}) != C ({})",
7498 gain.len(),
7499 channels
7500 );
7501 debug_assert_eq!(
7502 bias.len(),
7503 channels,
7504 "channel_affine_4d: bias len ({}) != C ({})",
7505 bias.len(),
7506 channels
7507 );
7508 let w_t = self
7509 .const_f32_like(gain, Shape::from_dims(&[channels]))?
7510 .reshape(Shape::from_dims(&[1, channels, 1, 1]))?;
7511 let b_t = self
7512 .const_f32_like(bias, Shape::from_dims(&[channels]))?
7513 .reshape(Shape::from_dims(&[1, channels, 1, 1]))?;
7514 self.broadcast_mul(&w_t)?.broadcast_add(&b_t)
7515 }
7516
7517 pub fn additive_causal_mask_like(anchor: &Tensor, seq_len: usize) -> Self {
7526 let mut data = vec![0.0_f32; seq_len * seq_len];
7527 for i in 0..seq_len {
7528 for j in (i + 1)..seq_len {
7529 data[i * seq_len + j] = f32::NEG_INFINITY;
7530 }
7531 }
7532 anchor
7536 .const_f32_like(
7537 std::sync::Arc::from(data),
7538 Shape::from_dims(&[seq_len, seq_len]),
7539 )
7540 .expect(
7541 "additive_causal_mask_like: vec![_; seq_len*seq_len] against [seq_len, seq_len]",
7542 )
7543 }
7544
7545 pub fn tril2(n: usize, dtype: DType, device: &Device) -> Self {
7548 let mut data = vec![0.0_f32; n * n];
7549 for i in 0..n {
7550 for j in 0..=i {
7551 data[i * n + j] = 1.0;
7552 }
7553 }
7554 let base = Self::from_f32(data, vec![n, n], device).expect(
7563 "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",
7564 );
7565 if dtype == DType::F32 {
7566 base
7567 } else {
7568 base.to_dtype(dtype).unwrap()
7569 }
7570 }
7571
7572 pub fn triu2(n: usize, dtype: DType, device: &Device) -> Self {
7574 let mut data = vec![0.0_f32; n * n];
7575 for i in 0..n {
7576 for j in i..n {
7577 data[i * n + j] = 1.0;
7578 }
7579 }
7580 let base = Self::from_f32(data, vec![n, n], device).expect(
7589 "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",
7590 );
7591 if dtype == DType::F32 {
7592 base
7593 } else {
7594 base.to_dtype(dtype).unwrap()
7595 }
7596 }
7597
7598 pub fn narrow<D: Dim>(
7605 &self,
7606 dim: D,
7607 start: usize,
7608 len: usize,
7609 ) -> std::result::Result<Self, fuel_ir::Error> {
7610 self.slice(dim, start, len)
7611 }
7612
7613 pub fn chunk<D: Dim>(
7619 &self,
7620 chunks: usize,
7621 dim: D,
7622 ) -> std::result::Result<Vec<Self>, fuel_ir::Error> {
7623 let shape = self.shape();
7624 let dim = dim.to_index(&shape, "chunk")?;
7625 if chunks == 0 {
7626 return Err(fuel_ir::Error::Msg("chunk: chunks must be > 0".into()).bt());
7627 }
7628 let dims = shape.dims();
7629 let size = dims[dim];
7630 if size < chunks {
7631 return Ok((0..size).map(|i| self.slice(dim, i, 1).unwrap()).collect());
7632 }
7633 let base = size / chunks;
7634 let extra = size % chunks;
7635 let mut out = Vec::with_capacity(chunks);
7636 let mut start = 0;
7637 for i in 0..chunks {
7638 let len = if i < extra { base + 1 } else { base };
7639 out.push(self.slice(dim, start, len).unwrap());
7640 start += len;
7641 }
7642 Ok(out)
7643 }
7644
7645 pub fn get(&self, i: usize) -> std::result::Result<Self, fuel_ir::Error> {
7648 let dims = self.shape().dims().to_vec();
7649 if dims.is_empty() {
7650 return Ok(self.clone());
7651 }
7652 self.slice(0, i, 1).unwrap().squeeze(0)
7653 }
7654
7655 pub fn get_on_dim<D: Dim>(
7659 &self,
7660 dim: D,
7661 index: usize,
7662 ) -> std::result::Result<Self, fuel_ir::Error> {
7663 let shape = self.shape();
7664 let dim = dim.to_index(&shape, "get_on_dim")?;
7665 self.slice(dim, index, 1).unwrap().squeeze(dim)
7666 }
7667
7668 pub fn sum_dims<D: Dims>(&self, dims: D) -> std::result::Result<Self, fuel_ir::Error> {
7672 let shape = self.shape();
7673 let mut sorted = dims.to_indexes(&shape, "sum_dims")?;
7674 sorted.sort_by(|a, b| b.cmp(a));
7675 sorted.dedup();
7676 let mut acc = self.clone();
7677 for d in sorted {
7678 acc = acc.sum_dim(d)?;
7679 }
7680 Ok(acc)
7681 }
7682
7683 pub fn mean_dims<D: Dims>(&self, dims: D) -> std::result::Result<Self, fuel_ir::Error> {
7686 let shape = self.shape();
7687 let mut sorted = dims.to_indexes(&shape, "mean_dims")?;
7688 sorted.sort_by(|a, b| b.cmp(a));
7689 sorted.dedup();
7690 let mut acc = self.clone();
7691 for d in sorted {
7692 acc = acc.mean_dim(d)?;
7693 }
7694 Ok(acc)
7695 }
7696
7697 pub fn sum_dims_keepdim(&self, dims: &[usize]) -> std::result::Result<Self, fuel_ir::Error> {
7702 let mut sorted: Vec<usize> = dims.to_vec();
7703 sorted.sort();
7704 sorted.dedup();
7705 let mut acc = self.clone();
7706 for d in sorted {
7707 acc = acc.sum_keepdim(d)?;
7708 }
7709 Ok(acc)
7710 }
7711
7712 pub fn mean_dims_keepdim(&self, dims: &[usize]) -> std::result::Result<Self, fuel_ir::Error> {
7714 let mut sorted: Vec<usize> = dims.to_vec();
7715 sorted.sort();
7716 sorted.dedup();
7717 let mut acc = self.clone();
7718 for d in sorted {
7719 acc = acc.mean_keepdim(d)?;
7720 }
7721 Ok(acc)
7722 }
7723
7724 pub fn rand_like(&self, lo: f64, up: f64) -> std::result::Result<Self, fuel_ir::Error> {
7727 Self::rand(self.shape(), lo, up, self.dtype(), &Device::cpu())
7728 }
7729
7730 pub fn randn_like(&self, mean: f64, stdev: f64) -> std::result::Result<Self, fuel_ir::Error> {
7733 Self::randn(self.shape(), mean, stdev, self.dtype(), &Device::cpu())
7734 }
7735
7736 pub fn rand(
7740 shape: impl Into<Shape>,
7741 lo: f64,
7742 up: f64,
7743 dtype: DType,
7744 device: &Device,
7745 ) -> std::result::Result<Self, fuel_ir::Error> {
7746 use rand::RngExt;
7747 let shape = shape.into();
7748 let n = shape.elem_count();
7749 let mut rng = rand::rng();
7750 match dtype {
7751 DType::F32 => {
7752 let data: Vec<f32> = (0..n).map(|_| rng.random_range(lo..up) as f32).collect();
7753 Self::from_f32(data, shape, device)
7754 }
7755 DType::F64 => {
7756 let data: Vec<f64> = (0..n).map(|_| rng.random_range(lo..up)).collect();
7757 Self::from_f64(data, shape, device)
7758 }
7759 DType::BF16 => {
7760 let data: Vec<half::bf16> = (0..n)
7761 .map(|_| fuel_ir::round::bf16_from_f64(rng.random_range(lo..up)))
7762 .collect();
7763 Self::from_bf16(data, shape, device)
7764 }
7765 DType::F16 => {
7766 let data: Vec<half::f16> = (0..n)
7767 .map(|_| fuel_ir::round::f16_from_f64(rng.random_range(lo..up)))
7768 .collect();
7769 Self::from_f16(data, shape, device)
7770 }
7771 other => {
7772 Err(fuel_ir::Error::Msg(format!("Tensor::rand: unsupported dtype {other:?}",)).bt())
7773 }
7774 }
7775 }
7776
7777 pub fn randn(
7781 shape: impl Into<Shape>,
7782 mean: f64,
7783 stdev: f64,
7784 dtype: DType,
7785 device: &Device,
7786 ) -> std::result::Result<Self, fuel_ir::Error> {
7787 use rand_distr::{Distribution, Normal};
7788 let shape = shape.into();
7789 let n = shape.elem_count();
7790 let normal = Normal::new(mean, stdev).map_err(|e| {
7791 fuel_ir::Error::Msg(format!("Tensor::randn: invalid stdev={stdev}: {e}",)).bt()
7792 })?;
7793 let mut rng = rand::rng();
7794 match dtype {
7795 DType::F32 => {
7796 let data: Vec<f32> = (0..n).map(|_| normal.sample(&mut rng) as f32).collect();
7797 Self::from_f32(data, shape, device)
7798 }
7799 DType::F64 => {
7800 let data: Vec<f64> = (0..n).map(|_| normal.sample(&mut rng)).collect();
7801 Self::from_f64(data, shape, device)
7802 }
7803 DType::BF16 => {
7804 let data: Vec<half::bf16> = (0..n)
7805 .map(|_| fuel_ir::round::bf16_from_f64(normal.sample(&mut rng)))
7806 .collect();
7807 Self::from_bf16(data, shape, device)
7808 }
7809 DType::F16 => {
7810 let data: Vec<half::f16> = (0..n)
7811 .map(|_| fuel_ir::round::f16_from_f64(normal.sample(&mut rng)))
7812 .collect();
7813 Self::from_f16(data, shape, device)
7814 }
7815 other => Err(fuel_ir::Error::Msg(format!(
7816 "Tensor::randn: unsupported dtype {other:?}",
7817 ))
7818 .bt()),
7819 }
7820 }
7821
7822 pub fn arange(start: f32, end: f32, device: &Device) -> Self {
7825 Self::arange_step(start, end, 1.0, device)
7826 }
7827
7828 pub fn arange_step(start: f32, end: f32, step: f32, device: &Device) -> Self {
7833 assert!(step != 0.0, "arange_step: step must be non-zero");
7834 let mut data = Vec::new();
7835 let mut current = start;
7836 if step > 0.0 {
7837 while current < end {
7838 data.push(current);
7839 current += step;
7840 }
7841 } else {
7842 while current > end {
7843 data.push(current);
7844 current += step;
7845 }
7846 }
7847 let n = data.len();
7848 Self::from_f32(data, vec![n], device).expect(
7855 "arange_step: shape is [n] where n IS data.len(), computed one line above from that same buffer -- the lengths cannot disagree",
7856 )
7857 }
7858
7859 pub fn linspace(start: f32, end: f32, n: usize, device: &Device) -> Self {
7862 assert!(n >= 1, "linspace: n must be >= 1");
7863 if n == 1 {
7864 return Self::from_f32(vec![start], vec![1], device)
7866 .expect("linspace: vec![start] has exactly 1 element and the shape is [1]");
7867 }
7868 let step = (end - start) / ((n - 1) as f32);
7869 let data: Vec<f32> = (0..n).map(|i| start + step * (i as f32)).collect();
7870 Self::from_f32(data, vec![n], device).expect(
7873 "linspace: data is (0..n).map(..).collect() so it has exactly n elements, and the shape is [n] -- both from the same `n`",
7874 )
7875 }
7876
7877 pub fn norm(&self) -> Self {
7879 self.sqr().sum_all().sqrt()
7880 }
7881
7882 pub fn conv1d(
7897 &self,
7898 weight: &Self,
7899 bias: Option<&Self>,
7900 stride: usize,
7901 padding: usize,
7902 groups: usize,
7903 ) -> std::result::Result<Self, fuel_ir::Error> {
7904 let x_dims = self.shape().dims().to_vec();
7905 let w_dims = weight.shape().dims().to_vec();
7906 if x_dims.len() != 3 {
7907 return Err(fuel_ir::Error::Msg(format!(
7908 "conv1d: x must be rank 3 [N, Cin, T], got {x_dims:?}",
7909 ))
7910 .bt());
7911 }
7912 if w_dims.len() != 3 {
7913 return Err(fuel_ir::Error::Msg(format!(
7914 "conv1d: weight must be rank 3 [Cout, Cin/groups, K], got {w_dims:?}",
7915 ))
7916 .bt());
7917 }
7918 if groups < 1 {
7919 return Err(fuel_ir::Error::Msg("conv1d: groups must be ≥ 1".into()).bt());
7920 }
7921 if stride < 1 {
7922 return Err(fuel_ir::Error::Msg("conv1d: stride must be ≥ 1".into()).bt());
7923 }
7924 let x_4d = self.unsqueeze(2_usize)?;
7926 let w_4d = weight.unsqueeze(2_usize)?;
7927 let out_4d = x_4d.conv2d(&w_4d, bias, (1, stride), (0, padding), groups)?;
7928 out_4d.squeeze(2)
7929 }
7930
7931 pub fn conv1d_with_algo<A>(
7936 &self,
7937 weight: &Self,
7938 bias: Option<&Self>,
7939 stride: usize,
7940 padding: usize,
7941 groups: usize,
7942 _algo: A,
7943 ) -> std::result::Result<Self, fuel_ir::Error> {
7944 self.conv1d(weight, bias, stride, padding, groups)
7945 }
7946
7947 pub fn avg_pool2d(
7957 &self,
7958 kernel: (usize, usize),
7959 stride: (usize, usize),
7960 padding: (usize, usize),
7961 count_include_pad: bool,
7962 ) -> std::result::Result<Self, fuel_ir::Error> {
7963 let dims = self.shape().dims().to_vec();
7964 if dims.len() != 4 {
7965 return Err(fuel_ir::Error::Msg(format!(
7966 "avg_pool2d: input must be rank 4 [N, C, H, W], got {dims:?}",
7967 ))
7968 .bt());
7969 }
7970 let (c, h, w) = (dims[1], dims[2], dims[3]);
7971 let (kh, kw) = kernel;
7972 if kh == 0 || kw == 0 {
7973 return Err(
7974 fuel_ir::Error::Msg("avg_pool2d: kernel sizes must be positive".into()).bt(),
7975 );
7976 }
7977
7978 if count_include_pad || padding == (0, 0) {
7983 let inv = 1.0_f32 / ((kh * kw) as f32);
7984 let weight =
7988 self.const_f32_like(vec![inv; c * kh * kw], Shape::from_dims(&[c, 1, kh, kw]))?;
7989 return self.conv2d(&weight, None, stride, padding, c);
7990 }
7991
7992 if let Some((axis, out_idx)) = first_zero_tap_output_index(h, kh, stride.0, padding.0)
8007 .map(|i| ("H", i))
8008 .or_else(|| first_zero_tap_output_index(w, kw, stride.1, padding.1).map(|i| ("W", i)))
8009 {
8010 return Err(fuel_ir::Error::Msg(format!(
8011 "avg_pool2d: count_include_pad=false has no valid (non-padded) \
8012 taps for output position {out_idx} on the {axis} axis \
8013 (kernel={kernel:?}, stride={stride:?}, padding={padding:?}, \
8014 input H×W={h}×{w}) — the average would divide by zero",
8015 ))
8016 .bt());
8017 }
8018
8019 let sum_weight = self.const_f32_like(
8020 vec![1.0_f32; c * kh * kw],
8021 Shape::from_dims(&[c, 1, kh, kw]),
8022 )?;
8023 let summed = self.conv2d(&sum_weight, None, stride, padding, c)?;
8024
8025 let ones_hw = self.const_f32_like(vec![1.0_f32; h * w], Shape::from_dims(&[1, 1, h, w]))?;
8029 let count_weight =
8030 self.const_f32_like(vec![1.0_f32; kh * kw], Shape::from_dims(&[1, 1, kh, kw]))?;
8031 let count = ones_hw.conv2d(&count_weight, None, stride, padding, 1)?;
8032
8033 summed.broadcast_div(&count)
8034 }
8035
8036 pub fn avg_pool2d_with_stride(
8040 &self,
8041 kernel: (usize, usize),
8042 stride: (usize, usize),
8043 ) -> std::result::Result<Self, fuel_ir::Error> {
8044 self.avg_pool2d(kernel, stride, (0, 0), true)
8047 }
8048
8049 pub fn max_pool2d(
8064 &self,
8065 kernel: (usize, usize),
8066 stride: (usize, usize),
8067 padding: (usize, usize),
8068 ) -> std::result::Result<Self, fuel_ir::Error> {
8069 self.max_pool2d_with_pad_value(kernel, stride, padding, f32::NEG_INFINITY)
8077 }
8078
8079 pub fn max_pool2d_with_pad_value(
8085 &self,
8086 kernel: (usize, usize),
8087 stride: (usize, usize),
8088 padding: (usize, usize),
8089 pad_value: f32,
8090 ) -> std::result::Result<Self, fuel_ir::Error> {
8091 let dims = self.shape().dims().to_vec();
8092 if dims.len() != 4 {
8093 return Err(fuel_ir::Error::Msg(format!(
8094 "max_pool2d: input must be rank 4 [N, C, H, W], got {dims:?}",
8095 ))
8096 .bt());
8097 }
8098 let (n, c, h, w) = (dims[0], dims[1], dims[2], dims[3]);
8099 let (kh, kw) = kernel;
8100 let (sh, sw) = stride;
8101 let (ph, pw) = padding;
8102 if kh == 0 || kw == 0 {
8103 return Err(
8104 fuel_ir::Error::Msg("max_pool2d: kernel sizes must be positive".into()).bt(),
8105 );
8106 }
8107 if sh == 0 || sw == 0 {
8108 return Err(fuel_ir::Error::Msg("max_pool2d: strides must be positive".into()).bt());
8109 }
8110 let h_padded_min = h + 2 * ph;
8111 let w_padded_min = w + 2 * pw;
8112 if h_padded_min < kh || w_padded_min < kw {
8113 return Err(fuel_ir::Error::Msg(format!(
8114 "max_pool2d: padded input ({h_padded_min}×{w_padded_min}) smaller than kernel ({kh}×{kw})",
8115 )).bt());
8116 }
8117 let h_out = (h_padded_min - kh) / sh + 1;
8118 let w_out = (w_padded_min - kw) / sw + 1;
8119 let h_total = h_out * sh + (kh - 1);
8122 let w_total = w_out * sw + (kw - 1);
8123 let extra_h = h_total.saturating_sub(h_padded_min);
8124 let extra_w = w_total.saturating_sub(w_padded_min);
8125 let padded = self
8126 .pad_with_value(2, ph, ph + extra_h, pad_value)?
8127 .pad_with_value(3, pw, pw + extra_w, pad_value)?;
8128 let mut acc: Option<Tensor> = None;
8130 for ky in 0..kh {
8131 let row_slice = padded.slice(2, ky, h_out * sh).unwrap();
8135 let row_reshaped = row_slice.reshape(vec![n, c, h_out, sh, w_total])?;
8138 let row_tap = row_reshaped.slice(3, 0, 1).unwrap().squeeze(3)?;
8139 for kx in 0..kw {
8140 let col_slice = row_tap.slice(3, kx, w_out * sw).unwrap();
8141 let col_reshaped = col_slice.reshape(vec![n, c, h_out, w_out, sw])?;
8142 let win = col_reshaped.slice(4, 0, 1).unwrap().squeeze(4)?;
8143 acc = Some(match acc {
8144 None => win,
8145 Some(a) => a.maximum(&win).unwrap(),
8146 });
8147 }
8148 }
8149 acc.ok_or_else(|| fuel_ir::Error::Msg("max_pool2d: empty kernel".into()).bt())
8150 }
8151
8152 pub fn max_pool2d_with_stride(
8154 &self,
8155 kernel: (usize, usize),
8156 stride: (usize, usize),
8157 ) -> std::result::Result<Self, fuel_ir::Error> {
8158 self.max_pool2d(kernel, stride, (0, 0))
8159 }
8160
8161 pub fn upsample_nearest2d(&self, scale: usize) -> std::result::Result<Self, fuel_ir::Error> {
8171 if scale == 0 {
8172 return Err(
8173 fuel_ir::Error::Msg("upsample_nearest2d: scale must be positive".into()).bt(),
8174 );
8175 }
8176 let dims = self.shape().dims().to_vec();
8177 if dims.len() != 4 {
8178 return Err(fuel_ir::Error::Msg(format!(
8179 "upsample_nearest2d: input must be rank 4 [N, C, H, W], got {dims:?}",
8180 ))
8181 .bt());
8182 }
8183 if scale == 1 {
8184 return Ok(self.clone());
8185 }
8186 let (n, c, h, w) = (dims[0], dims[1], dims[2], dims[3]);
8187 let expanded = self.reshape(vec![n, c, h, 1, w, 1])?;
8189 let h_expanded = (0..scale)
8191 .fold(None, |acc: Option<Tensor>, _| {
8192 Some(match acc {
8193 None => expanded.clone(),
8194 Some(a) => a.concat(&expanded, 3).unwrap(),
8195 })
8196 })
8197 .unwrap();
8198 let h_then_w = (0..scale)
8199 .fold(None, |acc: Option<Tensor>, _| {
8200 Some(match acc {
8201 None => h_expanded.clone(),
8202 Some(a) => a.concat(&h_expanded, 5).unwrap(),
8203 })
8204 })
8205 .unwrap();
8206 h_then_w.reshape(vec![n, c, h * scale, w * scale])
8207 }
8208
8209 pub fn upsample_nearest1d(&self, scale: usize) -> std::result::Result<Self, fuel_ir::Error> {
8213 if scale == 0 {
8214 return Err(
8215 fuel_ir::Error::Msg("upsample_nearest1d: scale must be positive".into()).bt(),
8216 );
8217 }
8218 let dims = self.shape().dims().to_vec();
8219 if dims.len() != 3 {
8220 return Err(fuel_ir::Error::Msg(format!(
8221 "upsample_nearest1d: input must be rank 3 [N, C, T], got {dims:?}",
8222 ))
8223 .bt());
8224 }
8225 if scale == 1 {
8226 return Ok(self.clone());
8227 }
8228 let (n, c, t) = (dims[0], dims[1], dims[2]);
8229 let expanded = self.reshape(vec![n, c, t, 1])?;
8230 let replicated = (0..scale)
8231 .fold(None, |acc: Option<Tensor>, _| {
8232 Some(match acc {
8233 None => expanded.clone(),
8234 Some(a) => a.concat(&expanded, 3).unwrap(),
8235 })
8236 })
8237 .unwrap();
8238 replicated.reshape(vec![n, c, t * scale])
8239 }
8240
8241 pub fn interpolate2d(
8251 &self,
8252 target_h: usize,
8253 target_w: usize,
8254 ) -> std::result::Result<Self, fuel_ir::Error> {
8255 let dims = self.shape().dims().to_vec();
8256 if dims.len() != 4 {
8257 return Err(fuel_ir::Error::Msg(format!(
8258 "interpolate2d: input must be rank 4 [N, C, H, W], got {dims:?}",
8259 ))
8260 .bt());
8261 }
8262 let h = dims[2];
8263 let w = dims[3];
8264 if h == 0 || w == 0 || target_h == 0 || target_w == 0 {
8265 return Err(fuel_ir::Error::Msg(
8266 "interpolate2d: input + target spatial dims must be positive".into(),
8267 )
8268 .bt());
8269 }
8270 if target_h == h && target_w == w {
8272 return Ok(self.clone());
8273 }
8274 if target_h.is_multiple_of(h) && target_w.is_multiple_of(w) && target_h / h == target_w / w
8278 {
8279 return self.upsample_nearest2d(target_h / h);
8280 }
8281 let h_idx: Vec<u32> = (0..target_h)
8285 .map(|oi| ((oi * h) / target_h).min(h - 1) as u32)
8286 .collect();
8287 let w_idx: Vec<u32> = (0..target_w)
8288 .map(|oj| ((oj * w) / target_w).min(w - 1) as u32)
8289 .collect();
8290 let h_idx_tensor = self.const_u32_like(h_idx, fuel_ir::Shape::from_dims(&[target_h]))?;
8291 let w_idx_tensor = self.const_u32_like(w_idx, fuel_ir::Shape::from_dims(&[target_w]))?;
8292 let after_h = self.index_select(2_usize, &h_idx_tensor)?;
8293 after_h.index_select(3_usize, &w_idx_tensor)
8294 }
8295
8296 pub fn interpolate1d(&self, target_t: usize) -> std::result::Result<Self, fuel_ir::Error> {
8300 let dims = self.shape().dims().to_vec();
8301 if dims.len() != 3 {
8302 return Err(fuel_ir::Error::Msg(format!(
8303 "interpolate1d: input must be rank 3 [N, C, T], got {dims:?}",
8304 ))
8305 .bt());
8306 }
8307 let t = dims[2];
8308 if t == 0 {
8309 return Err(
8310 fuel_ir::Error::Msg("interpolate1d: input length must be positive".into()).bt(),
8311 );
8312 }
8313 if !target_t.is_multiple_of(t) {
8314 return Err(fuel_ir::Error::Msg(format!(
8315 "interpolate1d: target {target_t} must be integer multiple of input {t}; non-integer ratios are future work",
8316 )).bt());
8317 }
8318 self.upsample_nearest1d(target_t / t)
8319 }
8320
8321 pub fn pad_with_zeros<D: Dim>(
8325 &self,
8326 dim: D,
8327 left: usize,
8328 right: usize,
8329 ) -> std::result::Result<Self, fuel_ir::Error> {
8330 self.pad_with_value(dim, left, right, 0.0)
8331 }
8332
8333 pub fn pad_with_value<D: Dim>(
8340 &self,
8341 dim: D,
8342 before: usize,
8343 after: usize,
8344 value: f32,
8345 ) -> std::result::Result<Self, fuel_ir::Error> {
8346 let shape = self.shape();
8347 let dim = dim.to_index(&shape, "pad_with_value")?;
8348 let rank = shape.dims().len();
8349 if before == 0 && after == 0 {
8350 return Ok(self.clone());
8351 }
8352 let mut padding: Vec<(usize, usize)> = vec![(0, 0); rank];
8353 padding[dim] = (before, after);
8354 self.pad(padding, fuel_graph::PadMode::Constant, value as f64)
8355 }
8356
8357 pub fn meshgrid(
8370 args: &[&Self],
8371 xy_indexing: bool,
8372 ) -> std::result::Result<Vec<Self>, fuel_ir::Error> {
8373 if args.len() < 2 {
8374 return Err(fuel_ir::Error::Msg(
8375 "meshgrid: requires at least two rank-1 tensors".into(),
8376 )
8377 .bt());
8378 }
8379 let ordered: Vec<&Self> = if xy_indexing {
8380 args.iter().rev().copied().collect()
8381 } else {
8382 args.to_vec()
8383 };
8384 let mut lens = Vec::with_capacity(ordered.len());
8385 for (i, t) in ordered.iter().enumerate() {
8386 let dims = t.shape().dims().to_vec();
8387 if dims.len() != 1 {
8388 return Err(fuel_ir::Error::Msg(format!(
8389 "meshgrid: input {i} must be rank 1, got shape {dims:?}",
8390 ))
8391 .bt());
8392 }
8393 lens.push(dims[0]);
8394 }
8395 let mut grids = Vec::with_capacity(ordered.len());
8396 for (idx, t) in ordered.iter().enumerate() {
8397 let mut shape = vec![1_usize; ordered.len()];
8398 shape[idx] = lens[idx];
8399 let placed = t.reshape(shape)?;
8400 let mut repeats = lens.clone();
8401 repeats[idx] = 1;
8402 let grid = placed.repeat(repeats)?;
8403 grids.push(grid);
8404 }
8405 if xy_indexing {
8406 grids.reverse();
8407 }
8408 Ok(grids)
8409 }
8410
8411 pub fn repeat(&self, repeats: impl Into<Shape>) -> std::result::Result<Self, fuel_ir::Error> {
8415 let repeats = repeats.into();
8416 let repeats: Vec<usize> = repeats.dims().to_vec();
8417 let self_rank = self.shape().dims().len();
8418 let target_rank = repeats.len();
8419 let mut work = if self_rank < target_rank {
8420 let pad_count = target_rank - self_rank;
8421 let mut new_shape: Vec<usize> = vec![1; pad_count];
8422 new_shape.extend_from_slice(self.shape().dims());
8423 self.reshape(new_shape)?
8424 } else if self_rank > target_rank {
8425 return Err(fuel_ir::Error::Msg(format!(
8426 "repeat: repeats rank {target_rank} smaller than tensor rank {self_rank}",
8427 ))
8428 .bt());
8429 } else {
8430 self.clone()
8431 };
8432 for (axis, &n) in repeats.iter().enumerate() {
8433 if n == 0 {
8434 return Err(fuel_ir::Error::Msg(format!(
8435 "repeat: zero repeat count at axis {axis} not supported",
8436 ))
8437 .bt());
8438 }
8439 if n == 1 {
8440 continue;
8441 }
8442 let base = work.clone();
8444 for _ in 1..n {
8445 work = work.concat(&base, axis)?;
8446 }
8447 }
8448 Ok(work)
8449 }
8450}
8451
8452fn first_zero_tap_output_index(
8461 dim: usize,
8462 kernel: usize,
8463 stride: usize,
8464 pad: usize,
8465) -> Option<usize> {
8466 let out_dim = (dim + 2 * pad).saturating_sub(kernel) / stride + 1;
8467 (0..out_dim).find(|&o| {
8468 let start = o as isize * stride as isize - pad as isize;
8469 let end = start + kernel as isize;
8470 let valid_start = start.max(0);
8471 let valid_end = end.min(dim as isize);
8472 valid_end <= valid_start
8473 })
8474}
8475
8476impl Tensor {
8479 pub fn from_safetensors_bytes(
8491 bytes: &[u8],
8492 dtype: safetensors::Dtype,
8493 shape: &[usize],
8494 device: &Device,
8495 ) -> crate::Result<Self> {
8496 use safetensors::Dtype;
8497 let shape_obj = Shape::from_dims(shape);
8498 let elem_count = shape_obj.elem_count();
8499
8500 let check_len = |expected: usize| -> crate::Result<()> {
8501 if bytes.len() != expected {
8502 crate::bail!(
8503 "from_safetensors_bytes: expected {expected} bytes for dtype {dtype:?} \
8504 and shape {shape:?}, got {}",
8505 bytes.len(),
8506 );
8507 }
8508 Ok(())
8509 };
8510
8511 match dtype {
8512 Dtype::F32 => {
8513 check_len(elem_count * 4)?;
8514 let mut data = Vec::with_capacity(elem_count);
8515 for chunk in bytes.as_chunks::<4>().0.iter() {
8516 data.push(f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
8517 }
8518 Self::from_f32(data, shape_obj, device)
8519 }
8520 Dtype::F64 => {
8521 check_len(elem_count * 8)?;
8522 let mut data = Vec::with_capacity(elem_count);
8523 for chunk in bytes.as_chunks::<8>().0.iter() {
8524 let arr: [u8; 8] = *chunk;
8525 data.push(f64::from_le_bytes(arr));
8526 }
8527 Self::from_f64(data, shape_obj, device)
8528 }
8529 Dtype::BF16 => {
8530 check_len(elem_count * 2)?;
8531 let mut data = Vec::with_capacity(elem_count);
8532 for chunk in bytes.as_chunks::<2>().0.iter() {
8533 let raw = u16::from_le_bytes([chunk[0], chunk[1]]);
8534 data.push(half::bf16::from_bits(raw));
8535 }
8536 Self::from_bf16(data, shape_obj, device)
8537 }
8538 Dtype::F16 => {
8539 check_len(elem_count * 2)?;
8540 let mut data = Vec::with_capacity(elem_count);
8541 for chunk in bytes.as_chunks::<2>().0.iter() {
8542 let raw = u16::from_le_bytes([chunk[0], chunk[1]]);
8543 data.push(half::f16::from_bits(raw));
8544 }
8545 Self::from_f16(data, shape_obj, device)
8546 }
8547 Dtype::U32 => {
8548 check_len(elem_count * 4)?;
8549 let mut data = Vec::with_capacity(elem_count);
8550 for chunk in bytes.as_chunks::<4>().0.iter() {
8551 data.push(u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
8552 }
8553 Self::from_u32(data, shape_obj, device)
8554 }
8555 other => crate::bail!(
8556 "from_safetensors_bytes: unsupported dtype {other:?} — extend Tensor's \
8557 safetensors loader to handle it",
8558 ),
8559 }
8560 }
8561
8562 pub fn from_safetensors_view(
8566 view: &safetensors::tensor::TensorView<'_>,
8567 device: &Device,
8568 ) -> crate::Result<Self> {
8569 Self::from_safetensors_bytes(view.data(), view.dtype(), view.shape(), device)
8570 }
8571}
8572
8573pub type LayerNormPair = (Arc<[f32]>, Arc<[f32]>);
8577
8578pub type ConvWeightBias = (Arc<[f32]>, Arc<[f32]>);
8582
8583#[derive(Debug, Clone)]
8606pub enum WeightStorage {
8607 F32(Arc<[f32]>),
8608 BF16(Arc<[half::bf16]>),
8609 Q4_0 {
8619 words: Arc<[u32]>,
8620 bytes_len: usize,
8621 in_features: usize,
8622 out_features: usize,
8623 },
8624 Ggml {
8630 qtype: fuel_graph::QuantType,
8631 words: Arc<[u32]>,
8632 bytes_len: usize,
8633 in_features: usize,
8634 out_features: usize,
8635 },
8636 Awq(Arc<crate::awq::AwqHostWeight>),
8641 WithLoRA {
8652 base: Box<WeightStorage>,
8653 lora_a: Arc<[f32]>,
8655 lora_b: Arc<[f32]>,
8657 rank: usize,
8658 alpha: f32,
8660 in_features: usize,
8661 out_features: usize,
8662 },
8663}
8664
8665impl WeightStorage {
8666 pub fn from_ggml_bytes(
8681 dtype: fuel_ir::quantized::GgmlDType,
8682 bytes: &[u8],
8683 in_features: usize,
8684 out_features: usize,
8685 ) -> Option<Self> {
8686 use fuel_ir::quantized::GgmlDType;
8687 let qtype = match dtype {
8688 GgmlDType::Q8_0 => fuel_graph::QuantType::Q8_0,
8689 GgmlDType::Q4K => fuel_graph::QuantType::Q4_K_M,
8690 GgmlDType::Q6K => fuel_graph::QuantType::Q6K,
8691 GgmlDType::Q3K => fuel_graph::QuantType::Q3K,
8692 GgmlDType::Q5K => fuel_graph::QuantType::Q5K,
8693 GgmlDType::Iq4Nl => fuel_graph::QuantType::Iq4Nl,
8694 GgmlDType::Iq4Xs => fuel_graph::QuantType::Iq4Xs,
8695 GgmlDType::Iq3S => fuel_graph::QuantType::Iq3S,
8696 GgmlDType::F32
8699 | GgmlDType::F16
8700 | GgmlDType::BF16
8701 | GgmlDType::Q4_0
8702 | GgmlDType::Q4_1
8703 | GgmlDType::Q5_0
8704 | GgmlDType::Q5_1
8705 | GgmlDType::Q8_1
8706 | GgmlDType::Q2K
8707 | GgmlDType::Q8K
8708 | GgmlDType::Iq2Xxs
8709 | GgmlDType::Iq2Xs
8710 | GgmlDType::Iq3Xxs
8711 | GgmlDType::Iq1S
8712 | GgmlDType::Iq2S
8713 | GgmlDType::Iq1M
8714 | GgmlDType::Tq1_0
8715 | GgmlDType::Tq2_0
8716 | GgmlDType::Mxfp4
8717 | GgmlDType::Nvfp4 => return None,
8718 };
8719 let block = qtype.elements_per_block();
8720 if in_features == 0 || !in_features.is_multiple_of(block) {
8721 return None;
8722 }
8723 if bytes.len() != out_features * (in_features / block) * qtype.bytes_per_block() {
8724 return None;
8725 }
8726 let mut padded = bytes.to_vec();
8728 padded.resize(bytes.len().div_ceil(4) * 4, 0);
8729 let words: Vec<u32> = padded
8730 .as_chunks::<4>()
8731 .0
8732 .iter()
8733 .map(|c| u32::from_le_bytes(*c))
8734 .collect();
8735 Some(Self::Ggml {
8736 qtype,
8737 words: Arc::from(words),
8738 bytes_len: bytes.len(),
8739 in_features,
8740 out_features,
8741 })
8742 }
8743
8744 pub fn resident_bytes(&self) -> usize {
8748 match self {
8749 Self::F32(a) => a.len() * std::mem::size_of::<f32>(),
8750 Self::BF16(a) => a.len() * std::mem::size_of::<half::bf16>(),
8751 Self::Q4_0 { bytes_len, .. } | Self::Ggml { bytes_len, .. } => *bytes_len,
8752 Self::Awq(w) => {
8753 w.weight.len() * std::mem::size_of::<u32>()
8754 + w.zeros.len() * std::mem::size_of::<u32>()
8755 + w.scales.len() * std::mem::size_of::<half::f16>()
8756 }
8757 Self::WithLoRA {
8758 base,
8759 lora_a,
8760 lora_b,
8761 ..
8762 } => base.resident_bytes() + (lora_a.len() + lora_b.len()) * std::mem::size_of::<f32>(),
8763 }
8764 }
8765
8766 pub fn elem_count(&self) -> usize {
8767 match self {
8768 Self::F32(a) => a.len(),
8769 Self::BF16(a) => a.len(),
8770 Self::Q4_0 {
8772 in_features,
8773 out_features,
8774 ..
8775 }
8776 | Self::Ggml {
8777 in_features,
8778 out_features,
8779 ..
8780 } => *in_features * *out_features,
8781 Self::Awq(w) => w.ic * w.oc,
8782 Self::WithLoRA {
8783 in_features,
8784 out_features,
8785 ..
8786 } => *in_features * *out_features,
8787 }
8788 }
8789
8790 pub fn dtype(&self) -> fuel_ir::DType {
8791 match self {
8792 Self::F32(_) => fuel_ir::DType::F32,
8793 Self::BF16(_) => fuel_ir::DType::BF16,
8794 Self::Q4_0 { .. } | Self::Ggml { .. } => fuel_ir::DType::U32,
8798 Self::Awq(_) => fuel_ir::DType::U32,
8800 Self::WithLoRA { base, .. } => base.dtype(),
8803 }
8804 }
8805
8806 pub fn const_like(
8817 &self,
8818 anchor: &Tensor,
8819 shape: Shape,
8820 ) -> std::result::Result<Tensor, fuel_ir::Error> {
8821 match self {
8822 Self::F32(a) => anchor.const_f32_like(a.clone(), shape),
8823 Self::BF16(a) => anchor.const_bf16_like(a.clone(), shape),
8824 Self::Q4_0 { words, .. } | Self::Ggml { words, .. } => {
8825 let _ = shape; anchor.const_u32_like(Arc::clone(words), Shape::from_dims(&[words.len()]))
8828 }
8829 Self::Awq(_) => Err(fuel_ir::Error::Msg(
8830 "WeightStorage::Awq::const_like is not supported — an AWQ weight is three operands \
8831 (weight, zeros, scales), applied via apply_linear."
8832 .into(),
8833 )
8834 .bt()),
8835 Self::WithLoRA { .. } => Err(fuel_ir::Error::Msg(
8836 "WeightStorage::WithLoRA::const_like is not supported \
8837 — the base + LoRA update must be applied via \
8838 apply_linear to produce the right graph structure."
8839 .into(),
8840 )
8841 .bt()),
8842 }
8843 }
8844
8845 pub fn apply_linear_with_bias(
8854 &self,
8855 x: &Tensor,
8856 in_features: usize,
8857 out_features: usize,
8858 bias: std::sync::Arc<[f32]>,
8859 ) -> std::result::Result<Tensor, fuel_ir::Error> {
8860 if bias.len() != out_features {
8861 return Err(fuel_ir::Error::Msg(format!(
8866 "apply_linear_with_bias: bias len ({}) != out_features ({out_features})",
8867 bias.len(),
8868 ))
8869 .bt());
8870 }
8871 let projected = self.apply_linear(x, in_features, out_features)?;
8872 let bias_t = projected.const_f32_like(bias, Shape::from_dims(&[out_features]))?;
8873 projected.broadcast_add(&bias_t)
8874 }
8875
8876 pub fn apply_linear(
8894 &self,
8895 x: &Tensor,
8896 in_features: usize,
8897 out_features: usize,
8898 ) -> std::result::Result<Tensor, fuel_ir::Error> {
8899 let x_dims = x.shape().dims().to_vec();
8905 match x_dims.last() {
8906 Some(&k) if k == in_features => {}
8907 _ => {
8908 return Err(fuel_ir::Error::Msg(format!(
8909 "apply_linear({in_features} -> {out_features}): input shape {x_dims:?} \
8910 must have trailing dim {in_features}",
8911 ))
8912 .bt());
8913 }
8914 }
8915 match self {
8916 Self::F32(_) | Self::BF16(_) => {
8917 let w = self.const_like(x, Shape::from_dims(&[in_features, out_features]))?;
8918 x.matmul(&w)
8919 }
8920 Self::Q4_0 {
8921 in_features: expected_in,
8922 out_features: expected_out,
8923 ..
8924 } => {
8925 if *expected_in != in_features || *expected_out != out_features {
8926 return Err(fuel_ir::Error::Msg(format!(
8927 "WeightStorage::Q4_0 shape mismatch: stored \
8928 [{expected_in}, {expected_out}], requested \
8929 [{in_features}, {out_features}]",
8930 ))
8931 .bt());
8932 }
8933 let w_bytes = self.const_like(x, Shape::from_dims(&[in_features, out_features]))?;
8934 x.qmatmul(
8935 &w_bytes,
8936 fuel_graph::QuantType::Q4_0,
8937 in_features,
8938 out_features,
8939 )
8940 }
8941 Self::Ggml {
8942 qtype,
8943 in_features: expected_in,
8944 out_features: expected_out,
8945 ..
8946 } => {
8947 if *expected_in != in_features || *expected_out != out_features {
8948 return Err(fuel_ir::Error::Msg(format!(
8949 "WeightStorage::Ggml({qtype:?}) shape mismatch: stored [{expected_in}, {expected_out}], requested [{in_features}, {out_features}]",
8950 ))
8951 .bt());
8952 }
8953 let w_bytes = self.const_like(x, Shape::from_dims(&[in_features, out_features]))?;
8954 x.qmatmul(&w_bytes, *qtype, in_features, out_features)
8955 }
8956 Self::Awq(w) => {
8957 if w.ic != in_features || w.oc != out_features {
8958 return Err(fuel_ir::Error::Msg(format!(
8959 "WeightStorage::Awq shape mismatch: stored [{}, {}], requested [{in_features}, {out_features}]",
8960 w.ic, w.oc,
8961 ))
8962 .bt());
8963 }
8964 w.matmul(x, 8)
8967 }
8968 Self::WithLoRA {
8969 base,
8970 lora_a,
8971 lora_b,
8972 rank,
8973 alpha,
8974 in_features: expected_in,
8975 out_features: expected_out,
8976 } => {
8977 if *expected_in != in_features || *expected_out != out_features {
8978 return Err(fuel_ir::Error::Msg(format!(
8979 "WeightStorage::WithLoRA shape mismatch: stored \
8980 [{expected_in}, {expected_out}], requested \
8981 [{in_features}, {out_features}]",
8982 ))
8983 .bt());
8984 }
8985 let base_out = base.apply_linear(x, in_features, out_features)?;
8987 let a_t =
8989 x.const_f32_like(Arc::clone(lora_a), Shape::from_dims(&[in_features, *rank]))?;
8990 let b_t =
8991 x.const_f32_like(Arc::clone(lora_b), Shape::from_dims(&[*rank, out_features]))?;
8992 let scale = *alpha as f64 / *rank as f64;
8993 let lora_path = Tensor {
8995 inner: x.matmul(&a_t)?.matmul(&b_t)?.inner.mul_scalar(scale),
8996 };
8997 base_out.add(&lora_path)
8998 }
8999 }
9000 }
9001
9002 pub fn apply_linear_dyn_m(
9015 &self,
9016 x: &Tensor,
9017 in_features: usize,
9018 out_features: usize,
9019 row_count: fuel_ir::DynScalar,
9020 ) -> std::result::Result<Tensor, fuel_ir::Error> {
9021 match self {
9022 Self::F32(_) => {
9023 let w = self
9025 .const_like(x, Shape::from_dims(&[in_features, out_features]))
9026 .expect("apply_linear_dyn_m F32 arm: const_like cannot fail for F32");
9027 x.matmul_dyn_m(&w, row_count)
9028 }
9029 other => Err(fuel_ir::Error::Msg(format!(
9030 "apply_linear_dyn_m: sparse-MoE dispatch is F32-only today, got {:?} \
9031 weight (cast the expert weights to F32)",
9032 other.dtype(),
9033 ))
9034 .bt()),
9035 }
9036 }
9037
9038 pub fn with_lora(
9043 self,
9044 lora_a: Arc<[f32]>,
9045 lora_b: Arc<[f32]>,
9046 rank: usize,
9047 alpha: f32,
9048 in_features: usize,
9049 out_features: usize,
9050 ) -> Self {
9051 assert_eq!(
9052 lora_a.len(),
9053 in_features * rank,
9054 "lora_a length {} does not match in_features ({in_features}) × rank ({rank}) = {}",
9055 lora_a.len(),
9056 in_features * rank,
9057 );
9058 assert_eq!(
9059 lora_b.len(),
9060 rank * out_features,
9061 "lora_b length {} does not match rank ({rank}) × out_features ({out_features}) = {}",
9062 lora_b.len(),
9063 rank * out_features,
9064 );
9065 assert!(
9066 !matches!(self, Self::WithLoRA { .. }),
9067 "with_lora: base is already WithLoRA (nested adapters unsupported)",
9068 );
9069 Self::WithLoRA {
9070 base: Box::new(self),
9071 lora_a,
9072 lora_b,
9073 rank,
9074 alpha,
9075 in_features,
9076 out_features,
9077 }
9078 }
9079}
9080
9081impl From<Arc<[f32]>> for WeightStorage {
9085 fn from(a: Arc<[f32]>) -> Self {
9086 Self::F32(a)
9087 }
9088}
9089impl From<Vec<f32>> for WeightStorage {
9090 fn from(v: Vec<f32>) -> Self {
9091 Self::F32(Arc::from(v))
9092 }
9093}
9094impl From<Arc<[half::bf16]>> for WeightStorage {
9095 fn from(a: Arc<[half::bf16]>) -> Self {
9096 Self::BF16(a)
9097 }
9098}
9099impl From<Vec<half::bf16>> for WeightStorage {
9100 fn from(v: Vec<half::bf16>) -> Self {
9101 Self::BF16(Arc::from(v))
9102 }
9103}
9104
9105#[derive(Debug, Clone)]
9117pub struct LayerWeights {
9118 pub attn_q: WeightStorage,
9120 pub attn_q_bias: Option<Arc<[f32]>>,
9122 pub attn_k: WeightStorage,
9124 pub attn_k_bias: Option<Arc<[f32]>>,
9126 pub attn_v: WeightStorage,
9128 pub attn_v_bias: Option<Arc<[f32]>>,
9130 pub attn_o: WeightStorage,
9132 pub ffn_gate: WeightStorage,
9134 pub ffn_up: WeightStorage,
9136 pub ffn_down: WeightStorage,
9138 pub attn_norm_gain: Arc<[f32]>,
9141 pub ffn_norm_gain: Arc<[f32]>,
9143}
9144
9145pub fn invalidate_decode_pair_if_stale<C>(
9146 session: &mut Option<crate::inference_context::DecodeSession>,
9147 captured: &mut Option<C>,
9148 ctx: &mut InferenceContext,
9149 seq: usize,
9150 max_seq_len: Option<usize>,
9151 cache_dtype: DType,
9152 n_layers: usize,
9153 shape_key: u64,
9154 kv: &dyn crate::inference_context::KvRebindSource,
9155 drop_session: impl FnOnce(
9156 &mut Option<crate::inference_context::DecodeSession>,
9157 &mut InferenceContext,
9158 ),
9159) -> SessionDisposition {
9160 refresh_decode_session(
9161 session,
9162 ctx,
9163 seq,
9164 max_seq_len,
9165 cache_dtype,
9166 n_layers,
9167 shape_key,
9168 kv,
9169 || *captured = None,
9173 drop_session,
9174 )
9175}
9176
9177#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9179pub enum SessionDisposition {
9180 Absent,
9182 Kept,
9184 Rebound,
9187 Dropped(Option<crate::inference_context::RebindRefusal>),
9191}
9192
9193pub fn refresh_decode_session(
9218 session: &mut Option<crate::inference_context::DecodeSession>,
9219 ctx: &mut InferenceContext,
9220 seq: usize,
9221 max_seq_len: Option<usize>,
9222 cache_dtype: DType,
9223 n_layers: usize,
9224 shape_key: u64,
9225 kv: &dyn crate::inference_context::KvRebindSource,
9226 on_invalidate: impl FnOnce(),
9227 drop_session: impl FnOnce(
9228 &mut Option<crate::inference_context::DecodeSession>,
9229 &mut InferenceContext,
9230 ),
9231) -> SessionDisposition {
9232 use crate::inference_context::PlanValidity;
9233
9234 let verdict = match (session.as_ref(), max_seq_len) {
9235 (None, _) => return SessionDisposition::Absent,
9236 (Some(s), Some(msl)) => {
9237 s.validity_for(seq, msl, n_layers, cache_dtype, shape_key, kv.alloc_id())
9238 }
9239 (Some(_), None) => PlanValidity::Stale,
9242 };
9243 if verdict == PlanValidity::Valid {
9244 return SessionDisposition::Kept;
9245 }
9246
9247 on_invalidate();
9248
9249 let refusal = if verdict == PlanValidity::AllocationChanged {
9250 match session.as_mut().map(|s| s.rebind_kv(kv)) {
9251 Some(Ok(())) => return SessionDisposition::Rebound,
9252 Some(Err(r)) => Some(r),
9253 None => None,
9257 }
9258 } else {
9259 None
9260 };
9261
9262 drop_session(session, ctx);
9263 SessionDisposition::Dropped(refusal)
9264}
9265
9266pub fn build_decode_causal_mask(cached_len: usize, seq: usize, max_seq_len: usize) -> Vec<f32> {
9267 let mut mask_data = vec![0.0_f32; seq * max_seq_len];
9268 for q_idx in 0..seq {
9269 let abs_q = cached_len + q_idx;
9270 for k_idx in (abs_q + 1)..max_seq_len {
9271 mask_data[q_idx * max_seq_len + k_idx] = f32::NEG_INFINITY;
9272 }
9273 }
9274 mask_data
9275}
9276
9277pub fn build_decode_causal_mask_windowed(
9317 cached_len: usize,
9318 seq: usize,
9319 max_seq_len: usize,
9320 window: usize,
9321) -> Vec<f32> {
9322 let mut mask_data = vec![0.0_f32; seq * max_seq_len];
9323 for q_idx in 0..seq {
9324 let abs_q = cached_len + q_idx;
9325 for k_idx in 0..max_seq_len {
9326 if k_idx > abs_q || k_idx + window <= abs_q {
9328 mask_data[q_idx * max_seq_len + k_idx] = f32::NEG_INFINITY;
9329 }
9330 }
9331 }
9332 mask_data
9333}
9334
9335#[cfg(test)]
9336mod decode_mask_tests {
9337 use super::{build_decode_causal_mask, build_decode_causal_mask_windowed};
9338
9339 fn attendable(row: &[f32]) -> Vec<u8> {
9342 row.iter().map(|&v| u8::from(v == 0.0)).collect()
9343 }
9344
9345 #[test]
9352 fn windowed_mask_excludes_positions_older_than_the_window() {
9353 let m = build_decode_causal_mask_windowed(3, 1, 6, 2);
9354 assert_eq!(
9355 attendable(&m),
9356 vec![0, 0, 1, 1, 0, 0],
9357 "window=2 at absolute position 3 must attend to exactly {{2, 3}}",
9358 );
9359 }
9360
9361 #[test]
9366 fn windowed_mask_offsets_each_row_by_cached_len() {
9367 let m = build_decode_causal_mask_windowed(1, 2, 5, 2);
9368 assert_eq!(
9369 attendable(&m[0..5]),
9370 vec![1, 1, 0, 0, 0],
9371 "row 0 = abs pos 1"
9372 );
9373 assert_eq!(
9374 attendable(&m[5..10]),
9375 vec![0, 1, 1, 0, 0],
9376 "row 1 = abs pos 2"
9377 );
9378 }
9379
9380 #[test]
9389 fn window_wider_than_capacity_is_byte_identical_to_the_dense_mask() {
9390 for (cached_len, seq, max_seq_len) in [(0, 1, 8), (3, 1, 8), (0, 4, 8), (2, 3, 8)] {
9391 let dense = build_decode_causal_mask(cached_len, seq, max_seq_len);
9392 let windowed =
9393 build_decode_causal_mask_windowed(cached_len, seq, max_seq_len, max_seq_len);
9394 assert_eq!(
9395 dense, windowed,
9396 "window == max_seq_len must equal dense at \
9397 (cached_len={cached_len}, seq={seq}, max_seq_len={max_seq_len})",
9398 );
9399 }
9400 }
9401
9402 #[test]
9411 fn decode_row_matches_the_prefill_mask_row_at_the_same_position() {
9412 let (n, window, max_seq_len) = (6_usize, 3_usize, 10_usize);
9413
9414 let mut prefill = vec![0.0_f32; n * n];
9416 for i in 0..n {
9417 for j in 0..n {
9418 if j > i || j + window <= i {
9419 prefill[i * n + j] = f32::NEG_INFINITY;
9420 }
9421 }
9422 }
9423
9424 for p in 0..n {
9425 let decode = build_decode_causal_mask_windowed(p, 1, max_seq_len, window);
9426 assert_eq!(
9427 attendable(&decode[0..n]),
9428 attendable(&prefill[p * n..(p + 1) * n]),
9429 "decode at cached_len={p} must match prefill row {p}",
9430 );
9431 assert!(
9432 decode[n..].iter().all(|&v| v == f32::NEG_INFINITY),
9433 "the unwritten tail beyond position {n} must stay masked",
9434 );
9435 }
9436 }
9437
9438 }
9479
9480pub fn flash_window_bounds(window: Option<usize>) -> (Option<usize>, Option<usize>) {
9518 match window {
9519 None => (None, None),
9520 Some(w) => (Some(w.saturating_sub(1)), Some(0)),
9521 }
9522}
9523
9524pub fn offer_flash_decode_arm_for_region(
9529 graph: &fuel_graph::SharedGraph,
9530 q: fuel_graph::NodeId,
9531 k: fuel_graph::NodeId,
9532 v: fuel_graph::NodeId,
9533 decomposed_out: fuel_graph::NodeId,
9534 reconverge: fuel_graph::NodeId,
9535 softmax_scale: f32,
9536 attended_len_sym: fuel_ir::SymId,
9537 attn_window: Option<usize>,
9538 softcap: Option<f32>,
9539 cap: fuel_dispatch::decode_flash::FlashArmCapability,
9540) -> crate::Result<Option<fuel_graph::NodeId>> {
9541 use fuel_dispatch::decode_flash::{DecodeFlashSpec, offer_decode_flash_arm};
9542 let (window_size_left, window_size_right) = flash_window_bounds(attn_window);
9543 let spec = DecodeFlashSpec {
9544 q,
9545 k,
9546 v,
9547 alibi: None,
9548 softmax_scale,
9549 causal: true,
9550 window_size_left,
9557 window_size_right,
9558 softcap,
9559 k_len: fuel_ir::DynScalar::Sym(attended_len_sym),
9560 decomposed_out,
9561 reconverge,
9562 };
9563 let mut g = graph.write().map_err(|_| {
9564 fuel_ir::Error::Msg("graph lock poisoned during flash-arm offer".into()).bt()
9565 })?;
9566 offer_decode_flash_arm(&mut g, &spec, cap)
9567}
9568
9569pub fn apply_affine_rms_norm(x: &Tensor, gain: &Arc<[f32]>, dim: usize, eps: f64) -> Tensor {
9570 assert_eq!(
9571 gain.len(),
9572 dim,
9573 "apply_affine_rms_norm: gain length must equal dim"
9574 );
9575 let normalized = x.rms_norm_last_dim(eps).unwrap();
9576 let gain_t = x
9582 .const_like_dtype(gain, Shape::from_dims(&[dim]), x.dtype())
9583 .expect("apply_affine_rms_norm: activation dtype must be F32 or BF16");
9584 normalized.broadcast_mul(&gain_t).unwrap()
9585}
9586
9587pub fn load_tensor_as_f32(
9594 st: &fuel_formats::safetensors::MmapedSafetensors,
9595 name: &str,
9596) -> crate::Result<Vec<f32>> {
9597 use safetensors::Dtype;
9598 let view = st.get(name)?;
9599 let bytes = view.data();
9600 match view.dtype() {
9601 Dtype::F32 => {
9602 let mut out = Vec::with_capacity(bytes.len() / 4);
9603 for chunk in bytes.as_chunks::<4>().0.iter() {
9604 out.push(f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
9605 }
9606 Ok(out)
9607 }
9608 Dtype::F64 => {
9609 let mut out = Vec::with_capacity(bytes.len() / 8);
9610 for chunk in bytes.as_chunks::<8>().0.iter() {
9611 let arr: [u8; 8] = *chunk;
9612 out.push(f64::from_le_bytes(arr) as f32);
9613 }
9614 Ok(out)
9615 }
9616 Dtype::BF16 => {
9617 let mut out = Vec::with_capacity(bytes.len() / 2);
9618 for chunk in bytes.as_chunks::<2>().0.iter() {
9619 let raw = u16::from_le_bytes([chunk[0], chunk[1]]);
9620 out.push(half::bf16::from_bits(raw).to_f32());
9621 }
9622 Ok(out)
9623 }
9624 Dtype::F16 => {
9625 let mut out = Vec::with_capacity(bytes.len() / 2);
9626 for chunk in bytes.as_chunks::<2>().0.iter() {
9627 let raw = u16::from_le_bytes([chunk[0], chunk[1]]);
9628 out.push(half::f16::from_bits(raw).to_f32());
9629 }
9630 Ok(out)
9631 }
9632 other => {
9633 crate::bail!("load_tensor_as_f32: unsupported dtype {other:?} for tensor {name:?}",)
9634 }
9635 }
9636}
9637
9638pub fn load_transposed_matrix(
9645 st: &fuel_formats::safetensors::MmapedSafetensors,
9646 name: &str,
9647 out_features: usize,
9648 in_features: usize,
9649) -> crate::Result<Vec<f32>> {
9650 let flat = load_tensor_as_f32(st, name)?;
9651 if flat.len() != out_features * in_features {
9652 crate::bail!(
9653 "load_transposed_matrix: tensor {name:?} has {} elements, expected {} ({out_features} × {in_features})",
9654 flat.len(),
9655 out_features * in_features,
9656 );
9657 }
9658 let mut out = vec![0.0_f32; out_features * in_features];
9662 for i in 0..out_features {
9663 for j in 0..in_features {
9664 out[j * out_features + i] = flat[i * in_features + j];
9665 }
9666 }
9667 Ok(out)
9668}
9669
9670pub fn load_transposed_matrix_preserve_dtype(
9682 st: &fuel_formats::safetensors::MmapedSafetensors,
9683 name: &str,
9684 out_features: usize,
9685 in_features: usize,
9686) -> crate::Result<WeightStorage> {
9687 use safetensors::Dtype;
9688 let view = st.get(name)?;
9689 let bytes = view.data();
9690 let expected = out_features * in_features;
9691 match view.dtype() {
9692 Dtype::BF16 => {
9693 if bytes.len() != expected * 2 {
9694 crate::bail!(
9695 "load_transposed_matrix_preserve_dtype: bf16 tensor {name:?} has {} bytes, expected {}",
9696 bytes.len(),
9697 expected * 2,
9698 );
9699 }
9700 let mut out = vec![half::bf16::ZERO; expected];
9703 for i in 0..out_features {
9704 for j in 0..in_features {
9705 let src_off = (i * in_features + j) * 2;
9706 let bits = u16::from_le_bytes([bytes[src_off], bytes[src_off + 1]]);
9707 out[j * out_features + i] = half::bf16::from_bits(bits);
9708 }
9709 }
9710 Ok(WeightStorage::BF16(Arc::from(out)))
9711 }
9712 _ => {
9713 let flat = load_transposed_matrix(st, name, out_features, in_features)?;
9717 Ok(WeightStorage::F32(Arc::from(flat)))
9718 }
9719 }
9720}
9721
9722#[derive(Debug, Clone, Copy, Default)]
9724pub enum SamplingStrategy {
9725 #[default]
9727 Greedy,
9728 Temperature { temp: f32, seed: u64 },
9733}
9734
9735fn argmax_logits(logits: &[f32]) -> u32 {
9736 let (i, _) = logits
9737 .iter()
9738 .enumerate()
9739 .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
9740 .expect("sample_logits: empty logits");
9741 i as u32
9742}
9743
9744pub fn sample_logits(logits: &[f32], strategy: SamplingStrategy, rng_state: &mut u64) -> u32 {
9748 match strategy {
9749 SamplingStrategy::Greedy => argmax_logits(logits),
9750 SamplingStrategy::Temperature { temp, .. } if temp.is_nan() || temp <= 0.0 => {
9753 argmax_logits(logits)
9754 }
9755 SamplingStrategy::Temperature { temp, .. } => {
9756 let inv_temp = 1.0 / temp;
9759 let scaled: Vec<f32> = logits.iter().map(|&x| x * inv_temp).collect();
9760 let max = scaled.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
9761 let exp: Vec<f32> = scaled.iter().map(|&x| (x - max).exp()).collect();
9762 let sum: f32 = exp.iter().sum();
9763 let probs: Vec<f32> = exp.iter().map(|&x| x / sum).collect();
9764 sample_multinomial(&probs, rng_state)
9765 }
9766 }
9767}
9768
9769pub fn spec_argmax(logits: &[f32]) -> u32 {
9777 let mut best = 0;
9778 let mut best_v = logits[0];
9779 for (i, &v) in logits.iter().enumerate().skip(1) {
9780 if v > best_v {
9781 best_v = v;
9782 best = i;
9783 }
9784 }
9785 best as u32
9786}
9787
9788pub fn spec_softmax_temp(logits: &[f32], temp: f32) -> Vec<f32> {
9790 let inv_t = if temp == 0.0 { 1.0 } else { 1.0 / temp };
9791 let max = logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
9792 let exp: Vec<f32> = logits.iter().map(|&x| ((x - max) * inv_t).exp()).collect();
9793 let sum: f32 = exp.iter().sum();
9794 exp.iter().map(|&x| x / sum).collect()
9795}
9796
9797pub fn spec_next_u01(state: &mut u64) -> f32 {
9799 *state = state
9800 .wrapping_mul(6364136223846793005)
9801 .wrapping_add(1442695040888963407);
9802 (*state >> 32) as f32 / u32::MAX as f32
9803}
9804
9805pub fn spec_sample_cat(probs: &[f32], state: &mut u64) -> u32 {
9807 let u = spec_next_u01(state);
9808 let mut cum = 0.0_f32;
9809 for (i, &p) in probs.iter().enumerate() {
9810 cum += p;
9811 if u <= cum {
9812 return i as u32;
9813 }
9814 }
9815 (probs.len() - 1) as u32
9816}
9817
9818pub fn sample_multinomial(probs: &[f32], rng_state: &mut u64) -> u32 {
9822 *rng_state = rng_state
9824 .wrapping_mul(6364136223846793005)
9825 .wrapping_add(1442695040888963407);
9826 let u = (*rng_state >> 32) as f32 / u32::MAX as f32;
9827 let mut cumulative = 0.0_f32;
9828 for (i, &p) in probs.iter().enumerate() {
9829 cumulative += p;
9830 if u <= cumulative {
9831 return i as u32;
9832 }
9833 }
9834 (probs.len() - 1) as u32
9836}
9837
9838#[cfg(test)]
9839mod lora_tests {
9840 use super::*;
9841 use crate::Shape;
9842
9843 #[test]
9844 fn with_lora_matches_manual_base_plus_lora() {
9845 let in_f = 4;
9847 let out_f = 3;
9848 let rank = 2;
9849 let alpha = 8.0_f32;
9850
9851 let anchor =
9852 Tensor::from_f32(vec![0.0_f32; 1], Shape::from_dims(&[1]), &Device::cpu()).unwrap();
9853 let base_vec: Vec<f32> = (0..in_f * out_f).map(|i| (i as f32) * 0.1).collect();
9855 let lora_a_vec: Vec<f32> = (0..in_f * rank).map(|i| (i as f32) * 0.05).collect();
9856 let lora_b_vec: Vec<f32> = (0..rank * out_f).map(|i| (i as f32) * 0.02).collect();
9857
9858 let ws = WeightStorage::F32(Arc::from(base_vec.clone())).with_lora(
9859 Arc::from(lora_a_vec.clone()),
9860 Arc::from(lora_b_vec.clone()),
9861 rank,
9862 alpha,
9863 in_f,
9864 out_f,
9865 );
9866
9867 let batch = 2;
9869 let x_data: Vec<f32> = (0..batch * in_f).map(|i| (i as f32) * 0.1 + 0.5).collect();
9870 let x = anchor
9871 .const_f32_like(x_data.clone(), Shape::from_dims(&[batch, in_f]))
9872 .unwrap();
9873 let y = ws.apply_linear(&x, in_f, out_f).unwrap();
9874 let got = y.realize_f32().to_vec();
9875
9876 let mut expected = vec![0.0_f32; batch * out_f];
9878 for b in 0..batch {
9879 for j in 0..out_f {
9880 let mut acc = 0.0_f32;
9881 for k in 0..in_f {
9883 acc += x_data[b * in_f + k] * base_vec[k * out_f + j];
9884 }
9885 let scale = alpha as f64 / rank as f64;
9887 for r in 0..rank {
9888 let mut xar = 0.0_f32;
9889 for k in 0..in_f {
9890 xar += x_data[b * in_f + k] * lora_a_vec[k * rank + r];
9891 }
9892 acc += (xar * lora_b_vec[r * out_f + j]) * scale as f32;
9893 }
9894 expected[b * out_f + j] = acc;
9895 }
9896 }
9897
9898 for (i, (&e, &g)) in expected.iter().zip(got.iter()).enumerate() {
9899 let diff = (e - g).abs();
9900 assert!(
9901 diff <= 1e-4,
9902 "LoRA mismatch at {i}: expected {e}, got {g} (diff {diff})",
9903 );
9904 }
9905 }
9906
9907 #[test]
9908 #[should_panic(expected = "lora_a length")]
9909 fn with_lora_rejects_mismatched_a_shape() {
9910 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);
9914 }
9915
9916 #[test]
9928 fn apply_linear_errors_on_trailing_dim_mismatch() {
9929 let ws = WeightStorage::F32(Arc::from(vec![0.0_f32; 12])); let x = Tensor::from_f32(
9931 vec![0.0_f32; 10],
9932 Shape::from_dims(&[2, 5]), &Device::cpu(),
9934 )
9935 .unwrap();
9936 let err = ws
9937 .apply_linear(&x, 4, 3)
9938 .expect_err("must not panic, must Err");
9939 let msg = err.to_string();
9940 assert!(
9941 msg.contains("trailing dim 4"),
9942 "error should name the expected trailing dim, got: {msg}",
9943 );
9944 }
9945
9946 #[test]
9947 fn apply_linear_errors_on_q4_0_stored_shape_mismatch() {
9948 let ws = WeightStorage::Q4_0 {
9951 words: Arc::from(vec![0_u32; 8]),
9952 bytes_len: 18, in_features: 4,
9954 out_features: 4,
9955 };
9956 let x =
9957 Tensor::from_f32(vec![0.0_f32; 8], Shape::from_dims(&[2, 4]), &Device::cpu()).unwrap();
9958 let err = ws
9961 .apply_linear(&x, 4, 7)
9962 .expect_err("must not panic, must Err");
9963 let msg = err.to_string();
9964 assert!(
9965 msg.contains("Q4_0 shape mismatch"),
9966 "error should name the stored/requested disagreement, got: {msg}",
9967 );
9968 }
9969
9970 #[test]
9971 fn apply_linear_with_bias_errors_on_wrong_bias_length() {
9972 let ws = WeightStorage::F32(Arc::from(vec![0.0_f32; 12])); let x =
9974 Tensor::from_f32(vec![0.0_f32; 8], Shape::from_dims(&[2, 4]), &Device::cpu()).unwrap();
9975 let bias: Arc<[f32]> = Arc::from(vec![0.0_f32; 2]); let err = ws
9977 .apply_linear_with_bias(&x, 4, 3, bias)
9978 .expect_err("wrong-length bias must Err in EVERY profile, not just debug");
9979 assert!(
9980 err.to_string().contains("bias len"),
9981 "error should name the bias length, got: {err}",
9982 );
9983 }
9984}
9985
9986#[cfg(test)]
9987mod safetensors_bridge_tests {
9988 use super::*;
9989
9990 #[test]
9991 fn from_safetensors_bytes_round_trip_f32() {
9992 let original: Vec<f32> = vec![1.0, -2.5, 3.25, 0.0];
9996 let mut bytes = Vec::with_capacity(original.len() * 4);
9997 for &v in &original {
9998 bytes.extend_from_slice(&v.to_le_bytes());
9999 }
10000 let t =
10001 Tensor::from_safetensors_bytes(&bytes, safetensors::Dtype::F32, &[4], &Device::cpu())
10002 .unwrap();
10003 assert_eq!(t.shape().dims(), &[4]);
10004 assert_eq!(t.dtype(), DType::F32);
10005 assert_eq!(t.realize_f32(), original);
10006 }
10007
10008 #[test]
10009 fn from_safetensors_bytes_round_trip_bf16() {
10010 let original_f32: Vec<f32> = vec![0.5, -1.0, 2.0, 4.0];
10011 let bf16_vec: Vec<half::bf16> = original_f32
10012 .iter()
10013 .map(|&v| half::bf16::from_f32(v))
10014 .collect();
10015 let mut bytes = Vec::with_capacity(bf16_vec.len() * 2);
10016 for b in &bf16_vec {
10017 bytes.extend_from_slice(&b.to_bits().to_le_bytes());
10018 }
10019 let t =
10020 Tensor::from_safetensors_bytes(&bytes, safetensors::Dtype::BF16, &[4], &Device::cpu())
10021 .unwrap();
10022 assert_eq!(t.dtype(), DType::BF16);
10023 let realized = t.realize_bf16();
10026 assert_eq!(realized, bf16_vec);
10027 }
10028
10029 #[test]
10030 fn from_safetensors_bytes_rejects_wrong_byte_count() {
10031 let bad_bytes = vec![0_u8; 4];
10034 let result = Tensor::from_safetensors_bytes(
10035 &bad_bytes,
10036 safetensors::Dtype::F32,
10037 &[3],
10038 &Device::cpu(),
10039 );
10040 assert!(result.is_err());
10041 }
10042}
10043
10044#[cfg(test)]
10053mod phase_a1_wrapper_tests {
10054 use super::*;
10055
10056 fn cpu_f32(data: Vec<f32>, shape: &[usize]) -> Tensor {
10057 Tensor::from_f32(data, shape.to_vec(), &Device::cpu()).unwrap()
10058 }
10059
10060 #[test]
10061 fn unsqueeze_adds_size_one_dim() {
10062 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
10063 let out = t.unsqueeze(0_usize).unwrap();
10064 assert_eq!(out.shape().dims(), &[1, 2, 2]);
10065 assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0, 4.0]);
10066 }
10067
10068 #[test]
10069 fn unsqueeze_errors_out_of_bounds() {
10070 let t = cpu_f32(vec![1.0, 2.0], &[2]);
10071 assert!(t.unsqueeze(0_usize).is_ok());
10073 assert!(t.unsqueeze(1_usize).is_ok());
10074 assert!(t.unsqueeze(2_usize).is_err());
10075 }
10076
10077 #[test]
10078 fn try_reshape_errors_on_size_mismatch() {
10079 let t = cpu_f32(vec![1.0; 6], &[2, 3]);
10080 assert!(t.reshape(vec![3, 2]).is_ok());
10081 assert!(t.reshape(vec![2, 2]).is_err());
10082 }
10083
10084 #[test]
10085 fn try_permute_validates_axes() {
10086 let t = cpu_f32(vec![0.0; 24], &[2, 3, 4]);
10087 assert!(t.permute((2_usize, 0_usize, 1_usize)).is_ok());
10089 assert!(t.permute([2_usize, 0, 1]).is_ok());
10090 assert!(t.permute([0_usize, 1]).is_err()); assert!(t.permute([0_usize, 0, 1]).is_err()); }
10093
10094 #[test]
10095 fn try_transpose_requires_rank_two_plus() {
10096 let scalar = cpu_f32(vec![1.0], &[1]);
10097 let _ = scalar.transpose();
10099 }
10100
10101 #[test]
10102 fn triu_tril_shape_preserved() {
10103 let t = cpu_f32(vec![1.0; 9], &[3, 3]);
10104 let upper = t.triu(0).unwrap();
10105 let lower = t.tril(0).unwrap();
10106 assert_eq!(upper.shape().dims(), &[3, 3]);
10107 assert_eq!(lower.shape().dims(), &[3, 3]);
10108 assert_eq!(
10110 lower.realize_f32(),
10111 vec![1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0]
10112 );
10113 }
10114
10115 #[test]
10116 fn triu_rejects_rank_one() {
10117 let t = cpu_f32(vec![1.0, 2.0], &[2]);
10118 assert!(t.triu(0).is_err());
10119 }
10120
10121 #[test]
10122 fn log_softmax_last_dim_shape_preserved() {
10123 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
10124 let out = t.log_softmax_last_dim().unwrap();
10125 assert_eq!(out.shape().dims(), &[2, 2]);
10126 for v in out.realize_f32() {
10128 assert!(v <= 0.0 + 1e-6, "log_softmax produced positive value: {v}");
10129 }
10130 }
10131
10132 #[test]
10133 fn softmax_general_axis_matches_hand_computed_rank3_middle_axis() {
10134 let data: Vec<f32> = vec![
10143 -1.0, 0.0, 0.0, -3.0, -2.0, -1.0, -2.0, -1.0, -1.0, -1.0, 0.0, 0.0, ];
10152 let t = cpu_f32(data, &[2, 3, 2]);
10153 let out = t.softmax(1_usize).unwrap();
10154 assert_eq!(out.shape().dims(), &[2, 3, 2]);
10155 let v = out.realize_f32();
10156
10157 let lane_softmax = |xs: [f32; 3]| -> [f32; 3] {
10159 let m = xs.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
10160 let exps = [(xs[0] - m).exp(), (xs[1] - m).exp(), (xs[2] - m).exp()];
10161 let s = exps[0] + exps[1] + exps[2];
10162 [exps[0] / s, exps[1] / s, exps[2] / s]
10163 };
10164 let lanes: [[f32; 3]; 4] = [
10166 [-1.0, 0.0, -2.0], [0.0, -3.0, -1.0], [-2.0, -1.0, 0.0], [-1.0, -1.0, 0.0], ];
10171 let refs: Vec<[f32; 3]> = lanes.iter().map(|l| lane_softmax(*l)).collect();
10172
10173 for b in 0..2 {
10175 for c in 0..2 {
10176 let lane_ix = b * 2 + c;
10177 for r in 0..3 {
10178 let got = v[b * 6 + r * 2 + c];
10179 let want = refs[lane_ix][r];
10180 assert!(
10181 (got - want).abs() < 1e-6,
10182 "softmax mismatch at (b={b}, r={r}, c={c}): got {got}, want {want}",
10183 );
10184 }
10185 let sum: f32 = (0..3).map(|r| v[b * 6 + r * 2 + c]).sum();
10187 assert!((sum - 1.0).abs() < 1e-6, "lane (b={b},c={c}) sums to {sum}");
10188 }
10189 }
10190 }
10191
10192 #[test]
10193 fn softmax_last_axis_matches_softmax_last_dim() {
10194 let data: Vec<f32> = vec![
10195 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,
10197 ];
10198 let t = cpu_f32(data, &[2, 2, 4]);
10199 let via_general = t.softmax(2_usize).unwrap();
10200 let via_fused = t.softmax_last_dim().unwrap();
10201 assert_eq!(via_general.shape().dims(), via_fused.shape().dims());
10202 let g = via_general.realize_f32();
10203 let f = via_fused.realize_f32();
10204 assert_eq!(g.len(), f.len());
10205 for (i, (a, b)) in g.iter().zip(f.iter()).enumerate() {
10206 assert!(
10207 (a - b).abs() < 1e-6,
10208 "softmax (general axis=2) vs softmax_last_dim diverge at {i}: {a} vs {b}",
10209 );
10210 }
10211 }
10212
10213 #[test]
10214 fn log_softmax_general_axis_matches_hand_computed_rank3_middle_axis() {
10215 let data: Vec<f32> = vec![
10218 -1.0, 0.0, 0.0, -3.0, -2.0, -1.0, -2.0, -1.0, -1.0, -1.0, 0.0, 0.0,
10219 ];
10220 let t = cpu_f32(data, &[2, 3, 2]);
10221 let out = t.log_softmax(1_usize).unwrap();
10222 assert_eq!(out.shape().dims(), &[2, 3, 2]);
10223 let v = out.realize_f32();
10224
10225 let lane_log_softmax = |xs: [f32; 3]| -> [f32; 3] {
10226 let m = xs.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
10227 let shifted = [xs[0] - m, xs[1] - m, xs[2] - m];
10228 let lse = (shifted[0].exp() + shifted[1].exp() + shifted[2].exp()).ln();
10229 [shifted[0] - lse, shifted[1] - lse, shifted[2] - lse]
10230 };
10231 let lanes: [[f32; 3]; 4] = [
10232 [-1.0, 0.0, -2.0],
10233 [0.0, -3.0, -1.0],
10234 [-2.0, -1.0, 0.0],
10235 [-1.0, -1.0, 0.0],
10236 ];
10237 let refs: Vec<[f32; 3]> = lanes.iter().map(|l| lane_log_softmax(*l)).collect();
10238
10239 for b in 0..2 {
10240 for c in 0..2 {
10241 let lane_ix = b * 2 + c;
10242 for r in 0..3 {
10243 let got = v[b * 6 + r * 2 + c];
10244 let want = refs[lane_ix][r];
10245 assert!(
10246 (got - want).abs() < 1e-6,
10247 "log_softmax mismatch at (b={b}, r={r}, c={c}): got {got}, want {want}",
10248 );
10249 assert!(got <= 1e-6, "log_softmax produced positive value: {got}");
10251 }
10252 }
10253 }
10254 }
10255
10256 #[test]
10257 fn log_softmax_last_axis_matches_log_softmax_last_dim() {
10258 let data: Vec<f32> = vec![
10259 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,
10260 ];
10261 let t = cpu_f32(data, &[2, 2, 4]);
10262 let via_general = t.log_softmax(2_usize).unwrap();
10263 let via_fused = t.log_softmax_last_dim().unwrap();
10264 assert_eq!(via_general.shape().dims(), via_fused.shape().dims());
10265 let g = via_general.realize_f32();
10266 let f = via_fused.realize_f32();
10267 assert_eq!(g.len(), f.len());
10268 for (i, (a, b)) in g.iter().zip(f.iter()).enumerate() {
10269 assert!(
10270 (a - b).abs() < 1e-6,
10271 "log_softmax (general axis=2) vs log_softmax_last_dim diverge at {i}: {a} vs {b}",
10272 );
10273 }
10274 }
10275
10276 #[test]
10277 fn argmin_dim_drops_reduced_axis() {
10278 let t = cpu_f32(vec![3.0, 1.0, 2.0, 0.5, 5.0, 4.0], &[2, 3]);
10279 let out = t.argmin_dim(1_usize).unwrap();
10280 assert_eq!(out.shape().dims(), &[2]);
10281 assert_eq!(out.dtype(), DType::U32);
10282 assert_eq!(out.realize_u32(), vec![1, 0]);
10283 }
10284
10285 #[test]
10286 fn masked_fill_smoke() {
10287 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
10288 let probe = t
10291 .const_f32_like(vec![0.0, 1.0, 1.0, 0.0], vec![2, 2])
10292 .unwrap();
10293 let threshold = t.const_f32_like(vec![0.5; 4], vec![2, 2]).unwrap();
10294 let mask = probe.gt(&threshold).unwrap(); let out = t.masked_fill(&mask, fuel_ir::Scalar::F32(-9.0)).unwrap();
10296 assert_eq!(out.realize_f32(), vec![1.0, -9.0, -9.0, 4.0]);
10297 }
10298
10299 #[test]
10305 fn bool_is_distinguishable_from_u8_end_to_end() {
10306 let t = cpu_f32(vec![0.0, 5.0, 3.0, 0.0], &[4]);
10311 let thr = t.const_f32_like(vec![0.5; 4], vec![4]).unwrap();
10312 let mask = t.gt(&thr).unwrap();
10313 assert_eq!(mask.dtype(), DType::Bool, "gt yields Bool, not U8");
10314 assert_eq!(mask.realize_u8(), vec![0, 1, 1, 0], "mask bytes are 0/1");
10315
10316 let u8_vals = t
10323 .const_f32_like(vec![0.0, 5.0, 3.0, 0.0], vec![4])
10324 .unwrap()
10325 .to_dtype(DType::U8)
10326 .unwrap();
10327 assert_eq!(u8_vals.dtype(), DType::U8);
10328 assert_eq!(
10329 u8_vals.realize_u8(),
10330 vec![0, 5, 3, 0],
10331 "negative control: the U8 source must really hold 5 and 3, else the \
10332 conversion assertion below cannot discriminate"
10333 );
10334
10335 let as_bool = u8_vals.to_dtype(DType::Bool).unwrap();
10339 assert_eq!(as_bool.dtype(), DType::Bool);
10340 assert_eq!(
10341 as_bool.realize_u8(),
10342 vec![0, 1, 1, 0],
10343 "U8->Bool must CONVERT (5 -> 1), not reinterpret (5 -> 5)"
10344 );
10345
10346 assert_eq!(
10348 as_bool.to_dtype(DType::F32).unwrap().realize_f32(),
10349 vec![0.0, 1.0, 1.0, 0.0],
10350 "Bool->F32 yields 0.0/1.0"
10351 );
10352 assert_eq!(
10355 mask.to_dtype(DType::U8).unwrap().realize_u8(),
10356 vec![0, 1, 1, 0]
10357 );
10358
10359 let err = t.masked_fill(&u8_vals, fuel_ir::Scalar::F32(-9.0));
10364 assert!(
10365 err.is_err(),
10366 "a U8 mask must be REJECTED by masked_fill — Bool and U8 are \
10367 byte-identical, so accepting it would 'work' and erase the distinction"
10368 );
10369 }
10370
10371 #[test]
10385 fn float_to_bool_lowering_preserves_ieee_semantics() {
10386 let t = cpu_f32(
10387 vec![
10388 0.0,
10389 -0.0,
10390 5.0,
10391 -3.0,
10392 f32::NAN,
10393 f32::INFINITY,
10394 f32::NEG_INFINITY,
10395 ],
10396 &[7],
10397 );
10398 let b = t.to_dtype(DType::Bool).unwrap();
10399 assert_eq!(b.dtype(), DType::Bool, "to_dtype(Bool) still yields Bool");
10400 assert_eq!(
10401 b.realize_u8(),
10402 vec![0, 0, 1, 1, 1, 1, 1],
10403 "0 and -0.0 are false; every other value including NaN and both \
10404 infinities is true",
10405 );
10406 }
10407
10408 #[test]
10409 fn index_add_smoke() {
10410 let base = cpu_f32(vec![1.0, 1.0, 1.0, 1.0], &[2, 2]);
10411 let src = base
10412 .const_f32_like(vec![10.0, 20.0, 30.0, 40.0], vec![2, 2])
10413 .unwrap();
10414 let indices = base.const_u32_like(vec![0_u32, 0_u32], vec![2]).unwrap();
10415 let out = base.index_add(0, &indices, &src).unwrap();
10416 assert_eq!(out.shape().dims(), &[2, 2]);
10417 let v = out.realize_f32();
10419 assert_eq!(v[0], 41.0); assert_eq!(v[1], 61.0); assert_eq!(v[2], 1.0);
10422 assert_eq!(v[3], 1.0);
10423 }
10424
10425 #[test]
10426 fn scatter_add_smoke() {
10427 let base = cpu_f32(vec![0.0, 0.0, 0.0, 0.0], &[2, 2]);
10428 let src = base
10429 .const_f32_like(vec![5.0, 6.0, 7.0, 8.0], vec![2, 2])
10430 .unwrap();
10431 let indices = base
10432 .const_u32_like(vec![0_u32, 1_u32, 1_u32, 0_u32], vec![2, 2])
10433 .unwrap();
10434 let out = base.scatter_add(0, &indices, &src).unwrap();
10435 assert_eq!(out.shape().dims(), &[2, 2]);
10436 }
10437
10438 #[test]
10439 fn inplace_activations_compile_and_run() {
10440 let t = cpu_f32(vec![-1.0, 0.5, -3.0, 2.0], &[4]);
10441 let r = cpu_f32(vec![-1.0, 0.5, -3.0, 2.0], &[4]).relu_inplace();
10443 let _ = cpu_f32(vec![-1.0, 0.5, -3.0, 2.0], &[4]).silu_inplace();
10444 let _ = cpu_f32(vec![-1.0, 0.5, -3.0, 2.0], &[4]).gelu_tanh_inplace();
10445 let _ = cpu_f32(vec![-1.0, 0.5, -3.0, 2.0], &[4]).tanh_inplace();
10446 let _ = cpu_f32(vec![-1.0, 0.5, -3.0, 2.0], &[4]).sigmoid_inplace();
10447 let _ = t.affine_inplace(2.0, 1.0);
10448 let v = r.realize_f32();
10450 assert_eq!(v, vec![0.0, 0.5, 0.0, 2.0]);
10451 }
10452
10453 #[test]
10454 fn const_f64_like_round_trips() {
10455 let anchor = cpu_f32(vec![0.0], &[1]);
10456 let t = anchor.const_f64_like(vec![1.5, 2.5, 3.5], vec![3]).unwrap();
10457 assert_eq!(t.shape().dims(), &[3]);
10458 assert_eq!(t.dtype(), DType::F64);
10459 assert_eq!(t.realize_f64(), vec![1.5, 2.5, 3.5]);
10460 }
10461
10462 #[test]
10463 fn const_i64_like_round_trips() {
10464 let anchor = cpu_f32(vec![0.0], &[1]);
10465 let t = anchor.const_i64_like(vec![-1_i64, 2, -3], vec![3]).unwrap();
10466 assert_eq!(t.shape().dims(), &[3]);
10467 assert_eq!(t.dtype(), DType::I64);
10468 }
10469
10470 #[test]
10471 fn on_device_smoke_cpu() {
10472 let t = cpu_f32(vec![1.0, 2.0], &[2]);
10473 let pinned = t.on_device(&Device::cpu());
10474 assert_eq!(pinned.realize_f32(), vec![1.0, 2.0]);
10475 }
10476
10477 #[test]
10478 fn copy_to_device_same_device_round_trips() {
10479 let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
10480 let copied = t.copy_to_device(&Device::cpu());
10481 assert_eq!(copied.realize_f32(), vec![1.0, 2.0, 3.0]);
10482 }
10483}
10484
10485#[cfg(test)]
10489mod phase_a2_composite_tests {
10490 use super::*;
10491
10492 fn cpu_f32(data: Vec<f32>, shape: &[usize]) -> Tensor {
10493 Tensor::from_f32(data, shape.to_vec(), &Device::cpu()).unwrap()
10494 }
10495
10496 #[test]
10497 fn transpose_last_two_swaps_last_two_dims() {
10498 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
10499 let out = t.transpose_last_two().unwrap();
10500 assert_eq!(out.shape().dims(), &[3, 2]);
10501 assert_eq!(out.realize_f32(), vec![1.0, 4.0, 2.0, 5.0, 3.0, 6.0]);
10502 }
10503
10504 #[test]
10505 fn t_is_alias_of_transpose_last_two() {
10506 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
10507 assert_eq!(
10508 t.t().unwrap().realize_f32(),
10509 t.transpose_last_two().unwrap().realize_f32()
10510 );
10511 }
10512
10513 #[test]
10514 fn transpose_dims_swaps_arbitrary_axes() {
10515 let t = cpu_f32((0..24).map(|i| i as f32).collect(), &[2, 3, 4]);
10516 let out = t.transpose_dims(0, 2).unwrap();
10517 assert_eq!(out.shape().dims(), &[4, 3, 2]);
10518 }
10519
10520 #[test]
10521 fn transpose_dims_identity_when_same_axis() {
10522 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
10523 let out = t.transpose_dims(0, 0).unwrap();
10524 assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0, 4.0]);
10525 }
10526
10527 #[test]
10528 fn transpose_dims_errors_out_of_bounds() {
10529 let t = cpu_f32(vec![0.0; 6], &[2, 3]);
10530 assert!(t.transpose_dims(0, 2).is_err());
10531 assert!(t.transpose_dims(5, 0).is_err());
10532 }
10533
10534 #[test]
10535 fn flatten_merges_middle_dims() {
10536 let t = cpu_f32(vec![0.0; 24], &[2, 3, 4]);
10537 let out = t.flatten(0, 1).unwrap();
10538 assert_eq!(out.shape().dims(), &[6, 4]);
10539 }
10540
10541 #[test]
10542 fn flatten_to_merges_leading_dims() {
10543 let t = cpu_f32(vec![0.0; 24], &[2, 3, 4]);
10544 let out = t.flatten_to(1).unwrap();
10545 assert_eq!(out.shape().dims(), &[6, 4]);
10546 }
10547
10548 #[test]
10549 fn flatten_from_merges_trailing_dims() {
10550 let t = cpu_f32(vec![0.0; 24], &[2, 3, 4]);
10551 let out = t.flatten_from(1).unwrap();
10552 assert_eq!(out.shape().dims(), &[2, 12]);
10553 }
10554
10555 #[test]
10556 fn flatten_all_produces_rank_one() {
10557 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
10558 let out = t.flatten_all().unwrap();
10559 assert_eq!(out.shape().dims(), &[6]);
10560 assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
10561 }
10562
10563 #[test]
10573 fn rope_batched_matches_single_position_rope_row_by_row() {
10574 let lcg = |n: usize, seed: u32| -> Vec<f32> {
10575 let mut s = seed;
10576 (0..n)
10577 .map(|_| {
10578 s = s.wrapping_mul(1103515245).wrapping_add(12345);
10579 ((s >> 16) as u16 as f32 / 65535.0 - 0.5) * 0.5
10580 })
10581 .collect()
10582 };
10583 let (b, heads, hd) = (3usize, 4usize, 8usize);
10584 let base = 10000.0f64;
10585 let positions = [0usize, 7, 3];
10586
10587 let x_data = lcg(b * heads * hd, 11);
10588 let x = cpu_f32(x_data.clone(), &[b, heads, 1, hd]);
10589 let (cos, sin) = x.rope_tables_const_batched(base, &positions, hd);
10590 let got = x.rope_batched(&cos, &sin).unwrap().realize_f32();
10591
10592 let per_row = heads * hd;
10593 for (row, &pos) in positions.iter().enumerate() {
10594 let row_data = x_data[row * per_row..(row + 1) * per_row].to_vec();
10595 let xr = cpu_f32(row_data, &[1, heads, 1, hd]);
10596 let (c, s) = xr.rope_tables_const(base, pos, 1, hd);
10597 let want = xr
10598 .rope_with_tables_decomposed(&c, &s)
10599 .unwrap()
10600 .realize_f32();
10601 assert_eq!(
10602 &got[row * per_row..(row + 1) * per_row],
10603 &want[..],
10604 "row {row} (position {pos}) != decomposed RoPE at that position",
10605 );
10606 }
10607
10608 let shared = [positions[0]; 3];
10613 let (c0, s0) = x.rope_tables_const_batched(base, &shared, hd);
10614 let wrong = x.rope_batched(&c0, &s0).unwrap().realize_f32();
10615 for (row, &pos) in positions.iter().enumerate().skip(1) {
10616 assert_ne!(
10617 &wrong[row * per_row..(row + 1) * per_row],
10618 &got[row * per_row..(row + 1) * per_row],
10619 "CONTROL: row {row} at shared position 0 matched its own position \
10620 {pos} — per-row RoPE not applied, or comparison blind to it",
10621 );
10622 }
10623 }
10624
10625 #[test]
10626 fn flatten_errors_on_bad_range() {
10627 let t = cpu_f32(vec![0.0; 6], &[2, 3]);
10628 assert!(t.flatten(0, 5).is_err());
10629 assert!(t.flatten(2, 1).is_err()); }
10631
10632 #[test]
10633 fn split_heads_then_merge_heads_round_trip() {
10634 let x = cpu_f32((0..12).map(|i| i as f32).collect(), &[1, 2, 6]);
10636 let split = x.split_heads(2, 3).unwrap();
10637 assert_eq!(split.shape().dims(), &[1, 2, 2, 3]);
10638 let merged = split.merge_heads().unwrap();
10639 assert_eq!(merged.shape().dims(), &[1, 2, 6]);
10640 let m = merged.realize_f32();
10641 let original = x.realize_f32();
10642 for (a, b) in m.iter().zip(original.iter()) {
10643 assert!((a - b).abs() < 1e-7, "{a} vs {b}");
10644 }
10645 }
10646
10647 #[test]
10648 fn rope_tables_const_shapes_and_anchoring() {
10649 let anchor = cpu_f32(vec![0.0_f32; 8], &[1, 4, 2]);
10650 let (cos, sin) = anchor.rope_tables_const(10_000.0, 0, 4, 8);
10651 assert_eq!(cos.shape().dims(), &[4, 8]);
10652 assert_eq!(sin.shape().dims(), &[4, 8]);
10653 let cv = cos.realize_f32();
10655 let sv = sin.realize_f32();
10656 for i in 0..8 {
10658 assert!((cv[i] - 1.0).abs() < 1e-5, "cos[0,{i}] = {}", cv[i]);
10659 assert!(sv[i].abs() < 1e-5, "sin[0,{i}] = {}", sv[i]);
10660 }
10661 }
10662
10663 #[test]
10664 fn embed_tokens_shape_and_lookup() {
10665 let vocab_size = 5;
10668 let hidden = 3;
10669 let table: Vec<f32> = (0..vocab_size)
10670 .flat_map(|i| vec![i as f32, i as f32 + 0.5, i as f32 + 1.0])
10671 .collect();
10672 let tokens = vec![1_u32, 3, 0];
10673 let out = Tensor::embed_tokens(
10674 std::sync::Arc::from(table),
10675 vocab_size,
10676 hidden,
10677 &tokens,
10678 &crate::Device::cpu(),
10679 )
10680 .unwrap();
10681 assert_eq!(out.shape().dims(), &[1, 3, hidden]);
10682 let v = out.realize_f32();
10683 let want = [
10684 1.0_f32, 1.5, 2.0, 3.0, 3.5, 4.0, 0.0, 0.5, 1.0, ];
10688 for (i, (&got, &exp)) in v.iter().zip(want.iter()).enumerate() {
10689 assert!((got - exp).abs() < 1e-5, "row {i}: got={got} want={exp}");
10690 }
10691 }
10692
10693 #[test]
10694 fn embed_tokens_anchored_lives_on_receiver_graph() {
10695 let vocab_size = 4;
10699 let hidden = 2;
10700 let table: Vec<f32> = (0..vocab_size)
10701 .flat_map(|i| vec![i as f32, i as f32 * 2.0])
10702 .collect();
10703 let table_arc: std::sync::Arc<[f32]> = std::sync::Arc::from(table);
10704 let tokens = vec![2_u32, 1];
10705
10706 let anchor = cpu_f32(vec![0.0_f32], &[1]);
10707 let embedded = anchor
10708 .embed_tokens_anchored(
10709 std::sync::Arc::clone(&table_arc),
10710 vocab_size,
10711 hidden,
10712 &tokens,
10713 )
10714 .unwrap();
10715 assert_eq!(embedded.shape().dims(), &[1, 2, hidden]);
10716
10717 let one_scaled = anchor
10719 .const_f32_like(std::sync::Arc::from(vec![1.0_f32]), Shape::from_dims(&[1]))
10720 .unwrap();
10721 let _ = embedded
10722 .add(
10723 &one_scaled
10724 .reshape(Shape::from_dims(&[1, 1, 1]))
10725 .unwrap()
10726 .broadcast_to(Shape::from_dims(&[1, 2, hidden]))
10727 .unwrap(),
10728 )
10729 .unwrap();
10730 let v = embedded.realize_f32();
10731 let want = [
10732 2.0_f32, 4.0, 1.0, 2.0, ];
10735 for (i, (&got, &exp)) in v.iter().zip(want.iter()).enumerate() {
10736 assert!((got - exp).abs() < 1e-5, "row {i}: got={got} want={exp}");
10737 }
10738 }
10739
10740 #[test]
10741 fn embed_tokens_empty_returns_error() {
10742 let r = Tensor::embed_tokens(
10743 std::sync::Arc::from(vec![0.0_f32]),
10744 1,
10745 1,
10746 &[],
10747 &crate::Device::cpu(),
10748 );
10749 assert!(r.is_err());
10750 }
10751
10752 #[test]
10753 fn softcap_matches_tanh_form() {
10754 let x = cpu_f32(vec![0.0_f32, 5.0, -5.0, 30.0], &[1, 4]);
10756 let capped = x.softcap(10.0).realize_f32();
10757 let expect = [0.0_f32, 4.6212, -4.6212, 9.9505];
10759 for (i, (&got, &want)) in capped.iter().zip(expect.iter()).enumerate() {
10760 assert!(
10761 (got - want).abs() < 1e-3,
10762 "softcap[{i}] got={got} want={want}"
10763 );
10764 }
10765 }
10766
10767 #[test]
10768 fn softcap_optional_none_returns_input_unchanged() {
10769 let x = cpu_f32(vec![1.0_f32, -2.0, 30.0], &[1, 3]);
10770 let out = x.softcap_optional(None).realize_f32();
10771 let expect = [1.0_f32, -2.0, 30.0];
10772 for (g, w) in out.iter().zip(expect.iter()) {
10773 assert!((g - w).abs() < 1e-6);
10774 }
10775 let out = x.softcap_optional(Some(0.0)).realize_f32();
10777 for (g, w) in out.iter().zip(expect.iter()) {
10778 assert!((g - w).abs() < 1e-6);
10779 }
10780 }
10781
10782 #[test]
10783 fn rope_partial_full_dim_matches_rope_with_tables() {
10784 let qk = cpu_f32(vec![1.0_f32; 1 * 1 * 2 * 4], &[1, 1, 2, 4]);
10786 let (cos, sin) = qk.rope_tables_const(10_000.0, 0, 2, 4);
10787 let via_partial = qk.rope_partial(&cos, &sin, 4).unwrap();
10788 let via_full = qk.rope_with_tables(&cos, &sin).unwrap();
10789 let a = via_partial.realize_f32();
10790 let b = via_full.realize_f32();
10791 for (i, (av, bv)) in a.iter().zip(b.iter()).enumerate() {
10792 assert!((av - bv).abs() < 1e-6, "{i}: {av} vs {bv}");
10793 }
10794 }
10795
10796 #[test]
10797 fn rope_partial_pass_through_suffix_unchanged() {
10798 let qk = cpu_f32(
10802 vec![
10803 1.0_f32, 2.0, 3.0, 4.0,
10805 ],
10806 &[1, 1, 1, 4],
10807 );
10808 let (cos, sin) = qk.rope_tables_const(10_000.0, 0, 1, 2);
10809 let out = qk.rope_partial(&cos, &sin, 2).unwrap().realize_f32();
10810 for (i, &v) in out.iter().enumerate() {
10811 let expect = [1.0_f32, 2.0, 3.0, 4.0][i];
10812 assert!((v - expect).abs() < 1e-6, "{i}: {v} != {expect}");
10813 }
10814 }
10815
10816 #[test]
10817 fn add_optional_trailing_bias_none_returns_input_unchanged() {
10818 let a = cpu_f32(vec![1.0_f32, 2.0, 3.0], &[1, 3]);
10819 let original = a.realize_f32();
10820 let out = a.add_optional_trailing_bias(None).unwrap();
10821 assert_eq!(out.realize_f32(), original);
10822 }
10823
10824 #[test]
10825 fn add_optional_trailing_bias_some_applies_add() {
10826 let a = cpu_f32(vec![1.0_f32, 2.0, 3.0], &[1, 3]);
10827 let bias = std::sync::Arc::<[f32]>::from(vec![10.0_f32, 20.0, 30.0]);
10828 let out = a.add_optional_trailing_bias(Some(&bias)).unwrap();
10829 assert_eq!(out.realize_f32(), vec![11.0, 22.0, 33.0]);
10830 }
10831
10832 #[test]
10833 fn add_trailing_bias_broadcasts_across_leading_dims() {
10834 let x = cpu_f32(vec![1.0_f32, 2.0, 3.0, 10.0, 20.0, 30.0], &[2, 3]);
10836 let bias = std::sync::Arc::<[f32]>::from(vec![100.0_f32, 200.0, 300.0]);
10837 let out = x.add_trailing_bias(bias).unwrap();
10838 assert_eq!(out.shape().dims(), &[2, 3]);
10839 let v = out.realize_f32();
10840 assert_eq!(v, vec![101.0, 202.0, 303.0, 110.0, 220.0, 330.0]);
10841 }
10842
10843 #[test]
10844 fn rms_norm_affine_with_offset_adds_offset_to_each_gain() {
10845 let x = cpu_f32(vec![1.0_f32, 2.0, 3.0], &[1, 3]);
10846 let gain_raw: [f32; 3] = [-0.5, 0.0, 0.5];
10847 let via_offset = x.rms_norm_affine_with_offset(&gain_raw, 1.0, 1e-6).unwrap();
10848 let gain_shifted = std::sync::Arc::<[f32]>::from(vec![0.5_f32, 1.0, 1.5]);
10849 let via_plain = x.rms_norm_affine(gain_shifted, 1e-6).unwrap();
10850 let a = via_offset.realize_f32();
10851 let b = via_plain.realize_f32();
10852 for (x, y) in a.iter().zip(b.iter()) {
10853 assert!((x - y).abs() < 1e-6, "{x} vs {y}");
10854 }
10855 }
10856
10857 #[test]
10858 fn global_avg_pool_2d_averages_spatial_dims() {
10859 let x = cpu_f32(
10863 vec![
10864 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,
10865 ],
10866 &[1, 2, 2, 3],
10867 );
10868 let out = x.global_avg_pool_2d().unwrap();
10869 assert_eq!(out.shape().dims(), &[1, 2]);
10870 let v = out.realize_f32();
10871 assert!((v[0] - 3.5).abs() < 1e-5);
10872 assert!((v[1] - 35.0).abs() < 1e-4);
10873 }
10874
10875 #[test]
10876 fn channel_affine_4d_applies_per_channel_gain_and_bias() {
10877 let x = cpu_f32(
10879 vec![
10880 1.0_f32, 2.0, 3.0, 4.0, 10.0, 20.0, 30.0, 40.0, ],
10883 &[1, 2, 2, 2],
10884 );
10885 let gain = std::sync::Arc::<[f32]>::from(vec![2.0_f32, 0.5]);
10886 let bias = std::sync::Arc::<[f32]>::from(vec![1.0_f32, -10.0]);
10887 let out = x.channel_affine_4d(gain, bias).unwrap();
10888 let v = out.realize_f32();
10889 assert_eq!(&v[0..4], &[3.0, 5.0, 7.0, 9.0]);
10891 assert_eq!(&v[4..8], &[-5.0, 0.0, 5.0, 10.0]);
10893 }
10894
10895 #[test]
10896 fn additive_causal_mask_has_strict_lower_triangle() {
10897 let anchor = cpu_f32(vec![0.0_f32], &[1]);
10898 let mask = Tensor::additive_causal_mask_like(&anchor, 4);
10899 assert_eq!(mask.shape().dims(), &[4, 4]);
10900 let v = mask.realize_f32();
10901 for i in 0..4 {
10907 for j in 0..4 {
10908 let got = v[i * 4 + j];
10909 if j > i {
10910 assert!(
10911 got.is_infinite() && got.is_sign_negative(),
10912 "above-diag (i={i}, j={j}) should be -inf, got {got}"
10913 );
10914 } else {
10915 assert_eq!(
10916 got, 0.0,
10917 "on/below-diag (i={i}, j={j}) should be 0, got {got}"
10918 );
10919 }
10920 }
10921 }
10922 }
10923
10924 #[test]
10925 fn layer_norm_affine_unit_gain_zero_bias_matches_layer_norm_last_dim() {
10926 let a = cpu_f32(vec![1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
10927 let gain = std::sync::Arc::<[f32]>::from(vec![1.0_f32; 3]);
10928 let bias = std::sync::Arc::<[f32]>::from(vec![0.0_f32; 3]);
10929 let out_affine = a.layer_norm_affine(gain, bias, 1e-5).unwrap();
10930 let out_plain = a.layer_norm_last_dim(1e-5).unwrap();
10931 let va = out_affine.realize_f32();
10932 let vp = out_plain.realize_f32();
10933 for (a, b) in va.iter().zip(vp.iter()) {
10934 assert!((a - b).abs() < 1e-5, "{a} vs {b}");
10935 }
10936 }
10937
10938 #[test]
10939 fn layer_norm_affine_applies_gain_and_bias() {
10940 let a = cpu_f32(vec![1.0_f32, 2.0, 3.0], &[1, 3]);
10941 let gain = std::sync::Arc::<[f32]>::from(vec![2.0_f32, 0.5, 1.5]);
10942 let bias = std::sync::Arc::<[f32]>::from(vec![10.0_f32, -5.0, 0.0]);
10943 let out = a.layer_norm_affine(gain, bias, 1e-5).unwrap();
10944 let v = out.realize_f32();
10945 let mean = 2.0_f32;
10947 let var = ((1.0 - mean).powi(2) + (2.0 - mean).powi(2) + (3.0 - mean).powi(2)) / 3.0;
10948 let den = (var + 1e-5_f32).sqrt();
10949 let expected = [
10950 ((1.0 - mean) / den) * 2.0 + 10.0,
10951 ((2.0 - mean) / den) * 0.5 + (-5.0),
10952 ((3.0 - mean) / den) * 1.5 + 0.0,
10953 ];
10954 for (got, want) in v.iter().zip(expected.iter()) {
10955 assert!((got - want).abs() < 1e-4, "{got} vs {want}");
10956 }
10957 }
10958
10959 #[test]
10960 fn l2_normalize_last_dim_unit_norm_per_row() {
10961 let a = cpu_f32(vec![3.0, 4.0, 0.0, 1.0, 2.0, 2.0], &[2, 3]);
10963 let out = a.l2_normalize(1_usize, 1e-12).unwrap();
10964 assert_eq!(out.shape().dims(), &[2, 3]);
10965 let v = out.realize_f32();
10966 let row0_norm = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
10967 let row1_norm = (v[3] * v[3] + v[4] * v[4] + v[5] * v[5]).sqrt();
10968 assert!((row0_norm - 1.0).abs() < 1e-5, "row 0 norm = {row0_norm}");
10969 assert!((row1_norm - 1.0).abs() < 1e-5, "row 1 norm = {row1_norm}");
10970 assert!((v[0] - 0.6).abs() < 1e-5);
10972 assert!((v[1] - 0.8).abs() < 1e-5);
10973 assert!(v[2].abs() < 1e-5);
10974 }
10975
10976 #[test]
10977 fn l2_normalize_eps_zero_works_when_nonzero() {
10978 let a = cpu_f32(vec![1.0_f32, 0.0], &[2]);
10979 let out = a.l2_normalize(0_usize, 0.0).unwrap();
10980 let v = out.realize_f32();
10981 assert!((v[0] - 1.0).abs() < 1e-6);
10982 assert!(v[1].abs() < 1e-6);
10983 }
10984
10985 #[test]
10986 fn repeat_interleave_last_dim_matches_torch_semantics() {
10987 let a = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
10991 let out = a.repeat_interleave(1_usize, 2).unwrap();
10992 assert_eq!(out.shape().dims(), &[2, 6]);
10993 assert_eq!(
10994 out.realize_f32(),
10995 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]
10996 );
10997 }
10998
10999 #[test]
11000 fn repeat_interleave_middle_dim() {
11001 let a = cpu_f32((0..8).map(|i| i as f32).collect(), &[2, 2, 2]);
11003 let out = a.repeat_interleave(1_usize, 3).unwrap();
11004 assert_eq!(out.shape().dims(), &[2, 6, 2]);
11005 let v = out.realize_f32();
11007 assert_eq!(&v[0..6], &[0.0, 1.0, 0.0, 1.0, 0.0, 1.0]);
11008 assert_eq!(&v[6..12], &[2.0, 3.0, 2.0, 3.0, 2.0, 3.0]);
11009 }
11010
11011 #[test]
11012 fn repeat_interleave_repeats_one_is_noop() {
11013 let a = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11014 let out = a.repeat_interleave(0_usize, 1).unwrap();
11015 assert_eq!(out.shape().dims(), &[3]);
11016 assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0]);
11017 }
11018
11019 #[test]
11020 fn repeat_interleave_repeats_zero_errors() {
11021 let a = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11022 assert!(a.repeat_interleave(0_usize, 0).is_err());
11023 }
11024
11025 #[test]
11026 fn stack_adds_leading_dim() {
11027 let a = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11028 let b = a.const_f32_like(vec![4.0, 5.0, 6.0], vec![3]).unwrap();
11029 let out = Tensor::stack(&[&a, &b], 0).unwrap();
11030 assert_eq!(out.shape().dims(), &[2, 3]);
11031 assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
11032 }
11033
11034 #[test]
11035 fn stack_adds_trailing_dim() {
11036 let a = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11037 let b = a.const_f32_like(vec![4.0, 5.0, 6.0], vec![3]).unwrap();
11038 let out = Tensor::stack(&[&a, &b], 1).unwrap();
11039 assert_eq!(out.shape().dims(), &[3, 2]);
11040 assert_eq!(out.realize_f32(), vec![1.0, 4.0, 2.0, 5.0, 3.0, 6.0]);
11041 }
11042
11043 #[test]
11044 fn stack_rejects_mismatched_shapes() {
11045 let a = cpu_f32(vec![1.0, 2.0], &[2]);
11046 let b = a.const_f32_like(vec![3.0, 4.0, 5.0], vec![3]).unwrap();
11047 assert!(Tensor::stack(&[&a, &b], 0).is_err());
11048 }
11049
11050 #[test]
11051 fn stack_rejects_empty_input() {
11052 let result = Tensor::stack(&[], 0);
11053 assert!(result.is_err());
11054 }
11055
11056 #[test]
11057 fn repeat_tiles_along_each_dim() {
11058 let t = cpu_f32(vec![1.0, 2.0], &[2]);
11059 let out = t.repeat(vec![3]).unwrap();
11060 assert_eq!(out.shape().dims(), &[6]);
11061 assert_eq!(out.realize_f32(), vec![1.0, 2.0, 1.0, 2.0, 1.0, 2.0]);
11062 }
11063
11064 #[test]
11065 fn repeat_extends_rank_when_needed() {
11066 let t = cpu_f32(vec![1.0, 2.0], &[2]);
11067 let out = t.repeat(vec![3, 2]).unwrap();
11069 assert_eq!(out.shape().dims(), &[3, 4]);
11070 }
11071
11072 #[test]
11073 fn repeat_identity_with_all_ones() {
11074 let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11075 let out = t.repeat(vec![1]).unwrap();
11076 assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0]);
11077 }
11078}
11079
11080#[cfg(test)]
11084mod phase_a3_keepdim_tests {
11085 use super::*;
11086
11087 fn cpu_f32(data: Vec<f32>, shape: &[usize]) -> Tensor {
11088 Tensor::from_f32(data, shape.to_vec(), &Device::cpu()).unwrap()
11089 }
11090
11091 #[test]
11092 fn sum_keepdim_preserves_dim_as_one() {
11093 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11094 let out = t.sum_keepdim(1_usize).unwrap();
11095 assert_eq!(out.shape().dims(), &[2, 1]);
11096 assert_eq!(out.realize_f32(), vec![3.0, 7.0]);
11097 }
11098
11099 #[test]
11100 fn mean_keepdim_preserves_dim_as_one() {
11101 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11102 let out = t.mean_keepdim(0_usize).unwrap();
11103 assert_eq!(out.shape().dims(), &[1, 2]);
11104 assert_eq!(out.realize_f32(), vec![2.0, 3.0]);
11105 }
11106
11107 #[test]
11108 fn max_keepdim_preserves_dim_as_one() {
11109 let t = cpu_f32(vec![1.0, 3.0, 2.0, 4.0], &[2, 2]);
11110 let out = t.max_keepdim(1_usize).unwrap();
11111 assert_eq!(out.shape().dims(), &[2, 1]);
11112 assert_eq!(out.realize_f32(), vec![3.0, 4.0]);
11113 }
11114
11115 #[test]
11116 fn min_keepdim_preserves_dim_as_one() {
11117 let t = cpu_f32(vec![1.0, 3.0, 2.0, 4.0], &[2, 2]);
11118 let out = t.min_keepdim(1_usize).unwrap();
11119 assert_eq!(out.shape().dims(), &[2, 1]);
11120 assert_eq!(out.realize_f32(), vec![1.0, 2.0]);
11121 }
11122
11123 fn var_in(dtype: &str, data: &[f64], shape: &[usize], dim: usize, correction: f64) -> Vec<f64> {
11130 let dev = Device::cpu();
11131 let s = Shape::from_dims(shape);
11132 match dtype {
11133 "f32" => Tensor::from_f32(data.iter().map(|&x| x as f32).collect::<Vec<_>>(), s, &dev)
11134 .unwrap()
11135 .var(dim, correction)
11136 .unwrap()
11137 .realize_f32()
11138 .iter()
11139 .map(|&x| x as f64)
11140 .collect(),
11141 "f64" => Tensor::from_f64(data.to_vec(), s, &dev)
11142 .unwrap()
11143 .var(dim, correction)
11144 .unwrap()
11145 .realize_f64(),
11146 "f16" => Tensor::from_f16(
11147 data.iter()
11148 .map(|&x| half::f16::from_f64(x))
11149 .collect::<Vec<_>>(),
11150 s,
11151 &dev,
11152 )
11153 .unwrap()
11154 .var(dim, correction)
11155 .unwrap()
11156 .realize_f16()
11157 .iter()
11158 .map(|x| x.to_f64())
11159 .collect(),
11160 "bf16" => Tensor::from_bf16(
11161 data.iter()
11162 .map(|&x| half::bf16::from_f64(x))
11163 .collect::<Vec<_>>(),
11164 s,
11165 &dev,
11166 )
11167 .unwrap()
11168 .var(dim, correction)
11169 .unwrap()
11170 .realize_bf16()
11171 .iter()
11172 .map(|x| x.to_f64())
11173 .collect(),
11174 other => panic!("dtype {other}"),
11175 }
11176 }
11177
11178 #[test]
11180 fn var_rejects_a_nan_correction() {
11181 let dev = Device::cpu();
11182 let x = Tensor::from_f32(vec![1.0, 3.0], Shape::from_dims(&[2]), &dev).unwrap();
11183 assert!(x.var_keepdim(0, f64::NAN).is_err());
11184 assert!(x.var_keepdim(0, 1.0).is_ok());
11186 }
11187
11188 #[test]
11189 fn var_divisor_is_clamped_at_zero_in_every_dtype() {
11190 for dt in ["f32", "f64", "f16", "bf16"] {
11191 assert!(var_in(dt, &[5.0], &[1], 0, 1.0)[0].is_nan(), "{dt} [5] c=1");
11193 let v = var_in(dt, &[5.0, 7.0], &[2, 1], 1, 1.0);
11194 assert!(v[0].is_nan() && v[1].is_nan(), "{dt} [[5],[7]] c=1: {v:?}");
11195 assert_eq!(
11197 var_in(dt, &[1.0, 3.0], &[2], 0, 2.0)[0],
11198 f64::INFINITY,
11199 "{dt} [1,3] c=2"
11200 );
11201 assert!(var_in(dt, &[5.0], &[1], 0, 2.0)[0].is_nan(), "{dt} [5] c=2");
11203 assert_eq!(
11204 var_in(dt, &[1.0, 3.0], &[2], 0, 3.0)[0],
11205 f64::INFINITY,
11206 "{dt} [1,3] c=3"
11207 );
11208 assert_eq!(var_in(dt, &[5.0], &[1], 0, 0.0)[0], 0.0, "{dt} [5] c=0");
11210 assert_eq!(
11211 var_in(dt, &[1.0, 3.0], &[2], 0, 1.0)[0],
11212 2.0,
11213 "{dt} [1,3] c=1"
11214 );
11215 }
11216 }
11217
11218 #[test]
11219 fn var_matches_unbiased_formula_with_correction_1() {
11220 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
11222 let out = t.var(1, 1.0).unwrap();
11223 assert_eq!(out.shape().dims(), &[2]);
11224 let v = out.realize_f32();
11225 assert!((v[0] - 1.0).abs() < 1e-5, "var row 0 = {} != 1.0", v[0]);
11226 assert!((v[1] - 1.0).abs() < 1e-5, "var row 1 = {} != 1.0", v[1]);
11227 }
11228
11229 #[test]
11234 fn var_population_with_correction_0() {
11235 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
11237 let out = t.var(1, 0.0).unwrap();
11238 let v = out.realize_f32();
11239 let want = 2.0 / 3.0;
11240 assert!(
11241 (v[0] - want).abs() < 1e-5,
11242 "population var row 0 = {} != {want}",
11243 v[0]
11244 );
11245 assert!(
11246 (v[1] - want).abs() < 1e-5,
11247 "population var row 1 = {} != {want}",
11248 v[1]
11249 );
11250 }
11251
11252 #[test]
11253 fn var_keepdim_preserves_dim() {
11254 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
11255 let out = t.var_keepdim(1, 1.0).unwrap();
11256 assert_eq!(out.shape().dims(), &[2, 1]);
11257 }
11258
11259 #[test]
11260 fn var_errors_out_of_bounds() {
11261 let t = cpu_f32(vec![1.0, 2.0], &[2]);
11262 assert!(t.var(3, 1.0).is_err());
11263 assert!(t.var_keepdim(3, 1.0).is_err());
11264 }
11265}
11266
11267#[cfg(test)]
11271mod phase_a4_composite_tests {
11272 use super::*;
11273
11274 fn cpu_f32(data: Vec<f32>, shape: &[usize]) -> Tensor {
11275 Tensor::from_f32(data, shape.to_vec(), &Device::cpu()).unwrap()
11276 }
11277
11278 #[test]
11279 fn affine_applies_mul_then_add() {
11280 let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11281 let out = t.affine(2.0, 10.0);
11282 assert_eq!(out.realize_f32(), vec![12.0, 14.0, 16.0]);
11283 }
11284
11285 #[test]
11286 fn scale_and_shift_alias_of_affine() {
11287 let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11288 assert_eq!(
11289 t.scale_and_shift(2.0, 10.0).realize_f32(),
11290 t.affine(2.0, 10.0).realize_f32(),
11291 );
11292 }
11293
11294 #[test]
11295 fn elu_matches_reference_values() {
11296 let t = cpu_f32(vec![1.0, 0.0, -1.0, -2.0], &[4]);
11297 let out = t.elu(1.0);
11298 let v = out.realize_f32();
11299 assert!((v[0] - 1.0).abs() < 1e-5);
11302 assert!(v[1].abs() < 1e-5);
11303 assert!((v[2] - ((-1.0_f32).exp() - 1.0)).abs() < 1e-5);
11304 assert!((v[3] - ((-2.0_f32).exp() - 1.0)).abs() < 1e-5);
11305 }
11306
11307 #[test]
11308 fn dot_of_rank_one_vectors() {
11309 let a = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11310 let b = a.const_f32_like(vec![4.0, 5.0, 6.0], vec![3]).unwrap();
11311 let out = a.dot(&b).unwrap();
11312 assert_eq!(out.shape().elem_count(), 1);
11313 let v = out.realize_f32();
11314 assert_eq!(v[0], 32.0); }
11316
11317 #[test]
11318 fn dot_rejects_non_rank_one() {
11319 let a = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11320 let b = a
11321 .const_f32_like(vec![1.0, 2.0, 3.0, 4.0], vec![2, 2])
11322 .unwrap();
11323 assert!(a.dot(&b).is_err());
11324 }
11325
11326 #[test]
11327 fn dot_rejects_length_mismatch() {
11328 let a = cpu_f32(vec![1.0, 2.0], &[2]);
11329 let b = a.const_f32_like(vec![1.0, 2.0, 3.0], vec![3]).unwrap();
11330 assert!(a.dot(&b).is_err());
11331 }
11332
11333 #[test]
11334 fn mv_matrix_times_vector() {
11335 let m = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
11336 let v = m.const_f32_like(vec![1.0, 1.0, 1.0], vec![3]).unwrap();
11337 let out = m.mv(&v).unwrap();
11338 assert_eq!(out.shape().dims(), &[2]);
11339 assert_eq!(out.realize_f32(), vec![6.0, 15.0]);
11340 }
11341
11342 #[test]
11343 fn matvec_is_mv_alias() {
11344 let m = cpu_f32(vec![1.0, 0.0, 0.0, 1.0], &[2, 2]);
11345 let v = m.const_f32_like(vec![3.0, 4.0], vec![2]).unwrap();
11346 let a = m.mv(&v).unwrap().realize_f32();
11347 let b = m.matvec(&v).unwrap().realize_f32();
11348 assert_eq!(a, b);
11349 }
11350
11351 #[test]
11352 fn mv_rejects_shape_mismatch() {
11353 let m = cpu_f32(vec![1.0; 6], &[2, 3]);
11354 let v = m.const_f32_like(vec![1.0, 1.0], vec![2]).unwrap();
11355 assert!(m.mv(&v).is_err());
11356 }
11357
11358 #[test]
11359 fn broadcast_matmul_passes_through_to_matmul() {
11360 let a = cpu_f32(vec![1.0, 0.0, 0.0, 1.0], &[2, 2]);
11361 let b = a
11362 .const_f32_like(vec![5.0, 6.0, 7.0, 8.0], vec![2, 2])
11363 .unwrap();
11364 let out = a.broadcast_matmul(&b).unwrap();
11365 assert_eq!(out.realize_f32(), vec![5.0, 6.0, 7.0, 8.0]);
11366 }
11367}
11368
11369#[cfg(test)]
11373mod phase_a5_factory_tests {
11374 use super::*;
11375
11376 fn cpu_f32(data: Vec<f32>, shape: &[usize]) -> Tensor {
11377 Tensor::from_f32(data, shape.to_vec(), &Device::cpu()).unwrap()
11378 }
11379
11380 #[test]
11381 fn ones_like_matches_shape_dtype_graph() {
11382 let t = cpu_f32(vec![5.0, 6.0, 7.0, 8.0], &[2, 2]);
11383 let ones = t.ones_like().unwrap();
11384 assert_eq!(ones.shape().dims(), t.shape().dims());
11385 assert_eq!(ones.dtype(), t.dtype());
11386 assert_eq!(ones.realize_f32(), vec![1.0; 4]);
11387 }
11388
11389 #[test]
11390 fn zeros_like_matches_shape_dtype_graph() {
11391 let t = cpu_f32(vec![5.0, 6.0, 7.0], &[3]);
11392 let zeros = t.zeros_like().unwrap();
11393 assert_eq!(zeros.realize_f32(), vec![0.0; 3]);
11394 }
11395
11396 #[test]
11397 fn static_ones_f32() {
11398 let t = Tensor::ones(vec![2, 3], DType::F32, &Device::cpu()).unwrap();
11399 assert_eq!(t.shape().dims(), &[2, 3]);
11400 assert_eq!(t.realize_f32(), vec![1.0; 6]);
11401 }
11402
11403 #[test]
11404 fn static_zeros_f64() {
11405 let t = Tensor::zeros(vec![4], DType::F64, &Device::cpu()).unwrap();
11406 assert_eq!(t.dtype(), DType::F64);
11407 assert_eq!(t.realize_f64(), vec![0.0; 4]);
11408 }
11409
11410 #[test]
11411 fn full_with_f32_scalar() {
11412 let t = Tensor::full(vec![5], fuel_ir::Scalar::F32(2.5), &Device::cpu()).unwrap();
11413 assert_eq!(t.realize_f32(), vec![2.5; 5]);
11414 }
11415
11416 #[test]
11417 fn eye_identity_matrix() {
11418 let t = Tensor::eye(3, DType::F32, &Device::cpu());
11419 assert_eq!(t.shape().dims(), &[3, 3]);
11420 assert_eq!(
11421 t.realize_f32(),
11422 vec![1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0],
11423 );
11424 }
11425
11426 #[test]
11427 fn tril2_lower_triangular_ones() {
11428 let t = Tensor::tril2(3, DType::F32, &Device::cpu());
11429 assert_eq!(
11430 t.realize_f32(),
11431 vec![1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0],
11432 );
11433 }
11434
11435 #[test]
11436 fn triu2_upper_triangular_ones() {
11437 let t = Tensor::triu2(3, DType::F32, &Device::cpu());
11438 assert_eq!(
11439 t.realize_f32(),
11440 vec![1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0],
11441 );
11442 }
11443
11444 #[test]
11445 fn meshgrid_ij_indexing_two_inputs() {
11446 let x = Tensor::from_f32(vec![1.0_f32, 2.0, 3.0], vec![3], &Device::cpu()).unwrap();
11447 let y = x.const_f32_like(vec![4.0_f32, 5.0], vec![2]).unwrap();
11448 let grids = Tensor::meshgrid(&[&x, &y], false).unwrap();
11449 assert_eq!(grids.len(), 2);
11450 assert_eq!(grids[0].shape().dims(), &[3, 2]);
11452 assert_eq!(grids[1].shape().dims(), &[3, 2]);
11453 assert_eq!(grids[0].realize_f32(), vec![1.0, 1.0, 2.0, 2.0, 3.0, 3.0]);
11455 assert_eq!(grids[1].realize_f32(), vec![4.0, 5.0, 4.0, 5.0, 4.0, 5.0]);
11457 }
11458
11459 #[test]
11460 fn meshgrid_xy_indexing_swaps_first_two() {
11461 let x = Tensor::from_f32(vec![1.0_f32, 2.0, 3.0], vec![3], &Device::cpu()).unwrap();
11462 let y = x.const_f32_like(vec![4.0_f32, 5.0], vec![2]).unwrap();
11463 let grids = Tensor::meshgrid(&[&x, &y], true).unwrap();
11464 assert_eq!(grids[0].shape().dims(), &[2, 3]);
11466 assert_eq!(grids[1].shape().dims(), &[2, 3]);
11467 assert_eq!(grids[0].realize_f32(), vec![1.0, 2.0, 3.0, 1.0, 2.0, 3.0]);
11469 assert_eq!(grids[1].realize_f32(), vec![4.0, 4.0, 4.0, 5.0, 5.0, 5.0]);
11471 }
11472
11473 #[test]
11474 fn meshgrid_rejects_single_input() {
11475 let x = Tensor::from_f32(vec![1.0_f32, 2.0], vec![2], &Device::cpu()).unwrap();
11476 assert!(Tensor::meshgrid(&[&x], false).is_err());
11477 }
11478
11479 #[test]
11480 fn meshgrid_rejects_non_rank_one() {
11481 let x = Tensor::from_f32(vec![1.0; 4], vec![2, 2], &Device::cpu()).unwrap();
11482 let y = x.const_f32_like(vec![1.0, 2.0], vec![2]).unwrap();
11483 assert!(Tensor::meshgrid(&[&x, &y], false).is_err());
11484 }
11485
11486 #[test]
11489 fn narrow_is_slice_alias() {
11490 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0], &[5]);
11491 let a = t.narrow(0, 1, 3).unwrap().realize_f32();
11492 let b = t.slice(0, 1, 3).unwrap().realize_f32();
11493 assert_eq!(a, b);
11494 assert_eq!(a, vec![2.0, 3.0, 4.0]);
11495 }
11496
11497 #[test]
11498 fn chunk_splits_evenly() {
11499 let t = cpu_f32((1..=6).map(|i| i as f32).collect(), &[6]);
11500 let parts = t.chunk(3, 0).unwrap();
11501 assert_eq!(parts.len(), 3);
11502 assert_eq!(parts[0].realize_f32(), vec![1.0, 2.0]);
11503 assert_eq!(parts[1].realize_f32(), vec![3.0, 4.0]);
11504 assert_eq!(parts[2].realize_f32(), vec![5.0, 6.0]);
11505 }
11506
11507 #[test]
11508 fn chunk_distributes_remainder_to_leading() {
11509 let t = cpu_f32((1..=7).map(|i| i as f32).collect(), &[7]);
11511 let parts = t.chunk(3, 0).unwrap();
11512 assert_eq!(parts.len(), 3);
11513 assert_eq!(parts[0].realize_f32(), vec![1.0, 2.0, 3.0]);
11514 assert_eq!(parts[1].realize_f32(), vec![4.0, 5.0]);
11515 assert_eq!(parts[2].realize_f32(), vec![6.0, 7.0]);
11516 }
11517
11518 #[test]
11519 fn chunk_returns_singletons_when_size_less_than_chunks() {
11520 let t = cpu_f32(vec![1.0, 2.0], &[2]);
11521 let parts = t.chunk(5, 0).unwrap();
11522 assert_eq!(parts.len(), 2);
11523 assert_eq!(parts[0].realize_f32(), vec![1.0]);
11524 assert_eq!(parts[1].realize_f32(), vec![2.0]);
11525 }
11526
11527 #[test]
11528 fn get_at_first_dim() {
11529 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[3, 2]);
11530 let row1 = t.get(1).unwrap();
11531 assert_eq!(row1.shape().dims(), &[2]);
11532 assert_eq!(row1.realize_f32(), vec![3.0, 4.0]);
11533 }
11534
11535 #[test]
11536 fn get_on_dim_arbitrary_axis() {
11537 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[3, 2]);
11538 let col0 = t.get_on_dim(1, 0).unwrap();
11539 assert_eq!(col0.shape().dims(), &[3]);
11540 assert_eq!(col0.realize_f32(), vec![1.0, 3.0, 5.0]);
11541 }
11542
11543 #[test]
11544 fn sum_dims_multi_dim_reduces_to_smaller() {
11545 let t = cpu_f32(vec![1.0; 24], &[2, 3, 4]);
11547 let s = t.sum_dims([0, 2_usize]).unwrap();
11548 assert_eq!(s.shape().dims(), &[3]);
11549 assert_eq!(s.realize_f32(), vec![8.0; 3]);
11551 }
11552
11553 #[test]
11554 fn mean_dims_multi_dim() {
11555 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11556 let m = t.mean_dims([0, 1_usize]).unwrap();
11557 assert_eq!(m.shape().dims(), &[] as &[usize]);
11558 assert_eq!(m.realize_f32(), vec![2.5]);
11559 }
11560
11561 #[test]
11562 fn sum_dims_keepdim_preserves_rank() {
11563 let t = cpu_f32(vec![1.0; 24], &[2, 3, 4]);
11564 let s = t.sum_dims_keepdim(&[0, 2]).unwrap();
11565 assert_eq!(s.shape().dims(), &[1, 3, 1]);
11566 }
11567
11568 #[test]
11569 fn mean_dims_keepdim_preserves_rank() {
11570 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11571 let m = t.mean_dims_keepdim(&[0, 1]).unwrap();
11572 assert_eq!(m.shape().dims(), &[1, 1]);
11573 assert_eq!(m.realize_f32(), vec![2.5]);
11574 }
11575
11576 #[test]
11577 fn rand_like_matches_shape_dtype() {
11578 let t = cpu_f32(vec![0.0; 6], &[2, 3]);
11579 let r = t.rand_like(-1.0, 1.0).unwrap();
11580 assert_eq!(r.shape().dims(), t.shape().dims());
11581 assert_eq!(r.dtype(), t.dtype());
11582 for v in r.realize_f32() {
11584 assert!((-1.0..1.0).contains(&v), "sample {v} out of [-1, 1)");
11585 }
11586 }
11587
11588 #[test]
11589 fn randn_like_matches_shape_dtype() {
11590 let t = cpu_f32(vec![0.0; 4], &[4]);
11591 let r = t.randn_like(0.0, 1.0).unwrap();
11592 assert_eq!(r.shape().dims(), &[4]);
11593 assert_eq!(r.dtype(), DType::F32);
11594 for v in r.realize_f32() {
11596 assert!(v.is_finite());
11597 }
11598 }
11599
11600 #[test]
11601 fn static_rand_f32() {
11602 let t = Tensor::rand(vec![100], 0.0, 1.0, DType::F32, &Device::cpu()).unwrap();
11603 let v = t.realize_f32();
11604 let mean: f32 = v.iter().sum::<f32>() / v.len() as f32;
11606 assert!((0.3..0.7).contains(&mean), "mean {mean} too far from 0.5");
11607 }
11608
11609 #[test]
11610 fn static_randn_f64() {
11611 let t = Tensor::randn(vec![1000], 0.0, 1.0, DType::F64, &Device::cpu()).unwrap();
11612 let v = t.realize_f64();
11613 let mean: f64 = v.iter().sum::<f64>() / v.len() as f64;
11614 assert!(mean.abs() < 0.2, "mean {mean} too far from 0");
11616 }
11617
11618 #[test]
11619 fn arange_int_step() {
11620 let t = Tensor::arange(0.0, 5.0, &Device::cpu());
11621 assert_eq!(t.shape().dims(), &[5]);
11622 assert_eq!(t.realize_f32(), vec![0.0, 1.0, 2.0, 3.0, 4.0]);
11623 }
11624
11625 #[test]
11626 fn arange_step_fractional() {
11627 let t = Tensor::arange_step(2.0, 4.0, 0.5, &Device::cpu());
11628 assert_eq!(t.realize_f32(), vec![2.0, 2.5, 3.0, 3.5]);
11629 }
11630
11631 #[test]
11632 fn arange_step_negative_descends() {
11633 let t = Tensor::arange_step(5.0, 0.0, -1.0, &Device::cpu());
11634 assert_eq!(t.realize_f32(), vec![5.0, 4.0, 3.0, 2.0, 1.0]);
11635 }
11636
11637 #[test]
11638 fn linspace_includes_endpoints() {
11639 let t = Tensor::linspace(0.0, 1.0, 5, &Device::cpu());
11640 assert_eq!(t.shape().dims(), &[5]);
11641 let v = t.realize_f32();
11642 assert!((v[0] - 0.0).abs() < 1e-6);
11643 assert!((v[4] - 1.0).abs() < 1e-6);
11644 assert!((v[2] - 0.5).abs() < 1e-6);
11645 }
11646
11647 #[test]
11648 fn linspace_n_one_returns_start() {
11649 let t = Tensor::linspace(7.0, 99.0, 1, &Device::cpu());
11650 assert_eq!(t.realize_f32(), vec![7.0]);
11651 }
11652
11653 #[test]
11654 fn norm_is_sqrt_sum_sq() {
11655 let t = Tensor::from_f32(vec![3.0_f32, 4.0], vec![2], &Device::cpu()).unwrap();
11656 let n = t.norm();
11657 assert!((n.realize_f32()[0] - 5.0).abs() < 1e-6);
11658 }
11659
11660 #[test]
11661 fn pad_with_zeros_left_and_right() {
11662 let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11663 let p = t.pad_with_zeros(0, 2, 1).unwrap();
11664 assert_eq!(p.shape().dims(), &[6]);
11665 assert_eq!(p.realize_f32(), vec![0.0, 0.0, 1.0, 2.0, 3.0, 0.0]);
11666 }
11667
11668 #[test]
11669 fn pad_with_zeros_identity_when_both_zero() {
11670 let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11671 let p = t.pad_with_zeros(0, 0, 0).unwrap();
11672 assert_eq!(p.realize_f32(), vec![1.0, 2.0, 3.0]);
11673 }
11674
11675 #[test]
11676 fn pad_with_zeros_rejects_bad_dim() {
11677 let t = cpu_f32(vec![1.0, 2.0], &[2]);
11678 assert!(t.pad_with_zeros(3, 1, 1).is_err());
11679 }
11680
11681 #[test]
11682 fn pad_with_value_zero_matches_pad_with_zeros() {
11683 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11686 let via_zeros = t.pad_with_zeros(0, 1, 2).unwrap();
11687 let via_value = t.pad_with_value(0, 1, 2, 0.0).unwrap();
11688 assert_eq!(via_zeros.shape().dims(), via_value.shape().dims());
11689 assert_eq!(via_zeros.shape().dims(), &[5, 2]);
11690 assert_eq!(via_zeros.realize_f32(), via_value.realize_f32());
11691 assert_eq!(
11692 via_value.realize_f32(),
11693 vec![0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 0.0, 0.0, 0.0, 0.0],
11694 );
11695 }
11696
11697 #[test]
11698 fn pad_with_value_neg_inf_then_max_reduce_ignores_pad() {
11699 let t = cpu_f32(vec![-1.0, -2.0, -3.0], &[3]);
11703 let padded = t.pad_with_value(0, 2, 2, f32::NEG_INFINITY).unwrap();
11704 assert_eq!(padded.shape().dims(), &[7]);
11705 let v = padded.realize_f32();
11706 assert!(v[0].is_infinite() && v[0].is_sign_negative());
11708 assert!(v[1].is_infinite() && v[1].is_sign_negative());
11709 assert_eq!(v[2], -1.0);
11710 assert_eq!(v[3], -2.0);
11711 assert_eq!(v[4], -3.0);
11712 assert!(v[5].is_infinite() && v[5].is_sign_negative());
11713 assert!(v[6].is_infinite() && v[6].is_sign_negative());
11714 let m = padded.max_all().realize_f32();
11716 assert_eq!(m, vec![-1.0]);
11717 }
11718
11719 #[test]
11720 fn pad_with_value_identity_when_both_zero() {
11721 let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11724 let p = t.pad_with_value(0, 0, 0, f32::NEG_INFINITY).unwrap();
11725 assert_eq!(p.realize_f32(), vec![1.0, 2.0, 3.0]);
11726 }
11727
11728 #[test]
11729 fn pad_with_value_rejects_bad_dim() {
11730 let t = cpu_f32(vec![1.0, 2.0], &[2]);
11731 assert!(t.pad_with_value(3, 1, 1, 0.0).is_err());
11732 }
11733
11734 #[test]
11735 fn max_pool2d_with_pad_value_neg_inf_on_negative_interior() {
11736 let x = cpu_f32(
11747 vec![-1.0, -2.0, -3.0, -4.0, -5.0, -6.0, -7.0, -8.0, -9.0],
11748 &[1, 1, 3, 3],
11749 );
11750 let out = x
11751 .max_pool2d_with_pad_value((3, 3), (1, 1), (1, 1), f32::NEG_INFINITY)
11752 .unwrap();
11753 assert_eq!(out.shape().dims(), &[1, 1, 3, 3]);
11754 let v = out.realize_f32();
11755 assert_eq!(v[0], -1.0);
11758 assert_eq!(v[4], -1.0);
11760 assert_eq!(v[8], -5.0);
11763
11764 let default_pad = x.max_pool2d((3, 3), (1, 1), (1, 1)).unwrap();
11774 let vd = default_pad.realize_f32();
11775 assert_eq!(
11776 vd[0], -1.0,
11777 "max_pool2d's default must now match NEG_INFINITY padding, not 0.0"
11778 );
11779 assert_eq!(vd[8], -5.0);
11780
11781 let explicit_zero_pad = x
11782 .max_pool2d_with_pad_value((3, 3), (1, 1), (1, 1), 0.0)
11783 .unwrap();
11784 let vz = explicit_zero_pad.realize_f32();
11785 assert_eq!(
11786 vz[0], 0.0,
11787 "explicit 0.0 padding must still be reachable via max_pool2d_with_pad_value"
11788 );
11789 assert_eq!(vz[8], 0.0);
11790 }
11791
11792 #[test]
11793 fn max_pool2d_with_pad_value_zero_matches_max_pool2d() {
11794 let data: Vec<f32> = (0..16).map(|i| i as f32).collect();
11797 let x = cpu_f32(data, &[1, 1, 4, 4]);
11798 let a = x.max_pool2d((2, 2), (2, 2), (0, 0)).unwrap();
11799 let b = x
11800 .max_pool2d_with_pad_value((2, 2), (2, 2), (0, 0), 0.0)
11801 .unwrap();
11802 assert_eq!(a.shape().dims(), b.shape().dims());
11803 assert_eq!(a.realize_f32(), b.realize_f32());
11804 }
11805
11806 #[test]
11809 fn conv1d_identity_kernel_passes_input_through() {
11810 let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0], &[1, 1, 5]);
11812 let w = x.const_f32_like(vec![1.0], vec![1, 1, 1]).unwrap();
11813 let out = x.conv1d(&w, None, 1, 0, 1).unwrap();
11814 assert_eq!(out.shape().dims(), &[1, 1, 5]);
11815 assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0, 4.0, 5.0]);
11816 }
11817
11818 #[test]
11819 fn conv1d_sum_kernel_two_wide() {
11820 let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[1, 1, 4]);
11822 let w = x.const_f32_like(vec![1.0, 1.0], vec![1, 1, 2]).unwrap();
11823 let out = x.conv1d(&w, None, 1, 0, 1).unwrap();
11824 assert_eq!(out.shape().dims(), &[1, 1, 3]);
11825 assert_eq!(out.realize_f32(), vec![3.0, 5.0, 7.0]);
11826 }
11827
11828 #[test]
11829 fn conv1d_with_bias_applies_correctly() {
11830 let x = cpu_f32(vec![1.0, 1.0, 1.0], &[1, 1, 3]);
11831 let w = x.const_f32_like(vec![1.0], vec![1, 1, 1]).unwrap();
11832 let bias = x.const_f32_like(vec![10.0], vec![1]).unwrap();
11833 let out = x.conv1d(&w, Some(&bias), 1, 0, 1).unwrap();
11834 assert_eq!(out.realize_f32(), vec![11.0, 11.0, 11.0]);
11835 }
11836
11837 #[test]
11838 fn conv1d_stride_two_halves_output() {
11839 let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[1, 1, 6]);
11841 let w = x.const_f32_like(vec![1.0, 1.0], vec![1, 1, 2]).unwrap();
11842 let out = x.conv1d(&w, None, 2, 0, 1).unwrap();
11843 assert_eq!(out.shape().dims(), &[1, 1, 3]);
11844 assert_eq!(out.realize_f32(), vec![3.0, 7.0, 11.0]);
11845 }
11846
11847 #[test]
11848 fn conv1d_padding_one_preserves_length() {
11849 let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[1, 1, 4]);
11851 let w = x
11852 .const_f32_like(vec![1.0, 1.0, 1.0], vec![1, 1, 3])
11853 .unwrap();
11854 let out = x.conv1d(&w, None, 1, 1, 1).unwrap();
11855 assert_eq!(out.shape().dims(), &[1, 1, 4]);
11856 assert_eq!(out.realize_f32(), vec![3.0, 6.0, 9.0, 7.0]);
11859 }
11860
11861 #[test]
11862 fn conv1d_multi_channel_output() {
11863 let x = cpu_f32(vec![1.0, 2.0, 3.0], &[1, 1, 3]);
11865 let w = x.const_f32_like(vec![2.0, -1.0], vec![2, 1, 1]).unwrap();
11867 let out = x.conv1d(&w, None, 1, 0, 1).unwrap();
11868 assert_eq!(out.shape().dims(), &[1, 2, 3]);
11869 assert_eq!(out.realize_f32(), vec![2.0, 4.0, 6.0, -1.0, -2.0, -3.0]);
11871 }
11872
11873 #[test]
11874 fn conv1d_rejects_rank_two_input() {
11875 let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11876 let w = x.const_f32_like(vec![1.0], vec![1, 1, 1]).unwrap();
11877 assert!(x.conv1d(&w, None, 1, 0, 1).is_err());
11878 }
11879
11880 #[test]
11881 fn conv1d_rejects_rank_two_weight() {
11882 let x = cpu_f32(vec![1.0; 4], &[1, 1, 4]);
11883 let w = x.const_f32_like(vec![1.0], vec![1, 1]).unwrap();
11884 assert!(x.conv1d(&w, None, 1, 0, 1).is_err());
11885 }
11886
11887 #[test]
11888 fn conv1d_rejects_zero_groups_or_stride() {
11889 let x = cpu_f32(vec![1.0; 4], &[1, 1, 4]);
11890 let w = x.const_f32_like(vec![1.0], vec![1, 1, 1]).unwrap();
11891 assert!(x.conv1d(&w, None, 0, 0, 1).is_err());
11892 assert!(x.conv1d(&w, None, 1, 0, 0).is_err());
11893 }
11894
11895 #[test]
11896 fn conv1d_with_algo_ignores_algo_param() {
11897 let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[1, 1, 4]);
11898 let w = x.const_f32_like(vec![1.0, 1.0], vec![1, 1, 2]).unwrap();
11899 let a = x.conv1d_with_algo(&w, None, 1, 0, 1, "unused").unwrap();
11901 let b = x.conv1d(&w, None, 1, 0, 1).unwrap();
11902 assert_eq!(a.realize_f32(), b.realize_f32());
11903 }
11904
11905 #[test]
11908 fn avg_pool2d_2x2_stride2() {
11909 let data: Vec<f32> = (0..16).map(|i| i as f32).collect();
11911 let x = cpu_f32(data, &[1, 1, 4, 4]);
11912 let out = x.avg_pool2d((2, 2), (2, 2), (0, 0), true).unwrap();
11913 assert_eq!(out.shape().dims(), &[1, 1, 2, 2]);
11914 let v = out.realize_f32();
11918 assert!((v[0] - 2.5).abs() < 1e-5);
11919 assert!((v[1] - 4.5).abs() < 1e-5);
11920 assert!((v[2] - 10.5).abs() < 1e-5);
11921 assert!((v[3] - 12.5).abs() < 1e-5);
11922 }
11923
11924 #[test]
11925 fn avg_pool2d_3x3_stride1_padding1_preserves_size() {
11926 let x = cpu_f32(vec![1.0; 16], &[1, 1, 4, 4]);
11927 let out = x.avg_pool2d((3, 3), (1, 1), (1, 1), true).unwrap();
11928 assert_eq!(out.shape().dims(), &[1, 1, 4, 4]);
11929 }
11930
11931 #[test]
11949 fn avg_pool2d_excludes_padding_keeps_uniform_data_exactly_at_its_true_value() {
11950 let x = cpu_f32(vec![1.0; 16], &[1, 1, 4, 4]);
11951 let included = x.avg_pool2d((3, 3), (1, 1), (1, 1), true).unwrap();
11952 let excluded = x.avg_pool2d((3, 3), (1, 1), (1, 1), false).unwrap();
11953 assert_eq!(included.shape().dims(), excluded.shape().dims());
11954
11955 let ve = excluded.realize_f32();
11956 for (i, &v) in ve.iter().enumerate() {
11957 assert!(
11958 (v - 1.0).abs() < 1e-5,
11959 "count_include_pad=false must be exactly 1.0 at every position \
11960 (all real taps are 1.0) — position {i} got {v}",
11961 );
11962 }
11963
11964 let vi = included.realize_f32();
11965 assert!(
11966 (vi[0] - 1.0).abs() > 0.1,
11967 "count_include_pad=true must NOT match at a corner (4 of 9 taps \
11968 real → 4/9, far from 1.0) — got {}, modes should disagree here",
11969 vi[0]
11970 );
11971 }
11972
11973 #[test]
11982 fn avg_pool2d_excludes_padding_from_divisor_discriminating() {
11983 let x = cpu_f32(vec![10.0, 10.0, 10.0, 10.0], &[1, 1, 2, 2]);
11984 let included = x.avg_pool2d((2, 2), (1, 1), (1, 1), true).unwrap();
11985 let excluded = x.avg_pool2d((2, 2), (1, 1), (1, 1), false).unwrap();
11986 let vi = included.realize_f32();
11987 let ve = excluded.realize_f32();
11988 assert!(
11989 (vi[0] - 2.5).abs() < 1e-5,
11990 "count_include_pad=true: top-left = 10/4 = 2.5, got {}",
11991 vi[0]
11992 );
11993 assert!(
11994 (ve[0] - 10.0).abs() < 1e-5,
11995 "count_include_pad=false: top-left = 10/1 (ONE real tap) = 10.0, got {}",
11996 ve[0]
11997 );
11998 }
11999
12000 #[test]
12005 fn avg_pool2d_rejects_zero_valid_tap_window() {
12006 let x = cpu_f32(vec![5.0], &[1, 1, 1, 1]);
12007 let err = x
12008 .avg_pool2d((1, 1), (1, 1), (2, 2), false)
12009 .expect_err("a window with zero real taps must be rejected, not silently NaN");
12010 let msg = err.to_string();
12011 assert!(
12012 msg.contains("divide by zero") || msg.contains("no valid"),
12013 "error should explain the zero-valid-tap cause, got: {msg}"
12014 );
12015
12016 let ok = x.avg_pool2d((1, 1), (1, 1), (2, 2), true);
12021 assert!(
12022 ok.is_ok(),
12023 "count_include_pad=true must still accept this shape (uniform divisor, never zero)"
12024 );
12025 }
12026
12027 #[test]
12028 fn avg_pool2d_multi_channel() {
12029 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]);
12031 let out = x.avg_pool2d((2, 2), (2, 2), (0, 0), true).unwrap();
12032 assert_eq!(out.shape().dims(), &[1, 2, 1, 1]);
12033 assert_eq!(out.realize_f32(), vec![0.0, 1.0]);
12034 }
12035
12036 #[test]
12037 fn max_pool2d_2x2_stride2() {
12038 let data: Vec<f32> = (0..16).map(|i| i as f32).collect();
12039 let x = cpu_f32(data, &[1, 1, 4, 4]);
12040 let out = x.max_pool2d((2, 2), (2, 2), (0, 0)).unwrap();
12041 assert_eq!(out.shape().dims(), &[1, 1, 2, 2]);
12042 assert_eq!(out.realize_f32(), vec![5.0, 7.0, 13.0, 15.0]);
12044 }
12045
12046 #[test]
12047 fn max_pool2d_3x3_stride1_padding1() {
12048 let x = cpu_f32(
12049 vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0],
12050 &[1, 1, 3, 3],
12051 );
12052 let out = x.max_pool2d((3, 3), (1, 1), (1, 1)).unwrap();
12053 assert_eq!(out.shape().dims(), &[1, 1, 3, 3]);
12054 let v = out.realize_f32();
12056 assert!((v[4] - 9.0).abs() < 1e-5);
12058 }
12059
12060 #[test]
12061 fn upsample_nearest2d_2x() {
12062 let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[1, 1, 2, 2]);
12063 let out = x.upsample_nearest2d(2).unwrap();
12064 assert_eq!(out.shape().dims(), &[1, 1, 4, 4]);
12065 assert_eq!(
12067 out.realize_f32(),
12068 vec![
12069 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,
12070 ],
12071 );
12072 }
12073
12074 #[test]
12075 fn upsample_nearest2d_3x() {
12076 let x = cpu_f32(vec![5.0], &[1, 1, 1, 1]);
12077 let out = x.upsample_nearest2d(3).unwrap();
12078 assert_eq!(out.shape().dims(), &[1, 1, 3, 3]);
12079 assert_eq!(out.realize_f32(), vec![5.0; 9]);
12080 }
12081
12082 #[test]
12083 fn upsample_nearest2d_identity_scale_one() {
12084 let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[1, 1, 2, 2]);
12085 let out = x.upsample_nearest2d(1).unwrap();
12086 assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0, 4.0]);
12087 }
12088
12089 #[test]
12090 fn upsample_nearest1d_2x() {
12091 let x = cpu_f32(vec![1.0, 2.0, 3.0], &[1, 1, 3]);
12092 let out = x.upsample_nearest1d(2).unwrap();
12093 assert_eq!(out.shape().dims(), &[1, 1, 6]);
12094 assert_eq!(out.realize_f32(), vec![1.0, 1.0, 2.0, 2.0, 3.0, 3.0]);
12095 }
12096
12097 #[test]
12098 fn interpolate2d_integer_multiple() {
12099 let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[1, 1, 2, 2]);
12100 let out = x.interpolate2d(4, 4).unwrap();
12101 assert_eq!(out.shape().dims(), &[1, 1, 4, 4]);
12102 }
12103
12104 #[test]
12105 fn interpolate2d_accepts_non_integer_ratio() {
12106 let x = cpu_f32(vec![1.0; 4], &[1, 1, 2, 2]);
12111 let out = x.interpolate2d(3, 4).unwrap();
12112 assert_eq!(out.shape().dims(), &[1, 1, 3, 4]);
12113 }
12114
12115 #[test]
12116 fn interpolate1d_integer_multiple() {
12117 let x = cpu_f32(vec![1.0, 2.0], &[1, 1, 2]);
12118 let out = x.interpolate1d(6).unwrap();
12119 assert_eq!(out.shape().dims(), &[1, 1, 6]);
12120 assert_eq!(out.realize_f32(), vec![1.0, 1.0, 1.0, 2.0, 2.0, 2.0]);
12121 }
12122
12123 #[test]
12124 fn pool_rejects_bad_rank() {
12125 let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
12126 assert!(x.avg_pool2d((2, 2), (2, 2), (0, 0), true).is_err());
12127 assert!(x.max_pool2d((2, 2), (2, 2), (0, 0)).is_err());
12128 }
12129
12130 #[test]
12131 fn pool_rejects_zero_kernel() {
12132 let x = cpu_f32(vec![1.0; 16], &[1, 1, 4, 4]);
12133 assert!(x.avg_pool2d((0, 2), (1, 1), (0, 0), true).is_err());
12134 assert!(x.max_pool2d((2, 0), (1, 1), (0, 0)).is_err());
12135 }
12136
12137 #[test]
12140 fn numel_matches_elem_count() {
12141 let t = cpu_f32(vec![1.0; 12], &[3, 4]);
12142 assert_eq!(t.numel(), t.elem_count());
12143 assert_eq!(t.numel(), 12);
12144 }
12145
12146 #[test]
12147 fn dim_returns_specific_axis_size() {
12148 let t = cpu_f32(vec![0.0; 24], &[2, 3, 4]);
12149 assert_eq!(t.dim(0).unwrap(), 2);
12150 assert_eq!(t.dim(1).unwrap(), 3);
12151 assert_eq!(t.dim(2).unwrap(), 4);
12152 assert!(t.dim(3).is_err());
12153 }
12154
12155 #[test]
12156 fn to_dtype_switches_dtype() {
12157 let t = cpu_f32(vec![1.0, 2.0], &[2]);
12158 let b = t.to_dtype(DType::F64).unwrap();
12159 assert_eq!(b.dtype(), DType::F64);
12160 assert_eq!(b.realize_f64(), vec![1.0, 2.0]);
12161 }
12162
12163 #[test]
12164 fn to_dtype_same_dtype_is_noop() {
12165 let t = cpu_f32(vec![1.0_f32], &[1]);
12166 let b = t.to_dtype(DType::F32).unwrap();
12167 assert_eq!(b.dtype(), DType::F32);
12168 }
12169
12170 #[test]
12171 fn detach_is_identity_on_lazy() {
12172 let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
12173 let d = t.detach();
12174 assert_eq!(d.realize_f32(), t.realize_f32());
12175 }
12176
12177 #[test]
12178 fn track_op_is_true_on_lazy() {
12179 let t = cpu_f32(vec![0.0], &[1]);
12180 assert!(t.track_op());
12181 }
12182
12183 #[test]
12186 fn try_permute_accepts_tuple_syntax() {
12187 let t = cpu_f32(vec![0.0; 24], &[2, 3, 4]);
12188 let out = t.permute((2_usize, 0_usize, 1_usize)).unwrap();
12190 assert_eq!(out.shape().dims(), &[4, 2, 3]);
12191 }
12192
12193 #[test]
12194 fn dim_arg_methods_accept_negative_indexing() {
12195 use fuel_ir::D;
12196 let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
12197 let sum_last = t.shape().dims().to_vec(); assert_eq!(sum_last, vec![2, 3]);
12200 let cumsum_last = t.cumsum(D::Minus1).unwrap();
12203 assert_eq!(cumsum_last.shape().dims(), &[2, 3]);
12204 }
12205
12206 #[test]
12207 fn unsqueeze_accepts_dim_trait() {
12208 use fuel_ir::D;
12209 let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
12210 let out = t.unsqueeze(D::Minus1).unwrap();
12212 assert_eq!(out.shape().dims().len(), 2);
12215 }
12216}
12217pub struct TokenDataHost {
12218 pub token_ids: fuel_ir::HostBuffer,
12219 pub rope_cos: fuel_ir::HostBuffer,
12220 pub rope_sin: fuel_ir::HostBuffer,
12221 pub mask: fuel_ir::HostBuffer,
12222 pub offset: Option<fuel_ir::HostBuffer>,
12223}
12224
12225#[cfg(feature = "cuda")]
12230pub struct TokenDataBytes {
12231 pub token_ids: Vec<u8>,
12232 pub rope_cos: Vec<u8>,
12233 pub rope_sin: Vec<u8>,
12234 pub mask: Vec<u8>,
12235 pub offset: Option<Vec<u8>>,
12236}
12237
12238#[cfg(feature = "cuda")]
12251pub fn captured_output_to_f32(
12252 output: &Arc<std::sync::RwLock<fuel_memory::Storage>>,
12253) -> fuel_ir::error::Result<Vec<f32>> {
12254 use fuel_memory::BackendStorage;
12255 let guard = output.read().map_err(|_| {
12256 fuel_ir::Error::Msg("captured decode output storage lock poisoned".into()).bt()
12257 })?;
12258 let bytes: Vec<u8> = match &guard.inner {
12259 BackendStorage::Cpu(c) => c.bytes().to_vec(),
12260 BackendStorage::Cuda(c) => c.to_cpu_bytes()?,
12261 #[allow(unreachable_patterns)]
12262 other => {
12263 return Err(fuel_ir::Error::Msg(format!(
12264 "captured decode output is BackendStorage::{:?}, expected Cpu or Cuda",
12265 std::mem::discriminant(other),
12266 ))
12267 .bt());
12268 }
12269 };
12270 Ok(bytemuck::cast_slice::<u8, f32>(&bytes).to_vec())
12271}