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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Compute Graph - Lazy Execution for Operation Batching
//!
//! **Problem**: wgpu has significant per-dispatch overhead (~50-100μs).
//! Individual operations like `tensor.add(&b)` each submit a separate command buffer.
//!
//! **Solution**: Record operations lazily, then batch them into a single submission.
//!
//! **Usage**:
//! ```rust,ignore
//! # use barracuda::prelude::*;
//! # async fn example() -> Result<()> {
//! let device = Arc::new(WgpuDevice::new().await?);
//! let mut graph = ComputeGraph::new(device.as_ref());
//! // Use record_add/record_mul with buffers, then graph.execute()
//! # Ok(())
//! # }
//! ```
//!
//! **Performance Impact**: Batching 100 operations reduces overhead from
//! ~10ms (100 × 100μs) to ~200μs (1 × 100μs + 100 × 1μs kernel dispatch).

use crate::device::WgpuDevice;
use crate::device::compute_pipeline::{storage_bgl_entry, uniform_bgl_entry};
use crate::error::Result;
use std::sync::Arc;

/// Recorded operation in the compute graph.
#[derive(Debug)]
pub enum RecordedOp {
    /// Element-wise add: output = a + b
    Add {
        /// First input buffer
        input_a: wgpu::Buffer,
        /// Second input buffer
        input_b: wgpu::Buffer,
        /// Output buffer
        output: wgpu::Buffer,
        /// Element count
        size: usize,
    },
    /// Element-wise multiply: output = a * b
    Mul {
        /// First input buffer
        input_a: wgpu::Buffer,
        /// Second input buffer
        input_b: wgpu::Buffer,
        /// Output buffer
        output: wgpu::Buffer,
        /// Element count
        size: usize,
    },
    /// Fused multiply-add: output = a * b + c
    Fma {
        /// First input buffer
        input_a: wgpu::Buffer,
        /// Second input buffer
        input_b: wgpu::Buffer,
        /// Third input buffer
        input_c: wgpu::Buffer,
        /// Output buffer
        output: wgpu::Buffer,
        /// Element count
        size: usize,
    },
    /// Scale: output = a * scalar
    Scale {
        /// Input buffer
        input: wgpu::Buffer,
        /// Scale factor
        scalar: f32,
        /// Output buffer
        output: wgpu::Buffer,
        /// Element count
        size: usize,
    },
    /// Custom shader operation
    Custom {
        /// WGSL shader source
        shader_source: String,
        /// Input/output buffers
        buffers: Vec<wgpu::Buffer>,
        /// Workgroup counts (x, y, z)
        workgroups: (u32, u32, u32),
    },
}

/// Compute graph for batching GPU operations
///
/// Records operations without executing them, then batches
/// all operations into a single command buffer submission.
pub struct ComputeGraph {
    wgpu_device: Arc<WgpuDevice>,
    device: crate::device::wgpu_device::GuardedDeviceHandle,
    queue: wgpu::Queue,
    device_name: String,
    ops: Vec<RecordedOp>,
    optimal_workgroup_size: u32,
}

impl ComputeGraph {
    /// Create a new compute graph for a device
    #[must_use]
    pub fn new(wgpu_device: &WgpuDevice) -> Self {
        Self::with_device(Arc::new(wgpu_device.clone()))
    }

    /// Create a new compute graph with an explicit device `Arc`.
    #[must_use]
    pub fn with_device(wgpu_device: Arc<WgpuDevice>) -> Self {
        let optimal_wg = wgpu_device.optimal_workgroup_size();
        let device = wgpu_device.device.clone();
        let queue = wgpu_device.queue.clone();
        let device_name = wgpu_device.name().to_string();
        Self {
            wgpu_device,
            device,
            queue,
            device_name,
            ops: Vec::new(),
            optimal_workgroup_size: optimal_wg,
        }
    }

    /// Device name (for debug logging and diagnostics).
    #[must_use]
    pub fn device_name(&self) -> &str {
        &self.device_name
    }

    /// Record an add operation
    pub fn record_add(
        &mut self,
        input_a: wgpu::Buffer,
        input_b: wgpu::Buffer,
        output: wgpu::Buffer,
        size: usize,
    ) {
        self.ops.push(RecordedOp::Add {
            input_a,
            input_b,
            output,
            size,
        });
    }

    /// Record a multiply operation
    pub fn record_mul(
        &mut self,
        input_a: wgpu::Buffer,
        input_b: wgpu::Buffer,
        output: wgpu::Buffer,
        size: usize,
    ) {
        self.ops.push(RecordedOp::Mul {
            input_a,
            input_b,
            output,
            size,
        });
    }

