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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Auto-Tuning Runtime for `BarraCuda`
//!
//! Discovers optimal GPU parameters at runtime through calibration.
//!
//! Philosophy:
//! - Don't assume vendor capabilities - discover ground truth
//! - Handle silicon lottery and generation differences
//! - Work seamlessly with unknown/new hardware
//! - Cache calibrations per GPU for fast startup

use crate::device::capabilities::WORKGROUP_SIZE_1D;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::RwLock;
use std::time::Instant;

/// Workgroup sizes to sweep during bandwidth calibration.
const CALIBRATION_WG_SIZES: [u32; 4] = [32, 64, 128, 256];

/// Element count for the bandwidth probe buffer.
const CALIBRATION_TEST_SIZE: usize = 4_000_000;

use wgpu::util::DeviceExt;

/// Trait for GPU devices that support calibration (submit+poll under lock).
/// Implemented by `WgpuDevice` to avoid circular dependency.
pub(crate) trait GpuDeviceForCalibration {
    fn device(&self) -> &wgpu::Device;
    fn name(&self) -> &str;
    /// Submit commands and poll, holding the GPU lock. Used during calibration.
    fn submit_and_poll_calibration(&self, commands: impl IntoIterator<Item = wgpu::CommandBuffer>);
}

/// Calibration result for a specific GPU
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GpuCalibration {
    /// Unique device identifier (from wgpu `global_id`)
    pub device_id: String,
    /// Device name (adapter name)
    pub device_name: String,
    /// Optimal workgroup size discovered
    pub optimal_workgroup_size: u32,
    /// Measured peak bandwidth (GB/s)
    pub peak_bandwidth_gbps: f64,
    /// Measured single-op overhead (μs)
    pub dispatch_overhead_us: f64,
    /// Calibration timestamp (epoch seconds)
    pub calibrated_at: u64,
}

impl Default for GpuCalibration {
    fn default() -> Self {
        Self {
            device_id: String::new(),
            device_name: String::new(),
            optimal_workgroup_size: WORKGROUP_SIZE_1D,
            peak_bandwidth_gbps: 0.0,
            dispatch_overhead_us: 0.0,
            calibrated_at: 0,
        }
    }
}

/// Auto-tuner for discovering optimal GPU parameters
#[derive(Default)]
pub struct AutoTuner {
    /// Cached calibrations by device name
    calibrations: RwLock<HashMap<String, GpuCalibration>>,
    /// Path to persistent cache file
    cache_path: Option<PathBuf>,
}

impl AutoTuner {
    /// Create a new auto-tuner
    #[must_use]
    pub fn new() -> Self {
        Self {
            calibrations: RwLock::new(HashMap::new()),
            cache_path: None,
        }
    }

    /// Create auto-tuner with persistent cache
    #[must_use]
    pub fn with_cache(cache_path: PathBuf) -> Self {
        let mut tuner = Self::new();
        tuner.cache_path = Some(cache_path.clone());

        // Try to load existing calibrations
        #[cfg(feature = "serde")]
        if let Ok(contents) = std::fs::read_to_string(&cache_path) {
            if let Ok(cals) = serde_json::from_str::<Vec<GpuCalibration>>(&contents) {
                let mut map = tuner
                    .calibrations
                    .write()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                for cal in cals {
                    map.insert(cal.device_name.clone(), cal);
                }
            }
        }
        #[cfg(not(feature = "serde"))]
        if let Err(e) = std::fs::read_to_string(&cache_path) {
            tracing::debug!(
                "autotune cache at {}: {e} (serde disabled, cannot parse)",
                cache_path.display()
            );
        }

        tuner
    }

    /// Get calibration for a device, or calibrate if needed
    pub(crate) fn get_or_calibrate(
        &self,
        wgpu_device: &impl GpuDeviceForCalibration,
    ) -> GpuCalibration {
        let device_name = wgpu_device.name();
        // Check cache first
        {
            let cals = self
                .calibrations
                .read()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            if let Some(cal) = cals.get(device_name) {
                return cal.clone();
            }
        }

        // Need to calibrate
        let cal = self.calibrate_device(wgpu_device);

        // Cache it
        {
            let mut cals = self
                .calibrations
                .write()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            cals.insert(device_name.to_string(), cal.clone());
        }

        // Persist if cache path set
        self.save_cache();

        cal
    }

