oxibonsai-model 0.1.4

Qwen3-8B Transformer implementation for OxiBonsai 1-bit inference
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
//! On-disk model cache for fast model reloading.
//!
//! Caches quantized model weights + metadata in a binary format (`.oxcache`)
//! for faster cold-start loading vs. re-parsing GGUF files.
//!
//! Format:
//!   Header: `"OXCA"` (4 bytes) + version u32 + num\_entries u64 + metadata\_len u32
//!   Metadata: JSON string (hand-serialised, no serde)
//!   Per entry: name\_len u32 + name (UTF-8) + quant\_type\_len u32 + quant\_type + data\_len u64 + data bytes

use std::collections::HashMap;
use std::io::{BufReader, BufWriter, Read, Write};
use std::path::Path;
use std::time::SystemTime;

/// Magic bytes identifying an OxiBonsai disk cache file.
pub const CACHE_MAGIC: &[u8; 4] = b"OXCA";
/// Current cache format version.
pub const CACHE_VERSION: u32 = 1;

// ---------------------------------------------------------------------------
// Error
// ---------------------------------------------------------------------------

/// Errors produced by disk-cache operations.
#[derive(Debug, thiserror::Error)]
pub enum DiskCacheError {
    /// Underlying I/O failure.
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),
    /// File does not start with `OXCA`.
    #[error("invalid cache magic")]
    InvalidMagic,
    /// Cache file was written by a newer/older incompatible version.
    #[error("unsupported cache version: {0}")]
    UnsupportedVersion(u32),
    /// Hand-rolled JSON metadata could not be parsed.
    #[error("metadata parse error: {0}")]
    MetadataParse(String),
    /// Cache is older than its source file.
    #[error("cache is stale")]
    StaleCache,
}

// ---------------------------------------------------------------------------
// CacheEntry
// ---------------------------------------------------------------------------

/// An entry in the disk cache, representing one named tensor blob.
#[derive(Debug, Clone)]
pub struct CacheEntry {
    /// Tensor / weight name (e.g. `"layers.0.attn.q_proj"`).
    pub name: String,
    /// Raw bytes of the (possibly quantized) tensor data.
    pub data: Vec<u8>,
    /// Quantization format identifier (e.g. `"f32"`, `"int8"`, `"q1_0_g128"`).
    pub quant_type: String,
}

impl CacheEntry {
    /// Create a new cache entry.
    pub fn new(name: impl Into<String>, data: Vec<u8>, quant_type: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            data,
            quant_type: quant_type.into(),
        }
    }

    /// Total size of the raw data in bytes.
    pub fn size_bytes(&self) -> usize {
        self.data.len()
    }
}

// ---------------------------------------------------------------------------
// DiskCache
// ---------------------------------------------------------------------------

/// In-memory representation of a `.oxcache` file.
#[derive(Debug)]
pub struct DiskCache {
    entries: Vec<CacheEntry>,
    metadata: HashMap<String, String>,
}

impl Default for DiskCache {
    fn default() -> Self {
        Self::new()
    }
}

impl DiskCache {
    /// Create an empty cache.
    pub fn new() -> Self {
        Self {
            entries: Vec::new(),
            metadata: HashMap::new(),
        }
    }

    /// Append an entry.
    pub fn add_entry(&mut self, entry: CacheEntry) {
        self.entries.push(entry);
    }

    /// Set a metadata key-value pair.
    pub fn set_metadata(&mut self, key: impl Into<String>, value: impl Into<String>) {
        self.metadata.insert(key.into(), value.into());
    }

    /// Look up a metadata value.
    pub fn get_metadata(&self, key: &str) -> Option<&str> {
        self.metadata.get(key).map(|s| s.as_str())
    }

    /// Find an entry by name.
    pub fn get_entry(&self, name: &str) -> Option<&CacheEntry> {
        self.entries.iter().find(|e| e.name == name)
    }

    /// Number of entries.
    pub fn num_entries(&self) -> usize {
        self.entries.len()
    }

    /// Sum of all entry data sizes.
    pub fn total_data_bytes(&self) -> usize {
        self.entries.iter().map(|e| e.data.len()).sum()
    }

