infernum-arbiter 0.2.0-rc.2

Unified GPU arbiter - coordinates Infernum (LLM) and Dantalion (Diffusion) workloads
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
//! Fragment cache for HoloTensor weights.
//!
//! Unified cache shared between Infernum and Dantalion for efficient
//! fragment reuse across workloads.

use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Instant;

use parking_lot::RwLock;
use serde::{Deserialize, Serialize};

/// Cache configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheConfig {
    /// VRAM cache capacity in bytes.
    pub vram_capacity: u64,
    /// RAM cache capacity in bytes.
    pub ram_capacity: u64,
}

impl Default for CacheConfig {
    fn default() -> Self {
        Self {
            vram_capacity: 10 * 1024 * 1024 * 1024, // 10GB
            ram_capacity: 32 * 1024 * 1024 * 1024,  // 32GB
        }
    }
}

/// Cache tier for fragments.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum CacheTier {
    /// GPU VRAM - fastest.
    Vram,
    /// System RAM - fast.
    Ram,
    /// Not cached.
    None,
}

/// Statistics for the fragment cache.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CacheStats {
    /// VRAM bytes used.
    pub vram_used: u64,
    /// RAM bytes used.
    pub ram_used: u64,
    /// Cache hits.
    pub hits: u64,
    /// Cache misses.
    pub misses: u64,
    /// Evictions from VRAM.
    pub vram_evictions: u64,
    /// Evictions from RAM.
    pub ram_evictions: u64,
    /// Total fragments cached.
    pub fragments_cached: u64,
}

impl CacheStats {
    /// Returns cache hit rate (0.0 - 1.0).
    pub fn hit_rate(&self) -> f64 {
        let total = self.hits + self.misses;
        if total == 0 {
            return 0.0;
        }
        self.hits as f64 / total as f64
    }

    /// Returns VRAM utilization.
    pub fn vram_utilization(&self, capacity: u64) -> f64 {
        if capacity == 0 {
            return 0.0;
        }
        self.vram_used as f64 / capacity as f64
    }

    /// Returns RAM utilization.
    pub fn ram_utilization(&self, capacity: u64) -> f64 {
        if capacity == 0 {
            return 0.0;
        }
        self.ram_used as f64 / capacity as f64
    }
}

/// A cached fragment entry.
#[derive(Debug, Clone)]
struct CacheEntry {
    /// Fragment identifier (stored for diagnostics; keyed in HashMap).
    _fragment_id: String,
    /// Size in bytes.
    size: u64,
    /// Current tier.
    tier: CacheTier,
    /// Last access time.
    last_access: Instant,
    /// Access count.
    access_count: u64,
    /// Which systems use this fragment.
    users: FragmentUsers,
}

/// Which systems use a fragment.
#[derive(Debug, Clone, Copy, Default)]
struct FragmentUsers {
    infernum: bool,
    dantalion: bool,
}

impl FragmentUsers {
    fn count(&self) -> u32 {
        self.infernum as u32 + self.dantalion as u32
    }
}

/// The unified fragment cache.
pub struct FragmentCache {
    config: CacheConfig,
    entries: RwLock<HashMap<String, CacheEntry>>,
    vram_used: AtomicU64,
    ram_used: AtomicU64,
    hits: AtomicU64,
    misses: AtomicU64,
    vram_evictions: AtomicU64,
    ram_evictions: AtomicU64,
}

impl FragmentCache {
    /// Creates a new cache with the given configuration.
    pub fn new(config: CacheConfig) -> Self {
        Self {
            config,
            entries: RwLock::new(HashMap::new()),
            vram_used: AtomicU64::new(0),
            ram_used: AtomicU64::new(0),
            hits: AtomicU64::new(0),
            misses: AtomicU64::new(0),
            vram_evictions: AtomicU64::new(0),
            ram_evictions: AtomicU64::new(0),
        }
    }

    /// Returns the configuration.
    pub fn config(&self) -> &CacheConfig {
        &self.config
    }

    /// Checks if a fragment is cached.
    pub fn contains(&self, fragment_id: &str) -> bool {
        self.entries.read().contains_key(fragment_id)
    }

    /// Gets the tier for a fragment.
    pub fn get_tier(&self, fragment_id: &str) -> CacheTier {
        self.entries
            .read()
            .get(fragment_id)
            .map(|e| e.tier)
            .unwrap_or(CacheTier::None)
    }

