xnn 0.2.0

A lightweight ML framework with GPU-first architecture
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
//! N-dimensional tensor with GPU-backed storage.

mod layout;

use alloc::vec::Vec;
use alloc::{format, vec};

use crate::element::{FloatElement, IntegerElement, LogicalElement, NumericElement, SignedElement};
use crate::error::{Error, TensorError};
use crate::kernel::ops;
use crate::{Buffer, Context, Element};
use layout::Layout;

/// N-dimensional tensor with GPU-backed storage.
pub struct Tensor<T: Element> {
    /// GPU buffer storing tensor elements.
    buffer: Buffer<T>,
    /// Shape and stride information.
    layout: Layout,
    /// GPU context for operations.
    ctx: Context,
}

impl<T: Element> Tensor<T> {
    /// Creates a tensor with constant values.
    ///
    /// If `value` has length 1, that single value is broadcast to fill the entire tensor.
    /// Otherwise, `value` length must equal the shape volume.
    ///
    /// # Errors
    ///
    /// - [`TensorError::InvalidShape`] if `value` is empty, any dimension is zero,
    ///   or value length is neither 1 nor equal to shape volume.
    /// - [`Error::Device`] if operation fails.
    pub fn constant(ctx: &Context, shape: &[usize], value: &[T]) -> Result<Self, Error> {
        if value.is_empty() {
            return Err(TensorError::InvalidShape("value must not be empty".into()).into());
        }

        let layout = Layout::from_dimensions(shape)?;
        let volume = layout.size();

        let buffer = match value.len() {
            1 => {
                let buffer = ctx.create_buffer(volume)?;
                let uniform = ctx.create_uniform_buffer(&value[0].to_native());
                ops::constant(ctx, &buffer, &uniform);
                buffer
            }
            n if n == volume => ctx.create_buffer_from_slice(value)?,
            n => {
                return Err(TensorError::InvalidShape(format!(
                    "value length {n} must be 1 or equal to shape volume {volume}"
                ))
                .into());
            }
        };

        Ok(Self {
            buffer,
            layout,
            ctx: ctx.clone(),
        })
    }

    /// Creates a tensor from shape and data slice.
    ///
    /// # Errors
    ///
    /// - [`TensorError::InvalidShape`] if any dimension is zero or size doesn't match data length.
    /// - [`Error::Device`] if operation fails.
    pub fn from_shape_slice(ctx: &Context, shape: &[usize], data: &[T]) -> Result<Self, Error> {
        Self::constant(ctx, shape, data)
    }

    /// Creates a 1D tensor from a data slice.
    ///
    /// # Errors
    ///
    /// - [`TensorError::InvalidShape`] if data is empty.
    /// - [`Error::Device`] if operation fails.
    pub fn from_slice(ctx: &Context, data: &[T]) -> Result<Self, Error> {
        Self::constant(ctx, &[data.len()], data)
    }

    /// Creates a copy of this tensor.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if operation fails.
    pub fn copy(&self) -> Result<Self, Error> {
        let buffer = self.ctx.create_buffer(self.buffer.len())?;
        ops::copy(&self.ctx, &self.buffer, &buffer);

        Ok(Self {
            buffer,
            layout: self.layout.clone(),
            ctx: self.ctx.clone(),
        })
    }

    /// Returns the tensor dimensions.
    #[must_use]
    pub fn dimensions(&self) -> &[usize] {
        self.layout.dimensions()
    }

    /// Asynchronously copies tensor data from GPU to CPU.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if operation fails.
    pub async fn to_vec_async(&self) -> Result<Vec<T>, Error> {
        self.ctx.read_buffer_async(&self.buffer).await
    }

