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
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Multi-head ESN: shared reservoir with per-head readouts (hotSpring 36-head concept).
//!
//! `HeadKind` provides a domain-agnostic head classification system:
//! - Pre-defined kinds for known physics/bio/steering domains
//! - `Custom(String)` for spring-specific or experimental heads
//!
//! Provenance: hotSpring V0615 (physics), wetSpring V86 (`BioHeadKind`) → generalized

use std::sync::Arc;

use crate::device::WgpuDevice;
use crate::error::{BarracudaError, Result as BarracudaResult};
use crate::linalg::solve_f64_cpu;
use crate::tensor::Tensor;

use super::config::{ESNConfig, validate_config};
use super::model::{ESN, ExportedWeights};

/// Domain-agnostic head classification for multi-head ESN.
///
/// Pre-defined kinds cover common domains across all springs.
/// Use `Custom(String)` for spring-specific or experimental heads.
///
/// # Evolution from `HeadGroup`
/// S79 had 6 fixed physics groups. S83 generalizes to support:
/// - hotSpring physics (Anderson, Qcd, Potts)
/// - wetSpring biology (Diversity, Taxonomy, Amr, Bloom)
/// - airSpring hydrology (Et0, `SoilMoisture`, Irrigation)
/// - Any custom domain via `Custom(String)`
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum HeadKind {
    // Physics (hotSpring)
    Anderson,
    Qcd,
    Potts,
    Steering,
    Brain,
    Meta,
    // Biology (wetSpring BioHeadKind absorption)
    Diversity,
    Taxonomy,
    Amr,
    Bloom,
    Disorder,
    // Hydrology (airSpring)
    Et0,
    SoilMoisture,
    Irrigation,
    // Extensible
    Custom(String),
}

/// Backward-compatible alias.
pub type HeadGroup = HeadKind;

/// Configuration for a head within a group.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct HeadConfig {
    /// Head domain/group.
    pub group: HeadKind,
    /// Human-readable label.
    pub label: String,
    /// Output dimension for this head.
    pub output_size: usize,
}

struct HeadReadout {
    w_out: Option<Tensor>,
    trained: bool,
}

/// Multi-head ESN wrapping a shared reservoir with per-head readout.
pub struct MultiHeadEsn {
    reservoir: ESN,
    heads: Vec<HeadReadout>,
    head_configs: Vec<HeadConfig>,
}

impl MultiHeadEsn {
    /// Create a shared reservoir with per-head readout slots (no readout weights yet).
    /// # Errors
    /// Returns [`Err`] if config validation fails, if heads is empty, if any head
    /// has zero `output_size`, or if ESN creation fails (device, buffer allocation).
    pub async fn new(base_config: ESNConfig, heads: Vec<HeadConfig>) -> BarracudaResult<Self> {
        validate_config(&base_config)?;
        if heads.is_empty() {
            return Err(BarracudaError::InvalidInput {
                message: "At least one head required".to_string(),
            });
        }
        for h in &heads {
            if h.output_size == 0 {
                return Err(BarracudaError::InvalidInput {
                    message: format!("Head '{}' has zero output_size", h.label),
                });
            }
        }

        let reservoir_config = ESNConfig {
            output_size: 1,
            ..base_config.clone()
        };
        let reservoir = ESN::new(reservoir_config).await?;

        let head_readouts = heads
            .iter()
            .map(|_| HeadReadout {
                w_out: None,
                trained: false,
            })
            .collect();

        Ok(Self {
            reservoir,
            heads: head_readouts,
            head_configs: heads,
        })
    }

