zuna-rs 0.0.4

ZUNA EEG Foundation Model — inference in Rust with Burn ML
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
//! [`ZunaInference<B>`] — single entry point for the ZUNA EEG model.
//!
//! This is the **only** place that ties together:
//! - model architecture (`model/`)
//! - pretrained weights (`weights.rs`)
//! - preprocessing config (`config.rs`)
//! - input loading (`data.rs`)
//!
//! The binary (`bin/infer.rs`) and any downstream code use only this API.
//!
//! # Quick start
//! ```rust,ignore
//! let (zuna, ms_load) = ZunaInference::<B>::load(
//!     Path::new("config.json"),
//!     Path::new("model.safetensors"),
//!     device,
//! )?;
//! let result = zuna.run_fif(Path::new("recording.fif"), steps, cfg, data_norm)?;
//! result.save_safetensors("output.safetensors")?;
//! ```

use std::{path::Path, time::Instant};

use anyhow::Context;
use burn::prelude::*;

use crate::{
    config::{DataConfig, ModelConfig},
    data::{load_batch, load_from_fif, invert_reshape, FifInfo, InputBatch},
    encoder::{EncodingResult, EpochEmbedding},
    model::{encoder_decoder::EncoderDecoder, rope::RotaryEmbedding},
    weights::load_model,
};

// ── Output types ──────────────────────────────────────────────────────────────

/// Reconstructed output for one 5-second epoch.
pub struct EpochOutput {
    /// Signal: `[n_channels, n_timesteps]` row-major f32.
    pub reconstructed: Vec<f32>,
    /// Shape: `[n_channels, n_timesteps]`.
    pub shape: Vec<usize>,
    /// Electrode positions: `[n_channels, 3]` row-major f32.
    pub chan_pos: Vec<f32>,
    /// Number of EEG channels.
    pub n_channels: usize,
}

/// Result returned by [`ZunaInference::run_fif`] or [`ZunaInference::run_safetensors_batch`].
pub struct InferenceResult {
    /// One entry per 5-second epoch.
    pub epochs: Vec<EpochOutput>,
    /// Metadata from the FIF file; `None` for safetensors batch input.
    pub fif_info: Option<FifInfo>,
    /// Preprocessing time (ms).
    pub ms_preproc: f64,
    /// Model inference time, all epochs combined (ms).
    pub ms_infer: f64,
}

impl InferenceResult {
    /// Write to a safetensors file.
    ///
    /// Keys:
    /// - `reconstructed_N` — `[C, T]` float32
    /// - `chan_pos_N`       — `[C, 3]` float32
    /// - `n_samples`        — scalar float32 = number of epochs
    pub fn save_safetensors(&self, path: &str) -> anyhow::Result<()> {
        use safetensors::{Dtype, View};
        use std::borrow::Cow;

        struct F32Tensor { data: Vec<u8>, shape: Vec<usize> }
        impl View for F32Tensor {
            fn dtype(&self)    -> Dtype          { Dtype::F32 }
            fn shape(&self)    -> &[usize]        { &self.shape }
            fn data(&self)     -> Cow<'_, [u8]>   { Cow::Borrowed(&self.data) }
            fn data_len(&self) -> usize            { self.data.len() }
        }
        fn to_bytes(v: &[f32]) -> Vec<u8> {
            v.iter().flat_map(|f| f.to_le_bytes()).collect()
        }

        // Collect owned strings + owned tensors side-by-side.
        let mut keys:    Vec<String>    = Vec::new();
        let mut tensors: Vec<F32Tensor> = Vec::new();

        for (i, ep) in self.epochs.iter().enumerate() {
            keys.push(format!("reconstructed_{i}"));
            tensors.push(F32Tensor { data: to_bytes(&ep.reconstructed), shape: ep.shape.clone() });
            keys.push(format!("chan_pos_{i}"));
            tensors.push(F32Tensor { data: to_bytes(&ep.chan_pos), shape: vec![ep.n_channels, 3] });
        }
        let n = self.epochs.len() as f32;
        keys.push("n_samples".into());
        tensors.push(F32Tensor { data: to_bytes(&[n]), shape: vec![1] });

        // safetensors::serialize wants (&str, impl View) — we give it (&str, F32Tensor).
        let pairs: Vec<(&str, F32Tensor)> =
            keys.iter().map(|s| s.as_str()).zip(tensors).collect();
        let bytes = safetensors::serialize(pairs, None)?;
        std::fs::write(path, bytes)?;
        Ok(())
    }
}