    /// Copies tensor data from GPU to CPU.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if operation fails.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn to_vec(&self) -> Result<Vec<T>, Error> {
        self.ctx.read_buffer(&self.buffer)
    }

    /// Applies a math binary operation with broadcasting.
    fn math_binary<U: Element>(
        &self,
        other: &Self,
        op: impl FnOnce(&Context, &Buffer<T>, &Buffer<T>, &Buffer<U>, &[usize], &[usize], &[usize]),
    ) -> Result<Tensor<U>, Error> {
        let (dimensions, strides) =
            Layout::broadcast(&[&self.layout, &other.layout]).ok_or_else(|| {
                TensorError::InvalidShape(format!(
                    "dimensions {:?} and {:?} are not broadcast-compatible",
                    self.dimensions(),
                    other.dimensions()
                ))
            })?;

        let layout = Layout::from_dimensions(&dimensions)?;
        let buffer = self.ctx.create_buffer(layout.size())?;

        op(
            &self.ctx,
            &self.buffer,
            &other.buffer,
            &buffer,
            &strides[0],
            &strides[1],
            layout.strides(),
        );

        Ok(Tensor {
            buffer,
            layout,
            ctx: self.ctx.clone(),
        })
    }

    /// Applies a math unary operation and returns a new tensor.
    fn math_unary(&self, op: impl FnOnce(&Context, &Buffer<T>, &Buffer<T>)) -> Result<Self, Error> {
        let buffer = self.ctx.create_buffer(self.buffer.len())?;
        op(&self.ctx, &self.buffer, &buffer);

        Ok(Self {
            buffer,
            layout: self.layout.clone(),
            ctx: self.ctx.clone(),
        })
    }
}

impl<T: NumericElement> Tensor<T> {
    /// Clamps tensor values: `y = max(min(x, b), a)`.
    ///
    /// # Errors
    ///
    /// - [`TensorError::InvalidShape`] if shapes are not broadcast-compatible.
    /// - [`Error::Device`] if GPU operation fails.
    pub fn clamp(&self, a: &Self, b: &Self) -> Result<Self, Error> {
        let (dimensions, strides) = Layout::broadcast(&[&self.layout, &a.layout, &b.layout])
            .ok_or_else(|| {
                TensorError::InvalidShape(format!(
                    "dimensions {:?}, {:?}, and {:?} are not broadcast-compatible",
                    self.dimensions(),
                    a.dimensions(),
                    b.dimensions()
                ))
            })?;

        let layout = Layout::from_dimensions(&dimensions)?;
        let buffer = self.ctx.create_buffer(layout.size())?;

        ops::clamp(
            &self.ctx,
            &self.buffer,
            &a.buffer,
            &b.buffer,
            &buffer,
            &strides[0],
            &strides[1],
            &strides[2],
            layout.strides(),
        );

        Ok(Self {
            buffer,
            layout,
            ctx: self.ctx.clone(),
        })
    }

    /// Element-wise addition with broadcasting.
    ///
    /// # Errors
    ///
    /// - [`TensorError::InvalidShape`] if shapes are not broadcast-compatible.
    /// - [`Error::Device`] if buffer allocation fails.
    pub fn add(&self, other: &Self) -> Result<Self, Error> {
        self.math_binary(other, |ctx, a, b, c, dimensions, a_strides, b_strides| {
            ops::add(ctx, a, b, c, dimensions, a_strides, b_strides);
        })
    }

    /// Element-wise subtraction with broadcasting.
    ///
    /// # Errors
    ///
    /// - [`TensorError::InvalidShape`] if shapes are not broadcast-compatible.
    /// - [`Error::Device`] if buffer allocation fails.
    pub fn sub(&self, other: &Self) -> Result<Self, Error> {
        self.math_binary(other, |ctx, a, b, c, dimensions, a_strides, b_strides| {
            ops::sub(ctx, a, b, c, dimensions, a_strides, b_strides);
        })
    }