    // ----- persistence -----

    /// Save to a file path.
    pub fn save(&self, path: &Path) -> Result<(), DiskCacheError> {
        let file = std::fs::File::create(path)?;
        let mut writer = BufWriter::new(file);
        self.write_to(&mut writer)
    }

    /// Load from a file path.
    pub fn load(path: &Path) -> Result<Self, DiskCacheError> {
        let file = std::fs::File::open(path)?;
        let mut reader = BufReader::new(file);
        Self::read_from(&mut reader)
    }

    /// Serialize to an arbitrary writer.
    pub fn write_to<W: Write>(&self, writer: &mut W) -> Result<(), DiskCacheError> {
        // Magic
        writer.write_all(CACHE_MAGIC)?;

        // Version (u32 LE)
        writer.write_all(&CACHE_VERSION.to_le_bytes())?;

        // Number of entries (u64 LE)
        writer.write_all(&(self.entries.len() as u64).to_le_bytes())?;

        // Metadata as JSON string
        let meta_json = metadata_to_json(&self.metadata);
        let meta_bytes = meta_json.as_bytes();
        writer.write_all(&(meta_bytes.len() as u32).to_le_bytes())?;
        writer.write_all(meta_bytes)?;

        // Entries
        for entry in &self.entries {
            // name
            let name_bytes = entry.name.as_bytes();
            writer.write_all(&(name_bytes.len() as u32).to_le_bytes())?;
            writer.write_all(name_bytes)?;

            // quant_type
            let qt_bytes = entry.quant_type.as_bytes();
            writer.write_all(&(qt_bytes.len() as u32).to_le_bytes())?;
            writer.write_all(qt_bytes)?;

            // data
            writer.write_all(&(entry.data.len() as u64).to_le_bytes())?;
            writer.write_all(&entry.data)?;
        }

        writer.flush()?;
        Ok(())
    }

    /// Deserialize from an arbitrary reader.
    pub fn read_from<R: Read>(reader: &mut R) -> Result<Self, DiskCacheError> {
        // Magic
        let mut magic = [0u8; 4];
        reader.read_exact(&mut magic)?;
        if &magic != CACHE_MAGIC {
            return Err(DiskCacheError::InvalidMagic);
        }

        // Version
        let mut buf4 = [0u8; 4];
        reader.read_exact(&mut buf4)?;
        let version = u32::from_le_bytes(buf4);
        if version != CACHE_VERSION {
            return Err(DiskCacheError::UnsupportedVersion(version));
        }

        // Num entries
        let mut buf8 = [0u8; 8];
        reader.read_exact(&mut buf8)?;
        let num_entries = u64::from_le_bytes(buf8) as usize;

        // Metadata
        reader.read_exact(&mut buf4)?;
        let meta_len = u32::from_le_bytes(buf4) as usize;
        let mut meta_buf = vec![0u8; meta_len];
        reader.read_exact(&mut meta_buf)?;
        let meta_str = String::from_utf8(meta_buf)
            .map_err(|e| DiskCacheError::MetadataParse(e.to_string()))?;
        let metadata = metadata_from_json(&meta_str)?;

        // Entries
        let mut entries = Vec::with_capacity(num_entries);
        for _ in 0..num_entries {
            // name
            reader.read_exact(&mut buf4)?;
            let name_len = u32::from_le_bytes(buf4) as usize;
            let mut name_buf = vec![0u8; name_len];
            reader.read_exact(&mut name_buf)?;
            let name = String::from_utf8(name_buf)
                .map_err(|e| DiskCacheError::MetadataParse(e.to_string()))?;

            // quant_type
            reader.read_exact(&mut buf4)?;
            let qt_len = u32::from_le_bytes(buf4) as usize;
            let mut qt_buf = vec![0u8; qt_len];
            reader.read_exact(&mut qt_buf)?;
            let quant_type = String::from_utf8(qt_buf)
                .map_err(|e| DiskCacheError::MetadataParse(e.to_string()))?;

            // data
            reader.read_exact(&mut buf8)?;
            let data_len = u64::from_le_bytes(buf8) as usize;
            let mut data = vec![0u8; data_len];
            reader.read_exact(&mut data)?;

            entries.push(CacheEntry {
                name,
                data,
                quant_type,
            });
        }

        Ok(Self { entries, metadata })
    }

