hive-gpu 0.2.0

High-performance GPU acceleration for vector operations with Device Info API (Metal, CUDA, ROCm)
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
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 Performance Benchmark Tests
//!
//! Tests that measure real performance and establish baselines:
//! - Vector addition throughput
//! - Search latency
//! - Batch processing performance
//! - Memory bandwidth
//! - Scalability tests

#[cfg(all(target_os = "macos", feature = "metal-native"))]
use std::time::Instant;

#[cfg(all(target_os = "macos", feature = "metal-native"))]
mod metal_performance_tests {
    use super::*;
    use hive_gpu::error::HiveGpuError;
    use hive_gpu::metal::MetalNativeContext;
    use hive_gpu::traits::GpuContext;
    use hive_gpu::types::{GpuDistanceMetric, GpuVector};

    /// Helper to create test vectors
    fn create_test_vectors(count: usize, dimension: usize) -> Vec<GpuVector> {
        (0..count)
            .map(|i| {
                let data: Vec<f32> = (0..dimension).map(|d| (i * dimension + d) as f32).collect();
                GpuVector::new(format!("vec_{}", i), data)
            })
            .collect()
    }

    #[test]
    fn test_vector_addition_throughput() {
        // Measure vector addition throughput
        let context = match MetalNativeContext::new() {
            Ok(ctx) => ctx,
            Err(HiveGpuError::NoDeviceAvailable) => {
                println!("⚠️  Metal not available, skipping test");
                return;
            }
            Err(e) => panic!("Failed to create Metal context: {}", e),
        };

        let dimension = 512;
        let sizes = vec![100, 500, 1000, 5000];

        println!("✅ Vector Addition Throughput Benchmark:");
        println!("   Dimension: {}", dimension);
        println!();

        for size in sizes {
            let vectors = create_test_vectors(size, dimension);
            let mut storage = context
                .create_storage(dimension, GpuDistanceMetric::Cosine)
                .expect("Failed to create storage");

            let start = Instant::now();
            storage
                .add_vectors(&vectors)
                .expect("Failed to add vectors");
            let duration = start.elapsed();

            let throughput = size as f64 / duration.as_secs_f64();
            let mb_per_sec =
                (size * dimension * 4) as f64 / duration.as_secs_f64() / 1024.0 / 1024.0;

            println!("   {} vectors:", size);
            println!("      Time: {:?}", duration);
            println!("      Throughput: {:.2} vectors/sec", throughput);
            println!("      Bandwidth: {:.2} MB/s", mb_per_sec);

            // Baseline: Should be able to add at least 100 vectors/sec
            assert!(
                throughput > 100.0,
                "Throughput too low: {:.2} vectors/sec",
                throughput
            );
        }
    }

    #[test]
    fn test_search_latency() {
        // Measure search latency
        let context = match MetalNativeContext::new() {
            Ok(ctx) => ctx,
            Err(HiveGpuError::NoDeviceAvailable) => {
                println!("⚠️  Metal not available, skipping test");
                return;
            }
            Err(e) => panic!("Failed to create Metal context: {}", e),
        };

        let dimension = 256;
        let vector_count = 1000;
        let vectors = create_test_vectors(vector_count, dimension);

        let mut storage = context
            .create_storage(dimension, GpuDistanceMetric::Cosine)
            .expect("Failed to create storage");

        storage
            .add_vectors(&vectors)
            .expect("Failed to add vectors");

        println!("✅ Search Latency Benchmark:");
        println!("   Dataset: {} vectors × {}D", vector_count, dimension);
        println!();

        let k_values = vec![1, 5, 10, 50, 100];
        let query = &vectors[0].data;

        for k in k_values {
            let iterations = 100;
            let start = Instant::now();

            for _ in 0..iterations {
                storage.search(query, k).expect("Failed to search");
            }

            let duration = start.elapsed();
            let avg_latency = duration.as_micros() as f64 / iterations as f64;

            println!("   k={} results:", k);
            println!("      Avg latency: {:.2} μs", avg_latency);
            println!("      QPS: {:.0} queries/sec", 1_000_000.0 / avg_latency);

            // Regression guard for k=10. The old CPU-fallback path was
            // sub-microsecond; the real Metal compute kernel introduced in
            // phase4a adds ~hundreds-of-μs dispatch/commit overhead per
            // call, and shared CI macOS runners add another order of
            // magnitude on top of that. 50ms keeps the test useful for
            // catching real regressions without flaking on hosted runners.
            if k == 10 {
                assert!(
                    avg_latency < 50_000.0,
                    "Search latency too high: {:.2} μs",
                    avg_latency
                );
            }
        }
    }

