primal-barracuda 0.4.0

barraCuda — BARrier-free Rust Abstracted Cross-platform Unified Dimensional Algebra. Vendor-agnostic GPU compute via WGSL.
Documentation
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Fused mean+variance (f64) — single-pass Welford, GPU-resident, pipeline-cached
//!
//! Evolved from separate mean+deviation passes to a single fused dispatch.
//! Absorbed from Kokkos `parallel_reduce` patterns: one kernel, zero intermediate
//! CPU round-trips for chained statistics.

use crate::device::WgpuDevice;
use crate::device::capabilities::{DeviceCapabilities, Fp64Strategy};
use crate::device::pipeline_cache::{BindGroupLayoutSignature, create_f64_data_pipeline};
use crate::device::tensor_context::get_device_context;
use crate::error::Result;
use bytemuck::{Pod, Zeroable};
use std::sync::Arc;

/// Fused mean+variance f64 shader (Welford single-pass).
const SHADER_FUSED: &str = include_str!("../shaders/reduce/mean_variance_f64.wgsl");
/// DF64 variant — same Welford algorithm, DF64 core-streaming arithmetic.
const SHADER_FUSED_DF64: &str = include_str!("../shaders/reduce/mean_variance_df64.wgsl");
/// DF64 core arithmetic library (f32-pair).
const DF64_CORE: &str = include_str!("../shaders/math/df64_core.wgsl");

/// Select the fused shader based on the device's FP64 strategy.
///
/// Native/Concurrent: use the native f64 Welford shader.
/// Hybrid: use the DF64 variant (polynomial accumulation on f32 cores).
fn fused_shader_for_device(device: &WgpuDevice) -> &'static str {
    let caps = DeviceCapabilities::from_device(device);
    match caps.fp64_strategy() {
        Fp64Strategy::Sovereign | Fp64Strategy::Native | Fp64Strategy::Concurrent => SHADER_FUSED,
        Fp64Strategy::Hybrid => {
            static DF64_COMBINED: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
                format!("enable f64;\n{DF64_CORE}\n{SHADER_FUSED_DF64}")
            });
            &DF64_COMBINED
        }
    }
}

/// Simple variance reduction variant (scalar path).
#[must_use]
pub fn wgsl_variance_simple() -> &'static str {
    static SHADER: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
        include_str!("../shaders/misc/variance_simple_f64.wgsl").to_string()
    });
    std::sync::LazyLock::force(&SHADER).as_str()
}

/// Special variance shader.
pub const WGSL_VARIANCE_SPECIAL: &str = include_str!("../shaders/special/variance.wgsl");

#[repr(C)]
#[derive(Copy, Clone, Pod, Zeroable)]
struct FusedParams {
    n: u32,
    ddof: u32,
    _pad0: u32,
    _pad1: u32,
}

/// f64 Variance/StdDev evaluator — fused single-pass Welford
pub struct VarianceF64 {
    device: Arc<WgpuDevice>,
}

impl VarianceF64 {
    /// Create new Variance f64 operation.
    /// # Errors
    /// Never returns an error; always returns `Ok`.
    pub fn new(device: Arc<WgpuDevice>) -> Result<Self> {
        Ok(Self { device })
    }

    /// Compute variance of a vector (population variance, ddof=0).
    /// # Errors
    /// Returns [`Err`] if the device is lost, if buffer recording fails, or if
    /// readback fails (e.g. buffer mapping channel closed).
    pub fn variance(&self, data: &[f64]) -> Result<f64> {
        self.variance_ddof(data, 0)
    }

    /// Compute sample variance (ddof=1).
    /// # Errors
    /// Returns [`Err`] if the device is lost, if buffer recording fails, or if
    /// readback fails (e.g. buffer mapping channel closed).
    pub fn sample_variance(&self, data: &[f64]) -> Result<f64> {
        self.variance_ddof(data, 1)
    }

    /// Compute variance with specified degrees of freedom adjustment.
    /// Uses a fused mean+variance Welford shader — single GPU dispatch,
    /// no intermediate readback between mean and deviation passes.
    /// # Errors
    /// Returns [`Err`] if the device is lost, if buffer recording fails, or if
    /// readback fails (e.g. buffer mapping channel closed).
    pub fn variance_ddof(&self, data: &[f64], ddof: usize) -> Result<f64> {
        if data.is_empty() || data.len() <= ddof {
            return Ok(0.0);
        }

        let result = self.fused_mean_variance(data, ddof)?;
        Ok(result[1])
    }

    /// Compute mean and variance together in a single GPU pass.
    /// Returns `[mean, variance]`.
    /// # Errors
    /// Returns [`Err`] if the device is lost, if buffer recording fails, or if
    /// readback fails (e.g. buffer mapping channel closed).
    pub fn mean_variance(&self, data: &[f64], ddof: usize) -> Result<[f64; 2]> {
        if data.is_empty() || data.len() <= ddof {
            return Ok([0.0, 0.0]);
        }

        let result = self.fused_mean_variance(data, ddof)?;
        Ok([result[0], result[1]])
    }

