Skip to main content

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