    #[test]
    fn test_batch_processing_performance() {
        // Measure batch processing performance
        let context = match MetalNativeContext::new() {
            Ok(ctx) => ctx,
            Err(HiveGpuError::NoDeviceAvailable) => {
                println!("⚠️  Metal not available, skipping test");
                return;
            }
            Err(e) => panic!("Failed to create Metal context: {}", e),
        };

        let dimension = 384;
        let batch_sizes = vec![10, 50, 100, 500];

        println!("✅ Batch Processing Performance:");
        println!("   Dimension: {}", dimension);
        println!();

        for batch_size in batch_sizes {
            let vectors = create_test_vectors(batch_size, dimension);
            let mut storage = context
                .create_storage(dimension, GpuDistanceMetric::Cosine)
                .expect("Failed to create storage");

            let start = Instant::now();
            storage
                .add_vectors(&vectors)
                .expect("Failed to add vectors");
            let duration = start.elapsed();

            let throughput = batch_size as f64 / duration.as_secs_f64();
            let time_per_vector = duration.as_micros() as f64 / batch_size as f64;

            println!("   Batch size: {}", batch_size);
            println!("      Total time: {:?}", duration);
            println!("      Time/vector: {:.2} μs", time_per_vector);
            println!("      Throughput: {:.2} vectors/sec", throughput);
        }
    }

    #[test]
    fn test_dimension_scaling() {
        // Test how performance scales with dimension
        let context = match MetalNativeContext::new() {
            Ok(ctx) => ctx,
            Err(HiveGpuError::NoDeviceAvailable) => {
                println!("⚠️  Metal not available, skipping test");
                return;
            }
            Err(e) => panic!("Failed to create Metal context: {}", e),
        };

        let dimensions = vec![64, 128, 256, 512, 1024];
        let vector_count = 100;

        println!("✅ Dimension Scaling Performance:");
        println!("   Vector count: {}", vector_count);
        println!();

        for dimension in dimensions {
            let vectors = create_test_vectors(vector_count, dimension);
            let mut storage = context
                .create_storage(dimension, GpuDistanceMetric::Cosine)
                .expect("Failed to create storage");

            let start = Instant::now();
            storage
                .add_vectors(&vectors)
                .expect("Failed to add vectors");
            let duration = start.elapsed();

            let throughput = vector_count as f64 / duration.as_secs_f64();
            let data_size = (vector_count * dimension * 4) / 1024; // KB

            println!("   Dimension: {}D", dimension);
            println!("      Data size: {} KB", data_size);
            println!("      Time: {:?}", duration);
            println!("      Throughput: {:.2} vectors/sec", throughput);
        }
    }

    #[test]
    fn test_vector_count_scaling() {
        // Test how performance scales with number of vectors
        let context = match MetalNativeContext::new() {
            Ok(ctx) => ctx,
            Err(HiveGpuError::NoDeviceAvailable) => {
                println!("⚠️  Metal not available, skipping test");
                return;
            }
            Err(e) => panic!("Failed to create Metal context: {}", e),
        };

        let dimension = 256;
        let vector_counts = vec![100, 500, 1000, 2500, 5000];

        println!("✅ Vector Count Scaling Performance:");
        println!("   Dimension: {}", dimension);
        println!();

        for count in vector_counts {
            let vectors = create_test_vectors(count, dimension);
            let mut storage = context
                .create_storage(dimension, GpuDistanceMetric::Cosine)
                .expect("Failed to create storage");

            let start = Instant::now();
            storage
                .add_vectors(&vectors)
                .expect("Failed to add vectors");
            let duration = start.elapsed();

            let throughput = count as f64 / duration.as_secs_f64();
            let data_size_mb = (count * dimension * 4) as f64 / 1024.0 / 1024.0;

            println!("   {} vectors:", count);
            println!("      Data size: {:.2} MB", data_size_mb);
            println!("      Time: {:?}", duration);
            println!("      Throughput: {:.2} vectors/sec", throughput);
        }
    }