    /// GPU-resident fused mean+variance — single Welford pass.
    fn fused_mean_variance(&self, data: &[f64], ddof: usize) -> Result<Vec<f64>> {
        let n = data.len();
        let ctx = get_device_context(&self.device);

        let input_buf = self
            .device
            .device
            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("FusedMeanVar Input"),
                contents: bytemuck::cast_slice(data),
                usage: wgpu::BufferUsages::STORAGE,
            });

        let output_buf = ctx.acquire_pooled_output_f64(2);

        let params = FusedParams {
            n: n as u32,
            ddof: ddof as u32,
            _pad0: 0,
            _pad1: 0,
        };
        let params_buf = self
            .device
            .create_uniform_buffer("FusedMeanVar Params", &params);

        let layout_sig = BindGroupLayoutSignature::reduction();
        let bind_group = ctx.get_or_create_bind_group(
            layout_sig,
            &[&input_buf, &output_buf, &params_buf],
            Some("FusedMeanVar BG"),
        );

        let shader_src = fused_shader_for_device(&self.device);
        let pipeline = create_f64_data_pipeline(
            &self.device,
            shader_src,
            layout_sig,
            "main",
            Some("FusedMeanVar Pipeline"),
        );

        ctx.record_operation(move |encoder| {
            let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                label: Some("FusedMeanVar Pass"),
                timestamp_writes: None,
            });
            pass.set_pipeline(&pipeline);
            pass.set_bind_group(0, Some(&*bind_group), &[]);
            pass.dispatch_workgroups(1, 1, 1);
        })?;

        self.device.read_buffer_f64(&output_buf, 2)
    }

    /// Compute mean and variance from a GPU-resident buffer — zero host transfer.
    /// The buffer must contain at least `n` f64 values.  Returns `[mean, variance]`.
    /// This is the persistent-buffer path that eliminates the Kokkos dispatch gap.
    /// # Errors
    /// Returns [`Err`] if the device is lost, if buffer recording fails, or if
    /// readback fails (e.g. buffer mapping channel closed).
    pub fn mean_variance_buffer(
        &self,
        buffer: &wgpu::Buffer,
        n: usize,
        ddof: usize,
    ) -> Result<[f64; 2]> {
        if n == 0 || n <= ddof {
            return Ok([0.0, 0.0]);
        }

        let ctx = get_device_context(&self.device);

        let output_buf = ctx.acquire_pooled_output_f64(2);

        let params = FusedParams {
            n: n as u32,
            ddof: ddof as u32,
            _pad0: 0,
            _pad1: 0,
        };
        let params_buf = self
            .device
            .create_uniform_buffer("FusedMeanVar:Buf Params", &params);

        let layout_sig = BindGroupLayoutSignature::reduction();
        let bind_group = ctx.get_or_create_bind_group(
            layout_sig,
            &[buffer, &output_buf, &params_buf],
            Some("FusedMeanVar:Buf BG"),
        );

        let shader_src = fused_shader_for_device(&self.device);
        let pipeline = create_f64_data_pipeline(
            &self.device,
            shader_src,
            layout_sig,
            "main",
            Some("FusedMeanVar:Buf Pipeline"),
        );

        ctx.record_operation(move |encoder| {
            let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                label: Some("FusedMeanVar:Buf Pass"),
                timestamp_writes: None,
            });
            pass.set_pipeline(&pipeline);
            pass.set_bind_group(0, Some(&*bind_group), &[]);
            pass.dispatch_workgroups(1, 1, 1);
        })?;

        let result = self.device.read_buffer_f64(&output_buf, 2)?;
        Ok([result[0], result[1]])
    }

    /// Fused mean+variance to a GPU-resident output buffer — zero CPU readback.
    ///
    /// The output buffer will contain `[mean, variance]` as 2×f64. Use this
    /// in chained GPU pipelines (e.g. normalize → reduce → next kernel)
    /// where reading back to CPU between dispatches is the bottleneck.
    ///
    /// Returns the output buffer handle. Chain with `encode_reduce_to_buffer`
    /// or bind directly to the next kernel's uniform/storage slot.
    ///
    /// # Errors
    /// Returns [`Err`] if the device is lost or buffer recording fails.
    pub fn mean_variance_to_buffer(
        &self,
        buffer: &wgpu::Buffer,
        n: usize,
        ddof: usize,
    ) -> Result<wgpu::Buffer> {
        let ctx = get_device_context(&self.device);

        let output_buf = ctx.acquire_pooled_output_f64(2);

        let params = FusedParams {
            n: n as u32,
            ddof: ddof as u32,
            _pad0: 0,
            _pad1: 0,
        };
        let params_buf = self
            .device
            .create_uniform_buffer("FusedMeanVar:GPU Params", &params);

        let layout_sig = BindGroupLayoutSignature::reduction();
        let bind_group = ctx.get_or_create_bind_group(
            layout_sig,
            &[buffer, &output_buf, &params_buf],
            Some("FusedMeanVar:GPU BG"),
        );

        let shader_src = fused_shader_for_device(&self.device);
        let pipeline = create_f64_data_pipeline(
            &self.device,
            shader_src,
            layout_sig,
            "main",
            Some("FusedMeanVar:GPU Pipeline"),
        );

        ctx.record_operation(move |encoder| {
            let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                label: Some("FusedMeanVar:GPU Pass"),
                timestamp_writes: None,
            });
            pass.set_pipeline(&pipeline);
            pass.set_bind_group(0, Some(&*bind_group), &[]);
            pass.dispatch_workgroups(1, 1, 1);
        })?;

        Ok(output_buf.into_buffer())
    }

    /// Compute standard deviation (population, ddof=0).
    /// # Errors
    /// Returns [`Err`] if the device is lost, if buffer recording fails, or if
    /// readback fails (e.g. buffer mapping channel closed).
    pub fn std_dev(&self, data: &[f64]) -> Result<f64> {
        Ok(self.variance(data)?.sqrt())
    }

    /// Compute sample standard deviation (ddof=1).
    /// # Errors
    /// Returns [`Err`] if the device is lost, if buffer recording fails, or if
    /// readback fails (e.g. buffer mapping channel closed).
    pub fn sample_std_dev(&self, data: &[f64]) -> Result<f64> {
        Ok(self.sample_variance(data)?.sqrt())
    }

    #[expect(
        dead_code,
        reason = "CPU reference implementation for GPU parity validation"
    )]
    fn variance_cpu(data: &[f64], ddof: usize) -> f64 {
        let n = data.len();
        if n <= ddof {
            return 0.0;
        }
        let mean: f64 = data.iter().sum::<f64>() / n as f64;
        let var_sum: f64 = data.iter().map(|x| (x - mean).powi(2)).sum();
        var_sum / (n - ddof) as f64
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::device::test_pool::get_test_device_if_f64_gpu_available;

    #[tokio::test]
    async fn test_variance_simple() {
        let Some(device) = get_test_device_if_f64_gpu_available().await else {
            return;
        };

        let var = VarianceF64::new(device).unwrap();
        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let result = var.variance(&data).unwrap();

        assert!(
            (result - 2.0).abs() < 1e-10,
            "Variance = {result}, expected 2.0"
        );
    }

    #[tokio::test]
    async fn test_sample_variance() {
        let Some(device) = get_test_device_if_f64_gpu_available().await else {
            return;
        };

        let var = VarianceF64::new(device).unwrap();
        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let result = var.sample_variance(&data).unwrap();

        assert!(
            (result - 2.5).abs() < 1e-10,
            "Sample variance = {result}, expected 2.5"
        );
    }

    #[tokio::test]
    async fn test_std_dev() {
        let Some(device) = get_test_device_if_f64_gpu_available().await else {
            return;
        };

        let var = VarianceF64::new(device).unwrap();
        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let result = var.std_dev(&data).unwrap();
        let expected = 2.0_f64.sqrt();

        assert!(
            (result - expected).abs() < 1e-10,
            "Std dev = {result}, expected {expected}"
        );
    }

    #[tokio::test]
    async fn test_variance_constant() {
        let Some(device) = get_test_device_if_f64_gpu_available().await else {
            return;
        };

        let var = VarianceF64::new(device).unwrap();
        let data = vec![5.0; 100];
        let result = var.variance(&data).unwrap();

        assert!(
            result.abs() < 1e-10,
            "Variance of constant = {result}, expected 0.0"
        );
    }

    #[tokio::test]
    async fn test_fused_mean_variance() {
        let Some(device) = get_test_device_if_f64_gpu_available().await else {
            return;
        };

        let var = VarianceF64::new(device).unwrap();
        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let [mean, variance] = var.mean_variance(&data, 0).unwrap();

        assert!((mean - 3.0).abs() < 1e-10, "Mean = {mean}, expected 3.0");
        assert!(
            (variance - 2.0).abs() < 1e-10,
            "Variance = {variance}, expected 2.0"
        );
    }

    #[tokio::test]
    async fn test_fused_mean_variance_large() {
        let Some(device) = get_test_device_if_f64_gpu_available().await else {
            return;
        };

        let var = VarianceF64::new(device).unwrap();
        let n = 10_000;
        let data: Vec<f64> = (0..n).map(|i| i as f64).collect();
        let [mean, variance] = var.mean_variance(&data, 0).unwrap();

        let expected_mean = (n - 1) as f64 / 2.0;
        let expected_var = ((n * n - 1) as f64) / 12.0;

        assert!(
            (mean - expected_mean).abs() / expected_mean < 1e-10,
            "Mean = {mean}, expected {expected_mean}"
        );
        assert!(
            (variance - expected_var).abs() / expected_var < 1e-6,
            "Variance = {variance}, expected {expected_var}"
        );
    }
}