    /// Element-wise multiplication with broadcasting.
    ///
    /// # Errors
    ///
    /// - [`TensorError::InvalidShape`] if shapes are not broadcast-compatible.
    /// - [`Error::Device`] if buffer allocation fails.
    pub fn mul(&self, other: &Self) -> Result<Self, Error> {
        self.math_binary(other, |ctx, a, b, c, dimensions, a_strides, b_strides| {
            ops::mul(ctx, a, b, c, dimensions, a_strides, b_strides);
        })
    }

    /// Element-wise division with broadcasting.
    ///
    /// # Errors
    ///
    /// - [`TensorError::InvalidShape`] if shapes are not broadcast-compatible.
    /// - [`Error::Device`] if buffer allocation fails.
    pub fn div(&self, other: &Self) -> Result<Self, Error> {
        self.math_binary(other, |ctx, a, b, c, dimensions, a_strides, b_strides| {
            ops::div(ctx, a, b, c, dimensions, a_strides, b_strides);
        })
    }

    /// Element-wise maximum with broadcasting.
    ///
    /// # Errors
    ///
    /// - [`TensorError::InvalidShape`] if shapes are not broadcast-compatible.
    /// - [`Error::Device`] if buffer allocation fails.
    pub fn max(&self, other: &Self) -> Result<Self, Error> {
        self.math_binary(other, |ctx, a, b, c, dimensions, a_strides, b_strides| {
            ops::max(ctx, a, b, c, dimensions, a_strides, b_strides);
        })
    }

    /// Element-wise minimum with broadcasting.
    ///
    /// # Errors
    ///
    /// - [`TensorError::InvalidShape`] if shapes are not broadcast-compatible.
    /// - [`Error::Device`] if buffer allocation fails.
    pub fn min(&self, other: &Self) -> Result<Self, Error> {
        self.math_binary(other, |ctx, a, b, c, dimensions, a_strides, b_strides| {
            ops::min(ctx, a, b, c, dimensions, a_strides, b_strides);
        })
    }

    /// Element-wise equality comparison with broadcasting.
    ///
    /// # Errors
    ///
    /// - [`TensorError::InvalidShape`] if shapes are not broadcast-compatible.
    /// - [`Error::Device`] if buffer allocation fails.
    pub fn eq(&self, other: &Self) -> Result<Tensor<bool>, Error> {
        self.math_binary(other, |ctx, a, b, c, dimensions, a_strides, b_strides| {
            ops::eq(ctx, a, b, c, dimensions, a_strides, b_strides);
        })
    }

    /// Element-wise inequality comparison with broadcasting.
    ///
    /// # Errors
    ///
    /// - [`TensorError::InvalidShape`] if shapes are not broadcast-compatible.
    /// - [`Error::Device`] if buffer allocation fails.
    pub fn ne(&self, other: &Self) -> Result<Tensor<bool>, Error> {
        self.math_binary(other, |ctx, a, b, c, dimensions, a_strides, b_strides| {
            ops::ne(ctx, a, b, c, dimensions, a_strides, b_strides);
        })
    }

    /// Element-wise greater-than-or-equal comparison with broadcasting.
    ///
    /// # Errors
    ///
    /// - [`TensorError::InvalidShape`] if shapes are not broadcast-compatible.
    /// - [`Error::Device`] if buffer allocation fails.
    pub fn ge(&self, other: &Self) -> Result<Tensor<bool>, Error> {
        self.math_binary(other, |ctx, a, b, c, dimensions, a_strides, b_strides| {
            ops::ge(ctx, a, b, c, dimensions, a_strides, b_strides);
        })
    }

    /// Element-wise greater-than comparison with broadcasting.
    ///
    /// # Errors
    ///
    /// - [`TensorError::InvalidShape`] if shapes are not broadcast-compatible.
    /// - [`Error::Device`] if buffer allocation fails.
    pub fn gt(&self, other: &Self) -> Result<Tensor<bool>, Error> {
        self.math_binary(other, |ctx, a, b, c, dimensions, a_strides, b_strides| {
            ops::gt(ctx, a, b, c, dimensions, a_strides, b_strides);
        })
    }