// ── ZunaInference ─────────────────────────────────────────────────────────────

/// ZUNA EEG Foundation Model — inference entry point.
///
/// Encapsulates architecture, weights, RoPE embeddings, and configs.
/// One instance per device; reuse across multiple recordings.
///
/// # Backend
/// Choose at compile time:
/// - CPU: `--features ndarray`  (default; + `blas-accelerate` on macOS)
/// - GPU: `--no-default-features --features wgpu`
pub struct ZunaInference<B: Backend> {
    model:     EncoderDecoder<B>,
    rope:      RotaryEmbedding<B>,
    /// Architecture hyperparameters.
    pub model_cfg: ModelConfig,
    /// Preprocessing / tokenisation parameters.
    pub data_cfg:  DataConfig,
    device:    B::Device,
}

impl<B: Backend> ZunaInference<B> {
    // ── Constructor ───────────────────────────────────────────────────────────

    /// Load model from a HuggingFace `config.json` and `model.safetensors`.
    ///
    /// Returns `(model, weight_load_ms)`.
    pub fn load(
        config_path:  &Path,
        weights_path: &Path,
        device:       B::Device,
    ) -> anyhow::Result<(Self, f64)> {
        // 1. Parse config
        let cfg_str = std::fs::read_to_string(config_path)
            .with_context(|| format!("config: {}", config_path.display()))?;
        let hf_val: serde_json::Value = serde_json::from_str(&cfg_str)?;
        let model_cfg: ModelConfig = serde_json::from_value(hf_val["model"].clone())
            .context("parsing model config")?;

        // 2. Rotary positional embeddings (shared, precomputed once)
        let rope = RotaryEmbedding::<B>::new(
            model_cfg.head_dim,
            model_cfg.rope_dim,
            model_cfg.max_seqlen,
            model_cfg.rope_theta,
            &device,
        );

        // 3. Load weights
        let t = Instant::now();
        let model = load_model::<B>(
            &model_cfg,
            weights_path.to_str().context("weights path not valid UTF-8")?,
            &device,
        )?;
        let ms_weights = t.elapsed().as_secs_f64() * 1000.0;

        Ok((Self { model, rope, model_cfg, data_cfg: DataConfig::default(), device }, ms_weights))
    }

    // ── Accessors ─────────────────────────────────────────────────────────────

    /// One-line description of the loaded model.
    pub fn describe(&self) -> String {
        let c = &self.model_cfg;
        // n_heads is inferred from weights (actual); approximation here is dim/head_dim
        format!(
            "ZUNA  dim={}  layers={}  head_dim={}  ffn_hidden={}  \
             rope_dim={}  max_seqlen={}",
            c.dim, c.n_layers, c.head_dim, c.ffn_hidden_dim(), c.rope_dim, c.max_seqlen,
        )
    }

    // ── Inference from a raw FIF recording ────────────────────────────────────

    /// Full pure-Rust pipeline: `.fif` → exg → ZUNA model.
    ///
    /// # Arguments
    /// - `steps`     — diffusion denoising steps (50 → full quality; 10 → fast preview)
    /// - `cfg`       — classifier-free guidance scale (1.0 = disabled)
    /// - `data_norm` — divisor applied to z-scored signal before entering model;
    ///                 same value is multiplied back into the output
    pub fn run_fif(
        &self,
        fif_path:  &Path,
        steps:     usize,
        cfg:       f32,
        data_norm: f32,
    ) -> anyhow::Result<InferenceResult> {
        let t_pp = Instant::now();
        let (batches, fif_info) = load_from_fif::<B>(
            fif_path, &self.data_cfg, data_norm, &self.device,
        ).with_context(|| format!("exg on {}", fif_path.display()))?;
        let ms_preproc = t_pp.elapsed().as_secs_f64() * 1000.0;

        let t_inf = Instant::now();
        let epochs = self.run_batches(batches, steps, cfg, data_norm)?;
        let ms_infer = t_inf.elapsed().as_secs_f64() * 1000.0;

        Ok(InferenceResult { epochs, fif_info: Some(fif_info), ms_preproc, ms_infer })
    }

