Skip to main content

fuel_tensor/
const_residency.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Device-resident weight storages kept by the identity of the host array they were built from
3//! (ROADMAP row 172).
4//!
5//! A prefill (`forward_with_kv_context`) builds a fresh graph on every call, so every weight `Const`
6//! is a new node with a new `NodeId` and a `NodeId`-keyed cache can never hit. What does not change is
7//! the shared host `Arc<[T]>` the weight was built from; `fuel_graph::ConstOrigin` records its identity
8//! and this registry keys the uploaded device storage by it. One registry belongs to one
9//! [`Device`](crate::Device) (every clone of it shares the registry), so a consumer that makes a new
10//! `InferenceContext` per sequence still finds the model already resident.
11//!
12//! Soundness: an entry keeps a strong pin on the source array, so the array's address cannot be
13//! reused while the entry exists, the array cannot be mutated in place (`Arc::get_mut` fails while the
14//! pin is held), and an immutable `Arc<[T]>` with the same address and length is the same bytes. A
15//! `Const` built from a per-call array has no live source ([`fuel_graph::ConstOrigin::pin`] returns
16//! `None`) and is never registered, so per-token data cannot accumulate here.
17//!
18//! Budget: the registry holds at most a byte cap (set by the device before every seeding: a stated
19//! share of the device's memory, see `inference_context`); past it the least recently used entries
20//! are evicted, and a weight larger than the whole cap is served to the one realize that uploaded it
21//! but never retained. A device that cannot report its memory gets no residency at all.
22//!
23//! Lifetime: an entry whose source array nothing else holds (the model was dropped) is evicted by
24//! [`WeightResidency::sweep_orphans`], which runs at the start of every seeding, so a model swap does
25//! not grow the registry. [`Device::clear_weight_residency`](crate::Device::clear_weight_residency)
26//! drops everything at once, and dropping the last clone of the `Device` drops the registry.
27
28use std::collections::HashMap;
29use std::sync::{Arc, Mutex, RwLock};
30
31use fuel_graph::{ConstOrigin, ConstOriginKey};
32use fuel_ir::Result;
33use fuel_memory::Storage;
34
35/// Counters of a device's weight residency (see [`Device::weight_residency_stats`](crate::Device::weight_residency_stats)).
36#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
37#[non_exhaustive]
38pub struct WeightResidencyStats {
39    /// Weight `Const`s served from an earlier upload.
40    pub hits: u64,
41    /// Weight `Const`s uploaded (each one a miss that became resident).
42    pub uploads: u64,
43    /// Entries dropped because their source array was no longer held by anything else.
44    pub evicted: u64,
45    /// Entries resident now.
46    pub resident: usize,
47    /// Bytes resident now (the sum of the entries' source-array sizes).
48    pub resident_bytes: u64,
49    /// Entries evicted to stay under the byte cap (a subset of `evicted`).
50    pub evicted_for_budget: u64,
51    /// Weights uploaded but not retained because one weight alone exceeded the whole cap.
52    pub rejected: u64,
53    /// The byte cap in force at the last seeding (`0` before any seeding).
54    pub cap_bytes: u64,
55}
56
57struct Resident<S> {
58    bytes: u64,
59    last_used: u64,
60    origin: ConstOrigin,
61    /// Keeps the source array alive for as long as its key is trusted.
62    _pin: Box<dyn std::any::Any + Send + Sync>,
63    storage: S,
64}
65
66/// Registry of uploaded weights, generic over the storage handle so the logic is testable without a GPU.
67pub(crate) struct WeightResidency<S> {
68    entries: HashMap<ConstOriginKey, Resident<S>>,
69    hits: u64,
70    uploads: u64,
71    evicted: u64,
72    evicted_for_budget: u64,
73    rejected: u64,
74    resident_bytes: u64,
75    /// Monotonic use counter: an entry's `last_used` is the tick of its latest hit or insert.
76    tick: u64,
77    /// Byte cap for what stays resident; `None` means no cap (only tests build that).
78    cap: Option<u64>,
79}
80
81/// Bytes of the host array a weight was built from.
82fn origin_bytes(origin: &ConstOrigin) -> u64 {
83    let k = origin.key();
84    (k.len as u64).saturating_mul(k.dtype.size_in_bytes() as u64)
85}
86
87impl<S: Clone> WeightResidency<S> {
88    pub(crate) fn new() -> Self {
89        Self {
90            entries: HashMap::new(),
91            hits: 0,
92            uploads: 0,
93            evicted: 0,
94            evicted_for_budget: 0,
95            rejected: 0,
96            resident_bytes: 0,
97            tick: 0,
98            cap: None,
99        }
100    }
101
102    /// Set the byte cap; a lowered cap takes effect at the next insert.
103    pub(crate) fn set_cap(&mut self, cap: Option<u64>) {
104        self.cap = cap;
105    }
106
107    /// Evict least recently used entries until `incoming` more bytes fit under the cap.
108    fn make_room(&mut self, incoming: u64) {
109        let Some(cap) = self.cap else { return };
110        while self.resident_bytes.saturating_add(incoming) > cap {
111            let Some(oldest) = self
112                .entries
113                .iter()
114                .min_by_key(|(_, r)| r.last_used)
115                .map(|(k, _)| *k)
116            else {
117                break;
118            };
119            if let Some(r) = self.entries.remove(&oldest) {
120                self.resident_bytes -= r.bytes;
121                self.evicted += 1;
122                self.evicted_for_budget += 1;
123            }
124        }
125    }
126
127    /// Drop every entry whose source array nothing but this registry's pin holds any more.
128    pub(crate) fn sweep_orphans(&mut self) -> usize {
129        let before = self.entries.len();
130        let mut freed = 0u64;
131        self.entries.retain(|_, r| {
132            let keep = r.origin.strong_count() > 1;
133            if !keep {
134                freed += r.bytes;
135            }
136            keep
137        });
138        self.resident_bytes -= freed;
139        let gone = before - self.entries.len();
140        self.evicted += gone as u64;
141        gone
142    }
143
144    /// Drop every entry.
145    pub(crate) fn clear(&mut self) {
146        self.evicted += self.entries.len() as u64;
147        self.entries.clear();
148        self.resident_bytes = 0;
149    }
150
151    /// The resident storage for `origin`, calling `upload` exactly once per live source array.
152    /// `Ok(None)` means the source is gone (a per-call array): the caller must not treat it as a weight.
153    pub(crate) fn get_or_upload(
154        &mut self,
155        origin: &ConstOrigin,
156        upload: impl FnOnce() -> Result<S>,
157    ) -> Result<Option<S>> {
158        self.tick += 1;
159        if let Some(r) = self.entries.get_mut(&origin.key()) {
160            self.hits += 1;
161            r.last_used = self.tick;
162            return Ok(Some(r.storage.clone()));
163        }
164        let Some(pin) = origin.pin() else {
165            return Ok(None);
166        };
167        let storage = upload()?;
168        self.uploads += 1;
169        let bytes = origin_bytes(origin);
170        if self.cap.is_some_and(|cap| bytes > cap) {
171            // One weight alone is bigger than the whole budget: this realize uses it, nobody keeps it.
172            self.rejected += 1;
173            return Ok(Some(storage));
174        }
175        self.make_room(bytes);
176        self.resident_bytes += bytes;
177        self.entries.insert(
178            origin.key(),
179            Resident {
180                bytes,
181                last_used: self.tick,
182                origin: origin.clone(),
183                _pin: pin,
184                storage: storage.clone(),
185            },
186        );
187        Ok(Some(storage))
188    }
189
190    pub(crate) fn stats(&self) -> WeightResidencyStats {
191        WeightResidencyStats {
192            hits: self.hits,
193            uploads: self.uploads,
194            evicted: self.evicted,
195            resident: self.entries.len(),
196            resident_bytes: self.resident_bytes,
197            evicted_for_budget: self.evicted_for_budget,
198            rejected: self.rejected,
199            cap_bytes: self.cap.unwrap_or(0),
200        }
201    }
202}
203
204/// The registry a [`Device`](crate::Device) carries: uploaded weight storages, shared by every clone.
205pub(crate) struct DeviceWeights(pub(crate) Mutex<WeightResidency<Arc<RwLock<Storage>>>>);
206
207impl DeviceWeights {
208    pub(crate) fn new() -> Self {
209        Self(Mutex::new(WeightResidency::new()))
210    }
211}
212
213impl std::fmt::Debug for DeviceWeights {
214    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
215        let stats = self.0.lock().unwrap_or_else(|p| p.into_inner()).stats();
216        f.debug_tuple("DeviceWeights").field(&stats).finish()
217    }
218}
219
220#[cfg(test)]
221mod tests {
222    use super::*;
223    use fuel_graph::NodeHandle;
224    use std::sync::Arc;
225
226    /// The origin a `Const` built from `data` records, read back through the graph.
227    fn origin_of(data: &Arc<[u32]>) -> ConstOrigin {
228        let dev = crate::Device::cpu();
229        let t = NodeHandle::from_u32(
230            Arc::clone(data),
231            fuel_ir::Shape::from_dims(&[data.len()]),
232            dev.as_dyn(),
233        )
234        .unwrap();
235        let g = t.graph().read().unwrap();
236        g.const_origins()
237            .next()
238            .map(|(_, o)| o.clone())
239            .expect("a Const built from an Arc records its origin")
240    }
241
242    #[test]
243    fn the_same_source_uploads_once_across_graphs() {
244        let w: Arc<[u32]> = vec![1, 2, 3, 4].into();
245        let mut r = WeightResidency::<u32>::new();
246        let mut calls = 0;
247        // Two DIFFERENT graphs (two `from_u32` calls), one source array.
248        for _ in 0..3 {
249            let o = origin_of(&w);
250            let got = r
251                .get_or_upload(&o, || {
252                    calls += 1;
253                    Ok(7)
254                })
255                .unwrap();
256            assert_eq!(got, Some(7));
257        }
258        assert_eq!(
259            calls, 1,
260            "one upload for one live source, however many graphs"
261        );
262        assert_eq!((r.stats().hits, r.stats().uploads), (2, 1));
263    }
264
265    /// The sabotage sibling: two different live arrays are two entries, never one (a key that ignored the
266    /// address would serve one weight's storage for the other).
267    #[test]
268    fn different_sources_do_not_share_a_storage() {
269        let a: Arc<[u32]> = vec![1, 2, 3, 4].into();
270        let b: Arc<[u32]> = vec![1, 2, 3, 4].into(); // equal bytes, different allocation
271        let mut r = WeightResidency::<u32>::new();
272        let sa = r.get_or_upload(&origin_of(&a), || Ok(1)).unwrap();
273        let sb = r.get_or_upload(&origin_of(&b), || Ok(2)).unwrap();
274        assert_eq!((sa, sb), (Some(1), Some(2)));
275        assert_eq!(r.stats().resident, 2);
276    }
277
278    /// A per-call array (its source already dropped) is never registered: per-token data cannot pile up.
279    #[test]
280    fn a_dropped_source_is_not_registered() {
281        let w: Arc<[u32]> = vec![9, 9].into();
282        let o = origin_of(&w);
283        drop(w);
284        let mut r = WeightResidency::<u32>::new();
285        let mut called = false;
286        let got = r
287            .get_or_upload(&o, || {
288                called = true;
289                Ok(0)
290            })
291            .unwrap();
292        assert_eq!(got, None);
293        assert!(!called && r.stats().resident == 0);
294    }
295
296    /// An entry pins its source: while it exists the array stays alive, so its address cannot be reused.
297    #[test]
298    fn an_entry_keeps_its_source_alive() {
299        let w: Arc<[u32]> = vec![5, 6].into();
300        let weak = Arc::downgrade(&w);
301        let mut r = WeightResidency::<u32>::new();
302        r.get_or_upload(&origin_of(&w), || Ok(3)).unwrap();
303        drop(w);
304        assert!(
305            weak.upgrade().is_some(),
306            "the registry pin must keep the array alive"
307        );
308        drop(r);
309        assert!(
310            weak.upgrade().is_none(),
311            "dropping the registry releases it"
312        );
313    }
314
315    // ---- LIFETIME ----
316
317    /// Dropping the model (the last holder of the source array) lets the sweep evict its entry, which
318    /// releases both the storage and the pin on the source.
319    #[test]
320    fn a_dropped_model_is_swept_and_its_storage_released() {
321        let w: Arc<[u32]> = vec![1, 2, 3].into();
322        let weak_src = Arc::downgrade(&w);
323        let storage = Arc::new(7u32);
324        let mut r = WeightResidency::<Arc<u32>>::new();
325        r.get_or_upload(&origin_of(&w), || Ok(Arc::clone(&storage)))
326            .unwrap();
327        assert_eq!(Arc::strong_count(&storage), 2, "registry holds one handle");
328        // The model still holds `w`: nothing to sweep.
329        assert_eq!(r.sweep_orphans(), 0);
330        assert_eq!(r.stats().resident, 1);
331        drop(w); // the model is unloaded
332        assert_eq!(r.sweep_orphans(), 1);
333        let st = r.stats();
334        assert_eq!(
335            (
336                st.hits,
337                st.uploads,
338                st.evicted,
339                st.resident,
340                st.resident_bytes
341            ),
342            (0, 1, 1, 0, 0)
343        );
344        assert_eq!(
345            Arc::strong_count(&storage),
346            1,
347            "the storage handle is released"
348        );
349        assert!(
350            weak_src.upgrade().is_none(),
351            "the source array is released too"
352        );
353    }
354
355    /// `clear` releases everything at once, models still loaded or not.
356    #[test]
357    fn clear_releases_every_storage() {
358        let ws: Vec<Arc<[u32]>> = (0..4u32).map(|i| vec![i, i + 1].into()).collect();
359        let storage = Arc::new(0u32);
360        let mut r = WeightResidency::<Arc<u32>>::new();
361        for w in &ws {
362            r.get_or_upload(&origin_of(w), || Ok(Arc::clone(&storage)))
363                .unwrap();
364        }
365        assert_eq!(Arc::strong_count(&storage), 5);
366        r.clear();
367        assert_eq!(Arc::strong_count(&storage), 1);
368        assert_eq!(r.stats().resident, 0);
369        assert_eq!(r.stats().evicted, 4);
370    }
371
372    /// A model swap loop (load, serve, drop, repeat) keeps the registry at one model's worth, never growing.
373    #[test]
374    fn a_model_swap_loop_does_not_grow_the_registry() {
375        let mut r = WeightResidency::<u32>::new();
376        let mut high_water = 0;
377        for model in 0..50u32 {
378            let weights: Vec<Arc<[u32]>> = (0..6u32)
379                .map(|i| vec![model, i, model ^ i, 1].into())
380                .collect();
381            r.sweep_orphans(); // what the device does at the start of every seeding
382            for w in &weights {
383                r.get_or_upload(&origin_of(w), || Ok(model)).unwrap();
384            }
385            high_water = high_water.max(r.stats().resident);
386            // the model is dropped here, at the end of the iteration
387        }
388        r.sweep_orphans();
389        assert_eq!(r.stats().resident, 0, "the last model dropped too");
390        assert!(
391            high_water <= 6,
392            "one model's worth (6) at a time, saw {high_water}"
393        );
394        assert_eq!(r.stats().uploads, 300);
395        assert_eq!(r.stats().evicted, 300);
396    }
397
398    // ---- IDENTITY ----
399
400    /// The address of a registered weight cannot be reused by a new array while the entry lives, so a
401    /// new array with different content can never alias a stale entry. Several thousand same-size
402    /// allocations are tried to make the allocator hand the old address back; a hit on any of them
403    /// would serve the OLD storage for the NEW bytes. (The mutant that drops the pin is run against this
404    /// in the row 172 notes: it goes red.)
405    #[test]
406    fn a_reused_address_is_never_a_hit() {
407        let a: Arc<[u32]> = vec![1, 1, 1, 1].into();
408        let old_ptr = a.as_ptr() as usize;
409        let mut r = WeightResidency::<u32>::new();
410        r.get_or_upload(&origin_of(&a), || Ok(100)).unwrap();
411        drop(a); // the model drops its handle; the registry's pin is all that is left
412        let mut keep = Vec::new();
413        let mut landed_on_old_address = false;
414        for i in 0..4000u32 {
415            let b: Arc<[u32]> = vec![i, 2, 2, 2].into(); // different bytes, same length
416            if b.as_ptr() as usize == old_ptr {
417                landed_on_old_address = true;
418            }
419            let got = r.get_or_upload(&origin_of(&b), || Ok(200 + i)).unwrap();
420            assert_eq!(
421                got,
422                Some(200 + i),
423                "iteration {i}: a new array must be uploaded, never served the old storage"
424            );
425            keep.push(b);
426        }
427        assert!(
428            !landed_on_old_address,
429            "the pin must keep the old address from being reused"
430        );
431    }
432
433    /// A registered weight cannot be mutated in place: the registry's pin makes the array shared, so
434    /// `Arc::get_mut` (the only in-place route for an `Arc<[T]>`) refuses. A replacement array with
435    /// equal content but its own allocation is a different weight and is uploaded afresh.
436    #[test]
437    fn a_pinned_weight_cannot_be_mutated_in_place() {
438        let mut w: Arc<[u32]> = vec![4, 5, 6].into();
439        assert!(Arc::get_mut(&mut w).is_some(), "unique before registration");
440        let mut r = WeightResidency::<u32>::new();
441        r.get_or_upload(&origin_of(&w), || Ok(1)).unwrap();
442        assert!(
443            Arc::get_mut(&mut w).is_none(),
444            "the registry pin must make in-place mutation impossible"
445        );
446        let copy: Arc<[u32]> = w.iter().copied().collect::<Vec<_>>().into();
447        let got = r.get_or_upload(&origin_of(&copy), || Ok(2)).unwrap();
448        assert_eq!(got, Some(2), "an equal-content copy is a distinct weight");
449    }
450
451    // ---- BYTE BUDGET ----
452
453    /// A 4-element `u32` array is 16 bytes.
454    fn arr(tag: u32) -> Arc<[u32]> {
455        vec![tag, tag + 1, tag + 2, tag + 3].into()
456    }
457
458    /// The registry never holds more than the cap and evicts the least recently used entry first; a hit
459    /// refreshes an entry. This test FAILS when the cap enforcement is removed (see the row 172 notes).
460    #[test]
461    fn the_byte_cap_holds_and_evicts_least_recently_used() {
462        let (a, b, c, d) = (arr(0), arr(10), arr(20), arr(30));
463        let mut r = WeightResidency::<u32>::new();
464        r.set_cap(Some(40)); // room for two 16-byte weights
465        r.get_or_upload(&origin_of(&a), || Ok(1)).unwrap();
466        r.get_or_upload(&origin_of(&b), || Ok(2)).unwrap();
467        assert_eq!((r.stats().resident, r.stats().resident_bytes), (2, 32));
468        r.get_or_upload(&origin_of(&c), || Ok(3)).unwrap(); // a is the least recently used
469        let st = r.stats();
470        assert!(
471            st.resident_bytes <= 40,
472            "over the cap: {} bytes",
473            st.resident_bytes
474        );
475        assert_eq!((st.resident, st.evicted_for_budget), (2, 1));
476        // `a` went; `b` is still a hit (and is now the most recently used).
477        assert_eq!(r.get_or_upload(&origin_of(&b), || Ok(99)).unwrap(), Some(2));
478        r.get_or_upload(&origin_of(&d), || Ok(4)).unwrap(); // evicts `c`, the least recently used now
479        assert_eq!(
480            r.get_or_upload(&origin_of(&b), || Ok(99)).unwrap(),
481            Some(2),
482            "b was refreshed, so it stays"
483        );
484        assert_eq!(
485            r.get_or_upload(&origin_of(&c), || Ok(33)).unwrap(),
486            Some(33),
487            "c was the least recently used, so it is a miss again"
488        );
489        assert!(r.stats().resident_bytes <= 40);
490    }
491
492    /// One weight bigger than the whole cap is handed to the realize that uploaded it and never kept.
493    #[test]
494    fn a_weight_larger_than_the_cap_is_served_but_not_kept() {
495        let big = arr(0); // 16 bytes
496        let mut r = WeightResidency::<u32>::new();
497        r.set_cap(Some(8));
498        let o = origin_of(&big);
499        assert_eq!(r.get_or_upload(&o, || Ok(5)).unwrap(), Some(5));
500        assert_eq!(
501            r.get_or_upload(&o, || Ok(6)).unwrap(),
502            Some(6),
503            "uploaded again: it was not kept"
504        );
505        let st = r.stats();
506        assert_eq!(
507            (st.resident, st.resident_bytes, st.rejected, st.uploads),
508            (0, 0, 2, 2)
509        );
510    }
511
512    /// `resident_bytes` follows sweeps and clears, so a freed model gives its budget back.
513    #[test]
514    fn freed_models_give_their_budget_back() {
515        let a = arr(0);
516        let mut r = WeightResidency::<u32>::new();
517        r.set_cap(Some(100));
518        r.get_or_upload(&origin_of(&a), || Ok(1)).unwrap();
519        assert_eq!(r.stats().resident_bytes, 16);
520        drop(a);
521        r.sweep_orphans();
522        assert_eq!(r.stats().resident_bytes, 0);
523        let b = arr(5);
524        r.get_or_upload(&origin_of(&b), || Ok(2)).unwrap();
525        r.clear();
526        assert_eq!(r.stats().resident_bytes, 0);
527    }
528}