    /// Element-wise less-than-or-equal comparison with broadcasting.
    ///
    /// # Errors
    ///
    /// - [`TensorError::InvalidShape`] if shapes are not broadcast-compatible.
    /// - [`Error::Device`] if buffer allocation fails.
    pub fn le(&self, other: &Self) -> Result<Tensor<bool>, Error> {
        self.math_binary(other, |ctx, a, b, c, dimensions, a_strides, b_strides| {
            ops::le(ctx, a, b, c, dimensions, a_strides, b_strides);
        })
    }

    /// Element-wise less-than comparison with broadcasting.
    ///
    /// # Errors
    ///
    /// - [`TensorError::InvalidShape`] if shapes are not broadcast-compatible.
    /// - [`Error::Device`] if buffer allocation fails.
    pub fn lt(&self, other: &Self) -> Result<Tensor<bool>, Error> {
        self.math_binary(other, |ctx, a, b, c, dimensions, a_strides, b_strides| {
            ops::lt(ctx, a, b, c, dimensions, a_strides, b_strides);
        })
    }

    /// Max reduction along specified axes.
    ///
    /// Output shape equals input shape with reduced axes set to 1.
    ///
    /// # Errors
    ///
    /// - [`TensorError::InvalidShape`] if axes are invalid or duplicate.
    /// - [`Error::Device`] if GPU operation fails.
    pub fn max_reduce(&self, axes: &[usize]) -> Result<Self, Error> {
        self.reduction(axes, ops::max_reduce)
    }

    /// Min reduction along specified axes.
    ///
    /// Output shape equals input shape with reduced axes set to 1.
    ///
    /// # Errors
    ///
    /// - [`TensorError::InvalidShape`] if axes are invalid or duplicate.
    /// - [`Error::Device`] if GPU operation fails.
    pub fn min_reduce(&self, axes: &[usize]) -> Result<Self, Error> {
        self.reduction(axes, ops::min_reduce)
    }

    /// Sum reduction along specified axes.
    ///
    /// Output shape equals input shape with reduced axes set to 1.
    ///
    /// # Errors
    ///
    /// - [`TensorError::InvalidShape`] if axes are invalid or duplicate.
    /// - [`Error::Device`] if GPU operation fails.
    pub fn sum_reduce(&self, axes: &[usize], normalize: bool) -> Result<Self, Error> {
        self.reduction(
            axes,
            |ctx, input, output, dims, x_strides, y_strides, axes| {
                ops::sum_reduce(
                    ctx, input, output, dims, x_strides, y_strides, axes, normalize,
                );
            },
        )
    }

    /// Mean reduction along specified axes.
    ///
    /// Output shape equals input shape with reduced axes set to 1.
    ///
    /// # Errors
    ///
    /// - [`TensorError::InvalidShape`] if axes are invalid or duplicate.
    /// - [`Error::Device`] if GPU operation fails.
    pub fn mean_reduce(&self, axes: &[usize]) -> Result<Self, Error> {
        self.sum_reduce(axes, true)
    }

    /// Applies a reduce operation with strides and returns a new tensor.
    fn reduction<F>(&self, axes: &[usize], op: F) -> Result<Self, Error>
    where
        F: FnOnce(&Context, &Buffer<T>, &Buffer<T>, &[usize], &[usize], &[usize], &[usize]),
    {
        let dimensions = self.layout.dimensions();
        let rank = dimensions.len();

        let mut seen = vec![false; rank];
        for &axis in axes {
            if axis >= rank {
                return Err(TensorError::InvalidShape(format!(
                    "axis {axis} out of bounds for tensor with rank {rank}"
                ))
                .into());
            }
            if seen[axis] {
                return Err(TensorError::InvalidShape(format!("duplicate axis {axis}")).into());
            }
            seen[axis] = true;
        }

        let out_dimensions: Vec<usize> = dimensions
            .iter()
            .enumerate()
            .map(|(i, &d)| if seen[i] { 1 } else { d })
            .collect();

        let layout = Layout::from_dimensions(&out_dimensions)?;
        let buffer = self.ctx.create_buffer(layout.size())?;

        op(
            &self.ctx,
            &self.buffer,
            &buffer,
            dimensions,
            self.layout.strides(),
            layout.strides(),
            axes,
        );

        Ok(Self {
            buffer,
            layout,
            ctx: self.ctx.clone(),
        })
    }
}

