Skip to main content

cubecl_server/
metadata_cache.rs

1//! Cache of per-launch **metadata info buffers** (kernel shapes, strides and
2//! scalars) keyed by the exact info bytes they were built from (see
3//! [`InfoCacheKey`]).
4//!
5//! Info depends only on shapes and scalar arguments — not on the tensor data
6//! pointers, which are separate kernel arguments — so two launches with identical
7//! info, even of different kernels, can share one read-only device buffer. Caching those
8//! buffers removes a fresh allocation and a host→device copy from every launch,
9//! and it is what makes hardware graph capture clean: a stable-shape decode's
10//! launches all hit warm buffers, so nothing is allocated or copied inside the
11//! capture window (a device allocation mid-capture is illegal).
12//!
13//! [`MetadataCachePolicy`] owns every decision: whether a given metadata info is
14//! worth caching at all (small enough, and the cache enabled) and how many
15//! entries to keep before the least-recently-used one is evicted. Its two knobs,
16//! `max_entries` and `max_cached_size`, are tuned by the backend. The current
17//! [`CacheMode`] feeds into those same decisions — during graph capture the
18//! policy caches everything and evicts nothing — so the runtime never has to
19//! special-case capture: it just asks the policy and follows the answer.
20//!
21//! A captured graph records the device pointer of every info buffer its launches
22//! touch, so those buffers must outlive the graph. While a capture is recording,
23//! every entry the launch path touches — a fresh miss *or* a hit on a buffer
24//! built earlier in normal operation — is **pinned** to the graph being built.
25//! Pinned entries are never evicted, so the pointer a graph recorded stays valid
26//! for its whole life even if the cache would otherwise reclaim it.
27//! [`capture_commit`](MetadataInfoCache::capture_commit) seals those pins under
28//! the graph's id at `end_capture`, and
29//! [`graph_release`](MetadataInfoCache::graph_release) drops them when the graph
30//! is destroyed, freeing any buffer no other live graph still pins. Pins are
31//! refcounted, so an info buffer shared by two graphs survives until both are
32//! gone.
33//!
34//! A launch asks [`lookup`](MetadataInfoCache::lookup) and follows the
35//! [`Lookup`] it gets back: a hit is the buffer, and a miss says whether the
36//! one it is about to build is worth [`store`](MetadataInfoCache::store)ing.
37//! Info the policy will not cache is built and forgotten, so a value is only
38//! ever cloned into the cache when it will actually be kept, and the cache
39//! never learns a key it would not have used.
40
41use alloc::vec::Vec;
42use cubecl_environment::collections::{HashMap, HashSet};
43
44use crate::id::GraphId;
45
46/// Identifies a cached info buffer: the exact metadata words (shapes, strides,
47/// scalars) the buffer was built from — nothing else.
48///
49/// The kernel is deliberately **not** part of the key. An info buffer is
50/// read-only metadata whose bytes are fully determined by these words, so two
51/// launches (even of different kernels) with identical info want a byte-identical
52/// buffer and can safely share one. Keying on the words alone means a hit needs
53/// only the caller's borrowed slice — no owned key to clone on the hot path — and
54/// buffers are reused across kernels, not just within one.
55pub type InfoCacheKey = Vec<u64>;
56
57/// How the cache should behave for the current launch. Fed into the
58/// [`MetadataCachePolicy`], so it shapes every decision, not just a setting.
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum CacheMode {
61    /// Normal operation: cache only info small enough to be worth it, and evict
62    /// the least-recently-used entry once the cache is full.
63    Normal,
64    /// Graph-capture warmup/recording: cache every info buffer regardless of
65    /// size and never evict, so the capture window finds every buffer warm and
66    /// no entry a recorded launch depends on is dropped mid-capture.
67    Capture,
68}
69
70/// Every caching decision, in one place. Given an info's size and the current
71/// [`CacheMode`], the policy decides whether that info is cached at all
72/// ([`should_cache`](Self::should_cache)) and, through its
73/// [`capacity`](Self::capacity), when the cache must evict to stay bounded. How
74/// those decisions are carried out (lookups, eviction) is the cache's job and
75/// differs per runtime; *what* to do lives here.
76///
77/// `max_entries` and `max_cached_size` are the backend-tunable knobs.
78#[derive(Debug, Clone, Copy)]
79pub struct MetadataCachePolicy {
80    max_entries: usize,
81    max_cached_size: usize,
82    mode: CacheMode,
83}
84
85impl Default for MetadataCachePolicy {
86    fn default() -> Self {
87        // 4096 entries, ~256 metadata words (2048 bytes): a handful of tensors'
88        // shapes and strides. Larger infos (many tensors / high rank) are
89        // cheaper to rebuild than to hash and look up.
90        Self::new(4096, 2048)
91    }
92}
93
94impl MetadataCachePolicy {
95    /// Build a policy in [`CacheMode::Normal`]. `max_entries` caps the number of
96    /// cached entries; `max_cached_size` (bytes) is the largest info still worth
97    /// caching in normal operation.
98    pub fn new(max_entries: usize, max_cached_size: usize) -> Self {
99        Self {
100            max_entries,
101            max_cached_size,
102            mode: CacheMode::Normal,
103        }
104    }
105
106    /// Switch the mode driving the policy's decisions (see [`CacheMode`]).
107    pub fn mode(&mut self, mode: CacheMode) {
108        self.mode = mode;
109    }
110
111    /// Whether an info of `size` bytes should go through the cache at all. In
112    /// [`CacheMode::Normal`] a too-large info (or a disabled cache) is skipped:
113    /// the runtime should create it directly, without a lookup or a store. In
114    /// [`CacheMode::Capture`] everything is cached so the capture window stays
115    /// warm.
116    pub fn should_cache(&self, size: usize) -> bool {
117        match self.mode {
118            CacheMode::Capture => true,
119            CacheMode::Normal => self.max_entries > 0 && size <= self.max_cached_size,
120        }
121    }
122
123    /// The entry bound the cache must hold to, or `None` when unbounded. In
124    /// [`CacheMode::Capture`] the cache is unbounded and never evicts (dropping
125    /// an entry could free a buffer a recorded launch still needs); in
126    /// [`CacheMode::Normal`] it is capped at `max_entries`.
127    pub fn capacity(&self) -> Option<usize> {
128        match self.mode {
129            CacheMode::Capture => None,
130            CacheMode::Normal => Some(self.max_entries),
131        }
132    }
133
134    /// Whether entries touched right now must be pinned to the graph being
135    /// captured. True in [`CacheMode::Capture`]: a graph records the device
136    /// pointer of every info buffer its launches touch, so those entries must
137    /// not be evicted for the graph's lifetime — even after the cache returns to
138    /// [`CacheMode::Normal`].
139    pub fn pins_entries(&self) -> bool {
140        matches!(self.mode, CacheMode::Capture)
141    }
142}
143
144#[derive(Debug)]
145struct Entry<V> {
146    value: V,
147    /// Clock tick of this entry's most recent use (insert or hit); the smallest
148    /// marks the least-recently-used entry, evicted first.
149    last_used: u64,
150    /// Number of live captured graphs that pinned this entry. While `> 0` the
151    /// entry is never evicted, so every graph that recorded this info buffer
152    /// keeps replaying against the exact buffer it captured. Dropped back toward
153    /// zero as those graphs are destroyed (see [`MetadataInfoCache::graph_release`]).
154    locks: u32,
155}
156
157/// What the cache says about an info buffer a launch is about to need.
158///
159/// Two answers, because a miss still has to say whether the result is worth
160/// keeping: an info too large for the policy is built and forgotten, and the
161/// cache never learns a key it would not have used.
162pub enum Lookup<V> {
163    /// The buffer is already cached, and this is it.
164    Hit(V),
165    /// Nothing is cached for it; build the buffer.
166    Build {
167        /// Whether to hand the result back through [`MetadataInfoCache::store`].
168        store: bool,
169    },
170}
171
172/// A cache of metadata info buffers keyed by [`InfoCacheKey`], generic over the
173/// value type `V` (a device buffer handle for a compute backend). Evicting an
174/// entry drops its `V`; when `V` is a memory handle that returns the buffer to
175/// the pool, so the cache never pins more device memory than its live entries.
176///
177/// All policy is delegated to [`MetadataCachePolicy`]; this type only carries
178/// out its decisions. See the [module docs](self) for the intended
179/// [`lookup`](MetadataInfoCache::lookup) is the entry point a launch wants;
180/// the steps it composes are public for the paths that need them apart.
181#[derive(Debug)]
182pub struct MetadataInfoCache<V> {
183    entries: HashMap<InfoCacheKey, Entry<V>>,
184    policy: MetadataCachePolicy,
185    /// Monotonic logical clock; advanced once per [`get`](Self::get).
186    clock: u64,
187    /// Keys touched during the in-progress capture, each pinned exactly once,
188    /// awaiting association with a [`GraphId`] at
189    /// [`capture_commit`](Self::capture_commit) (or release at
190    /// [`capture_discard`](Self::capture_discard) if the capture is abandoned).
191    pending: HashSet<InfoCacheKey>,
192    /// The keys each live captured graph pinned, so
193    /// [`graph_release`](Self::graph_release) can drop that graph's locks when it
194    /// is destroyed.
195    graph_locks: HashMap<GraphId, Vec<InfoCacheKey>>,
196}
197
198impl<V> MetadataInfoCache<V> {
199    /// Create a cache governed by `policy`.
200    pub fn new(policy: MetadataCachePolicy) -> Self {
201        Self {
202            entries: HashMap::new(),
203            policy,
204            clock: 0,
205            pending: HashSet::new(),
206            graph_locks: HashMap::new(),
207        }
208    }
209
210    /// Switch the [`CacheMode`] driving the policy (see
211    /// [`MetadataCachePolicy::mode`]).
212    pub fn mode(&mut self, mode: CacheMode) {
213        self.policy.mode(mode);
214    }
215
216    /// Whether an info of `size` bytes should be cached — see
217    /// [`MetadataCachePolicy::should_cache`]. When `false`, skip the cache
218    /// entirely and create the value directly.
219    pub fn should_cache(&self, size: usize) -> bool {
220        self.policy.should_cache(size)
221    }
222
223    /// Number of entries currently cached.
224    pub fn len(&self) -> usize {
225        self.entries.len()
226    }
227
228    /// Whether the cache holds no entries.
229    pub fn is_empty(&self) -> bool {
230        self.entries.is_empty()
231    }
232
233    /// Drop every cached entry (releasing every held `V`).
234    pub fn clear(&mut self) {
235        self.entries.clear();
236    }
237
238    /// Drop every entry no live graph pins (releasing their held `V`s),
239    /// keeping the pinned ones — their device pointers are recorded inside
240    /// captured graphs that will replay against them.
241    ///
242    /// The explicit-cleanup hook. Cached info buffers are live slices in the
243    /// dynamic memory pools, so a cleanup that left them there would hold a
244    /// page of every pool the workload ever grew out of.
245    pub fn clear_unpinned(&mut self) {
246        self.entries.retain(|_, entry| entry.locks > 0);
247    }
248}
249
250impl<V: Clone> MetadataInfoCache<V> {
251    /// Look up `key`, advancing the logical clock by one tick. On a hit the
252    /// entry is marked used — its recency resets — and the value is cloned out.
253    /// During a capture ([`pins_entries`](MetadataCachePolicy::pins_entries)) a
254    /// hit also pins the entry to the graph being recorded, once per capture.
255    ///
256    /// Call only when [`should_cache`](Self::should_cache) is `true`; on a miss
257    /// create the value and hand it to [`insert`](Self::insert).
258    /// What to do about the info `words`, under `mode`.
259    ///
260    /// The one entry point a launch needs: it sets the mode, asks the policy
261    /// whether this info is worth caching at all, and looks it up if so. A
262    /// caller that reached for [`mode`](Self::mode), [`should_cache`] and
263    /// [`get`] in sequence was spelling this out, and every backend spelled it
264    /// out the same way.
265    ///
266    /// The words are borrowed here so a hit clones nothing; a miss hands them
267    /// to [`store`](Self::store) by value, as the key.
268    ///
269    /// [`should_cache`]: Self::should_cache
270    /// [`get`]: Self::get
271    pub fn lookup(&mut self, mode: CacheMode, words: &[u64]) -> Lookup<V> {
272        self.mode(mode);
273        if !self.should_cache(core::mem::size_of_val(words)) {
274            return Lookup::Build { store: false };
275        }
276        match self.get(words) {
277            Some(value) => Lookup::Hit(value),
278            None => Lookup::Build { store: true },
279        }
280    }
281
282    /// Record `value` as the buffer for `words`, after a [`Lookup::Build`]
283    /// that asked for it.
284    pub fn store(&mut self, words: InfoCacheKey, value: V) {
285        self.insert(words, value);
286    }
287
288    /// Look up `key`, advancing the logical clock by one tick. On a hit the
289    /// entry is marked used — its recency resets — and the value is cloned out.
290    /// During a capture ([`pins_entries`](MetadataCachePolicy::pins_entries)) a
291    /// hit also pins the entry to the graph being recorded, once per capture.
292    ///
293    /// [`lookup`](Self::lookup) composes this with the policy check ahead of
294    /// it; reach for this directly only when that check has already been made.
295    pub fn get(&mut self, key: &[u64]) -> Option<V> {
296        self.clock += 1;
297        let clock = self.clock;
298        // Pin once per capture. Check membership first (borrowed, no alloc); only
299        // when this is a fresh pin do we materialize an owned key for `pending`.
300        // `pending`/`entries` are disjoint fields, so both borrows coexist.
301        let pin = self.policy.pins_entries() && !self.pending.contains(key);
302        let entry = self.entries.get_mut(key)?;
303        entry.last_used = clock;
304        if pin {
305            self.pending.insert(key.to_vec());
306            entry.locks += 1;
307        }
308        Some(entry.value.clone())
309    }
310
311    /// Store `value` under `key` after a [`get`](Self::get) miss. During a
312    /// capture the new entry is pinned to the graph being recorded; otherwise it
313    /// evicts the least-recently-used *unpinned* entry first if the cache is at
314    /// [capacity](MetadataCachePolicy::capacity) (a capture is unbounded and
315    /// never evicts).
316    ///
317    /// Because the runtime only reaches here on a
318    /// [`should_cache`](Self::should_cache) miss, the value it clones in is
319    /// always kept — no wasted clones.
320    pub fn insert(&mut self, key: InfoCacheKey, value: V) {
321        if let Some(capacity) = self.policy.capacity() {
322            if capacity == 0 {
323                return;
324            }
325            if self.entries.len() >= capacity {
326                self.evict_least_recently_used();
327            }
328        }
329        // A miss during capture pins the fresh entry to the graph being recorded.
330        let locks = if self.policy.pins_entries() {
331            self.pending.insert(key.clone());
332            1
333        } else {
334            0
335        };
336        self.entries.insert(
337            key,
338            Entry {
339                value,
340                last_used: self.clock,
341                locks,
342            },
343        );
344    }
345
346    /// Seal the entries pinned during the just-finished capture under `graph`,
347    /// so [`graph_release`](Self::graph_release) can drop their locks when the
348    /// graph is destroyed. Call once from `end_capture` after the graph is built.
349    pub fn capture_commit(&mut self, graph: GraphId) {
350        if !self.pending.is_empty() {
351            let keys = self.pending.drain().collect();
352            self.graph_locks.insert(graph, keys);
353        }
354    }
355
356    /// Drop the locks taken during a capture that was abandoned (never turned
357    /// into a graph), so the touched entries become evictable again. The entries
358    /// themselves stay as ordinary cached values.
359    pub fn capture_discard(&mut self) {
360        let keys: Vec<_> = self.pending.drain().collect();
361        for key in keys {
362            if let Some(entry) = self.entries.get_mut(&key) {
363                entry.locks = entry.locks.saturating_sub(1);
364            }
365        }
366    }
367
368    /// Release the entries a destroyed `graph` pinned. An entry no other live
369    /// graph still pins is removed, freeing its buffer — this is how the cache
370    /// is cleaned up when a graph is destroyed.
371    pub fn graph_release(&mut self, graph: GraphId) {
372        let Some(keys) = self.graph_locks.remove(&graph) else {
373            return;
374        };
375        for key in keys {
376            let drop_entry = match self.entries.get_mut(&key) {
377                Some(entry) => {
378                    entry.locks = entry.locks.saturating_sub(1);
379                    entry.locks == 0
380                }
381                None => false,
382            };
383            if drop_entry {
384                self.entries.remove(&key);
385            }
386        }
387    }
388
389    /// Drop the entry whose last use is oldest (largest "time since last use"),
390    /// skipping entries pinned to a live graph.
391    fn evict_least_recently_used(&mut self) {
392        let victim = self
393            .entries
394            .iter()
395            .filter(|(_, entry)| entry.locks == 0)
396            .min_by_key(|(_, entry)| entry.last_used)
397            .map(|(key, _)| key.clone());
398        if let Some(key) = victim {
399            self.entries.remove(&key);
400        }
401    }
402}
403
404#[cfg(test)]
405mod tests {
406    use super::*;
407
408    fn key(n: u64) -> InfoCacheKey {
409        alloc::vec![n]
410    }
411
412    fn cache(max_entries: usize) -> MetadataInfoCache<u32> {
413        MetadataInfoCache::new(MetadataCachePolicy::new(max_entries, 64))
414    }
415
416    #[test]
417    fn normal_mode_gates_on_size() {
418        let cache = cache(8);
419        assert!(cache.should_cache(64), "within max_cached_size");
420        assert!(!cache.should_cache(65), "over max_cached_size");
421    }
422
423    /// An explicit cleanup drops every entry except the ones live graphs pin:
424    /// the unpinned buffers are what keeps the dynamic pools from ever being
425    /// rebuilt, and the pinned ones are what recorded graphs replay against.
426    #[test]
427    fn clear_unpinned_keeps_only_graph_pinned_entries() {
428        let mut cache = cache(8);
429        cache.insert(key(0), 0);
430
431        // A capture touches entry 1 (fresh) and seals it under a graph.
432        cache.mode(CacheMode::Capture);
433        cache.insert(key(1), 1);
434        cache.capture_commit(GraphId::new());
435        cache.mode(CacheMode::Normal);
436
437        cache.insert(key(2), 2);
438        assert_eq!(cache.len(), 3);
439
440        cache.clear_unpinned();
441        assert!(cache.get(&key(0)).is_none(), "unpinned entries are dropped");
442        assert!(cache.get(&key(2)).is_none(), "unpinned entries are dropped");
443        assert_eq!(
444            cache.get(&key(1)),
445            Some(1),
446            "a graph-pinned entry survives: its pointer is recorded in the graph"
447        );
448    }
449
450    #[test]
451    fn capture_mode_caches_any_size() {
452        let mut cache = cache(8);
453        cache.mode(CacheMode::Capture);
454        assert!(cache.should_cache(10_000));
455    }
456
457    #[test]
458    fn hit_returns_value_and_records_use() {
459        let mut cache = cache(8);
460        let k = key(1);
461        assert!(cache.get(&k).is_none());
462        cache.insert(k.clone(), 42);
463        assert_eq!(cache.get(&k), Some(42));
464    }
465
466    #[test]
467    fn normal_mode_evicts_least_recently_used() {
468        // Capacity 2: fill it, keep entry 0 hot so entry 1 is the LRU, then
469        // insert a third entry and expect entry 1 evicted, entry 0 kept.
470        let mut cache = cache(2);
471        cache.insert(key(0), 0);
472        cache.insert(key(1), 1);
473
474        // Touch entry 0 so entry 1 becomes least-recently-used.
475        assert_eq!(cache.get(&key(0)), Some(0));
476
477        cache.insert(key(2), 2);
478        assert_eq!(cache.len(), 2, "stayed at capacity");
479        assert_eq!(cache.get(&key(0)), Some(0), "recently used entry kept");
480        assert!(cache.get(&key(1)).is_none(), "least-recently-used evicted");
481        assert_eq!(cache.get(&key(2)), Some(2), "new entry cached");
482    }
483
484    #[test]
485    fn capture_mode_is_unbounded() {
486        let mut cache = cache(2);
487        cache.mode(CacheMode::Capture);
488        for i in 0..10 {
489            cache.insert(key(i), i as u32);
490        }
491        assert_eq!(cache.len(), 10, "capture must cache every buffer");
492    }
493
494    #[test]
495    fn zero_capacity_disables_caching() {
496        let mut cache = cache(0);
497        assert!(!cache.should_cache(8), "disabled cache never caches");
498        cache.insert(key(0), 0);
499        assert!(cache.is_empty());
500    }
501
502    /// Capture one entry into a graph, then thrash the cache well past capacity
503    /// in normal mode: the pinned entry must survive (its buffer is still
504    /// replayed against), and only after the graph is released can it be evicted.
505    #[test]
506    fn pinned_entry_survives_eviction_until_graph_released() {
507        let mut cache = cache(2);
508        let graph = GraphId::new();
509
510        // Capture pins entry 0.
511        cache.mode(CacheMode::Capture);
512        cache.insert(key(0), 0);
513        cache.capture_commit(graph);
514
515        // Back to normal: flood the cache far past capacity (get-then-insert,
516        // as the launch path does, so recency advances per entry).
517        cache.mode(CacheMode::Normal);
518        for i in 1..20 {
519            cache.get(&key(i));
520            cache.insert(key(i), i as u32);
521        }
522        assert_eq!(cache.get(&key(0)), Some(0), "pinned entry never evicted");
523
524        // Destroying the graph releases the pin and drops the entry.
525        cache.graph_release(graph);
526        assert!(cache.get(&key(0)).is_none(), "released entry cleaned up");
527    }
528
529    /// A cache hit during capture (on a buffer built earlier in normal mode)
530    /// must pin that entry — otherwise later eviction would free a buffer the
531    /// graph still replays against. This is the finding-#1 regression guard.
532    #[test]
533    fn capture_hit_on_normal_entry_pins_it() {
534        let mut cache = cache(2);
535        let graph = GraphId::new();
536
537        // Built in normal mode (e.g. regular pool), cached.
538        cache.insert(key(0), 0);
539
540        // Captured: the launch hits the existing entry, which must pin it.
541        cache.mode(CacheMode::Capture);
542        assert_eq!(cache.get(&key(0)), Some(0));
543        cache.capture_commit(graph);
544
545        cache.mode(CacheMode::Normal);
546        for i in 1..20 {
547            cache.get(&key(i));
548            cache.insert(key(i), i as u32);
549        }
550        assert_eq!(cache.get(&key(0)), Some(0), "hit-pinned entry survives");
551    }
552
553    /// An entry shared by two graphs stays until both are destroyed (refcount).
554    #[test]
555    fn pin_is_refcounted_across_graphs() {
556        let mut cache = cache(8);
557        let (g1, g2) = (GraphId::new(), GraphId::new());
558
559        cache.mode(CacheMode::Capture);
560        cache.insert(key(0), 0);
561        cache.capture_commit(g1);
562
563        // Second capture hits the same entry.
564        assert_eq!(cache.get(&key(0)), Some(0));
565        cache.capture_commit(g2);
566
567        cache.mode(CacheMode::Normal);
568        cache.graph_release(g1);
569        assert_eq!(cache.get(&key(0)), Some(0), "still pinned by g2");
570        cache.graph_release(g2);
571        assert!(cache.get(&key(0)).is_none(), "gone once both released");
572    }
573
574    /// An abandoned capture releases its pins but keeps the entries as ordinary
575    /// cached values (they become evictable again).
576    #[test]
577    fn capture_discard_unpins_without_removing() {
578        let mut cache = cache(8);
579        cache.mode(CacheMode::Capture);
580        cache.insert(key(0), 0);
581        cache.capture_discard();
582
583        // Entry still present, but now evictable: flood past capacity in normal.
584        cache.mode(CacheMode::Normal);
585        assert_eq!(cache.get(&key(0)), Some(0), "kept as a normal entry");
586        for i in 1..20 {
587            cache.get(&key(i));
588            cache.insert(key(i), i as u32);
589        }
590        assert!(cache.get(&key(0)).is_none(), "no longer pinned, evicted");
591    }
592}