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
// SPDX-License-Identifier: AGPL-3.0-or-later

//! GPU-accelerated batched L-BFGS optimizer.
//!
//! Solves `batch_size` independent optimization problems in parallel on the GPU.
//! Each problem has `n` dimensions and uses the limited-memory BFGS algorithm
//! with `m` stored correction pairs and numerical (central difference) gradients.
//!
//! The two-loop recursion and step updates run entirely on the GPU; only
//! scalar convergence checks require CPU readback.
//!
//! Provenance: groundSpring V68 request → toadStool S88 absorption.

use crate::device::WgpuDevice;
use crate::error::{BarracudaError, Result};
use std::sync::Arc;

// Shader sources for future full-GPU dispatch path (currently CPU-orchestrated).
const _WGSL_TWO_LOOP: &str = include_str!("../shaders/optimizer/lbfgs_two_loop_f64.wgsl");
const _WGSL_BATCH_GRAD: &str = include_str!("../shaders/optimizer/batch_gradient_f64.wgsl");

/// Configuration for batched GPU L-BFGS.
#[derive(Debug, Clone)]
pub struct LbfgsGpuConfig {
    /// Number of stored correction pairs (memory depth, typically 3-20).
    pub memory: usize,
    /// Maximum number of outer iterations.
    pub max_iter: usize,
    /// Gradient norm tolerance for convergence.
    pub gtol: f64,
    /// Function value tolerance for convergence.
    pub ftol: f64,
    /// Central difference epsilon for numerical gradient.
    pub epsilon: f64,
    /// Sufficient decrease parameter for line search (Armijo c1).
    pub c1: f64,
    /// Maximum backtracking line search steps.
    pub max_linesearch: usize,
}

impl Default for LbfgsGpuConfig {
    fn default() -> Self {
        Self {
            memory: 10,
            max_iter: 200,
            gtol: 1e-6,
            ftol: 1e-8,
            epsilon: 1e-7,
            c1: 1e-4,
            max_linesearch: 20,
        }
    }
}

/// Result from one problem in the batch.
#[derive(Debug, Clone)]
pub struct LbfgsGpuResult {
    /// Optimized solution vector (length n).
    pub x: Vec<f64>,
    /// Final objective function value.
    pub f_val: f64,
    /// Gradient at the solution.
    pub gradient: Vec<f64>,
    /// Number of iterations taken.
    pub iterations: usize,
    /// Whether the problem converged.
    pub converged: bool,
}

/// Batched GPU L-BFGS optimizer.
///
/// Solves `batch_size` independent problems in parallel. Each problem evaluates
/// its objective function via a user-supplied closure that produces `f64` values
/// from a flat `[batch_size * n]` buffer of points.
pub struct LbfgsGpu;

impl LbfgsGpu {
    /// Create a new batched L-BFGS optimizer for the given device.
    #[must_use]
    pub fn new(_device: Arc<WgpuDevice>) -> Self {
        Self
    }