impl<T: SignedElement> Tensor<T> {
    /// Computes absolute value element-wise.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if operation fails.
    pub fn abs(&self) -> Result<Self, Error> {
        self.math_unary(ops::abs)
    }

    /// Computes negation element-wise.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if operation fails.
    pub fn neg(&self) -> Result<Self, Error> {
        self.math_unary(ops::neg)
    }

    /// Computes sign element-wise.
    ///
    /// Returns -1, 0, or 1.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if operation fails.
    pub fn sign(&self) -> Result<Self, Error> {
        self.math_unary(ops::sign)
    }
}

impl<T: IntegerElement> Tensor<T> {
    /// Element-wise remainder with broadcasting.
    ///
    /// # Errors
    ///
    /// - [`TensorError::InvalidShape`] if shapes are not broadcast-compatible.
    /// - [`Error::Device`] if buffer allocation fails.
    pub fn rem(&self, other: &Self) -> Result<Self, Error> {
        self.math_binary(other, |ctx, a, b, c, dimensions, a_strides, b_strides| {
            ops::rem(ctx, a, b, c, dimensions, a_strides, b_strides);
        })
    }
}

impl<T: FloatElement> Tensor<T> {
    /// Batched matrix multiplication with optional transposes.
    ///
    /// `A[..., m, k] × B[..., k, n] → C[..., m, n]`
    ///
    /// Batch dimensions are broadcast-compatible.
    ///
    /// # Errors
    ///
    /// - [`TensorError::InvalidShape`] if ranks differ or are less than 2.
    /// - [`TensorError::InvalidShape`] if inner dimensions don't match.
    /// - [`Error::Device`] if GPU operation fails.
    pub fn matmul(
        &self,
        other: &Self,
        transpose_a: bool,
        transpose_b: bool,
    ) -> Result<Self, Error> {
        let a_dims = self.layout.dimensions();
        let b_dims = other.layout.dimensions();
        let rank = a_dims.len();

        if rank < 2 || b_dims.len() < 2 {
            return Err(
                TensorError::InvalidShape("matmul requires tensors with rank >= 2".into()).into(),
            );
        }

        if rank != b_dims.len() {
            return Err(TensorError::InvalidShape(format!(
                "matmul requires equal ranks, got {} and {}",
                rank,
                b_dims.len()
            ))
            .into());
        }

        let (a_rows, a_cols) = (a_dims[rank - 2], a_dims[rank - 1]);
        let (b_rows, b_cols) = (b_dims[rank - 2], b_dims[rank - 1]);

        let (m, a_k) = if transpose_a {
            (a_cols, a_rows)
        } else {
            (a_rows, a_cols)
        };
        let (b_k, n) = if transpose_b {
            (b_cols, b_rows)
        } else {
            (b_rows, b_cols)
        };

        if a_k != b_k {
            return Err(TensorError::InvalidShape(format!(
                "matmul inner dimensions don't match: {a_k} vs {b_k}"
            ))
            .into());
        }

        let mut out_dims: Vec<usize> = a_dims[..rank - 2]
            .iter()
            .zip(&b_dims[..rank - 2])
            .map(|(&da, &db)| match (da, db) {
                (a, b) if a == b => Ok(a),
                (1, b) => Ok(b),
                (a, 1) => Ok(a),
                _ => Err(TensorError::InvalidShape(format!(
                    "batch dimensions not broadcast-compatible: {da} vs {db}"
                ))),
            })
            .collect::<Result<_, _>>()?;
        out_dims.extend([m, n]);

        let layout = Layout::from_dimensions(&out_dims)?;
        let buffer = self.ctx.create_buffer(layout.size())?;

        ops::matmul(
            &self.ctx,
            &self.buffer,
            &other.buffer,
            &buffer,
            a_dims,
            b_dims,
            &out_dims,
            transpose_a,
            transpose_b,
        );

        Ok(Self {
            buffer,
            layout,
            ctx: self.ctx.clone(),
        })
    }

