axonml-tensor 0.6.1

N-dimensional tensor operations for the Axonml ML framework
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
//! Views and Slicing - Tensor Indexing Operations
//!
//! # File
//! `crates/axonml-tensor/src/view.rs`
//!
//! # Author
//! Andrew Jewell Sr - AutomataNexus
//!
//! # Updated
//! March 8, 2026
//!
//! # Disclaimer
//! Use at own risk. This software is provided "as is", without warranty of any
//! kind, express or implied. The author and AutomataNexus shall not be held
//! liable for any damages arising from the use of this software.

use axonml_core::dtype::{Numeric, Scalar};
use axonml_core::error::{Error, Result};

use crate::shape::{Shape, numel};
use crate::tensor::Tensor;

// =============================================================================
// Slice Specification
// =============================================================================

/// Specifies how to slice along a single dimension.
#[derive(Debug, Clone, Copy)]
pub enum SliceSpec {
    /// Select a single index, reducing dimensionality.
    Index(isize),
    /// Select a range [start, stop) with optional step.
    Range {
        /// Start index (inclusive), None = beginning
        start: Option<isize>,
        /// Stop index (exclusive), None = end
        stop: Option<isize>,
        /// Step size, default 1
        step: isize,
    },
    /// Keep all elements in this dimension.
    All,
    /// Add a new dimension of size 1.
    NewAxis,
}

impl SliceSpec {
    /// Creates a range slice from start to stop.
    #[must_use]
    pub fn range(start: isize, stop: isize) -> Self {
        Self::Range {
            start: Some(start),
            stop: Some(stop),
            step: 1,
        }
    }

    /// Creates a range slice with step.
    #[must_use]
    pub fn range_step(start: isize, stop: isize, step: isize) -> Self {
        Self::Range {
            start: Some(start),
            stop: Some(stop),
            step,
        }
    }

    /// Creates a slice from start to end.
    #[must_use]
    pub fn from(start: isize) -> Self {
        Self::Range {
            start: Some(start),
            stop: None,
            step: 1,
        }
    }

    /// Creates a slice from beginning to stop.
    #[must_use]
    pub fn to(stop: isize) -> Self {
        Self::Range {
            start: None,
            stop: Some(stop),
            step: 1,
        }
    }
}

// =============================================================================
// Slicing Implementation
// =============================================================================

impl<T: Scalar> Tensor<T> {
    /// Returns a slice of the tensor along the first dimension.
    ///
    /// # Arguments
    /// * `start` - Start index (inclusive)
    /// * `end` - End index (exclusive)
    pub fn slice_dim0(&self, start: usize, end: usize) -> Result<Self> {
        if self.ndim() == 0 {
            return Err(Error::invalid_operation("Cannot slice a scalar"));
        }

        let dim_size = self.shape[0];
        if start > end || end > dim_size {
            return Err(Error::IndexOutOfBounds {
                index: end,
                size: dim_size,
            });
        }

        let mut new_shape = self.shape.clone();
        new_shape[0] = end - start;

        let new_offset = self.offset + start * self.strides[0] as usize;

        Ok(Self {
            storage: self.storage.clone(),
            shape: new_shape,
            strides: self.strides.clone(),
            offset: new_offset,
        })
    }

    /// Returns a view selecting a single index along a dimension.
    ///
    /// This reduces the dimensionality by 1.
    ///
    /// # Arguments
    /// * `dim` - Dimension to select from
    /// * `index` - Index to select
    pub fn select(&self, dim: usize, index: usize) -> Result<Self> {
        if dim >= self.ndim() {
            return Err(Error::InvalidDimension {
                index: dim as i64,
                ndim: self.ndim(),
            });
        }

        if index >= self.shape[dim] {
            return Err(Error::IndexOutOfBounds {
                index,
                size: self.shape[dim],
            });
        }

        let mut new_shape = self.shape.clone();
        new_shape.remove(dim);

        let mut new_strides = self.strides.clone();
        new_strides.remove(dim);

        let new_offset = self.offset + index * self.strides[dim] as usize;

        Ok(Self {
            storage: self.storage.clone(),
            shape: new_shape,
            strides: new_strides,
            offset: new_offset,
        })
    }