    /// Perform calibration for a device
    fn calibrate_device(&self, wgpu_device: &impl GpuDeviceForCalibration) -> GpuCalibration {
        let device = wgpu_device.device();
        let device_name = wgpu_device.name();
        let mut best_wg = WORKGROUP_SIZE_1D;
        let mut best_bw = 0.0f64;

        for &wg_size in &CALIBRATION_WG_SIZES {
            if let Some(bw) = self.measure_bandwidth(wgpu_device, wg_size, CALIBRATION_TEST_SIZE)
                && bw > best_bw
            {
                best_bw = bw;
                best_wg = wg_size;
            }
        }

        // Measure dispatch overhead with optimal WG
        let overhead = self.measure_overhead(wgpu_device, best_wg);

        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0, |d| d.as_secs());

        GpuCalibration {
            device_id: format!("{device:?}"),
            device_name: device_name.to_string(),
            optimal_workgroup_size: best_wg,
            peak_bandwidth_gbps: best_bw,
            dispatch_overhead_us: overhead,
            calibrated_at: now,
        }
    }

    /// Measure bandwidth for a given workgroup size
    fn measure_bandwidth(
        &self,
        wgpu_device: &impl GpuDeviceForCalibration,
        workgroup_size: u32,
        size: usize,
    ) -> Option<f64> {
        let device = wgpu_device.device();
        let shader_src = format!(
            r"
@group(0) @binding(0) var<storage, read> a: array<f32>;
@group(0) @binding(1) var<storage, read> b: array<f32>;
@group(0) @binding(2) var<storage, read_write> output: array<f32>;

@compute @workgroup_size({workgroup_size})
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {{
    let idx = global_id.x;
    if (idx >= arrayLength(&output)) {{
        return;
    }}
    output[idx] = a[idx] + b[idx];
}}
"
        );

        let data: Vec<f32> = (0..size).map(|i| i as f32 * 0.001).collect();

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

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

        let buf_out = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("Out"),
            size: (size * 4) as u64,
            usage: wgpu::BufferUsages::STORAGE,
            mapped_at_creation: false,
        });

        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: None,
            source: wgpu::ShaderSource::Wgsl(shader_src.into()),
        });

        let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: None,
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Storage { read_only: true },
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Storage { read_only: true },
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Storage { read_only: false },
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
            ],
        });

        let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: None,
            layout: &bgl,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: buf_a.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: buf_b.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: buf_out.as_entire_binding(),
                },
            ],
        });

        let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: None,
            bind_group_layouts: &[&bgl],
            immediate_size: 0,
        });

        let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
            label: None,
            layout: Some(&pl),
            module: &shader,
            entry_point: Some("main"),
            cache: None,
            compilation_options: Default::default(),
        });

        let workgroups = (size as u32).div_ceil(workgroup_size).min(65_535);

        // Warmup
        for _ in 0..3 {
            let mut encoder =
                device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
            {
                let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor::default());
                pass.set_pipeline(&pipeline);
                pass.set_bind_group(0, Some(&bind_group), &[]);
                pass.dispatch_workgroups(workgroups, 1, 1);
            }
            wgpu_device.submit_and_poll_calibration(Some(encoder.finish()));
        }

        // Measure
        let iterations = 10;
        let start = Instant::now();

        for _ in 0..iterations {
            let mut encoder =
                device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
            {
                let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor::default());
                pass.set_pipeline(&pipeline);
                pass.set_bind_group(0, Some(&bind_group), &[]);
                pass.dispatch_workgroups(workgroups, 1, 1);
            }
            wgpu_device.submit_and_poll_calibration(Some(encoder.finish()));
        }

        let elapsed = start.elapsed();
        let time_per_op = elapsed.as_secs_f64() / iterations as f64;

        // Bandwidth: (read A + read B + write C) = 3 * size * 4 bytes
        let bytes = size * 3 * 4;
        let bandwidth_gbps = bytes as f64 / time_per_op / 1e9;

        Some(bandwidth_gbps)
    }

    /// Measure dispatch overhead
    fn measure_overhead(
        &self,
        wgpu_device: &impl GpuDeviceForCalibration,
        workgroup_size: u32,
    ) -> f64 {
        let device = wgpu_device.device();
        // Use tiny workload to measure pure overhead
        let size = 1024usize;

        let shader_src = format!(
            r"
@group(0) @binding(0) var<storage, read_write> data: array<f32>;

@compute @workgroup_size({workgroup_size})
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {{
    let idx = global_id.x;
    if (idx < arrayLength(&data)) {{
        data[idx] = data[idx] + 1.0;
    }}
}}
"
        );

        let data: Vec<f32> = vec![0.0; size];

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

        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: None,
            source: wgpu::ShaderSource::Wgsl(shader_src.into()),
        });

        let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: None,
            entries: &[wgpu::BindGroupLayoutEntry {
                binding: 0,
                visibility: wgpu::ShaderStages::COMPUTE,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Storage { read_only: false },
                    has_dynamic_offset: false,
                    min_binding_size: None,
                },
                count: None,
            }],
        });

        let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: None,
            layout: &bgl,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: buffer.as_entire_binding(),
            }],
        });

        let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: None,
            bind_group_layouts: &[&bgl],
            immediate_size: 0,
        });

        let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
            label: None,
            layout: Some(&pl),
            module: &shader,
            entry_point: Some("main"),
            cache: None,
            compilation_options: Default::default(),
        });

        let workgroups = (size as u32).div_ceil(workgroup_size);

        // Warmup
        for _ in 0..10 {
            let mut encoder =
                device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
            {
                let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor::default());
                pass.set_pipeline(&pipeline);
                pass.set_bind_group(0, Some(&bind_group), &[]);
                pass.dispatch_workgroups(workgroups, 1, 1);
            }
            wgpu_device.submit_and_poll_calibration(Some(encoder.finish()));
        }

        // Measure many iterations
        let iterations = 100;
        let start = Instant::now();

        for _ in 0..iterations {
            let mut encoder =
                device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
            {
                let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor::default());
                pass.set_pipeline(&pipeline);
                pass.set_bind_group(0, Some(&bind_group), &[]);
                pass.dispatch_workgroups(workgroups, 1, 1);
            }
            wgpu_device.submit_and_poll_calibration(Some(encoder.finish()));
        }

        let elapsed = start.elapsed();
        elapsed.as_secs_f64() * 1e6 / iterations as f64
    }

    /// Save calibrations to cache file
    #[cfg(feature = "serde")]
    fn save_cache(&self) {
        if let Some(ref path) = self.cache_path {
            let cals = self
                .calibrations
                .read()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let cal_vec: Vec<&GpuCalibration> = cals.values().collect();
            if let Ok(json) = serde_json::to_string_pretty(&cal_vec) {
                if let Err(e) = std::fs::write(path, &json) {
                    tracing::debug!(path = %path.display(), error = %e, "autotune cache write failed");
                }
            }
        }
    }

    #[cfg(not(feature = "serde"))]
    fn save_cache(&self) {
        // No-op without serde
    }

    /// Force recalibration
    pub(crate) fn recalibrate(&self, wgpu_device: &impl GpuDeviceForCalibration) -> GpuCalibration {
        let cal = self.calibrate_device(wgpu_device);

        {
            let mut cals = self
                .calibrations
                .write()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            cals.insert(wgpu_device.name().to_string(), cal.clone());
        }

        self.save_cache();
        cal
    }
}

