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
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Map Operation - Element-wise transformations
//!
//! **Deep Debt Evolution**: Modernized from trait-based to direct `impl Tensor`
//!
//! ## Deep Debt Principles
//!
//! - ✅ Modern idiomatic Rust (direct `impl Tensor`, not trait extension)
//! - ✅ Universal compute (WGSL shader for all substrates)
//! - ✅ Safe Rust (no unsafe blocks)
//! - ✅ Agnostic design (operation enum, not hardcoded)
//!
//! ## Evolution History
//!
//! **Before** (Phase 3): `MapExt` trait extension\
//! **After** (Phase 6): Direct `impl Tensor` method
//!
//! ## Usage
//!
//! ```ignore
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # use barracuda::tensor::Tensor;
//! # use barracuda::ops::map::MapOperation;
//! # use barracuda::device::test_pool;
//! # let device = test_pool::tokio_block_on(test_pool::get_test_device()).unwrap();
//! let input = Tensor::from_data(&[1.0f32, 2.0, 3.0], vec![3], device)?;
//! let _squared = input.map(MapOperation::Square)?;
//! # Ok(())
//! # }
//! ```
use crate::device::ComputeDispatch;
use crate::error::Result;
use crate::tensor::Tensor;
#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct MapParams {
size: u32,
operation: u32,
}
/// Element-wise map operation (square, sqrt, abs, negate, reciprocal).
pub struct Map {
input: Tensor,
operation: MapOperation,
}
/// Element-wise map operations.
#[derive(Debug, Clone, Copy)]
pub enum MapOperation {
/// Square: x².
Square,
/// Square root.
Sqrt,
/// Absolute value.
Abs,
/// Negate: -x.
Negate,
/// Reciprocal: 1/x.
Reciprocal,
}
impl MapOperation {
fn to_u32(&self) -> u32 {
match self {
Self::Square => 0,
Self::Sqrt => 1,
Self::Abs => 2,
Self::Negate => 3,
Self::Reciprocal => 4,
}
}
}
impl Map {
fn wgsl_shader() -> &'static str {
static SHADER: std::sync::LazyLock<String> =
std::sync::LazyLock::new(|| include_str!("../shaders/misc/map_f64.wgsl").to_string());
std::sync::LazyLock::force(&SHADER).as_str()
}
/// Execute the map operation on GPU.
///
/// # Errors
///
/// Returns [`Err`] if buffer allocation, GPU dispatch, or buffer
/// readback fails (e.g. device lost or out of memory).
pub fn execute(self) -> Result<Tensor> {
let device = self.input.device();
let size = self.input.shape().iter().product::<usize>();
let params = MapParams {
size: size as u32,
operation: self.operation.to_u32(),
};
let output_buffer = device.create_buffer_f32(size)?;
let params_buffer = device.create_uniform_buffer("map_params", ¶ms);
ComputeDispatch::new(device, "map")
.shader(Self::wgsl_shader(), "main")
.storage_read(0, self.input.buffer())
.storage_rw(1, &output_buffer)
.uniform(2, ¶ms_buffer)
.dispatch_1d(size as u32)
.submit()?;
Ok(Tensor::from_buffer(
output_buffer,
self.input.shape().to_vec(),
device.clone(),
))
}
}
// ============================================================================
// Modern API: Direct impl Tensor (Phase 6 Evolution)
// ============================================================================
impl Tensor {
/// Apply element-wise transformation to tensor
///
/// **Deep Debt**: Modern direct method, no trait extension needed
///
/// ## Arguments
///
/// * `operation` - Map operation (Square, Sqrt, Abs, Negate, Reciprocal)
///
/// ## Example
///
/// ```ignore
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # use barracuda::tensor::Tensor;
/// # use barracuda::ops::map::MapOperation;
/// # use barracuda::device::test_pool;
/// # let device = test_pool::tokio_block_on(test_pool::get_test_device()).unwrap();
/// # let input = Tensor::from_data(&[1.0f32, 2.0, 3.0, 4.0], vec![4], device).unwrap();
/// // Square all elements
/// let _squared = input.clone().map(MapOperation::Square)?;
///
/// // Take square root
/// let _sqrt = input.map(MapOperation::Sqrt)?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns [`Err`] if buffer allocation, GPU dispatch, or buffer
/// readback fails (e.g. device lost or out of memory).
pub fn map(self, operation: MapOperation) -> Result<Self> {
let op = Map {
input: self,
operation,
};
op.execute()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_map_basic() {
let device = crate::device::test_pool::get_test_device().await;
let input = Tensor::from_data(&[1.0, 2.0, 3.0, 4.0], vec![4], device).unwrap();
let result = input.map(MapOperation::Square).unwrap();
let output = result.to_vec().unwrap();
assert_eq!(output.len(), 4);
assert!(output.iter().all(|&x| x.is_finite()));
}
#[tokio::test]
async fn test_map_edge_cases() {
let device = crate::device::test_pool::get_test_device().await;
// Single element
let input = Tensor::from_data(&[5.0], vec![1], device.clone()).unwrap();
let result = input.map(MapOperation::Square).unwrap();
let output = result.to_vec().unwrap();
assert_eq!(output.len(), 1);
assert!(output[0].is_finite());
// Negate operation
let input = Tensor::from_data(&[1.0, -2.0, 3.0], vec![3], device).unwrap();
let result = input.map(MapOperation::Negate).unwrap();
let output = result.to_vec().unwrap();
assert_eq!(output.len(), 3);
assert!(output.iter().all(|&x| x.is_finite()));
}
#[tokio::test]
async fn test_map_boundary() {
let device = crate::device::test_pool::get_test_device().await;
// Sqrt with various values
let input = Tensor::from_data(&[4.0, 9.0, 16.0], vec![3], device.clone()).unwrap();
let result = input.map(MapOperation::Sqrt).unwrap();
let output = result.to_vec().unwrap();
assert!(output.iter().all(|&x| x.is_finite()));
// Abs with negative values
let input = Tensor::from_data(&[-1.0, -2.0, -3.0], vec![3], device).unwrap();
let result = input.map(MapOperation::Abs).unwrap();
let output = result.to_vec().unwrap();
assert!(output.iter().all(|&x| x >= 0.0));
}
#[tokio::test]
async fn test_map_large_batch() {
let device = crate::device::test_pool::get_test_device().await;
// 1000 elements
let input_data: Vec<f32> = (1..=1000).map(|i| i as f32).collect();
let input = Tensor::from_data(&input_data, vec![1000], device).unwrap();
let result = input.map(MapOperation::Square).unwrap();
let output = result.to_vec().unwrap();
assert_eq!(output.len(), 1000);
assert!(output.iter().all(|&x| x.is_finite()));
}
#[tokio::test]
async fn test_map_precision() {
let device = crate::device::test_pool::get_test_device().await;
// Test square operation
let input = Tensor::from_data(&[2.0, 3.0], vec![2], device).unwrap();
let result = input.map(MapOperation::Square).unwrap();
let output = result.to_vec().unwrap();
assert_eq!(output.len(), 2);
assert!(output.iter().all(|&x| x.is_finite()));
}
}