    /// Reconstruct a multi-head ESN from previously exported weights.
    /// This enables CPU-to-GPU migration and cross-device deployment:
    /// train on one device, serialize via `export_weights()`, then
    /// reconstruct on another device via this constructor.
    /// Provenance: hotSpring V0617 absorption request.
    /// # Errors
    /// Returns [`Err`] if heads is empty, if exported weights have zero `reservoir_size`
    /// or `input_size`, if ESN creation or import fails, or if tensor creation from
    /// weight chunks fails.
    pub async fn from_exported_weights(
        weights: &ExportedWeights,
        heads: Vec<HeadConfig>,
    ) -> BarracudaResult<Self> {
        if heads.is_empty() {
            return Err(BarracudaError::InvalidInput {
                message: "At least one head required".to_string(),
            });
        }
        if weights.reservoir_size == 0 || weights.input_size == 0 {
            return Err(BarracudaError::InvalidInput {
                message: "ExportedWeights must have non-zero reservoir_size and input_size"
                    .to_string(),
            });
        }

        let config = ESNConfig {
            input_size: weights.input_size,
            reservoir_size: weights.reservoir_size,
            output_size: 1,
            spectral_radius: 0.9,
            leak_rate: weights.leak_rate,
            connectivity: 0.1,
            regularization: 1e-6,
            seed: 0,
            ..Default::default()
        };
        let mut reservoir = ESN::new(config).await?;
        reservoir.import_weights(&weights.w_in, &weights.w_res, None)?;

        let device = reservoir.state().device().clone();
        let rs = weights.reservoir_size;

        let mut head_readouts = Vec::with_capacity(heads.len());
        if let Some(ref w_out_flat) = weights.w_out {
            let mut offset = 0;
            for (i, cfg) in heads.iter().enumerate() {
                let chunk_len = rs * cfg.output_size;
                if offset + chunk_len <= w_out_flat.len() {
                    let chunk = &w_out_flat[offset..offset + chunk_len];
                    let w = Tensor::from_data(chunk, vec![rs, cfg.output_size], device.clone())?;
                    head_readouts.push(HeadReadout {
                        w_out: Some(w),
                        trained: true,
                    });
                    offset += chunk_len;
                } else {
                    head_readouts.push(HeadReadout {
                        w_out: None,
                        trained: false,
                    });
                    tracing::warn!(
                        "Head {} ('{}') has no w_out data in exported weights",
                        i,
                        cfg.label
                    );
                }
            }
        } else {
            for _ in &heads {
                head_readouts.push(HeadReadout {
                    w_out: None,
                    trained: false,
                });
            }
        }

        Ok(Self {
            reservoir,
            heads: head_readouts,
            head_configs: heads,
        })
    }

    /// Forward through shared reservoir; returns new state.
    ///
    /// # Errors
    ///
    /// Returns [`Err`] if buffer allocation, GPU dispatch, or buffer
    /// readback fails (e.g. device lost or out of memory).
    pub async fn update(&mut self, input: &Tensor) -> BarracudaResult<Tensor> {
        self.reservoir.update(input).await
    }

    /// Train a single head's readout via ridge regression.
    /// # Errors
    /// Returns [`Err`] if head index is out of range, states are empty, states
    /// length is not divisible by `reservoir_size`, targets length does not match
    /// `output_size * n_samples`, lambda is not positive, the CPU matrix solve
    /// fails, or tensor creation fails.
    pub fn train_head(
        &mut self,
        head_idx: usize,
        states: &[f64],
        targets: &[f64],
        lambda: f64,
    ) -> BarracudaResult<()> {
        let Some(cfg) = self.head_configs.get(head_idx) else {
            return Err(BarracudaError::InvalidInput {
                message: format!("Head index {head_idx} out of range"),
            });
        };
        let n = self.reservoir.config().reservoir_size;
        let m = cfg.output_size;

        if states.is_empty() {
            return Err(BarracudaError::InvalidInput {
                message: "States cannot be empty".to_string(),
            });
        }
        if !states.len().is_multiple_of(n) {
            return Err(BarracudaError::InvalidInput {
                message: format!(
                    "States length {} must be divisible by reservoir_size {}",
                    states.len(),
                    n
                ),
            });
        }
        let n_samples = states.len() / n;
        if targets.len() != m * n_samples {
            return Err(BarracudaError::InvalidInput {
                message: format!(
                    "Targets length {} expected {}",
                    targets.len(),
                    m * n_samples
                ),
            });
        }
        if lambda <= 0.0 {
            return Err(BarracudaError::InvalidInput {
                message: "Lambda must be positive".to_string(),
            });
        }

        let x = states;
        let y = targets;

        let mut m_mat = vec![0.0; n * n];
        for i in 0..n {
            for j in 0..n {
                let mut sum = 0.0;
                for k in 0..n_samples {
                    sum = x[i * n_samples + k].mul_add(x[j * n_samples + k], sum);
                }
                m_mat[i * n + j] = sum;
            }
            m_mat[i * n + i] += lambda;
        }

        let mut b_mat = vec![0.0; n * m];
        for i in 0..n {
            for j in 0..m {
                let mut sum = 0.0;
                for k in 0..n_samples {
                    sum = x[i * n_samples + k].mul_add(y[j * n_samples + k], sum);
                }
                b_mat[i * m + j] = sum;
            }
        }

        let mut w_out_t = vec![0.0; n * m];
        for j in 0..m {
            let b_col: Vec<f64> = (0..n).map(|i| b_mat[i * m + j]).collect();
            let w_col = solve_f64_cpu(&m_mat, &b_col, n)?;
            for (i, &w) in w_col.iter().enumerate() {
                w_out_t[i * m + j] = w;
            }
        }

        let device = self.reservoir.state().device().clone();
        let w_out_f32: Vec<f32> = w_out_t.iter().map(|&x| x as f32).collect();
        let w_out = Tensor::from_data(&w_out_f32, vec![n, m], device)?;

        let head = &mut self.heads[head_idx];
        head.w_out = Some(w_out);
        head.trained = true;

        Ok(())
    }

