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
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Cyclic Reduction (f64) — Parallel Tridiagonal Solver for PDEs
//!
//! Solves tridiagonal systems: a[i]*x[i-1] + b[i]*x[i] + c[i]*x[i+1] = d[i]
//!
//! **Use cases**:
//! - Crank-Nicolson PDE (heat, diffusion, Schrödinger) — all springs
//! - Richards equation for unsaturated flow — airSpring, wetSpring
//! - Implicit finite difference schemes — hotSpring
//! - Cubic spline interpolation
//!
//! **Deep Debt Principles**:
//! - Pure WGSL implementation (hardware-agnostic)
//! - Full f64 precision for science-grade stability
//! - O(log n) parallel complexity vs O(n) sequential Thomas
//! - Safe Rust wrapper (no unsafe code)
use crate::device::WgpuDevice;
use crate::error::{BarracudaError, Result};
use bytemuck::{Pod, Zeroable};
use std::sync::Arc;
/// Parameters for cyclic reduction shader
#[repr(C)]
#[derive(Copy, Clone, Pod, Zeroable)]
struct CyclicParams {
n: u32,
step: u32,
phase: u32, // 0 = reduction, 1 = substitution
_pad: u32,
}
/// Type alias for tridiagonal system: (`sub_diag`, `main_diag`, `super_diag`, rhs)
pub type TridiagonalSystem = (Vec<f64>, Vec<f64>, Vec<f64>, Vec<f64>);
/// GPU-accelerated f64 tridiagonal solver via cyclic reduction
pub struct CyclicReductionF64 {
device: Arc<WgpuDevice>,
}
impl CyclicReductionF64 {
fn wgsl_shader() -> &'static str {
include_str!("../../shaders/linalg/cyclic_reduction_f64.wgsl")
}
/// Create a new `CyclicReductionF64` orchestrator
/// # Errors
/// Returns [`Err`] if device initialization fails.
pub fn new(device: Arc<WgpuDevice>) -> Result<Self> {
Ok(Self { device })
}
/// Solve tridiagonal system Ax = d where A is tridiagonal
/// # Arguments
/// * `a` - Sub-diagonal (length n, a[0] unused)
/// * `b` - Main diagonal (length n)
/// * `c` - Super-diagonal (length n, c[n-1] unused)
/// * `d` - Right-hand side (length n)
/// # Returns
/// Solution vector x of length n
/// # Example
/// ```ignore
/// // Solve: 4x₀ + x₁ = 5
/// // x₀ + 4x₁ + x₂ = 6
/// // x₁ + 4x₂ = 5
/// let a = vec![0.0, 1.0, 1.0];
/// let b = vec![4.0, 4.0, 4.0];
/// let c = vec![1.0, 1.0, 0.0];
/// let d = vec![5.0, 6.0, 5.0];
/// let x = solver.solve(&a, &b, &c, &d)?;
/// // x ≈ [1.0, 1.0, 1.0]
/// ```
/// # Errors
/// Returns [`Err`] if a, c, or d length differs from b, n=1 with singular matrix (b[0]=0),
/// buffer allocation fails, GPU dispatch fails, buffer readback fails, or the device is lost.
pub fn solve(&self, a: &[f64], b: &[f64], c: &[f64], d: &[f64]) -> Result<Vec<f64>> {
let n = b.len();
if a.len() != n || c.len() != n || d.len() != n {
return Err(BarracudaError::InvalidInput {
message: format!(
"All vectors must have length {}: a={}, b={}, c={}, d={}",
n,
a.len(),
b.len(),
c.len(),
d.len()
),
});
}
if n == 0 {
return Ok(vec![]);
}
if n == 1 {
if b[0].abs() < 1e-14 {
return Err(BarracudaError::InvalidInput {
message: "Singular matrix: b[0] = 0".to_string(),
});
}
return Ok(vec![d[0] / b[0]]);
}
if n >= 2048 {
self.solve_gpu_parallel(a, b, c, d)
} else {
self.solve_gpu_serial(a, b, c, d)
}
}
/// Batched solve for multiple independent systems
/// # Arguments
/// * `systems` - Vector of `TridiagonalSystem` (a, b, c, d) tuples
/// # Returns
/// Vector of solution vectors
///
/// # Errors
///
/// Returns [`Err`] if buffer allocation, GPU dispatch, or buffer
/// readback fails (e.g. device lost or out of memory).
pub fn solve_batch(&self, systems: &[TridiagonalSystem]) -> Result<Vec<Vec<f64>>> {
// Sequential per-system solve — batched GPU version (parallel across
// systems) is a P2 evolution when batch sizes exceed ~64 systems
systems
.iter()
.map(|(a, b, c, d)| self.solve(a, b, c, d))
.collect()
}
/// GPU serial solver using Thomas algorithm in a single kernel
/// No synchronization issues - O(n) but runs on GPU memory
fn solve_gpu_serial(&self, a: &[f64], b: &[f64], c: &[f64], d: &[f64]) -> Result<Vec<f64>> {
let n = b.len();
let shader = self
.device
.compile_shader_f64(Self::wgsl_shader(), Some("Cyclic Serial f64"));
// Create GPU buffers
let a_buf = self
.device
.device
.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("A (sub-diag)"),
contents: bytemuck::cast_slice(a),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
});
let b_buf = self
.device
.device
.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("B (main-diag)"),
contents: bytemuck::cast_slice(b),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
});
let c_buf = self
.device
.device
.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("C (super-diag)"),
contents: bytemuck::cast_slice(c),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
});
let d_buf = self
.device
.device
.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("D (RHS/solution)"),
contents: bytemuck::cast_slice(d),
usage: wgpu::BufferUsages::STORAGE
| wgpu::BufferUsages::COPY_DST
| wgpu::BufferUsages::COPY_SRC,
});
// Create bind group layout
let bgl = self
.device
.device
.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Serial BGL"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
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: false },
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,
},
wgpu::BindGroupLayoutEntry {
binding: 3,
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,
},
wgpu::BindGroupLayoutEntry {
binding: 4,
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 pl = self
.device
.device
.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Serial PL"),
bind_group_layouts: &[&bgl],
immediate_size: 0,
});
let serial_pipeline =
self.device
.device
.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("Serial Pipeline"),
layout: Some(&pl),
module: &shader,
entry_point: Some("solve_serial_f64"),
cache: None,
compilation_options: Default::default(),
});
let params = CyclicParams {
n: n as u32,
step: 0,
phase: 0,
_pad: 0,
};
let params_buf = self
.device
.device
.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Params"),
contents: bytemuck::bytes_of(¶ms),
usage: wgpu::BufferUsages::UNIFORM,
});
let bg = self
.device
.device
.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Serial BG"),
layout: &bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: params_buf.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: a_buf.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 2,
resource: b_buf.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 3,
resource: c_buf.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 4,
resource: d_buf.as_entire_binding(),
},
],
});
let mut encoder = self
.device
.create_encoder_guarded(&wgpu::CommandEncoderDescriptor {
label: Some("Serial Encoder"),
});
{
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("Serial Pass"),
timestamp_writes: None,
});
pass.set_pipeline(&serial_pipeline);
pass.set_bind_group(0, Some(&bg), &[]);
pass.dispatch_workgroups(1, 1, 1);
}
// Read back solution
let staging = self.device.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Staging"),
size: (n * 8) as u64,
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
encoder.copy_buffer_to_buffer(&d_buf, 0, &staging, 0, (n * 8) as u64);
self.device.submit_commands(Some(encoder.finish()));
let result: Vec<f64> = self.device.map_staging_buffer(&staging, n)?;
Ok(result)
}
/// GPU parallel cyclic reduction solver
/// O(log n) parallel — dispatched for n >= 2048 where parallelism amortizes
/// the extra passes. For smaller systems, `solve_gpu_serial` is preferred.
fn solve_gpu_parallel(&self, a: &[f64], b: &[f64], c: &[f64], d: &[f64]) -> Result<Vec<f64>> {
let n = b.len();
let n_padded = n.next_power_of_two();
let num_steps = (n_padded as f64).log2() as u32;
// Pad arrays to power of 2
let mut a_data: Vec<f64> = a.to_vec();
let mut b_data: Vec<f64> = b.to_vec();
let mut c_data: Vec<f64> = c.to_vec();
let mut d_data: Vec<f64> = d.to_vec();
a_data.resize(n_padded, 0.0);
b_data.resize(n_padded, 1.0); // Identity for padded elements
c_data.resize(n_padded, 0.0);
d_data.resize(n_padded, 0.0);
let shader = self
.device
.compile_shader_f64(Self::wgsl_shader(), Some("Cyclic Reduction f64"));
// Create mutable GPU buffers
let a_buf = self
.device
.device
.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("A (sub-diag)"),
contents: bytemuck::cast_slice(&a_data),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
});
let b_buf = self
.device
.device
.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("B (main-diag)"),
contents: bytemuck::cast_slice(&b_data),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
});
let c_buf = self
.device
.device
.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("C (super-diag)"),
contents: bytemuck::cast_slice(&c_data),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
});
let d_buf = self
.device
.device
.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("D (RHS/solution)"),
contents: bytemuck::cast_slice(&d_data),
usage: wgpu::BufferUsages::STORAGE
| wgpu::BufferUsages::COPY_DST
| wgpu::BufferUsages::COPY_SRC,
});
// Create bind group layout
let bgl = self
.device
.device
.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Cyclic Reduction BGL"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
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: false },
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,
},
wgpu::BindGroupLayoutEntry {
binding: 3,
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,
},
wgpu::BindGroupLayoutEntry {
binding: 4,
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 pl = self
.device
.device
.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Cyclic Reduction PL"),
bind_group_layouts: &[&bgl],
immediate_size: 0,
});
// Create pipelines for reduction and substitution
let reduction_pipeline =
self.device
.device
.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("Reduction Pipeline"),
layout: Some(&pl),
module: &shader,
entry_point: Some("reduction_f64"),
cache: None,
compilation_options: Default::default(),
});
let substitution_pipeline =
self.device
.device
.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("Substitution Pipeline"),
layout: Some(&pl),
module: &shader,
entry_point: Some("substitution_f64"),
cache: None,
compilation_options: Default::default(),
});
// Multi-pass cyclic reduction
let workgroup_size = 256;
// Reduction phase: O(log n) passes
for step in 0..num_steps {
let params = CyclicParams {
n: n_padded as u32,
step,
phase: 0,
_pad: 0,
};
let params_buf =
self.device
.device
.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Params"),
contents: bytemuck::bytes_of(¶ms),
usage: wgpu::BufferUsages::UNIFORM,
});
let bg = self
.device
.device
.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Reduction BG"),
layout: &bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: params_buf.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: a_buf.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 2,
resource: b_buf.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 3,
resource: c_buf.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 4,
resource: d_buf.as_entire_binding(),
},
],
});
let n_threads = n_padded >> (step + 1);
let n_workgroups = n_threads.div_ceil(workgroup_size);
let mut encoder = self
.device
.create_encoder_guarded(&wgpu::CommandEncoderDescriptor {
label: Some("Reduction Encoder"),
});
{
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("Reduction Pass"),
timestamp_writes: None,
});
pass.set_pipeline(&reduction_pipeline);
pass.set_bind_group(0, Some(&bg), &[]);
pass.dispatch_workgroups(n_workgroups.max(1) as u32, 1, 1);
}
self.device.submit_commands(Some(encoder.finish()));
}
// Substitution phase: O(log n) passes in reverse
for step in (0..num_steps).rev() {
let params = CyclicParams {
n: n_padded as u32,
step,
phase: 1,
_pad: 0,
};
let params_buf =
self.device
.device
.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Params"),
contents: bytemuck::bytes_of(¶ms),
usage: wgpu::BufferUsages::UNIFORM,
});
let bg = self
.device
.device
.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Substitution BG"),
layout: &bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: params_buf.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: a_buf.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 2,
resource: b_buf.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 3,
resource: c_buf.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 4,
resource: d_buf.as_entire_binding(),
},
],
});
let n_threads = n_padded >> (step + 1);
let n_workgroups = n_threads.div_ceil(workgroup_size);
let mut encoder = self
.device
.create_encoder_guarded(&wgpu::CommandEncoderDescriptor {
label: Some("Substitution Encoder"),
});
{
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("Substitution Pass"),
timestamp_writes: None,
});
pass.set_pipeline(&substitution_pipeline);
pass.set_bind_group(0, Some(&bg), &[]);
pass.dispatch_workgroups(n_workgroups.max(1) as u32, 1, 1);
}
self.device.submit_commands(Some(encoder.finish()));
}
// Read back solution (stored in d_buf)
let staging = self.device.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Staging"),
size: (n * 8) as u64, // f64 = 8 bytes, only read first n
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let mut encoder = self
.device
.create_encoder_guarded(&wgpu::CommandEncoderDescriptor {
label: Some("Copy Encoder"),
});
encoder.copy_buffer_to_buffer(&d_buf, 0, &staging, 0, (n * 8) as u64);
self.device.submit_commands(Some(encoder.finish()));
let result: Vec<f64> = self.device.map_staging_buffer(&staging, n)?;
Ok(result)
}
}
#[cfg(test)]
mod cpu_reference;
#[cfg(test)]
mod tests;