    /// Check if a cache file exists and has valid magic + version.
    pub fn is_valid_cache(path: &Path) -> bool {
        let file = match std::fs::File::open(path) {
            Ok(f) => f,
            Err(_) => return false,
        };
        let mut reader = BufReader::new(file);

        let mut magic = [0u8; 4];
        if reader.read_exact(&mut magic).is_err() {
            return false;
        }
        if &magic != CACHE_MAGIC {
            return false;
        }

        let mut buf4 = [0u8; 4];
        if reader.read_exact(&mut buf4).is_err() {
            return false;
        }
        let version = u32::from_le_bytes(buf4);
        version == CACHE_VERSION
    }

    /// Returns `Ok(true)` if the cache file is newer than the source file.
    pub fn is_fresh(cache_path: &Path, source_path: &Path) -> Result<bool, DiskCacheError> {
        let cache_meta = std::fs::metadata(cache_path)?;
        let source_meta = std::fs::metadata(source_path)?;

        let cache_time = cache_meta.modified().map_err(DiskCacheError::Io)?;
        let source_time = source_meta.modified().map_err(DiskCacheError::Io)?;

        Ok(cache_time >= source_time)
    }
}

// ---------------------------------------------------------------------------
// CacheManager
// ---------------------------------------------------------------------------

/// Manages multiple cached model files with LRU eviction.
#[derive(Debug)]
pub struct CacheManager {
    cache_dir: String,
    max_cache_size_bytes: usize,
    entries: Vec<CacheFileInfo>,
}

/// Information about one cached model file on disk.
#[derive(Debug, Clone)]
pub struct CacheFileInfo {
    /// Absolute path to the `.oxcache` file.
    pub path: String,
    /// Size on disk in bytes.
    pub size_bytes: usize,
    /// Last time this cache was accessed / loaded.
    pub last_accessed: SystemTime,
    /// Human-readable model name.
    pub model_name: String,
}

impl CacheManager {
    /// Create a new manager for the given directory with a byte budget.
    pub fn new(cache_dir: impl Into<String>, max_size_bytes: usize) -> Self {
        Self {
            cache_dir: cache_dir.into(),
            max_cache_size_bytes: max_size_bytes,
            entries: Vec::new(),
        }
    }

    /// Register a cached file.
    pub fn register(&mut self, info: CacheFileInfo) {
        self.entries.push(info);
    }

    /// Total bytes used by all registered cache files.
    pub fn total_used_bytes(&self) -> usize {
        self.entries.iter().map(|e| e.size_bytes).sum()
    }

    /// Whether total usage exceeds the budget.
    pub fn should_evict(&self) -> bool {
        self.total_used_bytes() > self.max_cache_size_bytes
    }

    /// Candidates for eviction, sorted oldest-first (LRU).
    pub fn eviction_candidates(&self) -> Vec<&CacheFileInfo> {
        let mut sorted: Vec<&CacheFileInfo> = self.entries.iter().collect();
        sorted.sort_by_key(|e| e.last_accessed);
        sorted
    }

    /// Fraction of budget used (0.0 – 1.0+).
    pub fn utilization(&self) -> f32 {
        if self.max_cache_size_bytes == 0 {
            return 0.0;
        }
        self.total_used_bytes() as f32 / self.max_cache_size_bytes as f32
    }

    /// Human-readable summary.
    pub fn summary(&self) -> String {
        let used_mb = self.total_used_bytes() as f64 / (1024.0 * 1024.0);
        let max_mb = self.max_cache_size_bytes as f64 / (1024.0 * 1024.0);
        let pct = self.utilization() * 100.0;
        format!(
            "Cache dir: {dir}, {n} models, {used:.1}/{max:.1} MB ({pct:.1}%)",
            dir = self.cache_dir,
            n = self.entries.len(),
            used = used_mb,
            max = max_mb,
        )
    }
}

