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
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Dice Loss - GPU-accelerated segmentation loss
//!
//! **Deep Debt Principles**:
//! - ✅ Pure WGSL implementation (uses existing shader!)
//! - ✅ Safe Rust wrapper (no unsafe code)
//! - ✅ Hardware-agnostic via WebGPU
//! - ✅ Complete implementation (production-ready for medical imaging)
//!
//! ## Algorithm
//!
//! ```text
//! Dice coefficient: DC = 2|X ∩ Y| / (|X| + |Y|)
//! Dice loss: L = 1 - DC
//! ```
//!
//! **Implementation**: GPU reduction with workgroup shared memory
//!
//! **Key Properties**:
//! - Handles class imbalance naturally
//! - Directly optimizes IoU-like metric
//! - Common in medical image segmentation
//!
//! **Used By**: U-Net, V-Net, medical imaging models
//!
//! ## Usage
//!
//! ```rust,ignore
//! use barracuda::tensor::Tensor;
//!
//! let predictions = Tensor::randn(vec![4, 256, 256]).await?; // [batch, H, W]
//! let targets = Tensor::randn(vec![4, 256, 256]).await?;
//!
//! let loss = predictions.dice_loss(&targets, 1.0)?; // smoothing = 1.0
//! ```
use crate::device::compute_pipeline::ComputeDispatch;
use crate::error::{BarracudaError, Result};
use crate::tensor::Tensor;
/// Dice loss parameters for WGSL shader
#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct DiceParams {
smoothing: f32,
reduction_mode: u32,
batch_size: u32,
elements_per_sample: u32,
}
/// Dice Loss operation
///
/// **Deep Debt**: Uses existing WGSL shader with workgroup reduction
pub struct DiceLoss {
predictions: Tensor,
targets: Tensor,
smoothing: f32,
}
impl DiceLoss {
/// Create new Dice loss operation
/// # Errors
/// Returns [`Err`] if predictions and targets shapes differ.
pub fn new(predictions: Tensor, targets: Tensor, smoothing: f32) -> Result<Self> {
// Validate shapes match
if predictions.shape() != targets.shape() {
return Err(BarracudaError::shape_mismatch(
predictions.shape().to_vec(),
targets.shape().to_vec(),
));
}
Ok(Self {
predictions,
targets,
smoothing,
})
}
/// WGSL shader source
fn shader() -> &'static str {
static SHADER: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
include_str!("../shaders/loss/dice_loss_f64.wgsl").to_string()
});
&SHADER
}
/// Execute Dice loss (GPU reduction)
/// **Deep Debt**: Efficient workgroup reduction for large segmentations
/// # 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();
// Determine batch and elements
let total_size = self.predictions.len();
let batch_size = if self.predictions.shape().is_empty() {
1
} else {
self.predictions.shape()[0]
};
let elements_per_sample = total_size / batch_size;
// Create parameters
let params = DiceParams {
smoothing: self.smoothing,
reduction_mode: 0, // Mean reduction
batch_size: batch_size as u32,
elements_per_sample: elements_per_sample as u32,
};
let params_buffer = device.create_uniform_buffer("Dice Loss Params", ¶ms);
// Output buffer (one loss value per batch)
let output_buffer = device.create_buffer_f32(batch_size)?;
ComputeDispatch::new(device, "Dice Loss")
.shader(Self::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(batch_size as u32)
.submit()?;
// Return output tensor [batch_size]
Ok(Tensor::from_buffer(
output_buffer,
vec![batch_size],
device.clone(),
))
}
}
// ═══════════════════════════════════════════════════════════════
// TENSOR API INTEGRATION
// ═══════════════════════════════════════════════════════════════
impl Tensor {
/// Dice loss for segmentation
/// **Deep Debt**: Essential for medical imaging, handles class imbalance
/// # Arguments
/// - `targets`: Ground truth [same shape as predictions]
/// - `smoothing`: Smoothing factor (typically 1.0)
/// # Returns
/// - Loss tensor [`batch_size`] (one value per batch)
/// # Example
/// ```rust,ignore
/// let preds = Tensor::randn(vec![4, 256, 256]).await?;
/// let targets = Tensor::randn(vec![4, 256, 256]).await?;
/// let loss = preds.dice_loss(&targets, 1.0)?; // U-Net segmentation
/// ```
/// # Errors
/// Returns [`Err`] if shapes differ, buffer allocation fails, GPU dispatch fails, or the device is lost.
pub fn dice_loss(self, targets: &Self, smoothing: f32) -> Result<Self> {
DiceLoss::new(self, targets.clone(), smoothing)?.execute()
}
}
// ═══════════════════════════════════════════════════════════════
// TESTS
// ═══════════════════════════════════════════════════════════════
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_dice_loss_gpu_basic() {
let device = crate::device::test_pool::get_test_device().await;
let batch = 2;
let h = 16;
let w = 16;
// Perfect predictions
let preds =
Tensor::from_vec_on(vec![1.0; batch * h * w], vec![batch, h, w], device.clone())
.await
.unwrap();
let targets = Tensor::from_vec_on(vec![1.0; batch * h * w], vec![batch, h, w], device)
.await
.unwrap();
let loss = preds.dice_loss(&targets, 1.0).unwrap();
assert_eq!(loss.shape(), &[batch]);
let data = loss.to_vec().unwrap();
// Perfect prediction should have low loss
assert!(data.iter().all(|&x| x < 0.1));
}
#[tokio::test]
async fn test_dice_loss_gpu_mismatch() {
let device = crate::device::test_pool::get_test_device().await;
let batch = 1;
let size = 100;
// Complete mismatch
let preds = Tensor::from_vec_on(vec![1.0; batch * size], vec![batch, size], device.clone())
.await
.unwrap();
let targets = Tensor::from_vec_on(vec![0.0; batch * size], vec![batch, size], device)
.await
.unwrap();
let loss = preds.dice_loss(&targets, 1.0).unwrap();
let data = loss.to_vec().unwrap();
// High loss for mismatch
assert!(data[0] > 0.5);
}
#[tokio::test]
async fn test_dice_loss_gpu_medical_scale() {
let device = crate::device::test_pool::get_test_device().await;
// Medical imaging scale: 128x128 slices
let batch = 4;
let h = 128;
let w = 128;
let preds =
Tensor::from_vec_on(vec![0.8; batch * h * w], vec![batch, h, w], device.clone())
.await
.unwrap();
let targets = Tensor::from_vec_on(vec![1.0; batch * h * w], vec![batch, h, w], device)
.await
.unwrap();
let loss = preds.dice_loss(&targets, 1.0).unwrap();
assert_eq!(loss.shape(), &[batch]);
let data = loss.to_vec().unwrap();
assert!(
data.iter()
.all(|&x| x.is_finite() && (0.0..=1.0).contains(&x))
);
}
}