1use rlx_ir::quant::QuantScheme;
23use std::collections::HashMap;
24use std::sync::{Arc, OnceLock, RwLock};
25
26#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
27struct DequantKey {
28 k: u32,
29 n: u32,
30 scheme: u8,
31 bytes_hash: u64,
33}
34
35fn weight_bytes_hash(w_bytes: &[u8]) -> u64 {
36 use std::hash::{Hash, Hasher};
37 let mut hasher = std::collections::hash_map::DefaultHasher::new();
38 w_bytes.hash(&mut hasher);
39 hasher.finish()
40}
41
42fn scheme_tag(scheme: QuantScheme) -> u8 {
43 match scheme {
44 QuantScheme::GgufQ4K => 1,
45 QuantScheme::GgufQ5K => 2,
46 QuantScheme::GgufQ6K => 3,
47 QuantScheme::GgufQ8K => 4,
48 _ => 255,
49 }
50}
51
52fn dequant_gguf(w_bytes: &[u8], k: usize, n: usize, scheme: QuantScheme) -> Vec<f32> {
53 match scheme {
54 QuantScheme::GgufQ4K => rlx_gguf::dequant_q4_k(w_bytes, k * n),
55 QuantScheme::GgufQ5K => rlx_gguf::dequant_q5_k(w_bytes, k * n),
56 QuantScheme::GgufQ6K => rlx_gguf::dequant_q6_k(w_bytes, k * n),
57 QuantScheme::GgufQ8K => rlx_gguf::dequant_q8_k(w_bytes, k * n),
58 other => panic!("dequant_cache: unsupported GGUF scheme {other:?}"),
59 }
60 .expect("GGUF dequant failed")
61}
62
63static CACHE: OnceLock<RwLock<HashMap<DequantKey, Arc<[f32]>>>> = OnceLock::new();
64
65fn cache_enabled() -> bool {
66 !matches!(
67 rlx_ir::env::var("RLX_DEQUANT_CACHE").as_deref(),
68 Some("0") | Some("false") | Some("off")
69 )
70}
71
72pub fn gguf_weight_f32(
74 _w_off: usize,
75 w_bytes: &[u8],
76 k: usize,
77 n: usize,
78 scheme: QuantScheme,
79) -> Arc<[f32]> {
80 if !cache_enabled() {
81 return Arc::from(dequant_gguf(w_bytes, k, n, scheme).into_boxed_slice());
82 }
83 let key = DequantKey {
84 k: k as u32,
85 n: n as u32,
86 scheme: scheme_tag(scheme),
87 bytes_hash: weight_bytes_hash(w_bytes),
88 };
89 let cache = CACHE.get_or_init(|| RwLock::new(HashMap::new()));
90 if let Some(hit) = cache.read().expect("dequant cache poisoned").get(&key) {
91 return Arc::clone(hit);
92 }
93 let dense = dequant_gguf(w_bytes, k, n, scheme);
94 let arc: Arc<[f32]> = Arc::from(dense.into_boxed_slice());
95 cache
96 .write()
97 .expect("dequant cache poisoned")
98 .insert(key, Arc::clone(&arc));
99 arc
100}
101
102pub fn clear_dequant_cache() {
104 if let Some(c) = CACHE.get() {
105 c.write().expect("dequant cache poisoned").clear();
106 }
107}
108
109#[cfg(test)]
110mod tests {
111 use super::*;
112
113 #[test]
114 fn gguf_dequant_cache_hits_on_second_lookup() {
115 clear_dequant_cache();
116 const QK_K: usize = 256;
117 let mut packed = Vec::new();
118 packed.extend_from_slice(&half::f16::from_f32(1.0).to_le_bytes());
119 packed.extend_from_slice(&half::f16::from_f32(1.0).to_le_bytes());
120 let mut scales = [0u8; 12];
121 for s in &mut scales[0..4] {
122 *s = 0x01;
123 }
124 packed.extend_from_slice(&scales);
125 packed.extend(std::iter::repeat_n(0x77u8, QK_K / 2));
126 let k = 256;
127 let n = 1;
128 let w_off = 4096;
129 let hash = weight_bytes_hash(&packed);
130 let a = gguf_weight_f32(w_off, &packed, k, n, QuantScheme::GgufQ4K);
131 let b = gguf_weight_f32(w_off + 999, &packed, k, n, QuantScheme::GgufQ4K);
132 assert!(
133 Arc::ptr_eq(&a, &b),
134 "same bytes at different offsets should hit"
135 );
136 let mut other = packed.clone();
137 other[0] ^= 0x01;
138 let c = gguf_weight_f32(w_off, &other, k, n, QuantScheme::GgufQ4K);
139 assert!(!Arc::ptr_eq(&a, &c), "different bytes should miss: {hash}");
140 }
141}