| 1 | //! Bounded LRU cache for recent final evaluation outputs and VRAM budget accounting. |
| 2 | |
| 3 | use std::collections::{HashMap, VecDeque}; |
| 4 | use std::collections::hash_map::DefaultHasher; |
| 5 | use std::hash::{Hash, Hasher}; |
| 6 | use std::sync::Arc; |
| 7 | |
| 8 | use model::{Comp, NodeId}; |
| 9 | |
| 10 | use crate::cache::{CacheMode, CachedTexture}; |
| 11 | |
| 12 | use super::Engine; |
| 13 | |
| 14 | const MAX_OUTPUT_CACHE_BYTES: u64 = 128 * 1024 * 1024; |
| 15 | const MAX_OUTPUT_CACHE_ENTRIES: usize = 64; |
| 16 | |
| 17 | /// Bounded LRU of recent final output textures capped by byte budget (`min(vram_budget / 4, 128 MiB)`), |
| 18 | /// always keeping at least the most recent frame for `<0.1ms` warm hits during pan/zoom/exposure/scrubbing. |
| 19 | pub(super) struct OutputCache { |
| 20 | entries: VecDeque<(u64, CachedTexture, Vec<String>)>, |
| 21 | } |
| 22 | |
| 23 | impl OutputCache { |
| 24 | pub(super) fn new() -> Self { |
| 25 | Self { |
| 26 | entries: VecDeque::new(), |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | #[cfg(test)] |
| 31 | pub(super) fn len(&self) -> usize { |
| 32 | self.entries.len() |
| 33 | } |
| 34 | |
| 35 | pub(super) fn clear(&mut self) { |
| 36 | self.entries.clear(); |
| 37 | } |
| 38 | |
| 39 | pub(super) fn budget_bytes(vram_budget_bytes: u64) -> u64 { |
| 40 | if vram_budget_bytes < 64 * 1024 * 1024 { |
| 41 | 0 |
| 42 | } else { |
| 43 | (vram_budget_bytes / 4).min(MAX_OUTPUT_CACHE_BYTES) |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | /// Per distinct texture: `(bytes, entries referencing it, Arc::strong_count)`. |
| 48 | fn textures(&self) -> HashMap<*const wgpu::Texture, (u64, usize, usize)> { |
| 49 | let mut by_ptr = HashMap::new(); |
| 50 | for (_, tex, _) in &self.entries { |
| 51 | let slot = by_ptr |
| 52 | .entry(Arc::as_ptr(&tex.texture)) |
| 53 | .or_insert((tex.bytes, 0, Arc::strong_count(&tex.texture))); |
| 54 | slot.1 += 1; |
| 55 | } |
| 56 | by_ptr |
| 57 | } |
| 58 | |
| 59 | /// Total GPU bytes referenced by `output_cache` entries (including textures shared with `NodeCache`), |
| 60 | /// counting a texture once however many entries point at it. |
| 61 | pub(super) fn total_bytes(&self) -> u64 { |
| 62 | match self.entries.len() { |
| 63 | 0 => 0, |
| 64 | 1 => self.entries[0].1.bytes, |
| 65 | _ => self.textures().values().map(|&(bytes, _, _)| bytes).sum(), |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | /// GPU bytes held *exclusively* by `output_cache`: every strong reference to the texture is an entry here. |
| 70 | /// |
| 71 | /// Textures still resident in `NodeCache` or cloned out to a caller have `strong_count` above the entry |
| 72 | /// count and are already accounted for elsewhere, so skipping them avoids double-counting the VRAM budget. |
| 73 | pub(super) fn unshared_bytes(&self) -> u64 { |
| 74 | match self.entries.len() { |
| 75 | 0 => 0, |
| 76 | 1 => { |
| 77 | let tex = &self.entries[0].1; |
| 78 | if Arc::strong_count(&tex.texture) == 1 { |
| 79 | tex.bytes |
| 80 | } else { |
| 81 | 0 |
| 82 | } |
| 83 | } |
| 84 | _ => self |
| 85 | .textures() |
| 86 | .values() |
| 87 | .filter(|&&(_, entries, strong)| entries == strong) |
| 88 | .map(|&(bytes, _, _)| bytes) |
| 89 | .sum(), |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | pub(super) fn get(&mut self, key: u64, mode: CacheMode) -> Option<(CachedTexture, Vec<String>)> { |
| 94 | if mode == CacheMode::Bypass { |
| 95 | return None; |
| 96 | } |
| 97 | let pos = self.entries.iter().position(|(k, _, _)| *k == key)?; |
| 98 | let entry = self.entries.remove(pos)?; |
| 99 | let res = (entry.1.clone(), entry.2.clone()); |
| 100 | self.entries.push_back(entry); |
| 101 | Some(res) |
| 102 | } |
| 103 | |
| 104 | pub(super) fn insert( |
| 105 | &mut self, |
| 106 | key: u64, |
| 107 | tex: CachedTexture, |
| 108 | unsupported: Vec<String>, |
| 109 | mode: CacheMode, |
| 110 | cap: u64, |
| 111 | ) { |
| 112 | if mode == CacheMode::Bypass || cap == 0 { |
| 113 | return; |
| 114 | } |
| 115 | if let Some(pos) = self.entries.iter().position(|(k, _, _)| *k == key) { |
| 116 | self.entries.remove(pos); |
| 117 | } |
| 118 | self.entries.push_back((key, tex, unsupported)); |
| 119 | while self.entries.len() > 1 |
| 120 | && (self.total_bytes() > cap || self.entries.len() > MAX_OUTPUT_CACHE_ENTRIES) |
| 121 | { |
| 122 | self.entries.pop_front(); |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | pub(super) fn trim_to_cap(&mut self, cap: u64) { |
| 127 | if cap == 0 { |
| 128 | self.entries.clear(); |
| 129 | } else { |
| 130 | while self.entries.len() > 1 && self.total_bytes() > cap { |
| 131 | self.entries.pop_front(); |
| 132 | } |
| 133 | } |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | impl Engine { |
| 138 | pub(super) fn output_cache_budget_bytes(&self) -> u64 { |
| 139 | OutputCache::budget_bytes(self.vram_budget_bytes) |
| 140 | } |
| 141 | |
| 142 | /// Total GPU bytes held by `output_cache`. |
| 143 | pub fn output_cache_bytes(&self) -> u64 { |
| 144 | self.output_cache.total_bytes() |
| 145 | } |
| 146 | |
| 147 | /// Total resident GPU VRAM bytes across `NodeCache` (live + pooled), unshared `output_cache` |
| 148 | /// entries, 3D shadow/depth/mesh buffers, and optical flow scratch/cache buffers. |
| 149 | pub fn vram_bytes(&self) -> u64 { |
| 150 | self.cache |
| 151 | .total_vram_bytes() |
| 152 | .saturating_add(self.output_cache.unshared_bytes()) |
| 153 | .saturating_add(self.scene3d.shadow_vram_bytes()) |
| 154 | .saturating_add(self.scene3d.depth_vram_bytes()) |
| 155 | .saturating_add(self.scene3d.mesh_vram_bytes()) |
| 156 | .saturating_add(self.scene3d.uniform_vram_bytes()) |
| 157 | .saturating_add(self.optflow.get().map_or(0, |of| of.vram_bytes())) |
| 158 | .saturating_add(self.media.nv12_vram_bytes()) |
| 159 | } |
| 160 | |
| 161 | pub fn vram_mb(&self) -> f64 { |
| 162 | self.vram_bytes() as f64 / (1024.0 * 1024.0) |
| 163 | } |
| 164 | |
| 165 | pub(super) fn sync_node_cache_budget(&mut self) { |
| 166 | let remaining_bytes = self |
| 167 | .vram_budget_bytes |
| 168 | .saturating_sub(self.output_cache.unshared_bytes()); |
| 169 | let remaining_mb = remaining_bytes / (1024 * 1024); |
| 170 | if self.cache.budget_bytes != remaining_mb.saturating_mul(1024 * 1024) { |
| 171 | self.cache.set_budget_mb(remaining_mb); |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | pub fn set_vram_budget_mb(&mut self, budget_mb: u64) { |
| 176 | self.vram_budget_bytes = budget_mb.saturating_mul(1024 * 1024); |
| 177 | let cap = self.output_cache_budget_bytes(); |
| 178 | self.output_cache.trim_to_cap(cap); |
| 179 | self.sync_node_cache_budget(); |
| 180 | } |
| 181 | |
| 182 | pub fn vram_budget_mb(&self) -> u64 { |
| 183 | self.vram_budget_bytes / (1024 * 1024) |
| 184 | } |
| 185 | |
| 186 | pub(super) fn output_cache_key(&self, comp: &Comp, target: NodeId, time: f64) -> u64 { |
| 187 | let mut h = DefaultHasher::new(); |
| 188 | self.cache.gpu_salt.hash(&mut h); |
| 189 | comp.name.hash(&mut h); |
| 190 | comp.path.hash(&mut h); |
| 191 | comp.nodes.len().hash(&mut h); |
| 192 | comp.revision.hash(&mut h); |
| 193 | target.hash(&mut h); |
| 194 | time.to_bits().hash(&mut h); |
| 195 | self.proxy_scale.hash(&mut h); |
| 196 | self.hiq.hash(&mut h); |
| 197 | self.use_proxy_clips.hash(&mut h); |
| 198 | h.finish() |
| 199 | } |
| 200 | |
| 201 | pub(super) fn output_cache_get(&mut self, key: u64) -> Option<(CachedTexture, Vec<String>)> { |
| 202 | self.output_cache.get(key, self.cache.mode) |
| 203 | } |
| 204 | |
| 205 | pub(super) fn output_cache_insert(&mut self, key: u64, tex: CachedTexture, unsupported: Vec<String>) { |
| 206 | let cap = self.output_cache_budget_bytes(); |
| 207 | self.output_cache |
| 208 | .insert(key, tex, unsupported, self.cache.mode, cap); |
| 209 | self.sync_node_cache_budget(); |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | #[cfg(test)] |
| 214 | mod tests { |
| 215 | use super::*; |
| 216 | use model::BitDepth; |
| 217 | |
| 218 | #[test] |
| 219 | fn duplicate_arcs_count_once_and_caller_clones_count_as_shared() { |
| 220 | let eng = Engine::new_headless().expect("gpu"); |
| 221 | let tex = eng.alloc_tex([64, 64], BitDepth::Int8, 1); |
| 222 | let other = eng.alloc_tex([32, 32], BitDepth::Int8, 2); |
| 223 | let (tex_bytes, other_bytes) = (tex.bytes, other.bytes); |
| 224 | let mut cache = OutputCache::new(); |
| 225 | let cap = u64::MAX; |
| 226 | cache.insert(1, tex.clone(), vec![], CacheMode::Enabled, cap); |
| 227 | cache.insert(2, tex.clone(), vec![], CacheMode::Enabled, cap); |
| 228 | cache.insert(3, other.clone(), vec![], CacheMode::Enabled, cap); |
| 229 | assert_eq!(cache.len(), 3); |
| 230 | assert_eq!(cache.total_bytes(), tex_bytes + other_bytes); |
| 231 | |
| 232 | // The test's own clones stand in for `NodeCache` entries or in-flight callers. |
| 233 | assert_eq!(cache.unshared_bytes(), 0); |
| 234 | drop(other); |
| 235 | assert_eq!(cache.unshared_bytes(), other_bytes); |
| 236 | drop(tex); |
| 237 | assert_eq!(cache.unshared_bytes(), tex_bytes + other_bytes); |
| 238 | } |
| 239 | |
| 240 | #[test] |
| 241 | fn vram_bytes_includes_optflow_and_bust_caches_clears_scratch() { |
| 242 | let mut eng = Engine::new_headless().expect("gpu"); |
| 243 | assert_eq!(eng.vram_bytes(), 0); |
| 244 | |
| 245 | let a = eng.alloc_tex([64, 64], BitDepth::Int8, 10); |
| 246 | let b = eng.alloc_tex([64, 64], BitDepth::Int8, 11); |
| 247 | let optflow = eng |
| 248 | .optflow |
| 249 | .get_or_init(|| crate::optflow::OpticalFlowPipelines::new(&eng.device)); |
| 250 | let mut enc = eng.device.create_command_encoder(&Default::default()); |
| 251 | let _out = optflow.interpolate_flow( |
| 252 | &eng.device, |
| 253 | &eng.queue, |
| 254 | &mut enc, |
| 255 | &a, |
| 256 | &b, |
| 257 | 0.5, |
| 258 | wgpu::TextureFormat::Rgba8Unorm, |
| 259 | ); |
| 260 | eng.queue.submit(Some(enc.finish())); |
| 261 | |
| 262 | let optflow_bytes = eng.optflow.get().unwrap().vram_bytes(); |
| 263 | assert!(optflow_bytes > 0); |
| 264 | assert_eq!(eng.vram_bytes(), optflow_bytes); |
| 265 | |
| 266 | eng.bust_gpu_cache(); |
| 267 | let after_bust = eng.optflow.get().unwrap().vram_bytes(); |
| 268 | assert!(after_bust < optflow_bytes); |
| 269 | assert_eq!(eng.vram_bytes(), after_bust); |
| 270 | } |
| 271 | } |