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
use std::sync::{Arc, RwLock};
use crate::{
Shape, Tensor, TensorError,
tensor::{TensorData, TensorInner},
};
impl Tensor {
/// Add two tensors with broadcasting.
///
/// # Arguments
/// * `rhs` - The tensor to add.
///
/// # Returns
/// * `Ok(Tensor)` - The result tensor after addition.
/// * `Err(TensorError)` - The error when adding the tensors.
///
/// # Examples
/// ```
/// use nove::tensor::{Device, Tensor};
/// let device = Device::cpu();
/// let t1 = Tensor::from_data(vec![1.0, 2.0], &device, false).unwrap();
/// let t2 = Tensor::from_data(vec![3.0, 4.0], &device, false).unwrap();
///
/// let t3 = t1.add(&t2).unwrap();
/// println!("{:?}", t3);
/// ```
pub fn add(&self, rhs: &Self) -> Result<Self, TensorError> {
let inner1 = self.data.read()?;
let inner1_tensor = match &inner1.inner {
TensorInner::Tensor(tensor) => tensor,
TensorInner::Var(var) => var,
};
let inner2 = rhs.data.read()?;
let inner2_tensor = match &inner2.inner {
TensorInner::Tensor(tensor) => tensor,
TensorInner::Var(var) => var,
};
// Get the device from the first tensor
let device = self.data.read()?.device.clone();
let new_inner = TensorInner::Tensor(inner1_tensor.broadcast_add(inner2_tensor)?);
let parents = vec![self.clone(), rhs.clone()];
Ok(Self {
data: Arc::new(RwLock::new(TensorData {
inner: new_inner,
device,
parents,
grad: None,
name: None,
})),
})
}
/// Multiply two tensors with broadcasting.
///
/// # Arguments
/// * `rhs` - The tensor to multiply.
///
/// # Returns
/// * `Ok(Tensor)` - The result tensor after multiplication.
/// * `Err(TensorError)` - The error when multiplying the tensors.
///
/// # Examples
/// ```
/// use nove::tensor::{Device, Tensor};
/// let device = Device::cpu();
/// let t1 = Tensor::from_data(vec![1.0, 2.0], &device, false).unwrap();
/// let t2 = Tensor::from_data(vec![3.0, 4.0], &device, false).unwrap();
///
/// let t3 = t1.mul(&t2).unwrap();
/// println!("{:?}", t3);
/// ```
pub fn mul(&self, rhs: &Self) -> Result<Self, TensorError> {
let inner1 = self.data.read()?;
let inner1_tensor = match &inner1.inner {
TensorInner::Tensor(tensor) => tensor,
TensorInner::Var(var) => var,
};
let inner2 = rhs.data.read()?;
let inner2_tensor = match &inner2.inner {
TensorInner::Tensor(tensor) => tensor,
TensorInner::Var(var) => var,
};
let new_inner = TensorInner::Tensor(inner1_tensor.broadcast_mul(inner2_tensor)?);
Ok(Self {
data: Arc::new(RwLock::new(TensorData {
inner: new_inner,
device: self.data.read()?.device.clone(),
parents: vec![self.clone(), rhs.clone()],
grad: None,
name: None,
})),
})
}
/// Stack a list of tensors along a new dimension.
///
/// # Arguments
/// * `tensors` - The list of tensors to stack.
/// * `dim` - The dimension along which to stack the tensors.
///
/// # Returns
/// * `Ok(Tensor)` - The result tensor after stacking.
/// * `Err(TensorError)` - The error when stacking the tensors.
///
/// # Examples
/// ```
/// use nove::tensor::{Device, Tensor};
/// let device = Device::cpu();
/// let t1 = Tensor::from_data(vec![1.0, 2.0], &device, false).unwrap();
/// let t2 = Tensor::from_data(vec![3.0, 4.0], &device, false).unwrap();
/// let t3 = Tensor::from_data(vec![5.0, 6.0], &device, false).unwrap();
///
/// let t4 = Tensor::stack(&[t1, t2, t3], 0).unwrap();
/// println!("{:?}", t4);
/// ```
pub fn stack<A, D>(tensors: &[A], dim: D) -> Result<Self, TensorError>
where
A: AsRef<Tensor> + std::clone::Clone,
D: candle_core::shape::Dim,
{
let inner_tensors = tensors
.iter()
.map(|tensor| {
let data = tensor.as_ref().data.read()?;
match &data.inner {
TensorInner::Tensor(tensor) => Ok(tensor.clone()),
TensorInner::Var(var) => Ok(var.as_tensor().clone()),
}
})
.collect::<Result<Vec<_>, TensorError>>()?;
// Stack the tensors
let new_inner_tensor = candle_core::Tensor::stack(&inner_tensors, dim)?;
// Get the device from the first tensor
let device = tensors
.first()
.map(|t| t.as_ref().data.read().unwrap().device.clone())
.unwrap();
let new_inner = TensorInner::Tensor(new_inner_tensor);
// Set the parents
let parents = tensors
.iter()
.map(|tensor| tensor.as_ref().clone())
.collect::<Vec<_>>();
Ok(Self {
data: Arc::new(RwLock::new(TensorData {
inner: new_inner,
device,
parents,
grad: None,
name: None,
})),
})
}
/// Matrix multiplication between two tensors with broadcasting.
///
/// # Arguments
/// * `rhs` - The tensor to multiply.
///
/// # Returns
/// * `Ok(Tensor)` - The result tensor after matrix multiplication.
/// * `Err(TensorError)` - The error when multiplying the tensors.
///
/// # Examples
/// ```
/// use nove::tensor::{Device, Tensor};
/// let device = Device::cpu();
/// let t1 = Tensor::from_data(&[[1.0, 2.0]], &device, false).unwrap();
/// let t2 = Tensor::from_data(&[[5.0, 6.0], [7.0, 8.0]], &device, false).unwrap();
///
/// let t3 = t1.matmul(&t2).unwrap();
/// println!("{:?}", t3);
/// ```
pub fn matmul(&self, rhs: &Self) -> Result<Self, TensorError> {
let inner1 = self.data.read()?;
let inner1_tensor = match &inner1.inner {
TensorInner::Tensor(tensor) => tensor,
TensorInner::Var(var) => var,
};
let inner2 = rhs.data.read()?;
let inner2_tensor = match &inner2.inner {
TensorInner::Tensor(tensor) => tensor,
TensorInner::Var(var) => var,
};
let new_inner = TensorInner::Tensor(inner1_tensor.broadcast_matmul(inner2_tensor)?);
Ok(Self {
data: Arc::new(RwLock::new(TensorData {
inner: new_inner,
device: self.data.read()?.device.clone(),
parents: vec![self.clone(), rhs.clone()],
grad: None,
name: None,
})),
})
}
/// Compute the maximum value along a specified dimension or across all elements.
///
/// # Arguments
///
/// * `axis` - Optional `(dim, keep_dim)` tuple.
/// - `Some((dim, keep_dim))`: compute along `dim`
/// - `keep_dim = true`: keep dimension (size becomes 1)
/// - `keep_dim = false`: remove dimension
/// - `None`: compute across all elements
///
/// # Returns
/// * `Ok(Tensor)` - The result tensor containing the maximum values.
/// * `Err(TensorError)` - The error when computing the maximum.
///
/// # Examples
/// ```
/// use nove::tensor::{Device, Tensor};
/// let device = Device::cpu();
/// let t = Tensor::from_data(vec![1.0, 2.0, 3.0, 4.0], &device, false).unwrap();
///
/// let max_all = t.max(None).unwrap();
/// println!("{:?}", max_all);
/// ```
pub fn max(&self, axis: Option<(usize, bool)>) -> Result<Self, TensorError> {
let inner = self.data.read()?;
let inner_tensor = match &inner.inner {
TensorInner::Tensor(tensor) => tensor,
TensorInner::Var(var) => var,
};
let new_inner = match axis {
Some((dim, keep_dim)) => match keep_dim {
true => TensorInner::Tensor(inner_tensor.max_keepdim(dim)?),
false => TensorInner::Tensor(inner_tensor.max(dim)?),
},
None => TensorInner::Tensor(inner_tensor.max_all()?),
};
Ok(Self {
data: Arc::new(RwLock::new(TensorData {
inner: new_inner,
device: self.data.read()?.device.clone(),
parents: vec![self.clone()],
grad: None,
name: None,
})),
})
}
/// Compute the indices of the maximum values along a specified dimension.
///
/// # Arguments
/// * `axis` - `(dim, keep_dim)` tuple.
/// - `dim`: dimension to compute argmax
/// - `keep_dim`:
/// - `true`: keep dimension (size becomes 1)
/// - `false`: remove dimension
///
/// # Returns
/// * `Ok(Tensor)` - The result tensor with dtype `u64` containing the indices of maximum values.
/// * `Err(TensorError)` - The error when computing the argmax.
///
/// # Examples
/// ```
/// use nove::tensor::{Device, Tensor};
/// let device = Device::cpu();
/// let t = Tensor::from_data(vec![1.0, 2.0, 3.0, 4.0], &device, false).unwrap();
///
/// let argmax = t.argmax((0, false)).unwrap();
/// println!("{:?}", argmax);
/// ```
pub fn argmax(&self, axis: (usize, bool)) -> Result<Self, TensorError> {
let inner = self.data.read()?;
let inner_tensor = match &inner.inner {
TensorInner::Tensor(tensor) => tensor,
TensorInner::Var(var) => var,
};
let (dim, keep_dim) = axis;
let new_inner = match keep_dim {
true => TensorInner::Tensor(inner_tensor.argmax_keepdim(dim)?),
false => TensorInner::Tensor(inner_tensor.argmax(dim)?),
};
Ok(Self {
data: Arc::new(RwLock::new(TensorData {
inner: new_inner,
device: self.data.read()?.device.clone(),
parents: vec![self.clone()],
grad: None,
name: None,
})),
})
}
/// Compute the exponential (e^x) of each element in the tensor.
///
/// # Returns
/// * `Ok(Tensor)` - The result tensor with exponential values.
/// * `Err(TensorError)` - The error when computing the exponential.
///
/// # Examples
/// ```
/// use nove::tensor::{Device, Tensor};
/// let device = Device::cpu();
/// let t = Tensor::from_data(vec![0.0, 1.0, 2.0], &device, false).unwrap();
///
/// let exp = t.exp().unwrap();
/// println!("{:?}", exp);
/// ```
pub fn exp(&self) -> Result<Self, TensorError> {
let inner = self.data.read()?;
let inner_tensor = match &inner.inner {
TensorInner::Tensor(tensor) => tensor,
TensorInner::Var(var) => var,
};
let new_inner = TensorInner::Tensor(inner_tensor.exp()?);
Ok(Self {
data: Arc::new(RwLock::new(TensorData {
inner: new_inner,
device: self.data.read()?.device.clone(),
parents: vec![self.clone()],
grad: None,
name: None,
})),
})
}
/// Compute the sum of elements along a specified dimension or across all elements.
///
/// # Arguments
/// * `axis` - Optional `(dim, keep_dim)` tuple.
/// - `Some((dim, keep_dim))`: compute along `dim`
/// - `keep_dim = true`: keep dimension (size becomes 1)
/// - `keep_dim = false`: remove dimension
/// - `None`: compute across all elements
///
/// # Returns
/// * `Ok(Tensor)` - The result tensor containing the sum values.
/// * `Err(TensorError)` - The error when computing the sum.
///
/// # Examples
/// ```
/// use nove::tensor::{Device, Tensor};
/// let device = Device::cpu();
/// let t = Tensor::from_data(vec![1.0, 2.0, 3.0, 4.0], &device, false).unwrap();
///
/// let sum_all = t.sum(None).unwrap();
/// println!("{:?}", sum_all);
/// ```
pub fn sum(&self, axis: Option<(usize, bool)>) -> Result<Self, TensorError> {
let inner = self.data.read()?;
let inner_tensor = match &inner.inner {
TensorInner::Tensor(tensor) => tensor,
TensorInner::Var(var) => var,
};
let new_inner = match axis {
Some((dim, keep_dim)) => match keep_dim {
true => TensorInner::Tensor(inner_tensor.sum_keepdim(dim)?),
false => TensorInner::Tensor(inner_tensor.sum(dim)?),
},
None => TensorInner::Tensor(inner_tensor.sum_all()?),
};
Ok(Self {
data: Arc::new(RwLock::new(TensorData {
inner: new_inner,
device: self.data.read()?.device.clone(),
parents: vec![self.clone()],
grad: None,
name: None,
})),
})
}
/// Compute the natural logarithm (ln) of each element in the tensor.
///
/// # Returns
/// * `Ok(Tensor)` - The result tensor with logarithm values.
/// * `Err(TensorError)` - The error when computing the logarithm.
///
/// # Examples
/// ```
/// use nove::tensor::{Device, Tensor};
/// let device = Device::cpu();
/// let t = Tensor::from_data(vec![1.0, 2.0, 3.0], &device, false).unwrap();
///
/// let log = t.log().unwrap();
/// println!("{:?}", log);
/// ```
pub fn log(&self) -> Result<Self, TensorError> {
let inner = self.data.read()?;
let inner_tensor = match &inner.inner {
TensorInner::Tensor(tensor) => tensor,
TensorInner::Var(var) => var,
};
let new_inner = TensorInner::Tensor(inner_tensor.log()?);
Ok(Self {
data: Arc::new(RwLock::new(TensorData {
inner: new_inner,
device: self.data.read()?.device.clone(),
parents: vec![self.clone()],
grad: None,
name: None,
})),
})
}
/// Subtract two tensors with broadcasting.
///
/// # Arguments
/// * `rhs` - The tensor to subtract.
///
/// # Returns
/// * `Ok(Tensor)` - The result tensor after subtraction.
/// * `Err(TensorError)` - The error when subtracting the tensors.
///
/// # Examples
/// ```
/// use nove::tensor::{Device, Tensor};
/// let device = Device::cpu();
/// let t1 = Tensor::from_data(vec![5.0, 6.0], &device, false).unwrap();
/// let t2 = Tensor::from_data(vec![1.0, 2.0], &device, false).unwrap();
///
/// let t3 = t1.sub(&t2).unwrap();
/// println!("{:?}", t3);
/// ```
pub fn sub(&self, rhs: &Self) -> Result<Self, TensorError> {
let inner = self.data.read()?;
let inner_tensor = match &inner.inner {
TensorInner::Tensor(tensor) => tensor,
TensorInner::Var(var) => var,
};
let rhs_inner = rhs.data.read()?;
let rhs_inner_tensor = match &rhs_inner.inner {
TensorInner::Tensor(tensor) => tensor,
TensorInner::Var(var) => var,
};
let new_inner = TensorInner::Tensor(inner_tensor.broadcast_sub(rhs_inner_tensor)?);
Ok(Self {
data: Arc::new(RwLock::new(TensorData {
inner: new_inner,
device: self.data.read()?.device.clone(),
parents: vec![self.clone(), rhs.clone()],
grad: None,
name: None,
})),
})
}
/// Insert a dimension of size 1 at the specified position.
///
/// # Arguments
/// * `dim` - The dimension at which to insert the new dimension.
///
/// # Returns
/// * `Ok(Tensor)` - The result tensor with the new dimension added.
/// * `Err(TensorError)` - The error when adding the dimension.
///
/// # Examples
/// ```
/// use nove::tensor::{Device, Tensor};
/// let device = Device::cpu();
/// let t = Tensor::from_data(vec![1.0, 2.0, 3.0], &device, false).unwrap();
///
/// let t2 = t.unsqueeze(0).unwrap();
/// println!("{:?}", t2);
/// ```
pub fn unsqueeze(&self, dim: usize) -> Result<Self, TensorError> {
let inner = self.data.read()?;
let inner_tensor = match &inner.inner {
TensorInner::Tensor(tensor) => tensor,
TensorInner::Var(var) => var,
};
let new_inner = TensorInner::Tensor(inner_tensor.unsqueeze(dim)?);
Ok(Self {
data: Arc::new(RwLock::new(TensorData {
inner: new_inner,
device: self.data.read()?.device.clone(),
parents: vec![self.clone()],
grad: None,
name: None,
})),
})
}
/// Gather values from the tensor along the specified dimension using the provided indices.
///
/// # Notes
/// * The data type(`DType`) of the indices tensor must be i64(`DType::I64`).
///
/// # Arguments
/// * `indices` - The tensor containing the indices to gather.
/// * `dim` - The dimension along which to gather values.
///
/// # Returns
/// * `Ok(Tensor)` - The result tensor with gathered values.
/// * `Err(TensorError)` - The error when gathering values.
///
/// # Examples
/// ```
/// use nove::tensor::{Device, Tensor};
/// let device = Device::cpu();
/// let t = Tensor::from_data(vec![1.0, 2.0, 3.0, 4.0], &device, false).unwrap();
/// let indices = Tensor::from_data(vec![0i64, 2i64], &device, false).unwrap();
///
/// let result = t.gather(&indices, 0).unwrap();
/// println!("{:?}", result);
/// ```
pub fn gather(&self, indices: &Self, dim: usize) -> Result<Self, TensorError> {
let inner = self.data.read()?;
let inner_tensor = match &inner.inner {
TensorInner::Tensor(tensor) => tensor,
TensorInner::Var(var) => var,
};
let indices_inner = indices.data.read()?;
let indices_inner_tensor = match &indices_inner.inner {
TensorInner::Tensor(tensor) => tensor,
TensorInner::Var(var) => var,
};
let new_inner = TensorInner::Tensor(inner_tensor.gather(indices_inner_tensor, dim)?);
Ok(Self {
data: Arc::new(RwLock::new(TensorData {
inner: new_inner,
device: self.data.read()?.device.clone(),
parents: vec![self.clone(), indices.clone()],
grad: None,
name: None,
})),
})
}
/// Apply an affine transformation to each element in the tensor: `output = weight * input + bias`.
///
/// # Arguments
/// * `weight` - The multiplicative weight coefficient.
/// * `bias` - The additive bias coefficient.
///
/// # Returns
/// * `Ok(Tensor)` - The result tensor after applying the affine transformation.
/// * `Err(TensorError)` - The error when applying the affine transformation.
///
/// # Examples
/// ```
/// use nove::tensor::{Device, Tensor};
/// let device = Device::cpu();
/// let t = Tensor::from_data(vec![1.0, 2.0, 3.0], &device, false).unwrap();
///
/// let result = t.affine(2.0, 1.0).unwrap();
/// println!("{:?}", result);
/// ```
pub fn affine(&self, weight: f64, bias: f64) -> Result<Self, TensorError> {
let inner = self.data.read()?;
let inner_tensor = match &inner.inner {
TensorInner::Tensor(tensor) => tensor,
TensorInner::Var(var) => var,
};
let new_inner = TensorInner::Tensor(inner_tensor.affine(weight, bias)?);
Ok(Self {
data: Arc::new(RwLock::new(TensorData {
inner: new_inner,
device: self.data.read()?.device.clone(),
parents: vec![self.clone()],
grad: None,
name: None,
})),
})
}
/// Element-wise greater-than-or-equal (>=) comparison with broadcasting, returning a boolean tensor.
///
/// # Arguments
/// * `rhs` - The tensor to compare with.
///
/// # Returns
/// * `Ok(Tensor)` - The result tensor with boolean values.
/// * `Err(TensorError)` - The error when comparing the tensors.
///
/// # Examples
/// ```
/// use nove::tensor::{Device, Tensor};
/// let device = Device::cpu();
/// let lhs = Tensor::from_data(vec![1.0, 2.0, 0.0, 0.0], &device, false).unwrap();
/// let rhs = Tensor::from_data(vec![0.0, 0.0, 3.0, 4.0], &device, false).unwrap();
///
/// let result = lhs.ge(&rhs).unwrap();
/// println!("{:?}", result);
/// ```
pub fn ge(&self, rhs: &Self) -> Result<Self, TensorError> {
let lhs_inner = self.data.read()?;
let lhs_inner_tensor = match &lhs_inner.inner {
TensorInner::Tensor(tensor) => tensor,
TensorInner::Var(var) => var,
};
let rhs_inner = rhs.data.read()?;
let rhs_inner_tensor = match &rhs_inner.inner {
TensorInner::Tensor(tensor) => tensor,
TensorInner::Var(var) => var,
};
let new_inner = TensorInner::Tensor(lhs_inner_tensor.broadcast_ge(rhs_inner_tensor)?);
Ok(Self {
data: Arc::new(RwLock::new(TensorData {
inner: new_inner,
device: self.data.read()?.device.clone(),
parents: vec![self.clone(), rhs.clone()],
grad: None,
name: None,
})),
})
}
/// Element-wise equal (==) comparison with broadcasting, returning a boolean tensor.
///
/// # Arguments
/// * `rhs` - The tensor to compare with.
///
/// # Returns
/// * `Ok(Tensor)` - The result tensor with boolean values(dtype: U8).
/// * `Err(TensorError)` - The error when comparing the tensors.
///
/// # Examples
/// ```
/// use nove::tensor::{Device, Tensor};
/// let device = Device::cpu();
/// let lhs = Tensor::from_data(vec![1.0, 2.0, 0.0, 0.0], &device, false).unwrap();
/// let rhs = Tensor::from_data(vec![0.0, 0.0, 3.0, 4.0], &device, false).unwrap();
///
/// let result = lhs.eq(&rhs).unwrap();
/// println!("{:?}", result);
/// ```
pub fn eq(&self, rhs: &Self) -> Result<Self, TensorError> {
let lhs_inner = self.data.read()?;
let lhs_inner_tensor = match &lhs_inner.inner {
TensorInner::Tensor(tensor) => tensor,
TensorInner::Var(var) => var,
};
let rhs_inner = rhs.data.read()?;
let rhs_inner_tensor = match &rhs_inner.inner {
TensorInner::Tensor(tensor) => tensor,
TensorInner::Var(var) => var,
};
let new_inner = TensorInner::Tensor(lhs_inner_tensor.broadcast_eq(rhs_inner_tensor)?);
Ok(Self {
data: Arc::new(RwLock::new(TensorData {
inner: new_inner,
device: self.data.read()?.device.clone(),
parents: vec![self.clone(), rhs.clone()],
grad: None,
name: None,
})),
})
}
/// Broadcast the tensor to the specified shape.
///
/// # Parameters
/// * `shape` - The shape to broadcast the tensor to.
///
/// # Returns
/// * `Ok(Tensor)` - The broadcasted tensor if successful.
/// * `Err(TensorError)` - The error when broadcasting the tensor.
///
/// # Examples
/// ```
/// use nove::tensor::{Device, Shape, Tensor};
/// let device = Device::cpu();
/// let t = Tensor::from_data(vec![1.0, 2.0, 3.0, 4.0], &device, false).unwrap();
/// let shape = Shape::from_dims(&[2, 4]);
///
/// let result = t.broadcast(&shape).unwrap();
/// println!("{:?}", result);
/// ```
pub fn broadcast(&self, shape: &Shape) -> Result<Self, TensorError> {
let inner = match &self.data.read()?.inner {
TensorInner::Var(var) => {
TensorInner::Var(candle_core::Var::from_tensor(&var.broadcast_as(shape)?)?)
}
TensorInner::Tensor(tensor) => TensorInner::Tensor(tensor.broadcast_as(shape)?),
};
Ok(Self {
data: Arc::new(RwLock::new(TensorData {
inner,
device: self.data.read()?.device.clone(),
parents: vec![],
grad: None,
name: None,
})),
})
}
/// Apply the Rectified Linear Unit (ReLU) activation function element-wise.
///
/// # Returns
/// * `Ok(Tensor)` - The tensor after applying the ReLU activation function.
/// * `Err(TensorError)` - The error when applying the ReLU activation function.
///
/// # Examples
/// ```
/// use nove::tensor::{Device, Tensor};
/// let device = Device::cpu();
/// let t = Tensor::from_data(vec![-1.0, 2.0, -3.0, 4.0], &device, false).unwrap();
///
/// let result = t.relu().unwrap();
/// println!("{:?}", result);
/// ```
pub fn relu(&self) -> Result<Self, TensorError> {
let inner = self.data.read()?;
let inner_tensor = match &inner.inner {
TensorInner::Tensor(tensor) => tensor,
TensorInner::Var(var) => var,
};
let new_inner = TensorInner::Tensor(inner_tensor.relu()?);
Ok(Self {
data: Arc::new(RwLock::new(TensorData {
inner: new_inner,
device: self.data.read()?.device.clone(),
parents: vec![self.clone()],
grad: None,
name: None,
})),
})
}
/// Apply the 2D convolutional operation.
///
/// # Parameters
/// * `kernel` - The kernel tensor.
/// * `padding` - The padding size.
/// * `stride` - The stride size.
/// * `dilation` - The dilation size.
/// * `groups` - The number of groups.
///
/// # Returns
/// * `Ok(Tensor)` - The tensor after applying the convolutional operation.
/// * `Err(TensorError)` - The error when applying the convolutional operation.
///
/// # Examples
/// ```
/// use nove::tensor::{Device, Shape, Tensor};
/// let device = Device::cpu();
/// let t = Tensor::rand(0.0f32, 1.0f32, &Shape::from_dims(&[1, 3, 5, 5]), &device, false).unwrap();
/// let kernel = Tensor::rand(0.0f32, 1.0f32, &Shape::from_dims(&[7, 3, 3, 3]), &device, false).unwrap();
/// let result = t.conv2d(&kernel, 1, 1, 1, 1).unwrap();
/// println!("{:?}", result);
/// ```
pub fn conv2d(
&self,
kernel: &Self,
padding: usize,
stride: usize,
dilation: usize,
groups: usize,
) -> Result<Self, TensorError> {
let inner = self.data.read()?;
let inner_tensor = match &inner.inner {
TensorInner::Tensor(tensor) => tensor,
TensorInner::Var(var) => var,
};
let kernel_inner = kernel.data.read()?;
let kernel_inner_tensor = match &kernel_inner.inner {
TensorInner::Tensor(tensor) => tensor,
TensorInner::Var(var) => var,
};
let new_inner = TensorInner::Tensor(inner_tensor.conv2d(
kernel_inner_tensor,
padding,
stride,
dilation,
groups,
)?);
Ok(Self {
data: Arc::new(RwLock::new(TensorData {
inner: new_inner,
device: self.data.read()?.device.clone(),
parents: vec![self.clone(), kernel.clone()],
grad: None,
name: None,
})),
})
}
/// Apply the mean operation along the specified axis.
///
/// # Parameters
/// * `axis` - Optional `(dim, keep_dim)` tuple.
/// - `Some((dim, keep_dim))`: compute along `dim`
/// - `keep_dim = true`: keep dimension (size becomes 1)
/// - `keep_dim = false`: remove dimension
/// - `None`: compute across all elements
///
/// # Returns
/// * `Ok(Tensor)` - The tensor after applying the mean operation.
/// * `Err(TensorError)` - The error when applying the mean operation.
///
/// # Examples
/// ```
/// use nove::tensor::{Device, Shape, Tensor};
/// let device = Device::cpu();
/// let t = Tensor::rand(0.0f32, 1.0f32, &Shape::from_dims(&[1, 3, 5, 5]), &device, false).unwrap();
/// let result = t.mean(Some((1, false))).unwrap();
/// println!("{:?}", result);
/// ```
pub fn mean(&self, axis: Option<(usize, bool)>) -> Result<Self, TensorError> {
let inner = self.data.read()?;
let inner_tensor = match &inner.inner {
TensorInner::Tensor(tensor) => tensor,
TensorInner::Var(var) => var,
};
let new_inner = match axis {
Some((axis, false)) => TensorInner::Tensor(inner_tensor.mean(axis)?),
Some((axis, true)) => TensorInner::Tensor(inner_tensor.mean_keepdim(axis)?),
None => TensorInner::Tensor(inner_tensor.mean_all()?),
};
Ok(Self {
data: Arc::new(RwLock::new(TensorData {
inner: new_inner,
device: self.data.read()?.device.clone(),
parents: vec![self.clone()],
grad: None,
name: None,
})),
})
}
/// Apply the 2D max pooling operation.
///
/// # Parameters
/// * `kernel_size` - The kernel size.
/// * `stride` - The stride size.
///
/// # Returns
/// * `Ok(Tensor)` - The tensor after applying the max pooling operation.
/// * `Err(TensorError)` - The error when applying the max pooling operation.
///
/// # Examples
/// ```
/// use nove::tensor::{Device, Shape, Tensor};
/// let device = Device::cpu();
/// let t = Tensor::rand(0.0f32, 1.0f32, &Shape::from_dims(&[1, 3, 5, 5]), &device, false).unwrap();
/// let result = t.max_pool2d((2, 2), (2, 2)).unwrap();
/// println!("{:?}", result);
/// ```
pub fn max_pool2d(
&self,
kernel_size: (usize, usize),
stride: (usize, usize),
) -> Result<Self, TensorError> {
let inner = self.data.read()?;
let inner_tensor = match &inner.inner {
TensorInner::Tensor(tensor) => tensor,
TensorInner::Var(var) => var,
};
let new_inner =
TensorInner::Tensor(inner_tensor.max_pool2d_with_stride(kernel_size, stride)?);
Ok(Self {
data: Arc::new(RwLock::new(TensorData {
inner: new_inner,
device: self.data.read()?.device.clone(),
parents: vec![self.clone()],
grad: None,
name: None,
})),
})
}
/// Permute the dimensions of the tensor.
///
/// # Parameters
/// * `dims` - The new dimensions order.
///
/// # Returns
/// * `Ok(Tensor)` - The tensor after permuting the dimensions.
/// * `Err(TensorError)` - The error when permuting the dimensions.
///
/// # Examples
/// ```
/// use nove::tensor::{Device, Shape, Tensor};
/// let device = Device::cpu();
/// let t = Tensor::rand(0.0f32, 1.0f32, &Shape::from_dims(&[1, 3, 5, 5]), &device, false).unwrap();
/// let result = t.permute(&[0, 3, 1, 2]).unwrap();
/// println!("{:?}", result);
/// ```
pub fn permute(&self, dims: &[usize]) -> Result<Self, TensorError> {
let inner = self.data.read()?;
let inner_tensor = match &inner.inner {
TensorInner::Tensor(tensor) => tensor,
TensorInner::Var(var) => var,
};
let new_inner = TensorInner::Tensor(inner_tensor.permute(dims)?);
Ok(Self {
data: Arc::new(RwLock::new(TensorData {
inner: new_inner,
device: self.data.read()?.device.clone(),
parents: vec![self.clone()],
grad: None,
name: None,
})),
})
}
}