    /// Element-wise power with broadcasting.
    ///
    /// # Errors
    ///
    /// - [`TensorError::InvalidShape`] if shapes are not broadcast-compatible.
    /// - [`Error::Device`] if buffer allocation fails.
    pub fn pow(&self, other: &Self) -> Result<Self, Error> {
        self.math_binary(other, |ctx, a, b, c, dimensions, a_strides, b_strides| {
            ops::pow(ctx, a, b, c, dimensions, a_strides, b_strides);
        })
    }

    /// Computes sine element-wise.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if operation fails.
    pub fn sin(&self) -> Result<Self, Error> {
        self.math_unary(ops::sin)
    }

    /// Computes cosine element-wise.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if operation fails.
    pub fn cos(&self) -> Result<Self, Error> {
        self.math_unary(ops::cos)
    }

    /// Computes tangent element-wise.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if operation fails.
    pub fn tan(&self) -> Result<Self, Error> {
        self.math_unary(ops::tan)
    }

    /// Computes arc sine element-wise.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if operation fails.
    pub fn asin(&self) -> Result<Self, Error> {
        self.math_unary(ops::asin)
    }

    /// Computes arc cosine element-wise.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if operation fails.
    pub fn acos(&self) -> Result<Self, Error> {
        self.math_unary(ops::acos)
    }

    /// Computes arc tangent element-wise.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if operation fails.
    pub fn atan(&self) -> Result<Self, Error> {
        self.math_unary(ops::atan)
    }

    /// Computes hyperbolic sine element-wise.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if operation fails.
    pub fn sinh(&self) -> Result<Self, Error> {
        self.math_unary(ops::sinh)
    }

    /// Computes hyperbolic cosine element-wise.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if operation fails.
    pub fn cosh(&self) -> Result<Self, Error> {
        self.math_unary(ops::cosh)
    }

    /// Computes hyperbolic tangent element-wise.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if operation fails.
    pub fn tanh(&self) -> Result<Self, Error> {
        self.math_unary(ops::tanh)
    }

    /// Computes inverse hyperbolic sine element-wise.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if operation fails.
    pub fn asinh(&self) -> Result<Self, Error> {
        self.math_unary(ops::asinh)
    }

    /// Computes inverse hyperbolic cosine element-wise.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if operation fails.
    pub fn acosh(&self) -> Result<Self, Error> {
        self.math_unary(ops::acosh)
    }

    /// Computes inverse hyperbolic tangent element-wise.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if operation fails.
    pub fn atanh(&self) -> Result<Self, Error> {
        self.math_unary(ops::atanh)
    }

    /// Computes exponential (e^x) element-wise.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if operation fails.
    pub fn exp(&self) -> Result<Self, Error> {
        self.math_unary(ops::exp)
    }

    /// Computes natural logarithm element-wise.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if operation fails.
    pub fn log(&self) -> Result<Self, Error> {
        self.math_unary(ops::log)
    }

    /// Computes base-2 logarithm element-wise.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if operation fails.
    pub fn log2(&self) -> Result<Self, Error> {
        self.math_unary(ops::log2)
    }

    /// Computes square (x²) element-wise.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if operation fails.
    pub fn sqr(&self) -> Result<Self, Error> {
        self.math_unary(ops::sqr)
    }