    /// Records a cache access, returning the tier.
    pub fn access(&self, fragment_id: &str) -> CacheTier {
        let mut entries = self.entries.write();
        if let Some(entry) = entries.get_mut(fragment_id) {
            entry.last_access = Instant::now();
            entry.access_count += 1;
            self.hits.fetch_add(1, Ordering::Relaxed);
            entry.tier
        } else {
            self.misses.fetch_add(1, Ordering::Relaxed);
            CacheTier::None
        }
    }

    /// Inserts a fragment into the cache.
    pub fn insert(
        &self,
        fragment_id: impl Into<String>,
        size: u64,
        tier: CacheTier,
        for_infernum: bool,
    ) {
        let fragment_id = fragment_id.into();

        // Evict if necessary
        self.ensure_capacity(size, tier);

        let entry = CacheEntry {
            _fragment_id: fragment_id.clone(),
            size,
            tier,
            last_access: Instant::now(),
            access_count: 1,
            users: FragmentUsers {
                infernum: for_infernum,
                dantalion: !for_infernum,
            },
        };

        // Update usage tracking
        match tier {
            CacheTier::Vram => {
                self.vram_used.fetch_add(size, Ordering::Relaxed);
            },
            CacheTier::Ram => {
                self.ram_used.fetch_add(size, Ordering::Relaxed);
            },
            CacheTier::None => {},
        }

        self.entries.write().insert(fragment_id, entry);
    }

    /// Removes a fragment from the cache.
    pub fn remove(&self, fragment_id: &str) {
        let mut entries = self.entries.write();
        if let Some(entry) = entries.remove(fragment_id) {
            match entry.tier {
                CacheTier::Vram => {
                    self.vram_used.fetch_sub(entry.size, Ordering::Relaxed);
                },
                CacheTier::Ram => {
                    self.ram_used.fetch_sub(entry.size, Ordering::Relaxed);
                },
                CacheTier::None => {},
            }
        }
    }

    /// Promotes a fragment to a higher tier.
    pub fn promote(&self, fragment_id: &str, to_tier: CacheTier) {
        let mut entries = self.entries.write();
        if let Some(entry) = entries.get_mut(fragment_id) {
            let from_tier = entry.tier;
            if to_tier == from_tier {
                return;
            }

            // Update usage
            match from_tier {
                CacheTier::Vram => {
                    self.vram_used.fetch_sub(entry.size, Ordering::Relaxed);
                },
                CacheTier::Ram => {
                    self.ram_used.fetch_sub(entry.size, Ordering::Relaxed);
                },
                CacheTier::None => {},
            }

            match to_tier {
                CacheTier::Vram => {
                    self.vram_used.fetch_add(entry.size, Ordering::Relaxed);
                },
                CacheTier::Ram => {
                    self.ram_used.fetch_add(entry.size, Ordering::Relaxed);
                },
                CacheTier::None => {},
            }

            entry.tier = to_tier;
        }
    }

    /// Demotes a fragment to a lower tier.
    pub fn demote(&self, fragment_id: &str, to_tier: CacheTier) {
        self.promote(fragment_id, to_tier);
    }

    /// Marks a fragment as used by both systems (shared).
    pub fn mark_shared(&self, fragment_id: &str) {
        let mut entries = self.entries.write();
        if let Some(entry) = entries.get_mut(fragment_id) {
            entry.users.infernum = true;
            entry.users.dantalion = true;
        }
    }

    /// Returns current statistics.
    pub fn stats(&self) -> CacheStats {
        CacheStats {
            vram_used: self.vram_used.load(Ordering::Relaxed),
            ram_used: self.ram_used.load(Ordering::Relaxed),
            hits: self.hits.load(Ordering::Relaxed),
            misses: self.misses.load(Ordering::Relaxed),
            vram_evictions: self.vram_evictions.load(Ordering::Relaxed),
            ram_evictions: self.ram_evictions.load(Ordering::Relaxed),
            fragments_cached: self.entries.read().len() as u64,
        }
    }

    /// Returns VRAM used.
    pub fn vram_used(&self) -> u64 {
        self.vram_used.load(Ordering::Relaxed)
    }

    /// Returns RAM used.
    pub fn ram_used(&self) -> u64 {
        self.ram_used.load(Ordering::Relaxed)
    }

