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
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Hinge Loss - GPU-accelerated SVM-style classification loss
//!
//! **Deep Debt Principles**:
//! - ✅ Pure WGSL implementation (new shader!)
//! - ✅ Safe Rust wrapper (no unsafe code)
//! - ✅ Hardware-agnostic via WebGPU
//! - ✅ Complete implementation (production-ready for SVMs)
//!
//! ## Algorithm
//!
//! ```text
//! HingeLoss = max(0, margin - y * pred)
//! where y ∈ {-1, +1} is true label, pred is prediction
//! ```
//!
//! **Parameters**:
//! - `margin`: Typically 1.0 for standard SVM hinge loss
//!
//! **Key Properties**:
//! - Zero loss when prediction is correct and confident (y*pred > margin)
//! - Linear penalty for incorrect predictions
//! - Encourages max-margin separation
//! - Standard for support vector machines
//!
//! **Used By**: SVMs, max-margin classifiers, ranking
//!
//! ## Usage
//!
//! ```rust,ignore
//! use barracuda::tensor::Tensor;
//!
//! let predictions = Tensor::randn(vec![1000]).await?; // Raw scores
//! let targets = Tensor::randn(vec![1000]).await?; // Labels {-1, +1}
//!
//! let loss = predictions.hinge_loss(&targets, 1.0)?; // margin=1.0
//! ```
use crate::device::compute_pipeline::ComputeDispatch;
use crate::error::{BarracudaError, Result};
use crate::tensor::Tensor;
/// f64 is the canonical source — math is universal, precision is silicon.
const SHADER_F64: &str = include_str!("../shaders/loss/hinge_loss_f64.wgsl");
/// f32 variant derived from f64 via precision downcast.
static SHADER_F32: std::sync::LazyLock<String> =
std::sync::LazyLock::new(|| SHADER_F64.to_string());
#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct HingeLossParams {
size: u32,
margin: f32,
_padding: [u32; 2],
}
/// SVM-style hinge loss for max-margin classification.
pub struct HingeLoss {
predictions: Tensor,
targets: Tensor,
margin: f32,
}
impl HingeLoss {
/// Creates a new hinge loss. Margin is typically 1.0 for standard SVM.
/// # Errors
/// Returns [`Err`] if prediction and target shapes do not match, or if margin is not positive.
pub fn new(predictions: Tensor, targets: Tensor, margin: f32) -> Result<Self> {
// Validate shapes match
if predictions.shape() != targets.shape() {
return Err(BarracudaError::shape_mismatch(
predictions.shape().to_vec(),
targets.shape().to_vec(),
));
}
// Validate margin is positive
if margin <= 0.0 {
return Err(BarracudaError::invalid_op(
"HingeLoss",
format!("margin must be positive, got {margin}"),
));
}
Ok(Self {
predictions,
targets,
margin,
})
}
fn wgsl_shader() -> &'static str {
&SHADER_F32
}
/// Executes hinge loss and returns the loss tensor.
/// # Errors
/// Returns [`Err`] if buffer allocation fails, GPU dispatch fails, or the device is lost.
pub fn execute(self) -> Result<Tensor> {
let device = self.predictions.device();
let size = self.predictions.shape().iter().product::<usize>();
let params = HingeLossParams {
size: size as u32,
margin: self.margin,
_padding: [0; 2],
};
let output_buffer = device.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("hinge_loss_output"),
size: (size * std::mem::size_of::<f32>()) as u64,
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
mapped_at_creation: false,
});
let params_buffer = device.create_uniform_buffer("hinge_loss_params", ¶ms);
ComputeDispatch::new(device, "hinge_loss")
.shader(Self::wgsl_shader(), "main")
.storage_read(0, self.predictions.buffer())
.storage_read(1, self.targets.buffer())
.storage_rw(2, &output_buffer)
.uniform(3, ¶ms_buffer)
.dispatch_1d(size as u32)
.submit()?;
Ok(Tensor::from_buffer(
output_buffer,
self.predictions.shape().to_vec(),
device.clone(),
))
}
}
// ═══════════════════════════════════════════════════════════════
// TENSOR API INTEGRATION
// ═══════════════════════════════════════════════════════════════
impl Tensor {
/// Hinge loss for SVM-style max-margin classification
/// **Deep Debt**: Essential for support vector machines
/// # Arguments
/// - `targets`: Ground truth labels [same shape, values in {-1, +1}]
/// - `margin`: Margin threshold (typically 1.0)
/// # Returns
/// - Loss tensor [same shape as input]
/// # Example
/// ```rust,ignore
/// // Standard SVM hinge loss
/// let loss = predictions.hinge_loss(&targets, 1.0)?;
/// // Multi-class SVM (one-vs-all)
/// let loss = scores.hinge_loss(&labels, 1.0)?;
/// ```
/// # Note
/// - Targets should be {-1, +1} (not {0, 1})
/// - Predictions are raw scores (not probabilities)
/// - Loss = 0 when y*pred > margin (correct and confident)
/// - Standard margin = 1.0 for SVMs
/// # Errors
/// Returns [`Err`] if shapes do not match, margin is not positive, buffer allocation fails,
/// GPU dispatch fails, or the device is lost.
pub fn hinge_loss(self, targets: &Self, margin: f32) -> Result<Self> {
HingeLoss::new(self, targets.clone(), margin)?.execute()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_hinge_loss_basic() {
let device = crate::device::test_pool::get_test_device().await;
// Good predictions (correct sign, high magnitude)
let predictions = Tensor::from_vec_on(vec![2.0, -2.0, 1.5], vec![3], device.clone())
.await
.unwrap();
let targets = Tensor::from_vec_on(vec![1.0, -1.0, 1.0], vec![3], device.clone())
.await
.unwrap();
let loss = predictions.hinge_loss(&targets, 1.0).unwrap();
let data = loss.to_vec().unwrap();
// All should have zero or near-zero loss
assert!(data.iter().all(|&x| x < 0.1));
}
#[tokio::test]
async fn test_hinge_loss_wrong_predictions() {
let device = crate::device::test_pool::get_test_device().await;
// Wrong predictions (opposite sign)
let predictions = Tensor::from_vec_on(vec![-1.0, 1.0], vec![2], device.clone())
.await
.unwrap();
let targets = Tensor::from_vec_on(vec![1.0, -1.0], vec![2], device.clone())
.await
.unwrap();
let loss = predictions.hinge_loss(&targets, 1.0).unwrap();
let data = loss.to_vec().unwrap();
// Should have significant loss
assert!(data.iter().all(|&x| x > 1.0));
}
#[tokio::test]
async fn test_hinge_loss_exact_margin() {
let device = crate::device::test_pool::get_test_device().await;
// Prediction exactly at margin
let predictions = Tensor::from_vec_on(vec![0.5], vec![1], device.clone())
.await
.unwrap();
let targets = Tensor::from_vec_on(vec![1.0], vec![1], device.clone())
.await
.unwrap();
let loss = predictions.hinge_loss(&targets, 1.0).unwrap();
let data = loss.to_vec().unwrap();
// Loss = max(0, 1 - 1*0.5) = 0.5
assert!(
(data[0] - 0.5).abs() < 1e-5,
"Expected 0.5, got {}",
data[0]
);
}
#[tokio::test]
async fn test_hinge_loss_validation() {
let device = crate::device::test_pool::get_test_device().await;
// Shape mismatch
let predictions = Tensor::from_vec_on(vec![1.0; 10], vec![10], device.clone())
.await
.unwrap();
let targets = Tensor::from_vec_on(vec![1.0; 5], vec![5], device.clone())
.await
.unwrap();
assert!(predictions.hinge_loss(&targets, 1.0).is_err());
// Negative margin
let predictions = Tensor::from_vec_on(vec![1.0; 5], vec![5], device.clone())
.await
.unwrap();
let targets = Tensor::from_vec_on(vec![1.0; 5], vec![5], device.clone())
.await
.unwrap();
assert!(predictions.hinge_loss(&targets, -1.0).is_err());
}
#[tokio::test]
async fn test_hinge_loss_large_batch() {
let device = crate::device::test_pool::get_test_device().await;
let predictions: Vec<f32> = (0..1000)
.map(|i| if i % 2 == 0 { 2.0 } else { -2.0 })
.collect();
let targets: Vec<f32> = (0..1000)
.map(|i| if i % 2 == 0 { 1.0 } else { -1.0 })
.collect();
let pred_tensor = Tensor::from_vec_on(predictions, vec![1000], device.clone())
.await
.unwrap();
let target_tensor = Tensor::from_vec_on(targets, vec![1000], device.clone())
.await
.unwrap();
let loss = pred_tensor.hinge_loss(&target_tensor, 1.0).unwrap();
let data = loss.to_vec().unwrap();
assert_eq!(data.len(), 1000);
assert!(data.iter().all(|&x| x.is_finite() && x >= 0.0));
// Good predictions should have near-zero loss
assert!(data.iter().all(|&x| x < 0.1));
}
}