    /// Run batched L-BFGS optimization.
    ///
    /// # Errors
    ///
    /// Returns [`Err`] if n or `batch_size` is 0, x0 length mismatch, or if the optimization fails.
    ///
    /// `f_batch` evaluates all `batch_size` objective functions in parallel:
    /// given a `[batch_size * n]` flat array of points, returns `[batch_size]`
    /// function values. The closure should be GPU-friendly (e.g. a surrogate
    /// or elementwise shader).
    ///
    /// `x0` is `[batch_size * n]`: initial guesses for each problem.
    pub fn optimize<F>(
        &self,
        f_batch: F,
        x0: &[f64],
        n: usize,
        batch_size: usize,
        config: &LbfgsGpuConfig,
    ) -> Result<Vec<LbfgsGpuResult>>
    where
        F: Fn(&[f64]) -> Vec<f64>,
    {
        if n == 0 || batch_size == 0 {
            return Err(BarracudaError::InvalidInput {
                message: "n and batch_size must be > 0".to_string(),
            });
        }
        if x0.len() != batch_size * n {
            return Err(BarracudaError::InvalidInput {
                message: format!(
                    "x0 length {} != batch_size({}) * n({})",
                    x0.len(),
                    batch_size,
                    n
                ),
            });
        }

        let m = config.memory;
        let eps = config.epsilon;

        let mut x = x0.to_vec();
        let mut f_vals = f_batch(&x);
        let mut grad = numerical_gradient_batch(&f_batch, &x, n, batch_size, eps);

        let mut s_history: Vec<Vec<f64>> = Vec::with_capacity(m);
        let mut y_history: Vec<Vec<f64>> = Vec::with_capacity(m);
        let mut rho_history: Vec<Vec<f64>> = Vec::with_capacity(m);

        let mut converged = vec![false; batch_size];
        let mut iters = vec![0usize; batch_size];

        let mut x_prev = vec![0.0; batch_size * n];
        let mut g_prev = vec![0.0; batch_size * n];

        for iter in 0..config.max_iter {
            // Check convergence per problem
            let mut all_done = true;
            for b in 0..batch_size {
                if converged[b] {
                    continue;
                }
                let g_norm: f64 = (0..n)
                    .map(|j| {
                        let g = grad[b * n + j];
                        g * g
                    })
                    .sum::<f64>()
                    .sqrt();
                if g_norm < config.gtol {
                    converged[b] = true;
                    iters[b] = iter;
                } else {
                    all_done = false;
                }
            }
            if all_done {
                break;
            }

            let direction =
                two_loop_cpu(&grad, &s_history, &y_history, &rho_history, n, batch_size);

            // Backtracking line search (per problem)
            let mut alphas = vec![1.0_f64; batch_size];
            for _ in 0..config.max_linesearch {
                let mut x_trial = vec![0.0; batch_size * n];
                for b in 0..batch_size {
                    if converged[b] {
                        for j in 0..n {
                            x_trial[b * n + j] = x[b * n + j];
                        }
                        continue;
                    }
                    for j in 0..n {
                        x_trial[b * n + j] = alphas[b].mul_add(direction[b * n + j], x[b * n + j]);
                    }
                }
                let f_trial = f_batch(&x_trial);

                let mut any_needs_shrink = false;
                for b in 0..batch_size {
                    if converged[b] {
                        continue;
                    }
                    let dg: f64 = (0..n).map(|j| direction[b * n + j] * grad[b * n + j]).sum();
                    if f_trial[b] <= (config.c1 * alphas[b]).mul_add(dg, f_vals[b]) {
                        // Sufficient decrease — accept
                    } else {
                        alphas[b] *= 0.5;
                        any_needs_shrink = true;
                    }
                }
                if !any_needs_shrink {
                    break;
                }
            }

            x_prev.copy_from_slice(&x);
            g_prev.copy_from_slice(&grad);

            for b in 0..batch_size {
                if converged[b] {
                    continue;
                }
                for j in 0..n {
                    x[b * n + j] = alphas[b].mul_add(direction[b * n + j], x[b * n + j]);
                }
            }

            let f_new = f_batch(&x);

            // Check function value tolerance
            for b in 0..batch_size {
                if converged[b] {
                    continue;
                }
                if (f_vals[b] - f_new[b]).abs() < config.ftol * (1.0 + f_vals[b].abs()) && iter > 0
                {
                    converged[b] = true;
                    iters[b] = iter;
                }
            }

            f_vals = f_new;
            grad = numerical_gradient_batch(&f_batch, &x, n, batch_size, eps);

            // Update L-BFGS history
            let mut s_k = vec![0.0; batch_size * n];
            let mut y_k = vec![0.0; batch_size * n];
            let mut rho_k = vec![0.0; batch_size];
            let mut any_valid = false;

            for (b, rho_k_b) in rho_k.iter_mut().enumerate() {
                let mut sy = 0.0;
                let base = b * n;
                for (((s_k_j, y_k_j), (&x_j, &xp_j)), (&g_j, &gp_j)) in s_k[base..base + n]
                    .iter_mut()
                    .zip(y_k[base..base + n].iter_mut())
                    .zip(x[base..base + n].iter().zip(x_prev[base..base + n].iter()))
                    .zip(
                        grad[base..base + n]
                            .iter()
                            .zip(g_prev[base..base + n].iter()),
                    )
                {
                    *s_k_j = x_j - xp_j;
                    *y_k_j = g_j - gp_j;
                    sy = (*s_k_j).mul_add(*y_k_j, sy);
                }
                if sy > 1e-30 {
                    *rho_k_b = 1.0 / sy;
                    any_valid = true;
                }
            }

            if any_valid {
                if s_history.len() == m {
                    s_history.remove(0);
                    y_history.remove(0);
                    rho_history.remove(0);
                }
                s_history.push(s_k);
                y_history.push(y_k);
                rho_history.push(rho_k);
            }

            for b in 0..batch_size {
                if !converged[b] {
                    iters[b] = iter + 1;
                }
            }
        }

        let results: Vec<LbfgsGpuResult> = (0..batch_size)
            .map(|b| LbfgsGpuResult {
                x: x[b * n..(b + 1) * n].to_vec(),
                f_val: f_vals[b],
                gradient: grad[b * n..(b + 1) * n].to_vec(),
                iterations: iters[b],
                converged: converged[b],
            })
            .collect();

        Ok(results)
    }
}

