hive-gpu 0.1.7

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
# ๐Ÿ”— Hive-GPU Integration Guide

**Complete guide for integrating hive-gpu with vectorizer and standalone projects**

## ๐Ÿ“ฆ Version Information

- **hive-gpu**: v0.1.0
- **vectorizer**: v0.6.0
- **Rust Edition**: 2024

## ๐Ÿš€ Quick Integration

### 1. Add Dependencies

```toml
# Cargo.toml
[dependencies]
# For standalone use
hive-gpu = "0.1.0"

# For vectorizer integration
vectorizer = { git = "https://github.com/hivellm/vectorizer.git" }
hive-gpu = "0.1.0"
```

### 2. Enable GPU Features

```toml
# Choose your GPU backend
[dependencies]
hive-gpu = { version = "0.1.0", features = ["metal-native"] }  # macOS
hive-gpu = { version = "0.1.0", features = ["cuda"] }          # Linux/Windows
hive-gpu = { version = "0.1.0", features = ["wgpu"] }          # Cross-platform
```

## ๐Ÿ—๏ธ Integration Patterns

### Pattern 1: Direct GPU Usage

```rust
use hive_gpu::metal::context::MetalNativeContext;
use hive_gpu::traits::{GpuContext, GpuVectorStorage};
use hive_gpu::types::{GpuVector, GpuDistanceMetric};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize GPU context
    let context = MetalNativeContext::new()?;
    let mut storage = context.create_storage(512, GpuDistanceMetric::Cosine)?;
    
    // Your vector operations here
    let vectors = create_vectors();
    storage.add_vectors(&vectors)?;
    
    let results = storage.search(&query, 10)?;
    println!("Found {} results", results.len());
    
    Ok(())
}
```

### Pattern 2: Vectorizer Integration

```rust
use vectorizer::VectorStore;
use vectorizer::models::{CollectionConfig, DistanceMetric, HnswConfig};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create vectorizer store
    let mut store = VectorStore::new();
    
    // Configure collection with GPU acceleration
    let config = CollectionConfig {
        dimension: 512,
        metric: DistanceMetric::Cosine,
        hnsw_config: HnswConfig {
            m: 16,
            ef_construction: 200,
            ef_search: 50,
            seed: 42,
        },
    };
    
    // Create collection
    store.create_collection("my_collection", config)?;
    
    // Add vectors
    let vectors = create_document_vectors();
    store.add_vectors("my_collection", vectors)?;
    
    // Search
    let query = create_query_vector();
    let results = store.search("my_collection", &query, 10)?;
    
    println!("Search completed: {} results", results.len());
    Ok(())
}
```

### Pattern 3: Custom Wrapper

```rust
use hive_gpu::metal::context::MetalNativeContext;
use hive_gpu::traits::{GpuContext, GpuVectorStorage};
use hive_gpu::types::{GpuVector, GpuDistanceMetric};

pub struct MyVectorDatabase {
    storage: Box<dyn GpuVectorStorage>,
    dimension: usize,
}

impl MyVectorDatabase {
    pub async fn new(dimension: usize) -> Result<Self, Box<dyn std::error::Error>> {
        let context = MetalNativeContext::new()?;
        let storage = context.create_storage(dimension, GpuDistanceMetric::Cosine)?;
        
        Ok(Self {
            storage,
            dimension,
        })
    }
    
    pub async fn add_document(&mut self, id: &str, embedding: Vec<f32>, metadata: HashMap<String, String>) -> Result<(), Box<dyn std::error::Error>> {
        let vector = GpuVector {
            id: id.to_string(),
            data: embedding,
            metadata,
        };
        
        self.storage.add_vectors(&[vector])?;
        Ok(())
    }
    
    pub async fn search_similar(&self, query: &[f32], limit: usize) -> Result<Vec<(String, f32)>, Box<dyn std::error::Error>> {
        let results = self.storage.search(query, limit)?;
        Ok(results.into_iter().map(|r| (r.id, r.score)).collect())
    }
    
    pub fn vector_count(&self) -> usize {
        self.storage.vector_count()
    }
}
```

## ๐Ÿ”ง Configuration Examples

### Basic Configuration

```rust
use hive_gpu::metal::context::MetalNativeContext;
use hive_gpu::traits::{GpuContext, GpuVectorStorage};
use hive_gpu::types::{GpuDistanceMetric, HnswConfig};

// Basic setup
let context = MetalNativeContext::new()?;
let storage = context.create_storage(128, GpuDistanceMetric::Cosine)?;
```

### Advanced Configuration with HNSW

```rust
use hive_gpu::types::HnswConfig;

// Configure HNSW for better search performance
let hnsw_config = HnswConfig {
    m: 16,              // Number of bi-directional links
    ef_construction: 200, // Size of dynamic candidate list
    ef_search: 50,      // Size of dynamic candidate list for search
    seed: 42,           // Random seed
};

let storage = context.create_storage_with_config(
    512, 
    GpuDistanceMetric::Cosine, 
    hnsw_config
)?;
```

### Multi-Backend Support

```rust
use hive_gpu::traits::{GpuContext, GpuVectorStorage};

// Auto-detect best available backend
let context = if cfg!(target_os = "macos") {
    Box::new(hive_gpu::metal::context::MetalNativeContext::new()?)
} else if cfg!(feature = "cuda") {
    Box::new(hive_gpu::cuda::context::CudaContext::new()?)
} else {
    Box::new(hive_gpu::wgpu::context::WgpuContext::new()?)
};

let storage = context.create_storage(128, GpuDistanceMetric::Cosine)?;
```

## ๐Ÿ“Š Performance Optimization