    /// Input from a pre-processed safetensors batch (Python / legacy path).
    pub fn run_safetensors_batch(
        &self,
        batch_path: &Path,
        steps:      usize,
        cfg:        f32,
        data_norm:  f32,
    ) -> anyhow::Result<InferenceResult> {
        let t_pp = Instant::now();
        let batches = load_batch::<B>(
            batch_path.to_str().context("batch path not valid UTF-8")?,
            &self.data_cfg,
            &self.device,
        )?;
        let ms_preproc = t_pp.elapsed().as_secs_f64() * 1000.0;

        let t_inf = Instant::now();
        let epochs = self.run_batches(batches, steps, cfg, data_norm)?;
        let ms_infer = t_inf.elapsed().as_secs_f64() * 1000.0;

        Ok(InferenceResult { epochs, fif_info: None, ms_preproc, ms_infer })
    }

    // ── Encode-only convenience methods ───────────────────────────────────────

    /// Preprocess a `.fif` recording and encode it into latent embeddings,
    /// **without** running the decoder.
    ///
    /// Equivalent to [`crate::encoder::ZunaEncoder::encode_fif`] but uses the
    /// encoder that is already loaded as part of the full model — no extra
    /// weight loading required.
    pub fn encode_fif(
        &self,
        fif_path:  &Path,
        data_norm: f32,
    ) -> anyhow::Result<EncodingResult> {
        let t_pp = Instant::now();
        let (batches, fif_info) = load_from_fif::<B>(
            fif_path, &self.data_cfg, data_norm, &self.device,
        ).with_context(|| format!("exg on {}", fif_path.display()))?;
        let ms_preproc = t_pp.elapsed().as_secs_f64() * 1000.0;

        let t_enc = Instant::now();
        let epochs = self.encode_inputs(batches)?;
        let ms_encode = t_enc.elapsed().as_secs_f64() * 1000.0;

        Ok(EncodingResult { epochs, fif_info: Some(fif_info), ms_preproc, ms_encode })
    }

    /// Encode a pre-processed safetensors batch into latent embeddings,
    /// **without** running the decoder.
    pub fn encode_batch(
        &self,
        batch_path: &Path,
    ) -> anyhow::Result<EncodingResult> {
        let t_pp = Instant::now();
        let batches = load_batch::<B>(
            batch_path.to_str().context("batch path not valid UTF-8")?,
            &self.data_cfg,
            &self.device,
        )?;
        let ms_preproc = t_pp.elapsed().as_secs_f64() * 1000.0;

        let t_enc = Instant::now();
        let epochs = self.encode_inputs(batches)?;
        let ms_encode = t_enc.elapsed().as_secs_f64() * 1000.0;

        Ok(EncodingResult { epochs, fif_info: None, ms_preproc, ms_encode })
    }

    fn encode_inputs(
        &self,
        batches: Vec<InputBatch<B>>,
    ) -> anyhow::Result<Vec<EpochEmbedding>> {
        batches.into_iter().map(|batch| {
            let n_channels    = batch.n_channels;
            let tc            = batch.tc;
            let tok_idx_saved = batch.tok_idx.clone();
            let chan_pos_saved = batch.chan_pos.clone();

            // Encoder forward: [1, S, output_dim]
            let enc_out = self.model.encoder.forward(
                batch.encoder_input,
                batch.tok_idx,
                &self.rope,
            );
            let [_, s, output_dim] = enc_out.dims();

            let embeddings = enc_out
                .squeeze::<2>()
                .into_data()
                .to_vec::<f32>()
                .map_err(|e| anyhow::anyhow!("embedding→vec: {e:?}"))?;

            // NdArray backend stores Int as i64; wgpu backend stores Int as i32.
            let tok_idx_data = tok_idx_saved.into_data();
            let tok_idx: Vec<i64> = tok_idx_data
                .to_vec::<i64>()
                .or_else(|_| tok_idx_data.to_vec::<i32>()
                    .map(|v| v.into_iter().map(|x| x as i64).collect()))
                .map_err(|e| anyhow::anyhow!("tok_idx→vec: {e:?}"))?;

            let chan_pos = chan_pos_saved
                .into_data()
                .to_vec::<f32>()
                .map_err(|e| anyhow::anyhow!("chan_pos→vec: {e:?}"))?;

            Ok(EpochEmbedding {
                embeddings,
                shape: vec![s, output_dim],
                tok_idx,
                chan_pos,
                n_channels,
                tc,
            })
        }).collect()
    }

    // ── Decode from pre-computed embeddings ──────────────────────────────────