    /// Returns a narrow view along a dimension.
    ///
    /// # Arguments
    /// * `dim` - Dimension to narrow
    /// * `start` - Start index
    /// * `length` - Length of the narrow view
    pub fn narrow(&self, dim: usize, start: usize, length: usize) -> Result<Self> {
        if dim >= self.ndim() {
            return Err(Error::InvalidDimension {
                index: dim as i64,
                ndim: self.ndim(),
            });
        }

        if start + length > self.shape[dim] {
            return Err(Error::IndexOutOfBounds {
                index: start + length,
                size: self.shape[dim],
            });
        }

        let mut new_shape = self.shape.clone();
        new_shape[dim] = length;

        let new_offset = self.offset + start * self.strides[dim] as usize;

        Ok(Self {
            storage: self.storage.clone(),
            shape: new_shape,
            strides: self.strides.clone(),
            offset: new_offset,
        })
    }

    /// Splits the tensor into chunks along a dimension.
    ///
    /// # Arguments
    /// * `chunks` - Number of chunks
    /// * `dim` - Dimension to split along
    pub fn chunk(&self, chunks: usize, dim: usize) -> Result<Vec<Self>> {
        if dim >= self.ndim() {
            return Err(Error::InvalidDimension {
                index: dim as i64,
                ndim: self.ndim(),
            });
        }

        let dim_size = self.shape[dim];
        let chunk_size = dim_size.div_ceil(chunks);
        let mut result = Vec::with_capacity(chunks);

        let mut start = 0;
        while start < dim_size {
            let length = (chunk_size).min(dim_size - start);
            result.push(self.narrow(dim, start, length)?);
            start += length;
        }

        Ok(result)
    }

    /// Splits the tensor into parts of specified sizes along a dimension.
    ///
    /// # Arguments
    /// * `sizes` - Size of each part
    /// * `dim` - Dimension to split along
    pub fn split(&self, sizes: &[usize], dim: usize) -> Result<Vec<Self>> {
        if dim >= self.ndim() {
            return Err(Error::InvalidDimension {
                index: dim as i64,
                ndim: self.ndim(),
            });
        }

        let total: usize = sizes.iter().sum();
        if total != self.shape[dim] {
            return Err(Error::invalid_operation(format!(
                "Split sizes {} don't sum to dimension size {}",
                total, self.shape[dim]
            )));
        }

        let mut result = Vec::with_capacity(sizes.len());
        let mut start = 0;

        for &size in sizes {
            result.push(self.narrow(dim, start, size)?);
            start += size;
        }

        Ok(result)
    }
}

// =============================================================================
// Indexing Implementation
// =============================================================================

impl<T: Numeric> Tensor<T> {
    /// Gathers values along a dimension according to indices.
    ///
    /// # Arguments
    /// * `dim` - Dimension to gather along
    /// * `indices` - Indices tensor
    pub fn gather(&self, dim: usize, indices: &Tensor<i64>) -> Result<Self> {
        if dim >= self.ndim() {
            return Err(Error::InvalidDimension {
                index: dim as i64,
                ndim: self.ndim(),
            });
        }

        // For simplicity, this is a basic implementation
        // A full implementation would match PyTorch's semantics exactly
        let output_shape = indices.shape();
        let mut output_data = vec![T::zero(); numel(output_shape)];

        let indices_data = indices.to_vec();
        let self_data = self.to_vec();

        for (out_idx, &index) in indices_data.iter().enumerate() {
            let index = index as usize;
            if index >= self.shape[dim] {
                return Err(Error::IndexOutOfBounds {
                    index,
                    size: self.shape[dim],
                });
            }
            // Simplified: assumes 1D case
            output_data[out_idx] = self_data[index];
        }

        Tensor::from_vec(output_data, output_shape)
    }

    /// Returns elements selected by a boolean mask.
    ///
    /// # Arguments
    /// * `mask` - Boolean mask tensor
    pub fn masked_select(&self, mask: &[bool]) -> Result<Self> {
        if mask.len() != self.numel() {
            return Err(Error::shape_mismatch(&[mask.len()], &[self.numel()]));
        }

        let data = self.to_vec();
        let selected: Vec<T> = data
            .into_iter()
            .zip(mask.iter())
            .filter(|(_, m)| **m)
            .map(|(v, _)| v)
            .collect();

        let len = selected.len();
        Tensor::from_vec(selected, &[len])
    }

    /// Sets elements according to a boolean mask.
    ///
    /// # Arguments
    /// * `mask` - Boolean mask tensor
    /// * `value` - Value to set where mask is true
    pub fn masked_fill_(&self, mask: &[bool], value: T) -> Result<()> {
        if mask.len() != self.numel() {
            return Err(Error::shape_mismatch(&[mask.len()], &[self.numel()]));
        }

        if !self.is_contiguous() {
            return Err(Error::NotContiguous);
        }

        {
            let mut guard = self.storage.as_slice_mut();
            for (idx, &m) in mask.iter().enumerate() {
                if m {
                    guard[self.offset + idx] = value;
                }
            }
        }

        Ok(())
    }
}