### Batch Operations

```rust
// Efficient batch processing
let batch_size = 1000;
let mut vectors = Vec::with_capacity(batch_size);

for i in 0..batch_size {
    vectors.push(GpuVector {
        id: format!("batch_{}", i),
        data: generate_embedding(&format!("Document {}", i)),
        metadata: HashMap::new(),
    });
}

// Add in batches for better performance
storage.add_vectors(&vectors)?;
```

### Memory Management

```rust
use hive_gpu::monitoring::VramMonitor;

// Monitor GPU memory usage
let monitor = VramMonitor::new()?;
let stats = monitor.get_stats()?;

println!("GPU Memory Usage: {:.2} MB", stats.used_memory_mb);
println!("Available Memory: {:.2} MB", stats.available_memory_mb);
```

### Async Operations

```rust
use tokio::task;

// Parallel vector processing
let handles: Vec<_> = vector_batches
    .into_iter()
    .map(|batch| {
        let storage = storage.clone();
        task::spawn(async move {
            storage.add_vectors(&batch).await
        })
    })
    .collect();

// Wait for all batches to complete
for handle in handles {
    handle.await??;
}
```

## ๐Ÿงช Testing Integration

### Unit Tests

```rust
#[cfg(test)]
mod tests {
    use super::*;
    use hive_gpu::metal::context::MetalNativeContext;
    use hive_gpu::traits::{GpuContext, GpuVectorStorage};

    #[tokio::test]
    async fn test_gpu_integration() {
        let context = MetalNativeContext::new().unwrap();
        let mut storage = context.create_storage(4, GpuDistanceMetric::Cosine).unwrap();
        
        let vectors = vec![
            GpuVector {
                id: "test_1".to_string(),
                data: vec![1.0, 0.0, 0.0, 0.0],
                metadata: HashMap::new(),
            },
        ];
        
        storage.add_vectors(&vectors).unwrap();
        
        let query = vec![1.0, 0.0, 0.0, 0.0];
        let results = storage.search(&query, 1).unwrap();
        
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].id, "test_1");
    }
}
```

### Integration Tests

```rust
#[tokio::test]
async fn test_vectorizer_integration() {
    let mut store = VectorStore::new();
    
    let config = CollectionConfig {
        dimension: 128,
        metric: DistanceMetric::Cosine,
        hnsw_config: HnswConfig {
            m: 16,
            ef_construction: 200,
            ef_search: 50,
            seed: 42,
        },
    };
    
    store.create_collection("test_collection", config).unwrap();
    
    let vectors = vec![
        Vector {
            id: "doc_1".to_string(),
            data: vec![1.0; 128],
            payload: None,
        },
    ];
    
    store.add_vectors("test_collection", vectors).unwrap();
    
    let query = vec![1.0; 128];
    let results = store.search("test_collection", &query, 1).unwrap();
    
    assert_eq!(results.len(), 1);
}
```

## ๐Ÿš€ Deployment

### Docker Configuration

```dockerfile
# Dockerfile
FROM rust:1.75 as builder

# Install system dependencies
RUN apt-get update && apt-get install -y \
    libclang-dev \
    pkg-config

# Copy source
COPY . .
RUN cargo build --release

FROM ubuntu:22.04

# Install runtime dependencies
RUN apt-get update && apt-get install -y \
    libclang-14 \
    && rm -rf /var/lib/apt/lists/*

COPY --from=builder /app/target/release/my-app /usr/local/bin/

CMD ["my-app"]
```

### Environment Variables

```bash
# Development
export RUST_LOG=debug
export HIVE_GPU_MEMORY_LIMIT=4GB

# Production
export RUST_LOG=info
export HIVE_GPU_PROFILE=false
```

## ๐Ÿ” Troubleshooting

### Common Issues

#### 1. GPU Not Available
```rust
// Check GPU availability
if let Ok(context) = MetalNativeContext::new() {
    println!("GPU available");
} else {
    println!("GPU not available, falling back to CPU");
    // Implement CPU fallback
}
```

#### 2. Memory Issues
```rust
// Monitor memory usage
let monitor = VramMonitor::new()?;
let stats = monitor.get_stats()?;

if stats.used_memory_mb > 1000.0 {
    println!("Warning: High GPU memory usage");
}
```

#### 3. Performance Issues
```rust
// Use batch operations
let batch_size = 1000;
for chunk in vectors.chunks(batch_size) {
    storage.add_vectors(chunk)?;
}
```

### Debug Information

```rust
use tracing::{info, debug, error};

// Enable debug logging
tracing_subscriber::fmt::init();

// Log GPU operations
info!("Initializing GPU context");
let context = MetalNativeContext::new()?;
debug!("GPU context created successfully");

let storage = context.create_storage(128, GpuDistanceMetric::Cosine)?;
info!("Vector storage created with dimension: 128");
```

## ๐Ÿ“š Additional Resources

- **API Documentation**: [docs.rs/hive-gpu]https://docs.rs/hive-gpu
- **Examples**: [GitHub Examples]https://github.com/hivellm/hive-gpu/tree/main/examples
- **Vectorizer Integration**: [Vectorizer Docs]https://github.com/hivellm/vectorizer
- **Performance Guide**: [Benchmarking Guide]BENCHMARKING.md

## ๐Ÿค Support

- **GitHub Issues**: [Report issues]https://github.com/hivellm/hive-gpu/issues
- **Discussions**: [Community discussions]https://github.com/hivellm/hive-gpu/discussions
- **Documentation**: [Complete API reference]https://docs.rs/hive-gpu

---

**Ready to accelerate your vector operations with GPU power! ๐Ÿš€**