// ---------------------------------------------------------------------------
// Manual JSON helpers (no serde)
// ---------------------------------------------------------------------------

/// Serialize a `HashMap<String, String>` to a JSON object string.
fn metadata_to_json(map: &HashMap<String, String>) -> String {
    let mut out = String::from("{");
    let mut first = true;
    // Sort keys for deterministic output.
    let mut keys: Vec<&String> = map.keys().collect();
    keys.sort();
    for key in keys {
        let value = &map[key];
        if !first {
            out.push(',');
        }
        first = false;
        out.push('"');
        json_escape_into(&mut out, key);
        out.push_str("\":\"");
        json_escape_into(&mut out, value);
        out.push('"');
    }
    out.push('}');
    out
}

/// Deserialize a JSON object string to `HashMap<String, String>`.
fn metadata_from_json(s: &str) -> Result<HashMap<String, String>, DiskCacheError> {
    let s = s.trim();
    if s == "{}" || s.is_empty() {
        return Ok(HashMap::new());
    }
    let bytes = s.as_bytes();
    if bytes.first() != Some(&b'{') || bytes.last() != Some(&b'}') {
        return Err(DiskCacheError::MetadataParse(format!(
            "expected JSON object, got: {s}"
        )));
    }
    let inner = &s[1..s.len() - 1];
    let mut map = HashMap::new();
    if inner.trim().is_empty() {
        return Ok(map);
    }

    let chars: Vec<char> = inner.chars().collect();
    let mut pos = 0usize;

    loop {
        // Skip whitespace / commas.
        while pos < chars.len() && (chars[pos] == ',' || chars[pos].is_whitespace()) {
            pos += 1;
        }
        if pos >= chars.len() {
            break;
        }
        if chars[pos] != '"' {
            return Err(DiskCacheError::MetadataParse(format!(
                "expected '\"' at position {pos}, got '{}'",
                chars[pos]
            )));
        }
        pos += 1;
        let (key, new_pos) = parse_json_string(&chars, pos)?;
        pos = new_pos;

        // Skip ws, expect ':'
        skip_ws(&chars, &mut pos);
        if pos >= chars.len() || chars[pos] != ':' {
            return Err(DiskCacheError::MetadataParse(format!(
                "expected ':' after key '{key}'"
            )));
        }
        pos += 1;
        skip_ws(&chars, &mut pos);

        if pos >= chars.len() || chars[pos] != '"' {
            return Err(DiskCacheError::MetadataParse(format!(
                "expected '\"' for value of key '{key}'"
            )));
        }
        pos += 1;
        let (value, new_pos) = parse_json_string(&chars, pos)?;
        pos = new_pos;

        map.insert(key, value);
    }

    Ok(map)
}

fn parse_json_string(chars: &[char], mut pos: usize) -> Result<(String, usize), DiskCacheError> {
    let mut s = String::new();
    while pos < chars.len() {
        match chars[pos] {
            '"' => {
                pos += 1;
                return Ok((s, pos));
            }
            '\\' => {
                pos += 1;
                if pos >= chars.len() {
                    return Err(DiskCacheError::MetadataParse(
                        "unexpected end after backslash".into(),
                    ));
                }
                match chars[pos] {
                    '"' => s.push('"'),
                    '\\' => s.push('\\'),
                    'n' => s.push('\n'),
                    'r' => s.push('\r'),
                    't' => s.push('\t'),
                    other => {
                        return Err(DiskCacheError::MetadataParse(format!(
                            "unknown escape '\\{other}'"
                        )));
                    }
                }
                pos += 1;
            }
            ch => {
                s.push(ch);
                pos += 1;
            }
        }
    }
    Err(DiskCacheError::MetadataParse("unterminated string".into()))
}

fn skip_ws(chars: &[char], pos: &mut usize) {
    while *pos < chars.len() && chars[*pos].is_whitespace() {
        *pos += 1;
    }
}

fn json_escape_into(out: &mut String, s: &str) {
    for ch in s.chars() {
        match ch {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c => out.push(c),
        }
    }
}