    /// Predict from a single head given reservoir state.
    /// # Errors
    /// Returns [`Err`] if head index is out of range, if the head is not trained,
    /// or if transpose/matmul operations fail (e.g. shape mismatch).
    pub fn predict_head(&self, head_idx: usize, state: &Tensor) -> BarracudaResult<Tensor> {
        let head = self
            .heads
            .get(head_idx)
            .ok_or_else(|| BarracudaError::InvalidInput {
                message: format!("Head index {head_idx} out of range"),
            })?;
        let w_out = head
            .w_out
            .as_ref()
            .ok_or_else(|| BarracudaError::InvalidOperation {
                op: "MultiHeadEsn::predict_head".to_string(),
                reason: format!("Head {head_idx} not trained"),
            })?;
        w_out.transpose()?.matmul(state)
    }

    /// Predict from all trained heads.
    /// # Errors
    /// Returns [`Err`] if any trained head's `predict_head` fails (shape mismatch,
    /// device error).
    pub fn predict_all(&self, state: &Tensor) -> BarracudaResult<Vec<Tensor>> {
        let mut out = Vec::with_capacity(self.heads.len());
        for (i, head) in self.heads.iter().enumerate() {
            if head.trained {
                out.push(self.predict_head(i, state)?);
            }
        }
        Ok(out)
    }

    /// Mean pairwise L2 distance between head predictions (uncertainty signal).
    /// # Errors
    /// Returns [`Err`] if any trained head's `predict_head` or `to_vec` fails.
    pub fn head_disagreement(&self, state: &Tensor) -> BarracudaResult<f64> {
        let preds: Vec<Vec<f32>> = (0..self.heads.len())
            .filter(|&i| self.heads[i].trained)
            .map(|i| self.predict_head(i, state).and_then(|t| t.to_vec()))
            .collect::<BarracudaResult<Vec<_>>>()?;

        if preds.len() < 2 {
            return Ok(0.0);
        }

        let mut total = 0.0;
        let mut count = 0usize;
        for (i, a) in preds.iter().enumerate() {
            for b in &preds[i + 1..] {
                let len = a.len().min(b.len());
                let d2: f64 = (0..len)
                    .map(|k| {
                        let diff = a[k] as f64 - b[k] as f64;
                        diff * diff
                    })
                    .sum();
                total += d2.sqrt();
                count += 1;
            }
        }
        Ok(if count > 0 { total / count as f64 } else { 0.0 })
    }

    /// Direct access to the underlying `WgpuDevice` (delegates to reservoir).
    ///
    /// Springs that build custom GPU pipelines on top of a multi-head ESN
    /// need the device handle for buffer allocation and dispatch.
    #[must_use]
    pub fn wgpu_device(&self) -> &Arc<WgpuDevice> {
        self.reservoir.wgpu_device()
    }

    /// Export weights with `head_labels` populated.
    /// # Errors
    /// Returns [`Err`] if reservoir export fails, or if reading any head's
    /// readout weights to host fails.
    pub fn export_weights(&self) -> BarracudaResult<ExportedWeights> {
        let mut base = self.reservoir.export_weights()?;

        let mut all_w_out = Vec::new();
        let mut head_labels = Vec::new();
        let mut total_output_size = 0usize;

        for (i, head) in self.heads.iter().enumerate() {
            if let Some(ref w) = head.w_out {
                let data = w.to_vec()?;
                all_w_out.extend(data);
                total_output_size += self.head_configs[i].output_size;
                head_labels.push(self.head_configs[i].label.clone());
            }
        }

        base.w_out = if all_w_out.is_empty() {
            None
        } else {
            Some(all_w_out)
        };
        base.output_size = total_output_size;
        base.head_labels = head_labels;

        Ok(base)
    }
}