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
// SPDX-License-Identifier: AGPL-3.0-or-later
//! GPU-resident Conjugate Gradient solver
//!
//! Scalar values (α, β, ρ) remain on GPU; residual read only every `check_interval` iterations.

use super::CgGpu;
use super::CgGpuResult;
use crate::device::WgpuDevice;
use crate::device::capabilities::WORKGROUP_SIZE_1D;
use crate::error::{BarracudaError, Result};
use crate::linalg::sparse::csr::CsrMatrix;
use crate::linalg::sparse::gpu_helpers::{
    CgPipelineSet, SparseBindGroupLayouts, SparseBuffers, cg_dispatch_pass,
};
use std::sync::Arc;

impl CgGpu {
    /// Solve Ax = b using GPU-resident Conjugate Gradient (reduced CPU sync)
    /// This is the **recommended method** for large systems.
    /// Scalar values (α, β, ρ) remain on GPU; residual is only read every `check_interval` iterations.
    /// # Arguments
    /// * `device` - `WgpuDevice` to execute on
    /// * `a` - Symmetric positive definite CSR matrix (f64)
    /// * `b` - Right-hand side vector (f64)
    /// * `tol` - Convergence tolerance
    /// * `max_iter` - Maximum iterations
    /// * `check_interval` - How often to read residual from GPU (default: 10)
    /// # Performance
    /// For a 1000×1000 matrix:
    /// - Original: ~100 GPU↔CPU syncs for 100 iterations
    /// - GPU-resident (`check_interval=10)`: ~10 GPU↔CPU syncs
    /// # Errors
    /// Returns [`Err`] if the matrix is not square, if `b.len() != n`, or if
    /// buffer allocation, GPU dispatch, or readback fails (e.g. device lost or
    /// out of memory).
    pub fn solve_gpu_resident(
        device: Arc<WgpuDevice>,
        a: &CsrMatrix,
        b: &[f64],
        tol: f64,
        max_iter: usize,
        check_interval: usize,
    ) -> Result<CgGpuResult> {
        let n = a.n_rows;
        if a.n_cols != n {
            return Err(BarracudaError::InvalidInput {
                message: "CG requires square matrix".to_string(),
            });
        }
        if b.len() != n {
            return Err(BarracudaError::InvalidInput {
                message: format!("Vector length {} doesn't match matrix size {}", b.len(), n),
            });
        }

        let check_interval = check_interval.max(1);

        // Early exit for zero RHS
        let b_norm: f64 = b.iter().map(|x| x * x).sum::<f64>().sqrt();
        if b_norm < 1e-14 {
            return Ok(CgGpuResult {
                x: vec![0.0; n],
                iterations: 0,
                residual: 0.0,
                converged: true,
            });
        }

        // Create GPU buffers for CSR matrix
        let values_buffer = SparseBuffers::f64_from_slice(&device, "CG values", &a.values);
        let col_indices_buffer =
            SparseBuffers::u32_from_usize(&device, "CG col_idx", &a.col_indices);
        let row_ptrs_buffer = SparseBuffers::u32_from_usize(&device, "CG row_ptr", &a.row_ptr);

        // Create GPU buffers for vectors
        let x_buffer = SparseBuffers::f64_zeros(&device, "CG x", n);
        let r_buffer = SparseBuffers::f64_from_slice(&device, "CG r", b);
        let p_buffer = SparseBuffers::f64_from_slice(&device, "CG p", b);
        let ap_buffer = SparseBuffers::f64_zeros(&device, "CG Ap", n);

        // Scalar buffers (stay on GPU)
        let num_workgroups = n.div_ceil(WORKGROUP_SIZE_1D as usize);
        let partial_sums_buffer = SparseBuffers::f64_zeros(&device, "CG partial", num_workgroups);
        let rz_buffer = SparseBuffers::f64_zeros(&device, "CG rz", 1);
        let rz_new_buffer = SparseBuffers::f64_zeros(&device, "CG rz_new", 1);
        let pap_buffer = SparseBuffers::f64_zeros(&device, "CG pAp", 1);
        let alpha_buffer = SparseBuffers::f64_zeros(&device, "CG alpha", 1);
        let beta_buffer = SparseBuffers::f64_zeros(&device, "CG beta", 1);

        // Compile shader modules
        let spmv_shader = device.compile_shader_f64(Self::spmv_shader(), Some("CG SpMV"));
        let dot_reduce_shader =
            device.compile_shader_f64(Self::dot_reduce_shader(), Some("CG Dot/Reduce"));
        let cg_kernels_shader =
            device.compile_shader_f64(Self::cg_kernels_shader(), Some("CG Kernels"));

        // Create bind group layouts and pipelines
        let spmv_bgl = SparseBindGroupLayouts::spmv(&device);
        let dot_bgl = SparseBindGroupLayouts::dot(&device);
        let reduce_bgl = SparseBindGroupLayouts::reduce(&device);
        let update_xr_bgl = SparseBindGroupLayouts::cg_update_xr(&device);
        let update_p_bgl = SparseBindGroupLayouts::cg_update_p(&device);
        let compute_alpha_bgl = SparseBindGroupLayouts::compute_alpha(&device);
        let compute_beta_bgl = SparseBindGroupLayouts::compute_beta(&device);

        let pl = CgPipelineSet::new(
            &device,
            &spmv_shader,
            &dot_reduce_shader,
            &cg_kernels_shader,
            &spmv_bgl,
            &dot_bgl,
            &reduce_bgl,
            &update_xr_bgl,
            &update_p_bgl,
            &compute_alpha_bgl,
            &compute_beta_bgl,
        );

        // Create bind groups
        let spmv_params = [n as u32];
        let spmv_params_buf = device
            .device
            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("SpMV params"),
                contents: bytemuck::cast_slice(&spmv_params),
                usage: wgpu::BufferUsages::UNIFORM,
            });

        let spmv_bg = device.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("SpMV BG"),
            layout: &spmv_bgl,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: values_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: col_indices_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: row_ptrs_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 3,
                    resource: p_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 4,
                    resource: ap_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 5,
                    resource: spmv_params_buf.as_entire_binding(),
                },
            ],
        });

        let dot_params = [n as u32];
        let dot_params_buf = device
            .device
            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("Dot params"),
                contents: bytemuck::cast_slice(&dot_params),
                usage: wgpu::BufferUsages::UNIFORM,
            });

        // rᵀr dot product bind group
        let rr_bg = device.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("rr BG"),
            layout: &dot_bgl,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: r_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: r_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: partial_sums_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 3,
                    resource: dot_params_buf.as_entire_binding(),
                },
            ],
        });

        // pᵀAp dot product bind group
        let pap_bg = device.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("pAp BG"),
            layout: &dot_bgl,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: p_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: ap_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: partial_sums_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 3,
                    resource: dot_params_buf.as_entire_binding(),
                },
            ],
        });

        let reduce_params = [num_workgroups as u32];
        let reduce_params_buf =
            device
                .device
                .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                    label: Some("Reduce params"),
                    contents: bytemuck::cast_slice(&reduce_params),
                    usage: wgpu::BufferUsages::UNIFORM,
                });

        // Reduce to rz_buffer
        let reduce_rz_bg = device.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("Reduce rz BG"),
            layout: &reduce_bgl,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: partial_sums_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: rz_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: reduce_params_buf.as_entire_binding(),
                },
            ],
        });

        // Reduce to rz_new_buffer
        let reduce_rz_new_bg = device.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("Reduce rz_new BG"),
            layout: &reduce_bgl,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: partial_sums_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: rz_new_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: reduce_params_buf.as_entire_binding(),
                },
            ],
        });

        // Reduce to pap_buffer
        let reduce_pap_bg = device.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("Reduce pAp BG"),
            layout: &reduce_bgl,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: partial_sums_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: pap_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: reduce_params_buf.as_entire_binding(),
                },
            ],
        });

        let cg_params = [n as u32];
        let cg_params_buf = device
            .device
            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("CG params"),
                contents: bytemuck::cast_slice(&cg_params),
                usage: wgpu::BufferUsages::UNIFORM,
            });

        let update_xr_bg = device.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("Update xr BG"),
            layout: &update_xr_bgl,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: x_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: r_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: p_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 3,
                    resource: ap_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 4,
                    resource: alpha_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 5,
                    resource: cg_params_buf.as_entire_binding(),
                },
            ],
        });

        let update_p_bg = device.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("Update p BG"),
            layout: &update_p_bgl,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: r_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: p_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: beta_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 3,
                    resource: cg_params_buf.as_entire_binding(),
                },
            ],
        });

        let compute_alpha_bg = device.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("Compute alpha BG"),
            layout: &compute_alpha_bgl,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: rz_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: pap_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: alpha_buffer.as_entire_binding(),
                },
            ],
        });

        let compute_beta_bg = device.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("Compute beta BG"),
            layout: &compute_beta_bgl,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: rz_new_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: rz_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: beta_buffer.as_entire_binding(),
                },
            ],
        });

        // Initialize: compute rᵀr and store in rz_buffer
        {
            let mut encoder = device.create_encoder_guarded(&wgpu::CommandEncoderDescriptor {
                label: Some("Init rz"),
            });
            {
                let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                    label: Some("Dot rr Pass"),
                    timestamp_writes: None,
                });
                cg_dispatch_pass(&mut pass, &pl.dot, &rr_bg, num_workgroups as u32, 1, 1);
            }
            {
                let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                    label: Some("Reduce rz Pass"),
                    timestamp_writes: None,
                });
                cg_dispatch_pass(&mut pass, &pl.reduce, &reduce_rz_bg, 1, 1, 1);
            }
            device.submit_commands(Some(encoder.finish()));
        }

        // Main CG iteration loop
        let mut last_residual = 1.0;
        for iter in 0..max_iter {
            // 1. Compute Ap
            // 2. Compute pᵀAp
            // 3. α = rz / pAp
            // 4. x = x + α*p, r = r - α*Ap
            // 5. Compute new rᵀr
            // 6. β = rz_new / rz, update rz
            // 7. p = r + β*p

            let mut encoder = device.create_encoder_guarded(&wgpu::CommandEncoderDescriptor {
                label: Some("CG iter"),
            });

            // 1. SpMV: Ap = A * p
            {
                let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                    label: Some("SpMV"),
                    timestamp_writes: None,
                });
                cg_dispatch_pass(
                    &mut pass,
                    &pl.spmv,
                    &spmv_bg,
                    (n as u32).div_ceil(WORKGROUP_SIZE_1D),
                    1,
                    1,
                );
            }
            // 2. Dot: pᵀAp, then reduce
            {
                let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                    label: Some("Dot pAp"),
                    timestamp_writes: None,
                });
                cg_dispatch_pass(&mut pass, &pl.dot, &pap_bg, num_workgroups as u32, 1, 1);
            }
            {
                let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                    label: Some("Reduce pAp"),
                    timestamp_writes: None,
                });
                cg_dispatch_pass(&mut pass, &pl.reduce, &reduce_pap_bg, 1, 1, 1);
            }
            // 3. α = rz / pAp
            {
                let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                    label: Some("Compute alpha"),
                    timestamp_writes: None,
                });
                cg_dispatch_pass(&mut pass, &pl.compute_alpha, &compute_alpha_bg, 1, 1, 1);
            }
            // 4. x = x + α*p, r = r - α*Ap
            {
                let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                    label: Some("Update xr"),
                    timestamp_writes: None,
                });
                cg_dispatch_pass(
                    &mut pass,
                    &pl.update_xr,
                    &update_xr_bg,
                    (n as u32).div_ceil(WORKGROUP_SIZE_1D),
                    1,
                    1,
                );
            }
            // 5. New rᵀr
            {
                let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                    label: Some("Dot rr new"),
                    timestamp_writes: None,
                });
                cg_dispatch_pass(&mut pass, &pl.dot, &rr_bg, num_workgroups as u32, 1, 1);
            }
            {
                let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                    label: Some("Reduce rz new"),
                    timestamp_writes: None,
                });
                cg_dispatch_pass(&mut pass, &pl.reduce, &reduce_rz_new_bg, 1, 1, 1);
            }
            // 6. β = rz_new / rz, then rz = rz_new
            {
                let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                    label: Some("Compute beta"),
                    timestamp_writes: None,
                });
                cg_dispatch_pass(&mut pass, &pl.compute_beta, &compute_beta_bg, 1, 1, 1);
            }
            // 7. p = r + β*p
            {
                let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                    label: Some("Update p"),
                    timestamp_writes: None,
                });
                cg_dispatch_pass(
                    &mut pass,
                    &pl.update_p,
                    &update_p_bg,
                    (n as u32).div_ceil(WORKGROUP_SIZE_1D),
                    1,
                    1,
                );
            }

            device.submit_commands(Some(encoder.finish()));

            // Check convergence only every check_interval iterations
            if (iter + 1) % check_interval == 0 || iter == max_iter - 1 {
                let rz_new = SparseBuffers::read_f64(&device, &rz_new_buffer, 1)?;
                let r_norm = rz_new[0].sqrt();
                last_residual = r_norm / b_norm;

                if last_residual < tol {
                    let x_data = SparseBuffers::read_f64(&device, &x_buffer, n)?;
                    return Ok(CgGpuResult {
                        x: x_data,
                        iterations: iter + 1,
                        residual: last_residual,
                        converged: true,
                    });
                }
            }
        }

        // Did not converge
        let x_data = SparseBuffers::read_f64(&device, &x_buffer, n)?;

        Ok(CgGpuResult {
            x: x_data,
            iterations: max_iter,
            residual: last_residual,
            converged: false,
        })
    }
}