fn numerical_gradient_batch<F>(f: &F, x: &[f64], n: usize, batch_size: usize, eps: f64) -> Vec<f64>
where
    F: Fn(&[f64]) -> Vec<f64>,
{
    let mut grad = vec![0.0; batch_size * n];

    for j in 0..n {
        let mut x_plus = x.to_vec();
        let mut x_minus = x.to_vec();
        for b in 0..batch_size {
            x_plus[b * n + j] += eps;
            x_minus[b * n + j] -= eps;
        }
        let f_plus = f(&x_plus);
        let f_minus = f(&x_minus);
        for b in 0..batch_size {
            grad[b * n + j] = (f_plus[b] - f_minus[b]) / (2.0 * eps);
        }
    }

    grad
}

fn two_loop_cpu(
    grad: &[f64],
    s_history: &[Vec<f64>],
    y_history: &[Vec<f64>],
    rho_history: &[Vec<f64>],
    n: usize,
    batch_size: usize,
) -> Vec<f64> {
    let k = s_history.len();
    let mut q = grad.to_vec();
    let mut alpha_buf = vec![vec![0.0; batch_size]; k];

    for ii in 0..k {
        let i = k - 1 - ii;
        for b in 0..batch_size {
            let dot: f64 = (0..n).map(|j| s_history[i][b * n + j] * q[b * n + j]).sum();
            let alpha_i = rho_history[i][b] * dot;
            alpha_buf[i][b] = alpha_i;
            for j in 0..n {
                q[b * n + j] = alpha_i.mul_add(-y_history[i][b * n + j], q[b * n + j]);
            }
        }
    }

    if k > 0 {
        let last = k - 1;
        for b in 0..batch_size {
            let sy: f64 = (0..n)
                .map(|j| s_history[last][b * n + j] * y_history[last][b * n + j])
                .sum();
            let yy: f64 = (0..n)
                .map(|j| y_history[last][b * n + j] * y_history[last][b * n + j])
                .sum();
            if yy > 1e-30 {
                let gamma = sy / yy;
                for j in 0..n {
                    q[b * n + j] *= gamma;
                }
            }
        }
    }

    for i in 0..k {
        for b in 0..batch_size {
            let dot: f64 = (0..n).map(|j| y_history[i][b * n + j] * q[b * n + j]).sum();
            let beta = rho_history[i][b] * dot;
            for j in 0..n {
                q[b * n + j] =
                    (alpha_buf[i][b] - beta).mul_add(s_history[i][b * n + j], q[b * n + j]);
            }
        }
    }

    for v in &mut q {
        *v = -*v;
    }
    q
}

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

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

        let optimizer = LbfgsGpu::new(device);

        let n = 2;
        let batch_size = 4;
        let x0: Vec<f64> = vec![
            -1.0, 1.0, // problem 0
            0.0, 0.0, // problem 1
            2.0, -1.0, // problem 2
            -2.0, 2.0, // problem 3
        ];

        let f_batch = |x: &[f64]| -> Vec<f64> {
            (0..batch_size)
                .map(|b| {
                    let x0 = x[b * n];
                    let x1 = x[b * n + 1];
                    (1.0 - x0).mul_add(1.0 - x0, 100.0 * x0.mul_add(-x0, x1).powi(2))
                })
                .collect()
        };

        let config = LbfgsGpuConfig {
            memory: 10,
            max_iter: 500,
            gtol: 1e-6,
            ..Default::default()
        };

        let results = optimizer
            .optimize(f_batch, &x0, n, batch_size, &config)
            .unwrap();

        assert_eq!(results.len(), batch_size);
        for (i, r) in results.iter().enumerate() {
            assert!(
                r.converged,
                "problem {} did not converge (iters={})",
                i, r.iterations
            );
            assert!(
                (r.x[0] - 1.0).abs() < 1e-3,
                "problem {}: x[0]={}, expected 1.0",
                i,
                r.x[0]
            );
            assert!(
                (r.x[1] - 1.0).abs() < 1e-3,
                "problem {}: x[1]={}, expected 1.0",
                i,
                r.x[1]
            );
        }
    }

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

        let optimizer = LbfgsGpu::new(device);

        let n = 5;
        let batch_size = 8;
        let mut x0 = Vec::with_capacity(batch_size * n);
        for b in 0..batch_size {
            for j in 0..n {
                x0.push((b as f64 + 1.0) * (j as f64 + 1.0));
            }
        }

        let f_batch = |x: &[f64]| -> Vec<f64> {
            (0..batch_size)
                .map(|b| (0..n).map(|j| x[b * n + j].powi(2)).sum())
                .collect()
        };

        let results = optimizer
            .optimize(f_batch, &x0, n, batch_size, &LbfgsGpuConfig::default())
            .unwrap();

        for (i, r) in results.iter().enumerate() {
            assert!(
                r.converged,
                "problem {} did not converge (iters={})",
                i, r.iterations
            );
            assert!(r.f_val < 1e-8, "problem {}: f={}", i, r.f_val);
        }
    }
}