// Global auto-tuner instance (singleton pattern via std::sync::LazyLock)
// Evolved from lazy_static to pure std (Rust 1.80+)
/// Global auto-tuner instance for runtime GPU parameter calibration.
pub static GLOBAL_TUNER: std::sync::LazyLock<AutoTuner> = std::sync::LazyLock::new(|| {
    // Try to use a standard cache location
    let cache_dir = std::env::var("XDG_CACHE_HOME").map_or_else(
        |_| {
            std::env::var("HOME").map_or_else(
                |_| std::env::temp_dir(),
                |h| PathBuf::from(h).join(".cache"),
            )
        },
        PathBuf::from,
    );

    let cache_path = cache_dir
        .join(env!("CARGO_PKG_NAME"))
        .join("gpu_calibrations.json");

    if let Some(parent) = cache_path.parent()
        && let Err(e) = std::fs::create_dir_all(parent)
    {
        tracing::debug!(path = %parent.display(), error = %e, "autotune cache dir creation failed");
    }

    AutoTuner::with_cache(cache_path)
});

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_default_calibration() {
        let cal = GpuCalibration::default();
        assert_eq!(cal.optimal_workgroup_size, 256);
    }

    #[test]
    fn test_tuner_creation() {
        let tuner = AutoTuner::new();
        assert!(
            tuner
                .calibrations
                .read()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .is_empty()
        );
    }
}