prime-radiant 0.1.0

Universal coherence engine using sheaf Laplacian mathematics for AI safety, hallucination detection, and structural consistency verification in LLMs and distributed systems
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
//! GPU Coherence Engine Tests
//!
//! Comprehensive tests verifying GPU computation results match CPU results
//! within floating-point tolerance. These tests ensure correctness of:
//!
//! - GPU buffer management and data transfer
//! - Parallel residual computation
//! - Energy aggregation with tree reduction
//! - CPU fallback mechanism
//!
//! Run with: cargo test --features gpu

#![cfg(feature = "gpu")]

use prime_radiant::gpu::{
    GpuCoherenceEngine, GpuConfig, GpuBuffer, GpuParams, GpuEdge, GpuRestrictionMap,
    BufferUsage, GpuBufferManager, GpuResult, GpuError,
};
use prime_radiant::substrate::{
    SheafGraph, SheafNode, SheafEdge, SheafNodeBuilder, SheafEdgeBuilder,
    NodeId, EdgeId,
};
use std::collections::HashMap;
use uuid::Uuid;

/// Floating point tolerance for GPU vs CPU comparison
const TOLERANCE: f32 = 1e-5;

/// Create a simple test graph with 3 nodes forming a triangle
fn create_triangle_graph() -> SheafGraph {
    let graph = SheafGraph::new();

    // Create three nodes with states
    let node1 = SheafNodeBuilder::new()
        .state_from_slice(&[1.0, 0.0, 0.0])
        .namespace("test")
        .build();
    let node2 = SheafNodeBuilder::new()
        .state_from_slice(&[0.0, 1.0, 0.0])
        .namespace("test")
        .build();
    let node3 = SheafNodeBuilder::new()
        .state_from_slice(&[0.0, 0.0, 1.0])
        .namespace("test")
        .build();

    let id1 = graph.add_node(node1);
    let id2 = graph.add_node(node2);
    let id3 = graph.add_node(node3);

    // Create edges with identity restrictions
    let edge12 = SheafEdgeBuilder::new(id1, id2)
        .identity_restrictions(3)
        .weight(1.0)
        .namespace("test")
        .build();
    let edge23 = SheafEdgeBuilder::new(id2, id3)
        .identity_restrictions(3)
        .weight(1.0)
        .namespace("test")
        .build();
    let edge31 = SheafEdgeBuilder::new(id3, id1)
        .identity_restrictions(3)
        .weight(1.0)
        .namespace("test")
        .build();

    graph.add_edge(edge12).unwrap();
    graph.add_edge(edge23).unwrap();
    graph.add_edge(edge31).unwrap();

    graph
}

/// Create a coherent graph where all nodes have identical states
fn create_coherent_graph() -> SheafGraph {
    let graph = SheafGraph::new();

    // All nodes have the same state
    let state = [1.0, 1.0, 1.0];

    let node1 = SheafNodeBuilder::new()
        .state_from_slice(&state)
        .build();
    let node2 = SheafNodeBuilder::new()
        .state_from_slice(&state)
        .build();

    let id1 = graph.add_node(node1);
    let id2 = graph.add_node(node2);

    let edge = SheafEdgeBuilder::new(id1, id2)
        .identity_restrictions(3)
        .weight(1.0)
        .build();

    graph.add_edge(edge).unwrap();
    graph
}

/// Create a larger graph for performance testing
fn create_large_graph(num_nodes: usize, edges_per_node: usize) -> SheafGraph {
    let graph = SheafGraph::new();
    let state_dim = 64;

    // Create nodes with random states
    let mut node_ids = Vec::with_capacity(num_nodes);
    for i in 0..num_nodes {
        let state: Vec<f32> = (0..state_dim)
            .map(|j| ((i * state_dim + j) as f32 * 0.01).sin())
            .collect();

        let node = SheafNodeBuilder::new()
            .state_from_slice(&state)
            .build();

        node_ids.push(graph.add_node(node));
    }

    // Create edges
    for i in 0..num_nodes {
        for j in 1..=edges_per_node {
            let target_idx = (i + j) % num_nodes;
            if i != target_idx {
                let edge = SheafEdgeBuilder::new(node_ids[i], node_ids[target_idx])
                    .identity_restrictions(state_dim)
                    .weight(1.0)
                    .build();

                // Ignore duplicate edges
                let _ = graph.add_edge(edge);
            }
        }
    }

    graph
}

