Skip to content

Commit

Permalink
add permute operation to tensor
Browse files Browse the repository at this point in the history
  • Loading branch information
PaytonWebber committed Dec 18, 2024
1 parent bf28565 commit 72d51d6
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
8 changes: 8 additions & 0 deletions tensor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,14 @@ impl Tensor {
Ok(())
}

pub fn permute(&mut self, order: &[usize]) -> Result<(), &'static str> {
if order.len() != self.shape.len() {
return Err("The permutation does not align with the current shape.");
}
let new_shape: Vec<usize> = order.iter().map(|i| self.shape[*i]).collect();
self.reshape(&new_shape)
}

pub fn shape(&self) -> &Vec<usize> {
&self.shape
}
Expand Down
27 changes: 27 additions & 0 deletions tensor/tests/tensor_core_test.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::usize;

use tensor::Tensor;

#[test]
Expand Down Expand Up @@ -64,6 +66,31 @@ fn reshape_tensor_invalid_shape() {
}
}

#[test]
fn permute_tensor_valid_order() {
let original_shape: Vec<usize> = vec![4, 2, 2];
let mut a: Tensor = Tensor::ones(&original_shape);

let permutation: Vec<usize> = vec![1, 0, 2];
let new_strides: Vec<usize> = vec![8, 2, 1];
let new_shape: Vec<usize> = vec![2, 4, 2];
a.permute(&permutation).unwrap();

assert_eq!(new_strides, *a.strides());
assert_eq!(new_shape, *a.shape());
}

#[test]
fn permute_tensor_invalid_order() {
let original_shape: Vec<usize> = vec![4, 2];
let mut a: Tensor = Tensor::ones(&original_shape);

let permutation: Vec<usize> = vec![2, 0, 1];
if let Ok(()) = a.permute(&permutation) {
panic!("The permutation should've been invalid.")
}
}

#[test]
fn get_element_with_index() {
let length: usize = 24;
Expand Down

0 comments on commit 72d51d6

Please sign in to comment.