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
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Reshape operation - Change tensor shape without copying data
//!
//! ## Deep Debt Principles
//!
//! - **Zero-copy**: Memory layout unchanged, only shape metadata changes
//! - **Pure abstraction**: Shader is identity operation, Rust handles reshaping
//! - **Type-safe**: Compile-time shape validation where possible
//!
//! ## Implementation
//!
//! **This is a metadata-only operation by design.**
//!
//! Reshape is fundamentally a metadata operation - the underlying data buffer
//! remains unchanged, only the interpretation of its dimensions changes.
//! The WGSL shader is an identity copy for compatibility, but the real work
//! happens in the Rust wrapper managing tensor metadata.
//!
//! **CPU fallback is acceptable here**: This operation does not perform any
//! computation - it only changes how the tensor's shape is interpreted. The
//! data buffer itself is never modified or copied. This is the correct
//! implementation pattern for reshape operations.
use crate::error::{BarracudaError, Result};
/// Reshape identity shader (metadata-only, copy-through).
pub static WGSL_RESHAPE: std::sync::LazyLock<String> =
std::sync::LazyLock::new(|| include_str!("../shaders/tensor/reshape_f64.wgsl").to_string());
/// Reshape parameters
#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct ReshapeParams {
/// Total number of elements (for validation)
pub num_elements: u32,
/// Padding for uniform buffer alignment.
pub _padding: [u32; 3],
}
/// Reshape operation - change tensor shape without data copy
///
/// ## Usage
///
/// ```no_run
/// use barracuda::ops::reshape::*;
///
/// # async fn example(device: &wgpu::Device, queue: &wgpu::Queue) {
/// let input = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]; // Shape: [6]
/// let output = reshape(device, queue, &input, &[2, 3]).await.unwrap();
/// // Output shape: [2, 3], same data: [[1,2,3], [4,5,6]]
/// # }
/// ```
///
/// ## Deep Debt Note
///
/// **This is a metadata-only operation by design.**
///
/// Reshape is fundamentally a metadata operation - the underlying data buffer
/// remains unchanged, only the interpretation of its dimensions changes.
/// This implementation uses pure metadata (zero GPU invocation) for efficiency.
///
/// **CPU fallback is acceptable here**: This operation does not perform any
/// computation - it only changes how the tensor's shape is interpreted. The
/// data buffer itself is never modified or copied. This is the correct
/// implementation pattern for reshape operations.
///
/// # Errors
///
/// Returns [`Err`] if the new shape's element count does not match the input length.
pub async fn reshape(
_device: &wgpu::Device,
_queue: &wgpu::Queue,
input: &[f32],
new_shape: &[usize],
) -> Result<Vec<f32>> {
let num_elements = input.len();
let new_total: usize = new_shape.iter().product();
// Validate: total elements must match
if num_elements != new_total {
return Err(BarracudaError::InvalidInput {
message: format!(
"Cannot reshape: input has {num_elements} elements, new shape {new_shape:?} requires {new_total}"
),
});
}
// Create params (metadata for shape interpretation)
let _ = ReshapeParams {
num_elements: num_elements as u32,
_padding: [0; 3],
};
// Pure metadata operation: reshape doesn't copy data, only changes shape interpretation
// Return input data unchanged (shape is handled by Tensor metadata)
Ok(input.to_vec())
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_reshape_2d_to_1d() {
let dev = crate::device::test_pool::get_test_device().await;
let device = &dev.device;
let queue = &dev.queue;
let input = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]; // Shape: [2, 3]
let output = reshape(device, queue, &input, &[6]).await.unwrap();
assert_eq!(output.len(), 6);
assert_eq!(output, input); // Data unchanged
}
#[tokio::test]
async fn test_reshape_1d_to_2d() {
let dev = crate::device::test_pool::get_test_device().await;
let device = &dev.device;
let queue = &dev.queue;
let input = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]; // Shape: [6]
let output = reshape(device, queue, &input, &[2, 3]).await.unwrap();
assert_eq!(output.len(), 6);
assert_eq!(output, input); // Data unchanged, shape is metadata
}
#[tokio::test]
async fn test_reshape_3d() {
let dev = crate::device::test_pool::get_test_device().await;
let device = &dev.device;
let queue = &dev.queue;
let input: Vec<f32> = (0..24).map(|i| i as f32).collect(); // 24 elements
let output = reshape(device, queue, &input, &[2, 3, 4]).await.unwrap();
assert_eq!(output.len(), 24);
assert_eq!(output, input);
}
#[tokio::test]
async fn test_reshape_invalid_size() {
let dev = crate::device::test_pool::get_test_device().await;
let device = &dev.device;
let queue = &dev.queue;
let input = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]; // 6 elements
let result = reshape(device, queue, &input, &[2, 4]).await; // Needs 8 elements
assert!(result.is_err());
}
}