    /// Computes square root element-wise.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if operation fails.
    pub fn sqrt(&self) -> Result<Self, Error> {
        self.math_unary(ops::sqrt)
    }

    /// Computes reciprocal of square (1/x²) element-wise.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if operation fails.
    pub fn rsqr(&self) -> Result<Self, Error> {
        self.math_unary(ops::rsqr)
    }

    /// Computes reciprocal of square root (1/√x) element-wise.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if operation fails.
    pub fn rsqrt(&self) -> Result<Self, Error> {
        self.math_unary(ops::rsqrt)
    }

    /// Computes reciprocal (1/x) element-wise.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if operation fails.
    pub fn rcp(&self) -> Result<Self, Error> {
        self.math_unary(ops::rcp)
    }

    /// Computes ceiling element-wise.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if operation fails.
    pub fn ceil(&self) -> Result<Self, Error> {
        self.math_unary(ops::ceil)
    }

    /// Computes floor element-wise.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if operation fails.
    pub fn floor(&self) -> Result<Self, Error> {
        self.math_unary(ops::floor)
    }

    /// Rounds to nearest integer element-wise.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if operation fails.
    pub fn round(&self) -> Result<Self, Error> {
        self.math_unary(ops::round)
    }

    /// `ELU` activation: `y = x < 0 ? α(eˣ - 1) : x`.
    ///
    /// # Arguments
    ///
    /// * `alpha` - Slope for negative values. Default: `1.0`.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if buffer allocation fails.
    pub fn elu(&self, alpha: Option<f32>) -> Result<Self, Error> {
        let alpha = alpha.unwrap_or(1.0);
        self.nn_activation(|ctx, x, y| ops::elu(ctx, x, y, alpha))
    }

    /// `GELU` activation: `y = x · σ(1.702x)`.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if buffer allocation fails.
    pub fn gelu(&self) -> Result<Self, Error> {
        self.nn_activation(ops::gelu)
    }

    /// `Leaky ReLU` activation: `y = x < 0 ? αx : x`.
    ///
    /// # Arguments
    ///
    /// * `alpha` - Slope for negative values. Default: `0.01`.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if buffer allocation fails.
    pub fn leaky_relu(&self, alpha: Option<f32>) -> Result<Self, Error> {
        let alpha = alpha.unwrap_or(0.01);
        self.nn_activation(|ctx, x, y| ops::leaky_relu(ctx, x, y, alpha))
    }

    /// `PReLU` activation: `y = x < 0 ? αx : x`.
    ///
    /// # Arguments
    ///
    /// * `alpha` - Learnable parameter tensor with the same shape as `self`.
    ///
    /// # Errors
    ///
    /// - [`TensorError::InvalidShape`] if shapes mismatch.
    /// - [`Error::Device`] if buffer allocation fails.
    pub fn prelu(&self, alpha: &Self) -> Result<Self, Error> {
        if self.dimensions() != alpha.dimensions() {
            return Err(TensorError::InvalidShape(format!(
                "prelu shape mismatch: {:?} vs {:?}",
                self.dimensions(),
                alpha.dimensions()
            ))
            .into());
        }
        self.nn_activation(|ctx, x, y| ops::prelu(ctx, x, y, &alpha.buffer))
    }

    /// `ReLU` activation: `y = max(x, 0)`.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if buffer allocation fails.
    pub fn relu(&self) -> Result<Self, Error> {
        self.nn_activation(ops::relu)
    }

    /// `SELU` activation: `y = λ(x < 0 ? α(eˣ - 1) : x)`.
    ///
    /// # Arguments
    ///
    /// * `alpha` - Scale for negative values. Default: `1.673_263_2`.
    /// * `lambda` - Output scale. Default: `1.050_701`.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if buffer allocation fails.
    pub fn selu(&self, alpha: Option<f32>, lambda: Option<f32>) -> Result<Self, Error> {
        let alpha = alpha.unwrap_or(1.673_263_2);
        let lambda = lambda.unwrap_or(1.050_701);
        self.nn_activation(|ctx, x, y| ops::selu(ctx, x, y, alpha, lambda))
    }