// ============================================================================
// GPU Configuration Tests
// ============================================================================

#[test]
fn test_gpu_config_default() {
    let config = GpuConfig::default();

    assert!(config.enable_fallback);
    assert_eq!(config.beta, 1.0);
    assert!(config.threshold_lane0 < config.threshold_lane1);
    assert!(config.threshold_lane1 < config.threshold_lane2);
    assert!(config.timeout_ms > 0);
}

#[test]
fn test_gpu_config_custom() {
    let config = GpuConfig {
        enable_fallback: false,
        beta: 2.0,
        threshold_lane0: 0.05,
        threshold_lane1: 0.5,
        threshold_lane2: 5.0,
        ..Default::default()
    };

    assert!(!config.enable_fallback);
    assert_eq!(config.beta, 2.0);
    assert_eq!(config.threshold_lane0, 0.05);
}

// ============================================================================
// GPU Buffer Tests
// ============================================================================

#[test]
fn test_gpu_params_alignment() {
    // GPU struct alignment is critical for correct computation
    assert_eq!(std::mem::size_of::<GpuParams>(), 32);
    assert_eq!(std::mem::align_of::<GpuParams>(), 4);
}

#[test]
fn test_gpu_edge_alignment() {
    assert_eq!(std::mem::size_of::<GpuEdge>(), 32);
    assert_eq!(std::mem::align_of::<GpuEdge>(), 4);
}

#[test]
fn test_gpu_restriction_map_alignment() {
    assert_eq!(std::mem::size_of::<GpuRestrictionMap>(), 32);
    assert_eq!(std::mem::align_of::<GpuRestrictionMap>(), 4);
}

// ============================================================================
// CPU vs GPU Comparison Tests
// ============================================================================

/// Test that GPU energy matches CPU energy for triangle graph
#[tokio::test]
async fn test_gpu_cpu_energy_match_triangle() {
    let graph = create_triangle_graph();

    // Compute CPU energy
    let cpu_energy = graph.compute_energy();

    // Try GPU computation
    let config = GpuConfig::default();
    match GpuCoherenceEngine::try_new(config).await {
        Some(mut engine) => {
            engine.upload_graph(&graph).unwrap();
            let gpu_energy = engine.compute_energy().await.unwrap();

            // Compare total energies
            let diff = (cpu_energy.total_energy - gpu_energy.total_energy).abs();
            assert!(
                diff < TOLERANCE,
                "Energy mismatch: CPU={}, GPU={}, diff={}",
                cpu_energy.total_energy,
                gpu_energy.total_energy,
                diff
            );

            // Verify GPU was actually used
            assert!(gpu_energy.used_gpu);
        }
        None => {
            // GPU not available, skip test
            eprintln!("GPU not available, skipping GPU comparison test");
        }
    }
}

/// Test that coherent graph has near-zero energy on GPU
#[tokio::test]
async fn test_gpu_coherent_graph() {
    let graph = create_coherent_graph();

    // CPU energy should be near zero
    let cpu_energy = graph.compute_energy();
    assert!(
        cpu_energy.total_energy < 1e-10,
        "CPU energy for coherent graph should be near zero: {}",
        cpu_energy.total_energy
    );

    // Try GPU computation
    let config = GpuConfig::default();
    if let Some(mut engine) = GpuCoherenceEngine::try_new(config).await {
        engine.upload_graph(&graph).unwrap();
        let gpu_energy = engine.compute_energy().await.unwrap();

        assert!(
            gpu_energy.total_energy < 1e-5,
            "GPU energy for coherent graph should be near zero: {}",
            gpu_energy.total_energy
        );
    }
}