    #[test]
    fn test_memory_bandwidth() {
        // Estimate memory bandwidth
        let context = match MetalNativeContext::new() {
            Ok(ctx) => ctx,
            Err(HiveGpuError::NoDeviceAvailable) => {
                println!("⚠️  Metal not available, skipping test");
                return;
            }
            Err(e) => panic!("Failed to create Metal context: {}", e),
        };

        let dimension = 1024;
        let count = 1000;
        let vectors = create_test_vectors(count, dimension);

        let mut storage = context
            .create_storage(dimension, GpuDistanceMetric::Cosine)
            .expect("Failed to create storage");

        let data_size_bytes = (count * dimension * 4) as f64;
        let data_size_mb = data_size_bytes / 1024.0 / 1024.0;

        let start = Instant::now();
        storage
            .add_vectors(&vectors)
            .expect("Failed to add vectors");
        let duration = start.elapsed();

        let bandwidth_mbps = data_size_mb / duration.as_secs_f64();
        let bandwidth_gbps = bandwidth_mbps / 1024.0;

        println!("✅ Memory Bandwidth Benchmark:");
        println!("   Data transferred: {:.2} MB", data_size_mb);
        println!("   Time: {:?}", duration);
        println!("   Bandwidth: {:.2} MB/s", bandwidth_mbps);
        println!("   Bandwidth: {:.2} GB/s", bandwidth_gbps);

        // Note: This measures effective bandwidth including all overhead
        // (memory allocation, data transfer, Metal command submission, etc.)
        // The M3 Pro has ~200-400 GB/s theoretical unified memory bandwidth,
        // but practical application bandwidth is much lower due to overhead.
        // We just verify operations complete successfully.
        assert!(
            bandwidth_mbps > 1.0,
            "Bandwidth too low: {:.2} MB/s",
            bandwidth_mbps
        );

        println!("   ✅ Memory operations completed successfully");
    }

    #[test]
    fn test_cold_vs_warm_performance() {
        // Compare cold start vs warm cache performance
        let context = match MetalNativeContext::new() {
            Ok(ctx) => ctx,
            Err(HiveGpuError::NoDeviceAvailable) => {
                println!("⚠️  Metal not available, skipping test");
                return;
            }
            Err(e) => panic!("Failed to create Metal context: {}", e),
        };

        let dimension = 256;
        let count = 500;

        println!("✅ Cold vs Warm Performance:");
        println!();

        // Cold start
        {
            let vectors = create_test_vectors(count, dimension);
            let mut storage = context
                .create_storage(dimension, GpuDistanceMetric::Cosine)
                .expect("Failed to create storage");

            let start = Instant::now();
            storage
                .add_vectors(&vectors)
                .expect("Failed to add vectors");
            let cold_duration = start.elapsed();

            println!("   Cold start (first allocation):");
            println!("      Time: {:?}", cold_duration);
        }

        // Warm cache (repeated allocations)
        let iterations = 5;
        let mut warm_durations = Vec::new();

        for _ in 0..iterations {
            let vectors = create_test_vectors(count, dimension);
            let mut storage = context
                .create_storage(dimension, GpuDistanceMetric::Cosine)
                .expect("Failed to create storage");

            let start = Instant::now();
            storage
                .add_vectors(&vectors)
                .expect("Failed to add vectors");
            warm_durations.push(start.elapsed());
        }

        let avg_warm = warm_durations.iter().sum::<std::time::Duration>() / iterations as u32;
        let min_warm = warm_durations.iter().min().unwrap();
        let max_warm = warm_durations.iter().max().unwrap();

        println!("   Warm cache ({} iterations):", iterations);
        println!("      Avg time: {:?}", avg_warm);
        println!("      Min time: {:?}", min_warm);
        println!("      Max time: {:?}", max_warm);
    }