    /// `Sigmoid` activation: `y = 1/(1 + e⁻ˣ)`.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if buffer allocation fails.
    pub fn sigmoid(&self) -> Result<Self, Error> {
        self.nn_activation(ops::sigmoid)
    }

    /// `SiLU` activation: `y = x · σ(x)`.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if buffer allocation fails.
    pub fn silu(&self) -> Result<Self, Error> {
        self.nn_activation(ops::silu)
    }

    /// `Softplus` activation: `y = ln(eˣ + 1)`.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if buffer allocation fails.
    pub fn softplus(&self) -> Result<Self, Error> {
        self.nn_activation(ops::softplus)
    }

    /// Applies an activation operation.
    fn nn_activation(
        &self,
        op: impl FnOnce(&Context, &Buffer<T>, &Buffer<T>),
    ) -> Result<Self, Error> {
        let buffer = self.ctx.create_buffer(self.buffer.len())?;
        op(&self.ctx, &self.buffer, &buffer);
        Ok(Self {
            buffer,
            layout: self.layout.clone(),
            ctx: self.ctx.clone(),
        })
    }
}

impl<T: LogicalElement> Tensor<T> {
    /// Selects elements from `a` or `b` based on condition.
    ///
    /// For each element, returns `a` where condition is true, otherwise `b`.
    ///
    /// # Errors
    ///
    /// - [`TensorError::InvalidShape`] if shapes are not broadcast-compatible.
    /// - [`Error::Device`] if buffer allocation fails.
    pub fn select<U: NumericElement>(
        &self,
        a: &Tensor<U>,
        b: &Tensor<U>,
    ) -> Result<Tensor<U>, Error> {
        let (dimensions, strides) = Layout::broadcast(&[&self.layout, &a.layout, &b.layout])
            .ok_or_else(|| {
                TensorError::InvalidShape(format!(
                    "dimensions {:?}, {:?}, and {:?} are not broadcast-compatible",
                    self.dimensions(),
                    a.dimensions(),
                    b.dimensions()
                ))
            })?;

        let layout = Layout::from_dimensions(&dimensions)?;
        let buffer = self.ctx.create_buffer(layout.size())?;

        ops::select(
            &self.ctx,
            &self.buffer,
            &a.buffer,
            &b.buffer,
            &buffer,
            &strides[0],
            &strides[1],
            &strides[2],
            layout.strides(),
        );

        Ok(Tensor {
            buffer,
            layout,
            ctx: self.ctx.clone(),
        })
    }

    /// Element-wise logical AND with broadcasting.
    ///
    /// # Errors
    ///
    /// - [`TensorError::InvalidShape`] if shapes are not broadcast-compatible.
    /// - [`Error::Device`] if buffer allocation fails.
    pub fn and(&self, other: &Self) -> Result<Self, Error> {
        self.math_binary(other, |ctx, a, b, c, dimensions, a_strides, b_strides| {
            ops::and(ctx, a, b, c, dimensions, a_strides, b_strides);
        })
    }

    /// Element-wise logical OR with broadcasting.
    ///
    /// # Errors
    ///
    /// - [`TensorError::InvalidShape`] if shapes are not broadcast-compatible.
    /// - [`Error::Device`] if buffer allocation fails.
    pub fn or(&self, other: &Self) -> Result<Self, Error> {
        self.math_binary(other, |ctx, a, b, c, dimensions, a_strides, b_strides| {
            ops::or(ctx, a, b, c, dimensions, a_strides, b_strides);
        })
    }

    /// Computes logical NOT element-wise.
    ///
    /// # Errors
    ///
    /// - [`Error::Device`] if operation fails.
    pub fn not(&self) -> Result<Self, Error> {
        self.math_unary(ops::not)
    }
}