/// Test per-edge energy computation
#[tokio::test]
async fn test_gpu_per_edge_energies() {
    let graph = create_triangle_graph();

    // Compute CPU energy
    let cpu_energy = graph.compute_energy();

    let config = GpuConfig::default();
    if let Some(mut engine) = GpuCoherenceEngine::try_new(config).await {
        engine.upload_graph(&graph).unwrap();
        let gpu_energy = engine.compute_energy().await.unwrap();

        // Same number of edge energies
        assert_eq!(
            cpu_energy.edge_energies.len(),
            gpu_energy.edge_energies.len(),
            "Edge count mismatch"
        );

        // Each edge energy should match (order may differ)
        let cpu_sum: f32 = cpu_energy.edge_energies.values().sum();
        let gpu_sum: f32 = gpu_energy.edge_energies.iter().sum();

        let diff = (cpu_sum - gpu_sum).abs();
        assert!(
            diff < TOLERANCE,
            "Sum of edge energies mismatch: CPU={}, GPU={}, diff={}",
            cpu_sum,
            gpu_sum,
            diff
        );
    }
}

/// Test with larger graph
#[tokio::test]
async fn test_gpu_large_graph() {
    let graph = create_large_graph(100, 5);

    let cpu_energy = graph.compute_energy();

    let config = GpuConfig::default();
    if let Some(mut engine) = GpuCoherenceEngine::try_new(config).await {
        engine.upload_graph(&graph).unwrap();
        let gpu_energy = engine.compute_energy().await.unwrap();

        // Allow slightly larger tolerance for large graphs due to floating point accumulation
        let diff = (cpu_energy.total_energy - gpu_energy.total_energy).abs();
        let relative_diff = diff / cpu_energy.total_energy.max(1.0);

        assert!(
            relative_diff < 0.01, // 1% relative error
            "Large graph energy mismatch: CPU={}, GPU={}, relative_diff={:.2}%",
            cpu_energy.total_energy,
            gpu_energy.total_energy,
            relative_diff * 100.0
        );
    }
}

// ============================================================================
// Error Handling Tests
// ============================================================================

#[tokio::test]
async fn test_gpu_empty_graph_error() {
    let graph = SheafGraph::new();

    let config = GpuConfig::default();
    if let Some(mut engine) = GpuCoherenceEngine::try_new(config).await {
        let result = engine.upload_graph(&graph);
        assert!(result.is_err());
        match result {
            Err(GpuError::EmptyGraph) => {}
            Err(e) => panic!("Expected EmptyGraph error, got: {:?}", e),
            Ok(_) => panic!("Expected error for empty graph"),
        }
    }
}

#[test]
fn test_gpu_error_fallback_detection() {
    // Test that certain errors trigger fallback
    assert!(GpuError::NoAdapter.should_fallback());
    assert!(GpuError::NoDevice("test".into()).should_fallback());
    assert!(GpuError::DeviceCreation("test".into()).should_fallback());
    assert!(GpuError::AdapterRequest("test".into()).should_fallback());
    assert!(GpuError::UnsupportedFeature("test".into()).should_fallback());

    // These should not trigger fallback
    assert!(!GpuError::Timeout(100).should_fallback());
    assert!(!GpuError::EmptyGraph.should_fallback());
    assert!(!GpuError::BufferRead("test".into()).should_fallback());
}

#[test]
fn test_gpu_error_recoverable() {
    assert!(GpuError::Timeout(100).is_recoverable());
    assert!(GpuError::BufferRead("test".into()).is_recoverable());
    assert!(GpuError::ExecutionFailed("test".into()).is_recoverable());

    assert!(!GpuError::NoAdapter.is_recoverable());
    assert!(!GpuError::EmptyGraph.is_recoverable());
}

// ============================================================================
// GPU Capabilities Tests
// ============================================================================

#[tokio::test]
async fn test_gpu_capabilities() {
    let config = GpuConfig::default();
    if let Some(engine) = GpuCoherenceEngine::try_new(config).await {
        let caps = engine.capabilities();

        // Should have valid device info
        assert!(!caps.device_name.is_empty());
        assert!(!caps.backend.is_empty());

        // Should have reasonable limits
        assert!(caps.max_buffer_size > 0);
        assert!(caps.max_workgroup_size > 0);
        assert!(caps.max_workgroups[0] > 0);

        // Should be marked as supported
        assert!(caps.supported);
    }
}

// ============================================================================
// Synchronous API Tests
// ============================================================================

