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
use crate::gradient_function::{GradientFunction};
use crate::ndarray::flags::NdArrayFlags;
use crate::ndarray::NdArray;
use crate::util::flatten::Flatten;
use crate::util::nested::Nested;
use crate::util::shape::Shape;
use crate::util::to_vec::ToVec;
use crate::{Tensor, TensorDataType};
use crate::none_backwards::NoneBackwards;
impl<'a, T: TensorDataType> Tensor<'a, T> {
/// Constructs a new tensor from the given array, gradient function, and metadata
///
/// # Parameters
/// - `requires_grad`: If gradients need to be computed for this tensor
/// - `grad_fn`: The gradient function used on the backwards pass
pub(crate) unsafe fn from_raw_parts(array: NdArray<'a, T>,
requires_grad: bool,
grad_fn: GradientFunction<T>) -> Self {
let mut flags = NdArrayFlags::empty();
if requires_grad {
flags |= NdArrayFlags::RequiresGrad;
}
Self {
array,
flags,
grad_fn,
}
}
/// Constructs a new tensor from the given array
///
/// # Parameters
/// - `requires_grad`: If gradients need to be computed for this tensor
///
/// # Safety
/// - `user_created` must be set only if the Tensor was generated by the user outside this crate
pub(crate) unsafe fn from_array_and_flags(array: NdArray<'a, T>,
requires_grad: bool,
user_created: bool) -> Self {
let mut flags = NdArrayFlags::empty();
if requires_grad {
flags |= NdArrayFlags::RequiresGrad;
}
if user_created {
flags |= NdArrayFlags::UserCreated;
}
Self {
array,
flags,
grad_fn: NoneBackwards::new(),
}
}
/// Constructs an n-dimensional `Tensor` from input data such as a vector or array.
///
/// # Parameters
/// - `data`: a nested array or vector of valid data types (floats, integers, bools)
///
/// # Panics
/// - If the input data has inhomogeneous dimensions, i.e., nested arrays do not have consistent sizes.
/// - If the input data is empty (cannot create a zero-length tensor)
///
/// # Example
/// ```
/// # use chela::*;
///
/// let tensor = Tensor::from([[1.0, 2.0], [3.0, 4.0]]);
/// assert_eq!(tensor.shape(), &[2, 2]);
///
/// let tensor = Tensor::from(vec![1.0, 2.0, 3.0, 4.0, 5.0]);
/// assert_eq!(tensor.ndims(), 1);
/// ```
pub fn from<const D: usize>(data: impl Flatten<T> + Shape + Nested<{ D }>) -> Self {
let array = NdArray::from(data);
unsafe { Tensor::from_array_and_flags(array, false, true) }
}
/// Creates a tensor filled with a specified value and given shape.
///
/// # Parameters
///
/// * `n` - The value to fill the tensor with (can be any valid data type like float, integer, or bool).
/// * `shape` - An array or vector representing the shape of the tensor (e.g. `[2, 3, 5]`).
///
/// # Panics
/// This function panics if the provided shape is empty.
///
/// # Examples
///
/// ```
/// # use chela::*;
///
/// let tensor = Tensor::full(5.0, [2, 3]); // creates a 2x3 tensor filled with the value 5.
/// ```
pub fn full(n: T, shape: impl ToVec<usize>) -> Self {
let array = NdArray::full(n, shape);
unsafe { Tensor::from_array_and_flags(array, false, true) }
}
/// Creates a new tensor filled with zeros with the given shape.
///
/// # Parameters
/// - `shape`: An array or vector representing the shape of the tensor (e.g. `[2, 3, 5]`).
///
/// # Panics
/// This function panics if the provided shape is empty.
///
/// # Examples
/// ```
/// # use chela::*;
///
/// let tensor = Tensor::<f32>::zeros([2, 3]);
/// ```
pub fn zeros(shape: impl ToVec<usize>) -> Self {
let array = NdArray::zeros(shape);
unsafe { Tensor::from_array_and_flags(array, false, true) }
}
/// Creates a new tensor filled with ones with the given shape.
///
/// # Parameters
/// - `shape`: An array or vector representing the shape of the tensor (e.g. `[2, 3, 5]`).
///
/// # Panics
/// This function panics if the provided shape is empty.
///
/// # Examples
/// ```
/// # use chela::*;
///
/// let tensor = Tensor::<f32>::ones([2, 3]);
/// ```
pub fn ones(shape: impl ToVec<usize>) -> Self {
let array = NdArray::ones(shape);
unsafe { Tensor::from_array_and_flags(array, false, true) }
}
/// Creates a 0-dimensional (shapeless) tensor containing a single value.
///
/// # Parameters
/// - `n`: The value to be stored in the scalar tensor.
///
/// # Example
/// ```rust
/// # use chela::*;
///
/// let scalar_array = Tensor::scalar(42.0);
/// assert_eq!(scalar_array.shape(), []);
/// assert_eq!(scalar_array.value(), 42.0);
/// ```
pub fn scalar(n: T) -> Self {
let array = NdArray::scalar(n);
unsafe { Tensor::from_array_and_flags(array, false, true) }
}
/// Generates a 1D tensor with evenly spaced values within a specified range.
///
/// # Arguments
///
/// * `start` - The starting value of the sequence, inclusive.
/// * `stop` - The ending value of the sequence, exclusive.
///
/// # Returns
///
/// An `Tensor` containing values starting from `start` and ending before `stop`,
/// with a step-size of 1.
///
/// # Examples
///
/// ```rust
/// # use chela::*;
/// let tensor = Tensor::arange(0.0, 5.0); // [0, 1, 2, 3, 4].
/// ```
pub fn arange(start: T, stop: T) -> Tensor<'static, T> {
let array = NdArray::arange(start, stop);
unsafe { Tensor::from_array_and_flags(array, false, true) }
}
/// Generates a 1D tensor with evenly spaced values within a specified range.
///
/// # Arguments
///
/// * `start` - The starting value of the sequence, inclusive.
/// * `stop` - The ending value of the sequence, exclusive.
/// * `step` - The interval between each consecutive value
///
/// # Examples
///
/// ```rust
/// # use chela::*;
/// let tensor = Tensor::arange_with_step(0.0, 5.0, 2.0); // [0, 2, 4].
/// ```
pub fn arange_with_step(start: T, stop: T, step: T) -> Tensor<'static, T> {
let array = NdArray::arange_with_step(start, stop, step);
unsafe { Tensor::from_array_and_flags(array, false, true) }
}
/// Generates a 1-dimensional tensor with `num `evenly spaced values between `start` and `stop`
/// (inclusive).
///
/// # Arguments
///
/// * `start` - The starting value of the sequence.
/// * `stop` - The ending value of the sequence. The value is inclusive in the range.
/// * `num` - The number of evenly spaced values to generate. Must be greater than 0.
///
/// # Panic
///
/// Panics if `num` is 0.
///
/// # Example
///
/// ```
/// # use chela::*;
/// let result = Tensor::linspace(0f32, 1.0, 5); // [0.0, 0.25, 0.5, 0.75, 1.0]
/// assert_eq!(result, Tensor::from([0f32, 0.25, 0.5, 0.75, 1.0]));
/// ```
pub fn linspace(start: T, stop: T, num: usize) -> Tensor<'static, T> {
let array = NdArray::linspace(start, stop, num);
unsafe { Tensor::from_array_and_flags(array, false, true) }
}
/// Generates a 1-dimensional tensor with `num `evenly spaced values between `start` and `stop`
/// (exclusive).
///
/// # Arguments
///
/// * `start` - The starting value of the sequence.
/// * `stop` - The ending value of the sequence. The value is exclusive in the range.
/// * `num` - The number of evenly spaced values to generate. Must be greater than 0.
///
/// # Panic
///
/// Panics if `num` is 0.
///
/// # Example
///
/// ```
/// # use chela::*;
/// let result = Tensor::linspace_exclusive(0.0f32, 1.0, 5);
/// assert_eq!(result, Tensor::from([0f32, 0.2, 0.4, 0.6, 0.8]));
/// ```
pub fn linspace_exclusive(start: T, stop: T, num: usize) -> Tensor<'static, T> {
let array = NdArray::linspace_exclusive(start, stop, num);
unsafe { Tensor::from_array_and_flags(array, false, true) }
}
}