// =============================================================================
// Concatenation and Stacking
// =============================================================================

/// Concatenates tensors along an existing dimension.
///
/// # Arguments
/// * `tensors` - Slice of tensors to concatenate
/// * `dim` - Dimension along which to concatenate
pub fn cat<T: Scalar>(tensors: &[Tensor<T>], dim: usize) -> Result<Tensor<T>> {
    if tensors.is_empty() {
        return Err(Error::invalid_operation("Cannot concatenate empty list"));
    }

    let first = &tensors[0];
    let ndim = first.ndim();

    if dim >= ndim {
        return Err(Error::InvalidDimension {
            index: dim as i64,
            ndim,
        });
    }

    // Validate shapes match except for concat dimension
    for t in tensors.iter().skip(1) {
        if t.ndim() != ndim {
            return Err(Error::invalid_operation(
                "All tensors must have same number of dimensions",
            ));
        }
        for (d, (&s1, &s2)) in first.shape().iter().zip(t.shape().iter()).enumerate() {
            if d != dim && s1 != s2 {
                return Err(Error::shape_mismatch(first.shape(), t.shape()));
            }
        }
    }

    // Compute output shape
    let mut output_shape = Shape::from_slice(first.shape());
    output_shape[dim] = tensors.iter().map(|t| t.shape()[dim]).sum();

    // Allocate output
    let total_numel = numel(&output_shape);
    let mut output_data = vec![T::zeroed(); total_numel];

    // Copy data - simplified for contiguous case
    let mut offset = 0;
    for t in tensors {
        let data = t.to_vec();
        for val in data {
            output_data[offset] = val;
            offset += 1;
        }
    }

    Tensor::from_vec(output_data, &output_shape)
}

/// Stacks tensors along a new dimension.
///
/// # Arguments
/// * `tensors` - Slice of tensors to stack
/// * `dim` - Dimension at which to insert the new axis
pub fn stack<T: Scalar>(tensors: &[Tensor<T>], dim: usize) -> Result<Tensor<T>> {
    if tensors.is_empty() {
        return Err(Error::invalid_operation("Cannot stack empty list"));
    }

    // Unsqueeze each tensor and then concatenate
    let unsqueezed: Result<Vec<Tensor<T>>> =
        tensors.iter().map(|t| t.unsqueeze(dim as i64)).collect();

    cat(&unsqueezed?, dim)
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_slice_dim0() {
        let t = Tensor::<f32>::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[3, 2]).unwrap();

        let s = t.slice_dim0(1, 3).unwrap();
        assert_eq!(s.shape(), &[2, 2]);
        assert_eq!(s.get(&[0, 0]).unwrap(), 3.0);
    }

    #[test]
    fn test_select() {
        let t = Tensor::<f32>::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]).unwrap();

        let s = t.select(0, 1).unwrap();
        assert_eq!(s.shape(), &[3]);
        assert_eq!(s.to_vec(), vec![4.0, 5.0, 6.0]);
    }

    #[test]
    fn test_narrow() {
        let t = Tensor::<f32>::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0], &[5]).unwrap();

        let n = t.narrow(0, 1, 3).unwrap();
        assert_eq!(n.shape(), &[3]);
        assert_eq!(n.to_vec(), vec![2.0, 3.0, 4.0]);
    }

    #[test]
    fn test_chunk() {
        let t = Tensor::<f32>::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[6]).unwrap();

        let chunks = t.chunk(3, 0).unwrap();
        assert_eq!(chunks.len(), 3);
        assert_eq!(chunks[0].to_vec(), vec![1.0, 2.0]);
        assert_eq!(chunks[1].to_vec(), vec![3.0, 4.0]);
        assert_eq!(chunks[2].to_vec(), vec![5.0, 6.0]);
    }

    #[test]
    fn test_cat() {
        let a = Tensor::<f32>::from_vec(vec![1.0, 2.0], &[2]).unwrap();
        let b = Tensor::<f32>::from_vec(vec![3.0, 4.0], &[2]).unwrap();

        let c = cat(&[a, b], 0).unwrap();
        assert_eq!(c.shape(), &[4]);
        assert_eq!(c.to_vec(), vec![1.0, 2.0, 3.0, 4.0]);
    }

    #[test]
    fn test_stack() {
        let a = Tensor::<f32>::from_vec(vec![1.0, 2.0], &[2]).unwrap();
        let b = Tensor::<f32>::from_vec(vec![3.0, 4.0], &[2]).unwrap();

        let c = stack(&[a, b], 0).unwrap();
        assert_eq!(c.shape(), &[2, 2]);
    }
}