#[test]
fn test_sync_api() {
    use prime_radiant::gpu::sync;

    let config = GpuConfig::default();
    if let Some(mut engine) = sync::try_create_engine(config) {
        let graph = create_triangle_graph();

        engine.upload_graph(&graph).unwrap();
        let energy = sync::compute_energy(&mut engine).unwrap();

        assert!(energy.total_energy > 0.0);
        assert!(energy.used_gpu);
    }
}

// ============================================================================
// Resource Management Tests
// ============================================================================

#[tokio::test]
async fn test_gpu_resource_release() {
    let config = GpuConfig::default();
    if let Some(mut engine) = GpuCoherenceEngine::try_new(config).await {
        let graph = create_triangle_graph();

        // Upload and compute
        engine.upload_graph(&graph).unwrap();
        let _ = engine.compute_energy().await.unwrap();

        // Release resources
        engine.release();

        // Re-upload should work
        engine.upload_graph(&graph).unwrap();
        let energy = engine.compute_energy().await.unwrap();
        assert!(energy.total_energy > 0.0);
    }
}

#[tokio::test]
async fn test_gpu_multiple_computations() {
    let config = GpuConfig::default();
    if let Some(mut engine) = GpuCoherenceEngine::try_new(config).await {
        let graph = create_triangle_graph();
        engine.upload_graph(&graph).unwrap();

        // Multiple computations should give consistent results
        let energy1 = engine.compute_energy().await.unwrap();
        let energy2 = engine.compute_energy().await.unwrap();
        let energy3 = engine.compute_energy().await.unwrap();

        assert!(
            (energy1.total_energy - energy2.total_energy).abs() < TOLERANCE,
            "Inconsistent results between computations"
        );
        assert!(
            (energy2.total_energy - energy3.total_energy).abs() < TOLERANCE,
            "Inconsistent results between computations"
        );
    }
}

// ============================================================================
// Performance Tests (disabled by default)
// ============================================================================

#[tokio::test]
#[ignore] // Run with: cargo test --features gpu -- --ignored
async fn test_gpu_performance_1k_nodes() {
    let graph = create_large_graph(1000, 10);
    let edge_count = graph.edge_count();

    let config = GpuConfig::default();
    if let Some(mut engine) = GpuCoherenceEngine::try_new(config).await {
        engine.upload_graph(&graph).unwrap();

        // Warm up
        let _ = engine.compute_energy().await.unwrap();

        // Benchmark
        let start = std::time::Instant::now();
        let energy = engine.compute_energy().await.unwrap();
        let gpu_time = start.elapsed();

        // Compare with CPU
        let start = std::time::Instant::now();
        let cpu_energy = graph.compute_energy();
        let cpu_time = start.elapsed();

        println!(
            "Performance test ({} edges):",
            edge_count
        );
        println!("  GPU: {}us ({} edges/ms)", energy.compute_time_us, edge_count as u64 * 1000 / energy.compute_time_us.max(1));
        println!("  CPU: {}us", cpu_time.as_micros());
        println!("  Speedup: {:.2}x", cpu_time.as_micros() as f64 / gpu_time.as_micros() as f64);

        // Verify correctness
        let diff = (cpu_energy.total_energy - energy.total_energy).abs();
        let relative_diff = diff / cpu_energy.total_energy.max(1.0);
        assert!(relative_diff < 0.01, "Performance test: energy mismatch");
    }
}

#[tokio::test]
#[ignore]
async fn test_gpu_performance_10k_nodes() {
    let graph = create_large_graph(10000, 10);
    let edge_count = graph.edge_count();

    let config = GpuConfig::default();
    if let Some(mut engine) = GpuCoherenceEngine::try_new(config).await {
        engine.upload_graph(&graph).unwrap();

        // Warm up
        let _ = engine.compute_energy().await.unwrap();

        // Benchmark
        let energy = engine.compute_energy().await.unwrap();

        println!(
            "Large scale test ({} edges): {}us, {} edges/ms",
            edge_count,
            energy.compute_time_us,
            edge_count as u64 * 1000 / energy.compute_time_us.max(1)
        );

        assert!(energy.total_energy > 0.0);
    }
}