    /// Record a fused multiply-add operation
    pub fn record_fma(
        &mut self,
        input_a: wgpu::Buffer,
        input_b: wgpu::Buffer,
        input_c: wgpu::Buffer,
        output: wgpu::Buffer,
        size: usize,
    ) {
        self.ops.push(RecordedOp::Fma {
            input_a,
            input_b,
            input_c,
            output,
            size,
        });
    }

    /// Number of recorded operations
    #[must_use]
    pub fn len(&self) -> usize {
        self.ops.len()
    }

    /// Check if graph is empty
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.ops.is_empty()
    }

    /// Clear all recorded operations
    pub fn clear(&mut self) {
        self.ops.clear();
    }

    /// Execute all recorded operations in a single batch
    /// This is where the performance magic happens - all operations
    /// are encoded into a single command buffer and submitted together.
    /// # Errors
    /// Returns [`Err`] if buffer allocation, GPU dispatch, or device
    /// submission fails (e.g. device lost or out of memory).
    pub fn execute(&mut self) -> Result<()> {
        if self.ops.is_empty() {
            return Ok(());
        }

        let mut encoder =
            self.wgpu_device
                .create_encoder_guarded(&wgpu::CommandEncoderDescriptor {
                    label: Some("ComputeGraph Batch"),
                });

        let add_shader = self.compile_elementwise("output[idx] = a[idx] + b[idx];", "Add");
        let mul_shader = self.compile_elementwise("output[idx] = a[idx] * b[idx];", "Mul");
        let fma_shader = self.compile_shader(
            &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> c: array<f32>;
@group(0) @binding(3) var<storage, read_write> output: array<f32>;

@compute @workgroup_size({wg})
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {{
    let idx = global_id.x;
    if (idx >= arrayLength(&output)) {{ return; }}
    output[idx] = fma(a[idx], b[idx], c[idx]);
}}",
                wg = self.optimal_workgroup_size
            ),
            "FMA",
        );
        let scale_shader = self.compile_shader(
            &format!(
                r"
@group(0) @binding(0) var<storage, read> input: array<f32>;
@group(0) @binding(1) var<uniform> scalar: f32;
@group(0) @binding(2) var<storage, read_write> output: array<f32>;

@compute @workgroup_size({wg})
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {{
    let idx = gid.x;
    if (idx >= arrayLength(&output)) {{ return; }}
    output[idx] = input[idx] * scalar;
}}",
                wg = self.optimal_workgroup_size
            ),
            "Scale",
        );

        for op in &self.ops {
            match op {
                RecordedOp::Add {
                    input_a,
                    input_b,
                    output,
                    size,
                } => {
                    self.dispatch_pass(
                        &mut encoder,
                        &add_shader,
                        &[
                            storage_bgl_entry(0, true),
                            storage_bgl_entry(1, true),
                            storage_bgl_entry(2, false),
                        ],
                        &[input_a, input_b, output],
                        *size,
                    );
                }
                RecordedOp::Mul {
                    input_a,
                    input_b,
                    output,
                    size,
                } => {
                    self.dispatch_pass(
                        &mut encoder,
                        &mul_shader,
                        &[
                            storage_bgl_entry(0, true),
                            storage_bgl_entry(1, true),
                            storage_bgl_entry(2, false),
                        ],
                        &[input_a, input_b, output],
                        *size,
                    );
                }
                RecordedOp::Fma {
                    input_a,
                    input_b,
                    input_c,
                    output,
                    size,
                } => {
                    self.dispatch_pass(
                        &mut encoder,
                        &fma_shader,
                        &[
                            storage_bgl_entry(0, true),
                            storage_bgl_entry(1, true),
                            storage_bgl_entry(2, true),
                            storage_bgl_entry(3, false),
                        ],
                        &[input_a, input_b, input_c, output],
                        *size,
                    );
                }
                RecordedOp::Scale {
                    input,
                    scalar,
                    output,
                    size,
                } => {
                    let scalar_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
                        label: Some("Scalar Uniform"),
                        size: 4,
                        usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
                        mapped_at_creation: false,
                    });
                    self.queue
                        .write_buffer(&scalar_buffer, 0, bytemuck::bytes_of(scalar));
                    self.dispatch_pass(
                        &mut encoder,
                        &scale_shader,
                        &[
                            storage_bgl_entry(0, true),
                            uniform_bgl_entry(1),
                            storage_bgl_entry(2, false),
                        ],
                        &[input, &scalar_buffer, output],
                        *size,
                    );
                }
                RecordedOp::Custom {
                    shader_source,
                    buffers,
                    workgroups,
                } => {
                    self.encode_custom_op(&mut encoder, shader_source, buffers, *workgroups);
                }
            }
        }

        self.wgpu_device
            .submit_and_poll_inner(Some(encoder.finish()));
        self.ops.clear();
        if self.wgpu_device.is_lost() {
            return Err(crate::error::BarracudaError::device(
                "GPU device lost during compute graph execution",
            ));
        }

        Ok(())
    }

    // ── Shader compilation helpers ──────────────────────────────────────

    fn compile_shader(&self, source: &str, label: &str) -> wgpu::ShaderModule {
        self.device
            .create_shader_module(wgpu::ShaderModuleDescriptor {
                label: Some(label),
                source: wgpu::ShaderSource::Wgsl(source.into()),
            })
    }

    fn compile_elementwise(&self, body: &str, label: &str) -> wgpu::ShaderModule {
        self.compile_shader(
            &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({wg})
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {{
    let idx = global_id.x;
    if (idx >= arrayLength(&output)) {{ return; }}
    {body}
}}",
                wg = self.optimal_workgroup_size
            ),
            label,
        )
    }

    // ── Dispatch helpers ────────────────────────────────────────────────

    fn dispatch_pass(
        &self,
        encoder: &mut wgpu::CommandEncoder,
        shader: &wgpu::ShaderModule,
        bgl_entries: &[wgpu::BindGroupLayoutEntry],
        buffers: &[&wgpu::Buffer],
        size: usize,
    ) {
        let bgl = self
            .device
            .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                label: None,
                entries: bgl_entries,
            });

        let bind_entries: Vec<_> = buffers
            .iter()
            .enumerate()
            .map(|(i, buf)| wgpu::BindGroupEntry {
                binding: i as u32,
                resource: buf.as_entire_binding(),
            })
            .collect();

        let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: None,
            layout: &bgl,
            entries: &bind_entries,
        });

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

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

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

        {
            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);
        }
    }

    fn encode_custom_op(
        &self,
        encoder: &mut wgpu::CommandEncoder,
        shader_source: &str,
        buffers: &[wgpu::Buffer],
        workgroups: (u32, u32, u32),
    ) {
        let shader = self.compile_shader(shader_source, "Custom");

        let bgl_entries: Vec<_> = buffers
            .iter()
            .enumerate()
            .map(|(i, _)| storage_bgl_entry(i as u32, i < buffers.len() - 1))
            .collect();

        let bgl = self
            .device
            .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                label: None,
                entries: &bgl_entries,
            });

        let bind_entries: Vec<_> = buffers
            .iter()
            .enumerate()
            .map(|(i, buf)| wgpu::BindGroupEntry {
                binding: i as u32,
                resource: buf.as_entire_binding(),
            })
            .collect();

        let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: None,
            layout: &bgl,
            entries: &bind_entries,
        });

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

        let pipeline = self
            .device
            .create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
                label: None,
                layout: Some(&pipeline_layout),
                module: &shader,
                entry_point: Some("main"),
                cache: None,
                compilation_options: Default::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.0, workgroups.1, workgroups.2);
        }
    }
}

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

    fn make_storage_buf(device: &WgpuDevice, label: &str, data: &[f32]) -> wgpu::Buffer {
        device
            .device
            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some(label),
                contents: bytemuck::cast_slice(data),
                usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
            })
    }

    fn make_output_buf(device: &WgpuDevice, label: &str, n: usize) -> wgpu::Buffer {
        device.device.create_buffer(&wgpu::BufferDescriptor {
            label: Some(label),
            size: (n * 4) as u64,
            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
            mapped_at_creation: false,
        })
    }

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

        let mut graph = ComputeGraph::new(&device);

        let data_a: Vec<f32> = (0..1000).map(|i| i as f32).collect();
        let data_b: Vec<f32> = (0..1000).map(|i| (i * 2) as f32).collect();

        let buf_a = make_storage_buf(&device, "A", &data_a);
        let buf_b = make_storage_buf(&device, "B", &data_b);
        let buf_out = make_output_buf(&device, "Out", 1000);

        graph.record_add(buf_a, buf_b, buf_out, 1000);

        assert_eq!(graph.len(), 1);

        graph.execute().unwrap();

        assert!(graph.is_empty());
    }

    #[test]
    fn test_graph_empty_execute() {
        let graph_len = 0_usize;
        assert_eq!(graph_len, 0);
    }

    #[tokio::test]
    async fn test_graph_new_is_empty() {
        let Some(device) = test_pool::get_test_device_if_gpu_available().await else {
            return;
        };
        let graph = ComputeGraph::new(&device);
        assert!(graph.is_empty());
        assert_eq!(graph.len(), 0);
    }

    #[tokio::test]
    async fn test_graph_device_name_populated() {
        let Some(device) = test_pool::get_test_device_if_gpu_available().await else {
            return;
        };
        let graph = ComputeGraph::new(&device);
        assert!(!graph.device_name().is_empty());
    }

    #[tokio::test]
    async fn test_graph_record_mul_increments_len() {
        let Some(device) = test_pool::get_test_device_if_gpu_available().await else {
            return;
        };
        let mut graph = ComputeGraph::new(&device);
        let a = make_storage_buf(&device, "a", &[1.0, 2.0]);
        let b = make_storage_buf(&device, "b", &[3.0, 4.0]);
        let out = make_output_buf(&device, "o", 2);
        graph.record_mul(a, b, out, 2);
        assert_eq!(graph.len(), 1);
    }

    #[tokio::test]
    async fn test_graph_record_fma_increments_len() {
        let Some(device) = test_pool::get_test_device_if_gpu_available().await else {
            return;
        };
        let mut graph = ComputeGraph::new(&device);
        let a = make_storage_buf(&device, "a", &[1.0, 2.0]);
        let b = make_storage_buf(&device, "b", &[3.0, 4.0]);
        let c = make_storage_buf(&device, "c", &[5.0, 6.0]);
        let out = make_output_buf(&device, "o", 2);
        graph.record_fma(a, b, c, out, 2);
        assert_eq!(graph.len(), 1);
    }

    #[tokio::test]
    async fn test_graph_clear() {
        let Some(device) = test_pool::get_test_device_if_gpu_available().await else {
            return;
        };
        let mut graph = ComputeGraph::new(&device);
        let a = make_storage_buf(&device, "a", &[1.0]);
        let b = make_storage_buf(&device, "b", &[2.0]);
        let out = make_output_buf(&device, "o", 1);
        graph.record_add(a, b, out, 1);
        assert_eq!(graph.len(), 1);
        graph.clear();
        assert!(graph.is_empty());
    }

    #[tokio::test]
    async fn test_graph_multiple_ops_batch() {
        let Some(device) = test_pool::get_test_device_if_gpu_available().await else {
            return;
        };
        let mut graph = ComputeGraph::new(&device);
        let n = 64;
        let ones: Vec<f32> = vec![1.0; n];
        let twos: Vec<f32> = vec![2.0; n];
        let threes: Vec<f32> = vec![3.0; n];

        let a1 = make_storage_buf(&device, "a1", &ones);
        let b1 = make_storage_buf(&device, "b1", &twos);
        let o1 = make_output_buf(&device, "o1", n);
        graph.record_add(a1, b1, o1, n);

        let a2 = make_storage_buf(&device, "a2", &twos);
        let b2 = make_storage_buf(&device, "b2", &threes);
        let o2 = make_output_buf(&device, "o2", n);
        graph.record_mul(a2, b2, o2, n);

        let fa = make_storage_buf(&device, "fa", &ones);
        let fb = make_storage_buf(&device, "fb", &twos);
        let fc = make_storage_buf(&device, "fc", &threes);
        let fo = make_output_buf(&device, "fo", n);
        graph.record_fma(fa, fb, fc, fo, n);

        assert_eq!(graph.len(), 3);
        graph.execute().unwrap();
        assert!(graph.is_empty());
    }

    #[tokio::test]
    async fn test_graph_execute_empty_is_noop() {
        let Some(device) = test_pool::get_test_device_if_gpu_available().await else {
            return;
        };
        let mut graph = ComputeGraph::new(&device);
        graph.execute().unwrap();
        assert!(graph.is_empty());
    }

    #[tokio::test]
    async fn test_graph_reuse_after_execute() {
        let Some(device) = test_pool::get_test_device_if_gpu_available().await else {
            return;
        };
        let mut graph = ComputeGraph::new(&device);

        let a = make_storage_buf(&device, "a", &[1.0, 2.0, 3.0, 4.0]);
        let b = make_storage_buf(&device, "b", &[5.0, 6.0, 7.0, 8.0]);
        let o = make_output_buf(&device, "o", 4);
        graph.record_add(a, b, o, 4);
        graph.execute().unwrap();
        assert!(graph.is_empty());

        let a2 = make_storage_buf(&device, "a2", &[10.0, 20.0]);
        let b2 = make_storage_buf(&device, "b2", &[30.0, 40.0]);
        let o2 = make_output_buf(&device, "o2", 2);
        graph.record_mul(a2, b2, o2, 2);
        assert_eq!(graph.len(), 1);
        graph.execute().unwrap();
        assert!(graph.is_empty());
    }
}