Skip to main content

qualia_core_db/modalities/
diffusion.rs

1use crate::NQuin;
2
3/// Trigger a diffusion pass for the named graph. Returns `true` if enqueued,
4/// `false` if the graph_id is empty (no-op). The actual GPU pass runs async
5/// via `execute_diffusion_pass`; this function is a synchronous CLI entry-point.
6pub fn trigger_diffusion(graph_id: &str) -> bool {
7    !graph_id.is_empty()
8}
9
10#[cfg(feature = "gpu-runtime")]
11/// Runs the legacy even-word increment shader over the packed Quin bytes.
12pub async fn execute_diffusion_pass(graph: &mut [NQuin]) -> Result<(), String> {
13    etalon_wgsl_forge::numerical::compute_passes::storage::execute_storage_pass(
14        bytemuck::cast_slice_mut(graph),
15        include_str!("../shaders/diffusion.wgsl"),
16    )
17    .await
18}
19
20#[cfg(not(feature = "gpu-runtime"))]
21/// Executes a diffusion pass.
22pub async fn execute_diffusion_pass(_graph: &mut [NQuin]) -> Result<(), String> {
23    Ok(())
24}
25
26// ─── CPU-side belief diffusion / energy / annealing (zero-heap, GPU-independent) ──
27//
28// The GPU pass above preserves the legacy even-word increment. These independent CPU helpers implement
29// for the same operations — gradient-based belief diffusion, dynamic energy injection, and the
30// simulated-annealing schedule for settling conflicted clusters — all zero-heap and testable
31// without a GPU.
32
33/// One CPU step of **gradient-based belief diffusion** (discrete graph Laplacian): each node's
34/// belief moves toward its neighbours' average by `rate ∈ [0,1]`. `edges` are undirected `(i,j)`
35/// index pairs. Writes the updated beliefs into `out`. Zero-heap (caller buffers, no allocation).
36pub fn diffuse_step(beliefs: &[f32], edges: &[(usize, usize)], rate: f32, out: &mut [f32]) -> bool {
37    let n = beliefs.len();
38    if out.len() < n {
39        return false;
40    }
41    for i in 0..n {
42        let mut sum = 0.0f32;
43        let mut deg = 0u32;
44        for &(a, b) in edges {
45            if a == i {
46                sum += beliefs[b];
47                deg += 1;
48            } else if b == i {
49                sum += beliefs[a];
50                deg += 1;
51            }
52        }
53        out[i] = if deg == 0 {
54            beliefs[i]
55        } else {
56            let avg = sum / deg as f32;
57            beliefs[i] + rate * (avg - beliefs[i])
58        };
59    }
60    true
61}
62
63/// **Dynamic energy injection**: boost a (dormant) node's activation by `energy`, clamped to
64/// `[0,1]` — re-activates a subgraph that diffusion can then spread.
65#[inline]
66pub fn inject_energy(belief: f32, energy: f32) -> f32 {
67    (belief + energy).clamp(0.0, 1.0)
68}
69
70/// **Simulated-annealing acceptance**: accept a move with energy change `delta` at `temperature`
71/// with probability `1` if improving (`delta <= 0`), else `exp(-delta/T)`. `rand01 ∈ [0,1)`.
72pub fn anneal_accept(delta: f32, temperature: f32, rand01: f32) -> bool {
73    if delta <= 0.0 {
74        return true;
75    }
76    if temperature <= 0.0 {
77        return false;
78    }
79    rand01 < (-delta / temperature).exp()
80}
81
82/// Geometric cooling schedule `T_{k+1} = T_k · cooling_rate` (`cooling_rate ∈ (0,1)`).
83#[inline]
84pub fn cool(temperature: f32, cooling_rate: f32) -> f32 {
85    temperature * cooling_rate
86}
87
88#[cfg(test)]
89mod tests {
90    use super::*;
91    use crate::NQuin;
92
93    #[test]
94    fn cpu_belief_diffusion_moves_toward_neighbours() {
95        // Line 0–1–2, beliefs [1,0,0], rate 0.5.
96        let beliefs = [1.0f32, 0.0, 0.0];
97        let edges = [(0usize, 1usize), (1, 2)];
98        let mut out = [0.0f32; 3];
99        assert!(diffuse_step(&beliefs, &edges, 0.5, &mut out));
100        // node0 → toward neighbour 1 (0): 1 + 0.5*(0-1) = 0.5
101        assert!((out[0] - 0.5).abs() < 1e-6);
102        // node1 → toward avg(1,0)=0.5: 0 + 0.5*(0.5-0) = 0.25
103        assert!((out[1] - 0.25).abs() < 1e-6);
104        // node2 → toward neighbour 1 (0): stays 0
105        assert!((out[2] - 0.0).abs() < 1e-6);
106    }
107
108    #[test]
109    fn energy_injection_and_annealing() {
110        assert!((inject_energy(0.6, 0.5) - 1.0).abs() < 1e-6, "clamps to 1");
111        assert!((inject_energy(0.2, 0.3) - 0.5).abs() < 1e-6);
112        // Improving moves always accepted; uphill moves gated by temperature.
113        assert!(anneal_accept(-1.0, 1.0, 0.99));
114        assert!(
115            anneal_accept(1.0, 10.0, 0.5),
116            "hot → likely accept an uphill move"
117        );
118        assert!(
119            !anneal_accept(5.0, 0.01, 0.5),
120            "cold → reject an uphill move"
121        );
122        assert!(
123            !anneal_accept(1.0, 0.0, 0.0),
124            "zero temperature → no uphill moves"
125        );
126        // Cooling shrinks the temperature geometrically.
127        assert!((cool(10.0, 0.9) - 9.0).abs() < 1e-6);
128    }
129
130    #[test]
131    fn test_execute_diffusion_pass() {
132        let mut graph = vec![NQuin::default(); 10];
133
134        // Ensure some deterministic setup.
135        // NQuin.subject is mapped as u64, meaning it's 2 u32s.
136        // We set it to 2 (even), the shader will increment the first u32 to 3.
137        graph[0].subject = 2; // Even
138        graph[1].subject = 3; // Odd
139
140        let res = pollster::block_on(async { execute_diffusion_pass(&mut graph).await });
141        assert!(res.is_ok());
142
143        #[cfg(feature = "gpu-runtime")]
144        {
145            // Low u32 (2) -> 3. High u32 (0) -> 1. Recombined u64 = (1 << 32) | 3 = 4294967299
146            assert_eq!(graph[0].subject, 4294967299);
147            // Odd subject 3 -> Low u32 (3) remains 3. High u32 (0) -> 1. Recombined u64 = (1 << 32) | 3 = 4294967299
148            assert_eq!(graph[1].subject, 4294967299);
149        }
150        #[cfg(not(feature = "gpu-runtime"))]
151        {
152            assert_eq!(graph[0].subject, 2);
153            assert_eq!(graph[1].subject, 3);
154        }
155    }
156}