    /// Clears all cached fragments.
    pub fn clear(&self) {
        self.entries.write().clear();
        self.vram_used.store(0, Ordering::Relaxed);
        self.ram_used.store(0, Ordering::Relaxed);
    }

    /// Ensures capacity for a new entry, evicting if necessary.
    fn ensure_capacity(&self, size: u64, tier: CacheTier) {
        let (capacity, used) = match tier {
            CacheTier::Vram => (
                self.config.vram_capacity,
                self.vram_used.load(Ordering::Relaxed),
            ),
            CacheTier::Ram => (
                self.config.ram_capacity,
                self.ram_used.load(Ordering::Relaxed),
            ),
            CacheTier::None => return,
        };

        if used + size <= capacity {
            return;
        }

        // Need to evict - use LRU
        let needed = used + size - capacity;
        self.evict_lru(tier, needed);
    }

    /// Evicts least recently used entries.
    fn evict_lru(&self, tier: CacheTier, needed: u64) {
        let mut entries = self.entries.write();
        let mut candidates: Vec<_> = entries
            .iter()
            .filter(|(_, e)| e.tier == tier)
            .map(|(id, e)| (id.clone(), e.last_access, e.size, e.users.count()))
            .collect();

        // Sort by: shared count (evict non-shared first), then access time
        candidates.sort_by(|a, b| a.3.cmp(&b.3).then(a.1.cmp(&b.1)));

        let mut freed = 0u64;
        for (id, _, _size, _) in candidates {
            if freed >= needed {
                break;
            }

            if let Some(entry) = entries.remove(&id) {
                freed += entry.size;
                match tier {
                    CacheTier::Vram => {
                        self.vram_used.fetch_sub(entry.size, Ordering::Relaxed);
                        self.vram_evictions.fetch_add(1, Ordering::Relaxed);
                    },
                    CacheTier::Ram => {
                        self.ram_used.fetch_sub(entry.size, Ordering::Relaxed);
                        self.ram_evictions.fetch_add(1, Ordering::Relaxed);
                    },
                    CacheTier::None => {},
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_cache_insert_and_access() {
        let cache = FragmentCache::new(CacheConfig {
            vram_capacity: 1000,
            ram_capacity: 1000,
        });

        cache.insert("frag1", 100, CacheTier::Vram, true);
        assert!(cache.contains("frag1"));
        assert_eq!(cache.get_tier("frag1"), CacheTier::Vram);

        let tier = cache.access("frag1");
        assert_eq!(tier, CacheTier::Vram);

        let stats = cache.stats();
        assert_eq!(stats.hits, 1);
        assert_eq!(stats.vram_used, 100);
    }

    #[test]
    fn test_cache_miss() {
        let cache = FragmentCache::new(CacheConfig::default());

        let tier = cache.access("nonexistent");
        assert_eq!(tier, CacheTier::None);

        let stats = cache.stats();
        assert_eq!(stats.misses, 1);
    }

    #[test]
    fn test_cache_eviction() {
        let cache = FragmentCache::new(CacheConfig {
            vram_capacity: 200,
            ram_capacity: 1000,
        });

        cache.insert("frag1", 100, CacheTier::Vram, true);
        cache.insert("frag2", 100, CacheTier::Vram, true);

        // This should trigger eviction
        cache.insert("frag3", 100, CacheTier::Vram, true);

        let stats = cache.stats();
        assert!(stats.vram_evictions >= 1);
        assert!(stats.vram_used <= 200);
    }

    #[test]
    fn test_cache_promote_demote() {
        let cache = FragmentCache::new(CacheConfig {
            vram_capacity: 1000,
            ram_capacity: 1000,
        });

        cache.insert("frag1", 100, CacheTier::Ram, true);
        assert_eq!(cache.ram_used(), 100);
        assert_eq!(cache.vram_used(), 0);

        cache.promote("frag1", CacheTier::Vram);
        assert_eq!(cache.ram_used(), 0);
        assert_eq!(cache.vram_used(), 100);
        assert_eq!(cache.get_tier("frag1"), CacheTier::Vram);
    }

    #[test]
    fn test_hit_rate() {
        let stats = CacheStats {
            hits: 80,
            misses: 20,
            ..Default::default()
        };

        assert!((stats.hit_rate() - 0.8).abs() < 0.001);
    }
}