mod compute;
#[cfg(test)]
mod tests;
use crate::error::{BarracudaError, Result};
use crate::tensor::Tensor;
#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct TransposeParams2D {
pub rows: u32,
pub cols: u32,
pub _padding: [u32; 2],
}
pub struct Transpose {
input: Tensor,
permutation: Option<Vec<usize>>,
}
impl Transpose {
pub fn new(input: Tensor) -> Result<Self> {
Ok(Self {
input,
permutation: None,
})
}
pub fn with_permutation(input: Tensor, permutation: Vec<usize>) -> Result<Self> {
let num_dims = input.shape().len();
if permutation.len() != num_dims {
return Err(BarracudaError::invalid_op(
"Transpose",
format!(
"Permutation length {} doesn't match tensor rank {}",
permutation.len(),
num_dims
),
));
}
let mut seen = vec![false; num_dims];
for &idx in &permutation {
if idx >= num_dims {
return Err(BarracudaError::invalid_op(
"Transpose",
format!("Invalid permutation index {idx} for rank {num_dims}"),
));
}
if seen[idx] {
return Err(BarracudaError::invalid_op(
"Transpose",
format!("Duplicate index {idx} in permutation"),
));
}
seen[idx] = true;
}
Ok(Self {
input,
permutation: Some(permutation),
})
}
pub(super) fn wgsl_shader() -> &'static str {
{
static S: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
include_str!("../../shaders/tensor/transpose_f64.wgsl").to_string()
});
&S
}
}
pub fn execute(self) -> Result<Tensor> {
compute::execute_transpose(self.input, self.permutation)
}
}
impl Tensor {
pub fn transpose(&self) -> Result<Self> {
Transpose::new(self.clone())?.execute()
}
pub fn transpose_with_permutation(&self, permutation: Vec<usize>) -> Result<Self> {
Transpose::with_permutation(self.clone(), permutation)?.execute()
}
}