    /// Decode [`EncodingResult`] through the decoder diffusion loop.
    ///
    /// Lets you run encode and decode as separate timed steps.
    /// Each epoch is decoded independently; returned `ms_infer` covers all epochs.
    pub fn decode_embeddings(
        &self,
        embeddings: &EncodingResult,
        steps:      usize,
        cfg:        f32,
        data_norm:  f32,
    ) -> anyhow::Result<InferenceResult> {
        let t = Instant::now();
        let epochs = embeddings.epochs
            .iter()
            .map(|ep| self.decode_epoch(ep, steps, cfg, data_norm))
            .collect::<anyhow::Result<Vec<_>>>()?;
        let ms_infer = t.elapsed().as_secs_f64() * 1000.0;
        Ok(InferenceResult { epochs, fif_info: None, ms_preproc: 0.0, ms_infer })
    }

    /// Decode a **single** [`EpochEmbedding`] through the decoder diffusion loop.
    ///
    /// Use this to time each epoch individually.
    pub fn decode_epoch(
        &self,
        ep:        &EpochEmbedding,
        steps:     usize,
        cfg:       f32,
        data_norm: f32,
    ) -> anyhow::Result<EpochOutput> {
        use burn::tensor::Distribution;

        let n_tokens = ep.n_tokens();
        let dc       = &self.data_cfg;

        // Reconstruct encoder conditioning from stored Vec<f32>.
        let enc_out = Tensor::<B, 2>::from_data(
            TensorData::new(ep.embeddings.clone(), ep.shape.clone()),
            &self.device,
        )
        .unsqueeze_dim::<3>(0); // [1, S, output_dim]

        let tok_idx = Tensor::<B, 2, Int>::from_data(
            TensorData::new(ep.tok_idx.clone(), vec![n_tokens, 4]),
            &self.device,
        );

        let [b, s, d] = enc_out.dims();
        let dt = 1.0_f32 / steps as f32;

        // Initial noise z ~ N(0, σ²)
        let mut z = Tensor::<B, 3>::random(
            [b, s, d],
            Distribution::Normal(0.0, self.model.global_sigma as f64),
            &self.device,
        );

        // Rectified-flow Euler diffusion loop
        for i in (1..=steps).rev() {
            let t_val  = dt * i as f32;
            let time_t = Tensor::<B, 3>::full([b, 1, 1], t_val, &self.device);

            let vc = self.model.decoder.forward(
                z.clone(), enc_out.clone(), time_t.clone(), tok_idx.clone(), &self.rope,
            );
            let vc = if (cfg - 1.0).abs() > 1e-4 {
                let enc_zeros = Tensor::zeros([b, s, d], &self.device);
                let vc_u = self.model.decoder.forward(
                    z.clone(), enc_zeros, time_t, tok_idx.clone(), &self.rope,
                );
                vc_u.clone() + (vc - vc_u).mul_scalar(cfg)
            } else {
                vc
            };
            z = z - vc.mul_scalar(dt);
        }

        let [_, s, tf] = z.dims();
        let recon = invert_reshape(
            z.reshape([s, tf]), ep.n_channels, ep.tc, dc.num_fine_time_pts,
        );
        let recon = recon.mul_scalar(data_norm);
        let shape         = recon.dims().to_vec();
        let reconstructed = recon.into_data().to_vec::<f32>()
            .map_err(|e| anyhow::anyhow!("recon→vec: {e:?}"))?;
        Ok(EpochOutput { reconstructed, shape, chan_pos: ep.chan_pos.clone(), n_channels: ep.n_channels })
    }

    // ── Internal ──────────────────────────────────────────────────────────────

    fn run_batches(
        &self,
        batches:   Vec<InputBatch<B>>,
        steps:     usize,
        cfg:       f32,
        data_norm: f32,
    ) -> anyhow::Result<Vec<EpochOutput>> {
        let dc = &self.data_cfg;
        batches.into_iter().map(|batch| {
            let z = self.model.sample(
                batch.encoder_input,
                batch.tok_idx,
                &self.rope,
                steps,
                cfg,
            );
            let [_, s, tf] = z.dims();
            let z     = z.reshape([s, tf]);
            let recon = invert_reshape(z, batch.n_channels, batch.tc, dc.num_fine_time_pts);
            let recon = recon.mul_scalar(data_norm);

            let shape         = recon.dims().to_vec();
            let reconstructed = recon.into_data().to_vec::<f32>()
                .map_err(|e| anyhow::anyhow!("tensor→vec: {e:?}"))?;
            let chan_pos = batch.chan_pos.into_data().to_vec::<f32>()
                .map_err(|e| anyhow::anyhow!("chan_pos→vec: {e:?}"))?;

            Ok(EpochOutput { reconstructed, shape, chan_pos, n_channels: batch.n_channels })
        }).collect()
    }
}