    #[test]
    fn test_distance_metric_performance() {
        // Compare performance of different distance metrics
        let context = match MetalNativeContext::new() {
            Ok(ctx) => ctx,
            Err(HiveGpuError::NoDeviceAvailable) => {
                println!("⚠️  Metal not available, skipping test");
                return;
            }
            Err(e) => panic!("Failed to create Metal context: {}", e),
        };

        let dimension = 256;
        let count = 1000;
        let vectors = create_test_vectors(count, dimension);

        println!("✅ Distance Metric Performance:");
        println!("   Dataset: {} vectors × {}D", count, dimension);
        println!();

        let metrics = vec![
            ("Cosine", GpuDistanceMetric::Cosine),
            ("Euclidean", GpuDistanceMetric::Euclidean),
            ("DotProduct", GpuDistanceMetric::DotProduct),
        ];

        for (name, metric) in metrics {
            let mut storage = context
                .create_storage(dimension, metric)
                .expect("Failed to create storage");

            let start = Instant::now();
            storage
                .add_vectors(&vectors)
                .expect("Failed to add vectors");
            let add_duration = start.elapsed();

            // Measure search time
            let query = &vectors[0].data;
            let search_start = Instant::now();
            storage.search(query, 10).expect("Failed to search");
            let search_duration = search_start.elapsed();

            println!("   {}:", name);
            println!("      Add time: {:?}", add_duration);
            println!("      Search time: {:?}", search_duration);
        }
    }

    #[test]
    fn test_concurrent_operations() {
        // Test performance with multiple concurrent operations
        let context = match MetalNativeContext::new() {
            Ok(ctx) => ctx,
            Err(HiveGpuError::NoDeviceAvailable) => {
                println!("⚠️  Metal not available, skipping test");
                return;
            }
            Err(e) => panic!("Failed to create Metal context: {}", e),
        };

        let dimension = 128;
        let count = 200;
        let num_storages = 5;

        println!("✅ Concurrent Operations Performance:");
        println!("   {} independent storages", num_storages);
        println!();

        let start = Instant::now();

        for i in 0..num_storages {
            let vectors = create_test_vectors(count, dimension);
            let mut storage = context
                .create_storage(dimension, GpuDistanceMetric::Cosine)
                .expect("Failed to create storage");

            storage
                .add_vectors(&vectors)
                .expect("Failed to add vectors");

            if i == 0 {
                println!("   Storage {} time: {:?}", i + 1, start.elapsed());
            }
        }

        let total_duration = start.elapsed();
        let avg_time = total_duration / num_storages as u32;

        println!("   Total time: {:?}", total_duration);
        println!("   Avg per storage: {:?}", avg_time);
        println!(
            "   Throughput: {:.2} storages/sec",
            num_storages as f64 / total_duration.as_secs_f64()
        );
    }

    #[test]
    fn test_performance_baseline() {
        // Establish performance baseline for CI/CD
        let context = match MetalNativeContext::new() {
            Ok(ctx) => ctx,
            Err(HiveGpuError::NoDeviceAvailable) => {
                println!("⚠️  Metal not available, skipping test");
                return;
            }
            Err(e) => panic!("Failed to create Metal context: {}", e),
        };

        let dimension = 512;
        let count = 1000;
        let vectors = create_test_vectors(count, dimension);

        let mut storage = context
            .create_storage(dimension, GpuDistanceMetric::Cosine)
            .expect("Failed to create storage");

        let start = Instant::now();
        storage
            .add_vectors(&vectors)
            .expect("Failed to add vectors");
        let duration = start.elapsed();

        let throughput = count as f64 / duration.as_secs_f64();

        println!("✅ Performance Baseline:");
        println!("   Config: {} vectors × {}D", count, dimension);
        println!("   Time: {:?}", duration);
        println!("   Throughput: {:.2} vectors/sec", throughput);

        // Baseline thresholds (conservative for CI)
        assert!(
            duration.as_secs() < 5,
            "Operation took too long: {:?}",
            duration
        );
        assert!(
            throughput > 200.0,
            "Throughput below baseline: {:.2} vectors/sec",
            throughput
        );

        println!("   ✅ Performance within baseline");
    }
}