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
use std::sync::{Arc, RwLock};
use crate::{
DType, Device, Shape, Tensor, TensorError,
tensor::{TensorData, TensorInner},
};
impl Tensor {
/// Move the tensor to the specified device inplace.
///
/// # Arguments
/// * `device` - The device to move the tensor to.
///
/// # Returns
/// * `Ok(())` - If the tensor is successfully moved to the device.
/// * `Err(TensorError)` - The error when moving the tensor to the device.
///
/// # Examples
/// ```
/// use nove::tensor::{Device, Tensor, TensorError};
/// let cpu = Device::cpu();
/// let tensor = Tensor::from_data(&[1.0f32, 2.0f32], &cpu, false).unwrap();
///
/// // Move the tensor to the CPU
/// match tensor.to_device_inplace(&cpu) {
/// Ok(()) => println!("Tensor has been moved to CPU"),
/// Err(err) => println!("Error moving tensor to CPU: {:?}", err),
/// }
/// ```
pub fn to_device_inplace(&self, device: &Device) -> Result<(), TensorError> {
// Check the device
if self.device()? == *device {
return Ok(());
}
// Create the new inner
let new_inner = match &*self.data.inner.read()? {
TensorInner::Tensor(tensor) => TensorInner::Tensor(tensor.to_device(device)?),
TensorInner::Var(var) => {
TensorInner::Var(candle_core::Var::from_tensor(&var.to_device(device)?)?)
}
};
// Create the new gradient
let new_grad = match &*self.data.grad.read()? {
Some(grad) => Some(grad.to_device(device)?),
None => None,
};
{
let mut inner_write = self.data.inner.write()?;
let mut grad_write = self.data.grad.write()?;
let mut device_write = self.data.device.write()?;
// Update the inner
*inner_write = new_inner;
// Update the gradient
*grad_write = new_grad;
// Update the device
*device_write = device.clone();
}
Ok(())
}
/// Create a new tensor like the current tensor, but on the specified device.
///
/// # Arguments
/// * `device` - The device to move the tensor to.
///
/// # Returns
/// * `Ok(Tensor)` - The new tensor on the specified device.
/// * `Err(TensorError)` - The error when moving the tensor to the device.
pub fn to_device(&self, device: &Device) -> Result<Tensor, TensorError> {
// Check the device, if the device is the same, return the original tensor
if self.device()? == *device {
return Ok(self.clone());
}
// Create the new inner
let new_inner = match &*self.data.inner.read()? {
TensorInner::Tensor(tensor) => TensorInner::Tensor(tensor.to_device(device)?),
TensorInner::Var(var) => {
TensorInner::Var(candle_core::Var::from_tensor(&var.to_device(device)?)?)
}
};
// Create the new gradient
let new_grad = match &*self.data.grad.read()? {
Some(grad) => Some(grad.to_device(device)?),
None => None,
};
// Create the new tensor
Ok(Tensor {
data: Arc::new(TensorData {
inner: RwLock::new(new_inner),
grad: RwLock::new(new_grad),
device: RwLock::new(device.clone()),
parents: RwLock::new(vec![self.clone()]),
}),
})
}
/// Get the device of the tensor.
///
/// # Returns
/// * `Ok(device)` - The device of the tensor.
/// * `Err(TensorError)` - The error when getting the device of the tensor.
///
/// # Examples
/// ```
/// use nove::tensor::{Device, Tensor};
/// let cpu = Device::cpu();
/// let tensor = Tensor::from_data(&[1.0f32, 2.0f32], &cpu, false).unwrap();
///
/// // Get the device of the tensor
/// let device = tensor.device().unwrap();
/// println!("The tensor is on device: {:?}", device);
/// ```
pub fn device(&self) -> Result<Device, TensorError> {
let device = self.data.device.read()?;
Ok(device.clone())
}
/// Convert the tensor to the specified dtype inplace.
///
/// # Notes
/// * The gradient (if present) is also converted to the same dtype to maintain consistency.
///
/// # Arguments
/// * `dtype` - The dtype to convert the tensor to.
///
/// # Returns
/// * `Ok(())` - If the tensor is successfully converted to the dtype.
/// * `Err(TensorError)` - The error when converting the tensor to the dtype.
///
/// # Examples
/// ```
/// use nove::tensor::{Device, DType, Tensor, TensorError};
/// let cpu = Device::cpu();
/// let mut tensor = Tensor::from_data(&[1.0f32, 2.0f32], &cpu, false).unwrap();
///
/// // Convert the tensor to F64 dtype
/// match tensor.to_dtype_inplace(&DType::F64) {
/// Ok(()) => println!("Tensor has been converted to F64 dtype"),
/// Err(err) => println!("Error converting tensor to F64 dtype: {:?}", err),
/// }
/// ```
pub fn to_dtype_inplace(&self, dtype: &DType) -> Result<(), TensorError> {
// Check current dtype first to avoid unnecessary conversion
let current_dtype = {
let inner = self.data.inner.read()?;
match &*inner {
TensorInner::Tensor(tensor) => tensor.dtype(),
TensorInner::Var(var) => var.dtype(),
}
};
// If already the target dtype, return Ok
if current_dtype == *dtype {
return Ok(());
}
// Create the new inner
let new_inner = match &*self.data.inner.read()? {
TensorInner::Tensor(tensor) => TensorInner::Tensor(tensor.to_dtype(*dtype)?),
TensorInner::Var(var) => {
TensorInner::Var(candle_core::Var::from_tensor(&var.to_dtype(*dtype)?)?)
}
};
// Create the new gradient
let new_grad = match &*self.data.grad.read()? {
Some(grad) => Some(grad.to_dtype(*dtype)?),
None => None,
};
{
let mut inner_write = self.data.inner.write()?;
let mut grad_write = self.data.grad.write()?;
// Update the inner
*inner_write = new_inner;
// Update the gradient
*grad_write = new_grad;
}
Ok(())
}
/// Get the dtype of the tensor.
///
/// # Returns
/// * `Ok(Dtype)` - The dtype of the tensor.
/// * `Err(TensorError)` - The error when getting the dtype of the tensor.
///
/// # Examples
/// ```
/// use nove::tensor::{Device, Tensor};
/// let cpu = Device::cpu();
/// let tensor = Tensor::from_data(&[1.0f32, 2.0f32], &cpu, false).unwrap();
///
/// // Get the dtype of the tensor
/// let dtype = tensor.dtype().unwrap();
/// println!("The dtype of the tensor is: {:?}", dtype);
/// ```
pub fn dtype(&self) -> Result<DType, TensorError> {
let inner = self.data.inner.read()?;
let dtype = match &*inner {
TensorInner::Tensor(tensor) => tensor.dtype(),
TensorInner::Var(var) => var.dtype(),
};
Ok(dtype)
}
/// Reshape the tensor inplace to the specified shape.
///
/// # Arguments
/// * `shape` - The shape to reshape the tensor to.
///
/// # Returns
/// * `Ok(())` - If the tensor is successfully reshaped.
/// * `Err(TensorError)` - The error when reshaping the tensor.
pub fn to_shape_inplace(&self, shape: &Shape) -> Result<(), TensorError> {
let new_inner = match &*self.data.inner.read()? {
TensorInner::Tensor(tensor) => TensorInner::Tensor(tensor.reshape(shape)?),
TensorInner::Var(var) => {
TensorInner::Var(candle_core::Var::from_tensor(&var.reshape(shape)?)?)
}
};
let new_grad = match &*self.data.grad.read()? {
Some(grad) => Some(grad.reshape(shape)?),
None => None,
};
{
let mut inner_write = self.data.inner.write()?;
let mut grad_write = self.data.grad.write()?;
// Update the inner
*inner_write = new_inner;
// Update the gradient
*grad_write = new_grad;
}
Ok(())
}
/// Create a new tensor like the current tensor with the specified shape.
///
/// # Arguments
/// * `shape` - The shape to reshape the tensor to.
///
/// # Returns
/// * `Ok(Tensor)` - The new tensor with the specified shape.
/// * `Err(TensorError)` - The error when reshaping the tensor.
pub fn to_shape(&self, shape: &Shape) -> Result<Tensor, TensorError> {
let new_inner = match &*self.data.inner.read()? {
TensorInner::Tensor(tensor) => TensorInner::Tensor(tensor.reshape(shape)?),
TensorInner::Var(var) => {
TensorInner::Var(candle_core::Var::from_tensor(&var.reshape(shape)?)?)
}
};
let new_grad = match &*self.data.grad.read()? {
Some(grad) => Some(grad.reshape(shape)?),
None => None,
};
Ok(Tensor {
data: Arc::new(TensorData {
inner: RwLock::new(new_inner),
grad: RwLock::new(new_grad),
device: RwLock::new(self.data.device.read()?.clone()),
parents: RwLock::new(vec![self.clone()]),
}),
})
}
/// Get the shape of the tensor.
///
/// # Returns
/// * `Ok(shape)` - The shape of the tensor.
/// * `Err(TensorError)` - The error when getting the shape of the tensor.
///
/// # Examples
/// ```
/// use nove::tensor::{Device, Shape, Tensor};
/// let cpu = Device::cpu();
/// let tensor = Tensor::from_data(&[1.0f32, 2.0f32], &cpu, false).unwrap();
///
/// // Get the shape of the tensor
/// let shape = tensor.shape().unwrap();
/// println!("The shape of the tensor is: {:?}", shape);
/// ```
pub fn shape(&self) -> Result<Shape, TensorError> {
let inner = self.data.inner.read()?;
let shape = match &*inner {
TensorInner::Tensor(tensor) => tensor.shape(),
TensorInner::Var(var) => var.shape(),
};
Ok(Shape::from(shape))
}
/// Get the number of dimensions of the tensor.
///
/// # Returns
/// * `Ok(num_dim)` - The number of dimensions of the tensor.
/// * `Err(TensorError)` - The error when getting the number of dimensions of the tensor.
///
/// # Examples
/// ```
/// use nove::tensor::{Device, Tensor};
/// let cpu = Device::cpu();
/// let tensor = Tensor::from_data(&[1.0f32, 2.0f32], &cpu, false).unwrap();
///
/// // Get the number of dimensions of the tensor
/// let num_dim = tensor.num_dim().unwrap();
/// println!("The number of dimensions of the tensor is : {:?}", num_dim);
/// ```
pub fn num_dim(&self) -> Result<usize, TensorError> {
let shape = self.shape()?;
Ok(shape.rank())
}
}