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
use std::sync::{Arc, RwLock};
use crate::{
DType, Device, Shape, Tensor, TensorError,
tensor::{TensorData, TensorInner},
};
impl Tensor {
/// 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());
}
let new_inner = match &self.data.read()?.inner {
TensorInner::Tensor(tensor) => TensorInner::Tensor(tensor.to_device(device)?),
TensorInner::Var(var) => {
TensorInner::Var(candle_core::Var::from_tensor(&var.to_device(device)?)?)
}
};
let new_grad = match &self.data.read()?.grad {
Some(grad) => Some(grad.to_device(device)?),
None => None,
};
Ok(Tensor {
data: Arc::new(RwLock::new(TensorData {
inner: new_inner,
grad: new_grad,
device: device.clone(),
parents: vec![self.clone()],
name: self.data.read()?.name.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 data = self.data.read()?;
Ok(data.device.clone())
}
/// Create a new tensor like the current tensor but with the specified dtype.
///
/// # Arguments
/// * `dtype` - The dtype to convert the tensor to.
///
/// # Returns
/// * `Ok(tensor)` - The new tensor if successful.
/// * `Err(TensorError)` - The error when converting the tensor to the dtype.
pub fn to_dtype(&self, dtype: &DType) -> Result<Tensor, TensorError> {
// Check current dtype first to avoid unnecessary conversion
let current_dtype = {
let data = self.data.read()?;
match &data.inner {
TensorInner::Tensor(tensor) => tensor.dtype(),
TensorInner::Var(var) => var.dtype(),
}
};
// If already the target dtype, return the tensor itself
if current_dtype == *dtype {
return Ok(self.clone());
}
let new_inner = match &self.data.read()?.inner {
TensorInner::Tensor(tensor) => TensorInner::Tensor(tensor.to_dtype(*dtype)?),
TensorInner::Var(var) => {
TensorInner::Var(candle_core::Var::from_tensor(&var.to_dtype(*dtype)?)?)
}
};
let new_grad = match &self.data.read()?.grad {
Some(grad) => Some(grad.to_dtype(dtype)?),
None => None,
};
Ok(Tensor {
data: Arc::new(RwLock::new(TensorData {
inner: new_inner,
device: self.data.read()?.device.clone(),
grad: new_grad,
parents: vec![self.clone()],
name: self.data.read()?.name.clone(),
})),
})
}
/// 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 data = self.data.read()?;
let dtype = match &data.inner {
TensorInner::Tensor(tensor) => tensor.dtype(),
TensorInner::Var(var) => var.dtype(),
};
Ok(dtype)
}
/// 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.
///
/// # Examples
/// ```
/// use nove::tensor::{Device, Shape, Tensor};
/// let cpu = Device::cpu();
/// let tensor = Tensor::from_data(&[1.0f32, 2.0f32], &cpu, false).unwrap();
///
/// // Reshape the tensor
/// let reshaped_tensor = tensor.reshape(&Shape::from(&[2, 1])).unwrap();
///
/// // Get the shape of the reshaped tensor
/// let shape = reshaped_tensor.shape().unwrap();
/// println!("The shape of the reshaped tensor is: {:?}", shape);
/// ```
pub fn reshape(&self, shape: &Shape) -> Result<Tensor, TensorError> {
let new_inner = match &self.data.read()?.inner {
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.read()?.grad {
Some(grad) => Some(grad.reshape(shape)?),
None => None,
};
Ok(Tensor {
data: Arc::new(RwLock::new(TensorData {
inner: new_inner,
grad: new_grad,
device: self.data.read()?.device.clone(),
parents: vec![self.clone()],
name: self.data.read()?.name.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 data = self.data.read()?;
let shape = match &data.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())
}
/// Get the name of the tensor.
///
/// # Returns
/// * `Ok(Some(name))` - The name of the tensor if it has been set.
/// * `Ok(None)` - The tensor does not have a name.
/// * `Err(TensorError)` - The error when getting the name 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();
///
/// // Set the name of the tensor
/// let named_tensor = tensor.require_name("my_tensor").unwrap();
///
/// // Get the name of the tensor
/// let name = named_tensor.name().unwrap();
/// println!("The name of the tensor is: {:?}", name);
/// ```
pub fn name(&self) -> Result<Option<String>, TensorError> {
let data = self.data.read()?;
Ok(data.name.clone())
}
/// Create a new tensor like the current tensor with the specified name.
///
/// # Arguments
/// * `name` - The name to set for the tensor.
///
/// # Returns
/// * `Ok(Tensor)` - The new tensor with the specified name.
/// * `Err(TensorError)` - The error when setting the name 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();
///
/// // Set the name of the tensor
/// let named_tensor = tensor.require_name("my_tensor").unwrap();
///
/// // Get the name of the tensor
/// let name = named_tensor.name().unwrap();
/// println!("The name of the tensor is: {:?}", name);
/// ```
pub fn require_name(&self, name: &str) -> Result<Tensor, TensorError> {
let new_tensor = self.deep_clone()?;
new_tensor.data.write()?.name = Some(name.to_string());
Ok(new_tensor)
}
}