Skip to main content

quilt_jepa/
lib.rs

1//! quilt-jepa — the JEPA primitive of a Quilt cell.
2//! 
3//! JEPA = Joint Embedding Predictive Architecture.
4//! Predict the next state. Observe the actual. Surprise = ||predicted - actual||^2.
5
6use serde::{Deserialize, Serialize};
7use std::collections::HashMap;
8
9#[derive(Debug, Clone, Default, Serialize, Deserialize)]
10pub struct Jepa {
11    pub history: Vec<f64>,
12}
13
14impl Jepa {
15    pub fn new() -> Self { Self::default() }
16    pub fn predict(&self, state: &HashMap<String, f64>) -> HashMap<String, f64> {
17        state.clone()  // identity prediction by default
18    }
19    pub fn observe(&mut self, predicted: &HashMap<String, f64>, actual: &HashMap<String, f64>) -> f64 {
20        let mut surprise = 0.0;
21        let mut all_keys: Vec<&String> = predicted.keys().collect();
22        for k in actual.keys() {
23            if !all_keys.contains(&k) { all_keys.push(k); }
24        }
25        for k in all_keys {
26            let p = predicted.get(k).copied().unwrap_or(0.0);
27            let a = actual.get(k).copied().unwrap_or(0.0);
28            surprise += (p - a).powi(2);
29        }
30        surprise = surprise.sqrt();
31        self.history.push(surprise);
32        surprise
33    }
34    pub fn mean_surprise(&self) -> f64 {
35        if self.history.is_empty() { return 0.0; }
36        self.history.iter().sum::<f64>() / self.history.len() as f64
37    }
38    pub fn total_surprise(&self) -> f64 {
39        self.history.iter().sum()
40    }
41}
42
43#[cfg(test)]
44mod tests {
45    use super::*;
46    #[test]
47    fn test_jepa_identity() {
48        let mut j = Jepa::new();
49        let state: HashMap<String, f64> = [("x".to_string(), 1.0)].iter().cloned().collect();
50        let s = j.observe(&state, &state);
51        assert_eq!(s, 0.0);
52    }
53    #[test]
54    fn test_jepa_surprise() {
55        let mut j = Jepa::new();
56        let p: HashMap<String, f64> = [("x".to_string(), 1.0)].iter().cloned().collect();
57        let a: HashMap<String, f64> = [("x".to_string(), 4.0)].iter().cloned().collect();
58        let s = j.observe(&p, &a);
59        assert_eq!(s, 3.0);  // sqrt((1-4)^2) = 3
60    }
61}