From e44c996f55a67e9dffeed9bfb8bc40dbdf33f6d1 Mon Sep 17 00:00:00 2001 From: clover caruso Date: Mon, 30 Nov 2026 16:13:34 -0800 Subject: [PATCH] Add GPU texture pool reuse and per-node --profile telemetry (#25) --- crates/engine/src/bin/render_check.rs | 37 +- crates/engine/src/cache.rs | 635 +++++++++++++++++++++++++- crates/engine/src/lib.rs | 7 +- crates/engine/src/profile.rs | 327 +++++++++++++ 4 files changed, 981 insertions(+), 25 deletions(-) create mode 100644 crates/engine/src/profile.rs diff --git a/crates/engine/src/bin/render_check.rs b/crates/engine/src/bin/render_check.rs index 710477bd2fd4b1abeb3adea33004009792f0e08c..2e6c7b5d95a625cb8a04d52c5645b9a28c825533 100644 --- a/crates/engine/src/bin/render_check.rs +++ b/crates/engine/src/bin/render_check.rs @@ -335,7 +335,7 @@ fn main() -> Result<(), Box> { } if args.len() < 3 { eprintln!( - "usage:\n render-check [--out ] [--ref ] [--node ] [--proxy <1|2|4>] [--fast]\n render-check --render .. --out-dir [--node ] [--proxy <1|2|4>]\n render-check --export [--saver ] [--range ..] [--out-dir ] [--proxy <1|2|4>] [--fast]\n render-check --export-mp4 [--node ] [--range ..] [--crf ] [--max-height ] [--no-audio] [--proxy <1|2|4>] [--fast]\n render-check --export-prores [--node ] [--range ..] [--no-audio] [--proxy <1|2|4>] [--fast]\n render-check --roundtrip \n render-check --suite [--fast]" + "usage:\n render-check [--out ] [--ref ] [--node ] [--proxy <1|2|4>] [--fast] [--bench] [--profile]\n render-check --render .. --out-dir [--node ] [--proxy <1|2|4>]\n render-check --export [--saver ] [--range ..] [--out-dir ] [--proxy <1|2|4>] [--fast]\n render-check --export-mp4 [--node ] [--range ..] [--crf ] [--max-height ] [--no-audio] [--proxy <1|2|4>] [--fast]\n render-check --export-prores [--node ] [--range ..] [--no-audio] [--proxy <1|2|4>] [--fast]\n render-check --roundtrip \n render-check --suite [--fast]" ); std::process::exit(2); } @@ -520,6 +520,7 @@ fn main() -> Result<(), Box> { let mut vram_budget_mb: Option = None; let mut hiq = true; let mut bench = false; + let mut profile = false; let mut i = 3; while i < args.len() { match args[i].as_str() { @@ -555,8 +556,12 @@ fn main() -> Result<(), Box> { bench = true; i += 1; } + "--profile" => { + profile = true; + i += 1; + } other => { - eprintln!("unexpected argument '{other}' (use --out, --ref, --node, --proxy, --proxy-clips, --vram-mb, --fast, --bench)"); + eprintln!("unexpected argument '{other}' (use --out, --ref, --node, --proxy, --proxy-clips, --vram-mb, --fast, --bench, --profile)"); std::process::exit(2); } } @@ -587,7 +592,18 @@ fn main() -> Result<(), Box> { } engine.hiq = hiq; + if profile { + engine.cache.begin_frame_profile_with_comp(&comp); + } let (tex, cold) = engine.evaluate(&comp, target, frame); + let cold_profile = if profile { + engine.cache.take_frame_profile().map(|mut fp| { + fp.total_eval_ms = cold.eval_ms; + fp + }) + } else { + None + }; eprintln!( "[cold] {:.2} ms | eval={} hits={} misses={} loads={} pruned={} vram={:.1}MB unsupported={:?}", cold.eval_ms, @@ -599,6 +615,9 @@ fn main() -> Result<(), Box> { cold.cached_vram_mb, cold.unsupported_nodes ); + if let Some(fp) = &cold_profile { + eprint!("{}", fp.format_top_nodes(15)); + } if bench { let (_, warm) = engine.evaluate(&comp, target, frame); @@ -608,11 +627,25 @@ fn main() -> Result<(), Box> { ); engine.bust_gpu_cache(); + if profile { + engine.cache.begin_frame_profile_with_comp(&comp); + } let (_, gpu_bust) = engine.evaluate(&comp, target, frame); + let bust_profile = if profile { + engine.cache.take_frame_profile().map(|mut fp| { + fp.total_eval_ms = gpu_bust.eval_ms; + fp + }) + } else { + None + }; eprintln!( "[bust] {:.2} ms | eval={} hits={} misses={} loads={}", gpu_bust.eval_ms, gpu_bust.nodes_evaluated, gpu_bust.cache_hits, gpu_bust.cache_misses, gpu_bust.source_loads ); + if let Some(fp) = &bust_profile { + eprint!("{}", fp.format_top_nodes(15)); + } engine.set_cache_mode(CacheMode::Bypass); let (_, bypass) = engine.evaluate(&comp, target, frame); diff --git a/crates/engine/src/cache.rs b/crates/engine/src/cache.rs index 5ee5f7f3a159576fb1f31f592e513e468923acbc..80cf4f98d10901bcad8fe16e7532afde84298d8d 100644 --- a/crates/engine/src/cache.rs +++ b/crates/engine/src/cache.rs @@ -1,9 +1,11 @@ //! Content-hashed GPU texture cache with hard VRAM budget, LRU eviction, -//! and surgical cache-busting modes for profiling and playback verification. +//! VRAM-budgeted texture pooling, per-node profiling hooks, and surgical +//! cache-busting modes for profiling and playback verification. -use model::{BitDepth, NodeId}; -use std::collections::{HashMap, HashSet}; -use std::sync::Arc; +use crate::profile::{FrameProfile, ProfileRecorder}; +use model::{BitDepth, Comp, NodeId}; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::sync::{Arc, Mutex}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CacheMode { @@ -35,6 +37,28 @@ pub struct CachedTexture { pub bytes: u64, } +fn depth_for_format(format: wgpu::TextureFormat) -> BitDepth { + match format { + wgpu::TextureFormat::Rgba16Float => BitDepth::Float16, + wgpu::TextureFormat::Rgba32Float => BitDepth::Float32, + _ => BitDepth::Int8, + } +} + +fn bytes_per_pixel(format: wgpu::TextureFormat) -> u64 { + match format { + wgpu::TextureFormat::Rgba32Float => 16, + wgpu::TextureFormat::Rgba16Float => 8, + _ => u64::from(format.block_copy_size(None).unwrap_or(4)), + } +} + +fn texture_bytes(size: [u32; 2], format: wgpu::TextureFormat) -> u64 { + u64::from(size[0].max(1)) + .saturating_mul(u64::from(size[1].max(1))) + .saturating_mul(bytes_per_pixel(format)) +} + impl CachedTexture { pub fn from_texture(texture: wgpu::Texture, size: [u32; 2], content_hash: u64) -> Self { Self::from_texture_dod(texture, size, [0, 0], size, content_hash) @@ -48,11 +72,7 @@ impl CachedTexture { content_hash: u64, ) -> Self { let format = texture.format(); - let depth = match format { - wgpu::TextureFormat::Rgba16Float => BitDepth::Float16, - wgpu::TextureFormat::Rgba32Float => BitDepth::Float32, - _ => BitDepth::Int8, - }; + let depth = depth_for_format(format); Self::from_texture_dod_depth(texture, size, origin, canvas_size, depth, content_hash) } @@ -65,13 +85,8 @@ impl CachedTexture { content_hash: u64, ) -> Self { let format = texture.format(); - let bpp = match format { - wgpu::TextureFormat::Rgba32Float => 16u64, - wgpu::TextureFormat::Rgba16Float => 8u64, - _ => 4u64, - }; let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); - let bytes = u64::from(size[0]) * u64::from(size[1]) * bpp; + let bytes = texture_bytes(size, format); Self { texture: Arc::new(texture), view: Arc::new(view), @@ -87,6 +102,33 @@ impl CachedTexture { } } + #[allow(clippy::too_many_arguments)] + pub(crate) fn from_parts( + texture: Arc, + view: Arc, + size: [u32; 2], + origin: [i32; 2], + canvas_size: [u32; 2], + depth: BitDepth, + format: wgpu::TextureFormat, + content_hash: u64, + bytes: u64, + ) -> Self { + Self { + texture, + view, + size, + origin, + canvas_size, + depth, + format, + tex_scale: 1.0, + edge_mode: None, + content_hash, + bytes, + } + } + pub fn has_dod(&self) -> bool { self.origin != [0, 0] || self.size != self.canvas_size } @@ -107,6 +149,175 @@ pub struct EvalStats { pub unsupported_nodes: Vec, } +/// Key identifying compatible GPU textures in `TexturePool`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct TexturePoolKey { + pub width: u32, + pub height: u32, + pub format: wgpu::TextureFormat, + pub usage: wgpu::TextureUsages, +} + +/// Snapshot of `TexturePool` counters and resident VRAM. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct TexturePoolStats { + pub pooled_count: usize, + pub pooled_bytes: u64, + pub hits: u64, + pub misses: u64, + pub evictions: u64, + pub returns: u64, +} + +struct PooledTexture { + texture: Arc, + view: Arc, + bytes: u64, + last_returned: u64, +} + +/// LRU pool of recycled `wgpu::Texture` allocations keyed by `(width, height, format, usage)`. +pub struct TexturePool { + buckets: HashMap>, + total_bytes: u64, + pooled_count: usize, + tick: u64, + hits: u64, + misses: u64, + evictions: u64, + returns: u64, +} + +impl Default for TexturePool { + fn default() -> Self { + Self::new() + } +} + +impl TexturePool { + pub fn new() -> Self { + Self { + buckets: HashMap::new(), + total_bytes: 0, + pooled_count: 0, + tick: 0, + hits: 0, + misses: 0, + evictions: 0, + returns: 0, + } + } + + pub fn stats(&self) -> TexturePoolStats { + TexturePoolStats { + pooled_count: self.pooled_count, + pooled_bytes: self.total_bytes, + hits: self.hits, + misses: self.misses, + evictions: self.evictions, + returns: self.returns, + } + } + + pub fn pooled_bytes(&self) -> u64 { + self.total_bytes + } + + pub fn pooled_count(&self) -> usize { + self.pooled_count + } + + pub fn hits(&self) -> u64 { + self.hits + } + + pub fn misses(&self) -> u64 { + self.misses + } + + pub fn evictions(&self) -> u64 { + self.evictions + } + + pub fn clear(&mut self) { + self.buckets.clear(); + self.total_bytes = 0; + self.pooled_count = 0; + } + + fn push(&mut self, tex: &CachedTexture) { + if tex.bytes == 0 || tex.size[0] == 0 || tex.size[1] == 0 { + return; + } + let key = TexturePoolKey { + width: tex.size[0], + height: tex.size[1], + format: tex.format, + usage: tex.texture.usage(), + }; + self.tick += 1; + self.total_bytes = self.total_bytes.saturating_add(tex.bytes); + self.pooled_count += 1; + self.returns += 1; + self.buckets.entry(key).or_default().push_back(PooledTexture { + texture: Arc::clone(&tex.texture), + view: Arc::clone(&tex.view), + bytes: tex.bytes, + last_returned: self.tick, + }); + } + + /// Pops an exclusively owned (`Arc::strong_count == 1`) texture matching `key`. + /// Entries still referenced elsewhere (e.g. by `output_cache`) are dropped from the pool + /// rather than aliased. + fn pop(&mut self, key: TexturePoolKey) -> Option<(Arc, Arc, u64)> { + let mut found = None; + let remove_bucket = if let Some(bucket) = self.buckets.get_mut(&key) { + while let Some(item) = bucket.pop_back() { + self.total_bytes = self.total_bytes.saturating_sub(item.bytes); + self.pooled_count = self.pooled_count.saturating_sub(1); + if Arc::strong_count(&item.texture) == 1 && Arc::strong_count(&item.view) == 1 { + found = Some((item.texture, item.view, item.bytes)); + break; + } + } + bucket.is_empty() + } else { + false + }; + if remove_bucket { + self.buckets.remove(&key); + } + found + } + + /// Evicts the globally oldest pooled texture (FIFO/LRU by return order). + fn evict_oldest(&mut self) -> bool { + let oldest_key = self + .buckets + .iter() + .filter_map(|(&k, q)| q.front().map(|front| (k, front.last_returned))) + .min_by_key(|(_, tick)| *tick) + .map(|(k, _)| k); + let Some(key) = oldest_key else { + return false; + }; + let mut remove_bucket = false; + if let Some(bucket) = self.buckets.get_mut(&key) { + if let Some(item) = bucket.pop_front() { + self.total_bytes = self.total_bytes.saturating_sub(item.bytes); + self.pooled_count = self.pooled_count.saturating_sub(1); + self.evictions += 1; + } + remove_bucket = bucket.is_empty(); + } + if remove_bucket { + self.buckets.remove(&key); + } + true + } +} + struct Entry { tex: CachedTexture, last_used: u64, @@ -117,6 +328,9 @@ struct Entry { /// Default GPU texture cache VRAM budget (768 MiB keeps heavy 150+ node comps well below 1 GiB). pub const DEFAULT_VRAM_BUDGET_MB: u64 = 768; +/// Alias for `NodeCache` (GPU texture cache + VRAM-budgeted `TexturePool`). +pub type GpuCache = NodeCache; + pub struct NodeCache { pub mode: CacheMode, pub budget_bytes: u64, @@ -128,6 +342,8 @@ pub struct NodeCache { pub gpu_salt: u64, /// Per-node salt bumped when surgically busting a subtree. node_salts: HashMap, + pool: Mutex, + profiler: Option, } impl NodeCache { @@ -141,12 +357,25 @@ impl NodeCache { evictions: 0, gpu_salt: 0, node_salts: HashMap::new(), + pool: Mutex::new(TexturePool::new()), + profiler: None, } } + /// Standard compositor GPU texture usage flags used by `Evaluator`. + pub fn default_texture_usage() -> wgpu::TextureUsages { + wgpu::TextureUsages::TEXTURE_BINDING + | wgpu::TextureUsages::STORAGE_BINDING + | wgpu::TextureUsages::COPY_SRC + | wgpu::TextureUsages::COPY_DST + | wgpu::TextureUsages::RENDER_ATTACHMENT + } + pub fn set_budget_mb(&mut self, budget_mb: u64) { self.budget_bytes = budget_mb.saturating_mul(1024 * 1024); + self.trim_pool_to_budget(); self.evict_over_budget(); + self.trim_pool_to_budget(); } pub fn budget_mb(&self) -> u64 { @@ -161,6 +390,142 @@ impl NodeCache { self.node_salts.get(&id).copied().unwrap_or(0) } + pub fn pool_stats(&self) -> TexturePoolStats { + self.pool.lock().expect("texture pool lock").stats() + } + + pub fn pooled_bytes(&self) -> u64 { + self.pool.lock().expect("texture pool lock").pooled_bytes() + } + + pub fn pooled_mb(&self) -> f64 { + self.pooled_bytes() as f64 / (1024.0 * 1024.0) + } + + pub fn live_bytes(&self) -> u64 { + self.total_bytes + } + + pub fn live_mb(&self) -> f64 { + self.total_bytes as f64 / (1024.0 * 1024.0) + } + + pub fn total_vram_bytes(&self) -> u64 { + self.total_bytes.saturating_add(self.pooled_bytes()) + } + + /// Acquires a GPU texture matching `(width, height, format, usage)` from the pool if an + /// exclusively-owned texture is available, otherwise allocates a fresh one on `device`. + pub fn acquire_texture( + &self, + device: &wgpu::Device, + width: u32, + height: u32, + format: wgpu::TextureFormat, + usage: wgpu::TextureUsages, + ) -> CachedTexture { + let clamped = [width.max(1), height.max(1)]; + let bytes = texture_bytes(clamped, format); + let key = TexturePoolKey { + width: clamped[0], + height: clamped[1], + format, + usage, + }; + let depth = depth_for_format(format); + + { + let mut pool = self.pool.lock().expect("texture pool lock"); + if let Some((texture, view, pooled_bytes)) = pool.pop(key) { + pool.hits += 1; + return CachedTexture::from_parts( + texture, + view, + clamped, + [0, 0], + clamped, + depth, + format, + 0, + pooled_bytes, + ); + } + pool.misses += 1; + // Evict oldest pooled textures upfront so live + pooled + new allocation stays within budget. + while self + .total_bytes + .saturating_add(pool.total_bytes) + .saturating_add(bytes) + > self.budget_bytes + { + if !pool.evict_oldest() { + break; + } + } + } + + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("comp-tex"), + size: wgpu::Extent3d { + width: clamped[0], + height: clamped[1], + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage, + view_formats: &[], + }); + CachedTexture::from_texture_dod_depth(texture, clamped, [0, 0], clamped, depth, 0) + } + + /// Pool-backed DoD texture allocation matching `create_texture_dod_fmt` semantics. + #[allow(clippy::too_many_arguments)] + pub fn acquire_texture_dod_fmt( + &self, + device: &wgpu::Device, + size: [u32; 2], + origin: [i32; 2], + canvas_size: [u32; 2], + depth: BitDepth, + format: wgpu::TextureFormat, + content_hash: u64, + ) -> CachedTexture { + let mut tex = self.acquire_texture( + device, + size[0], + size[1], + format, + Self::default_texture_usage(), + ); + tex.origin = origin; + tex.canvas_size = [canvas_size[0].max(1), canvas_size[1].max(1)]; + tex.depth = depth; + tex.content_hash = content_hash; + tex + } + + /// Starts per-node profiling for the upcoming frame evaluation. + pub fn begin_frame_profile(&mut self) { + let stats = self.pool_stats(); + self.profiler = Some(ProfileRecorder::new(stats.hits, stats.misses)); + } + + /// Starts per-node profiling with node names and kinds pre-populated from `comp`. + pub fn begin_frame_profile_with_comp(&mut self, comp: &Comp) { + let stats = self.pool_stats(); + self.profiler = Some(ProfileRecorder::with_comp(comp, stats.hits, stats.misses)); + } + + /// Stops profiling and returns the collected `FrameProfile`, if active. + pub fn take_frame_profile(&mut self) -> Option { + let rec = self.profiler.take()?; + let stats = self.pool_stats(); + Some(rec.finish(self.total_bytes, stats.pooled_bytes, stats.hits, stats.misses)) + } + pub fn get(&mut self, key: u64, node: NodeId, frame: i64) -> Option { if self.mode == CacheMode::Bypass { return None; @@ -170,18 +535,28 @@ impl NodeCache { e.last_used = self.tick; e.producers.insert(node); e.frames.insert(frame); - Some(e.tex.clone()) + let tex = e.tex.clone(); + if let Some(prof) = &mut self.profiler { + prof.record(node, true, tex.size, tex.bytes); + } + Some(tex) } pub fn insert(&mut self, key: u64, tex: CachedTexture, node: NodeId, frame: i64) { + if let Some(prof) = &mut self.profiler { + prof.record(node, false, tex.size, tex.bytes); + } if self.mode == CacheMode::Bypass { return; } self.tick += 1; if let Some(old) = self.entries.remove(&key) { self.total_bytes = self.total_bytes.saturating_sub(old.tex.bytes); + if !Arc::ptr_eq(&old.tex.texture, &tex.texture) { + self.return_to_pool(&old.tex); + } } - self.total_bytes += tex.bytes; + self.total_bytes = self.total_bytes.saturating_add(tex.bytes); let mut producers = HashSet::new(); producers.insert(node); let mut frames = HashSet::new(); @@ -195,7 +570,32 @@ impl NodeCache { frames, }, ); + // Trim pooled textures before evicting live cached nodes so live working sets stay hot. + self.trim_pool_to_budget(); self.evict_over_budget(); + self.trim_pool_to_budget(); + } + + fn return_to_pool(&self, tex: &CachedTexture) { + if tex.bytes == 0 || tex.bytes > self.budget_bytes { + return; + } + let mut pool = self.pool.lock().expect("texture pool lock"); + pool.push(tex); + while self.total_bytes.saturating_add(pool.total_bytes) > self.budget_bytes { + if !pool.evict_oldest() { + break; + } + } + } + + fn trim_pool_to_budget(&self) { + let mut pool = self.pool.lock().expect("texture pool lock"); + while self.total_bytes.saturating_add(pool.total_bytes) > self.budget_bytes { + if !pool.evict_oldest() { + break; + } + } } fn evict_over_budget(&mut self) { @@ -207,18 +607,46 @@ impl NodeCache { if let Some(removed) = self.entries.remove(&oldest_key) { self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes); self.evictions += 1; + if self + .total_bytes + .saturating_add(self.pooled_bytes()) + .saturating_add(removed.tex.bytes) + <= self.budget_bytes + { + self.return_to_pool(&removed.tex); + } } } } - /// Wipes every cached GPU node texture and bumps global salt. + /// Wipes every cached GPU node texture (returning eligible textures to the pool) and bumps global salt. pub fn bust_all(&mut self) { - self.entries.clear(); + let _ = self.clear_dynamic(); + } + + /// Clears all dynamic cached GPU node textures into the pool (within VRAM budget) and bumps global salt. + pub fn clear_dynamic(&mut self) -> usize { + let count = self.entries.len(); + let drained: Vec = self.entries.drain().map(|(_, e)| e).collect(); self.total_bytes = 0; self.gpu_salt += 1; + if !drained.is_empty() && self.budget_bytes > 0 { + let mut pool = self.pool.lock().expect("texture pool lock"); + for entry in drained { + if entry.tex.bytes > 0 && entry.tex.bytes <= self.budget_bytes { + pool.push(&entry.tex); + } + } + while self.total_bytes.saturating_add(pool.total_bytes) > self.budget_bytes { + if !pool.evict_oldest() { + break; + } + } + } + count } - /// Removes cached entries produced for a specific integer frame. + /// Removes cached entries produced for a specific integer frame, returning them to the pool. pub fn bust_frame(&mut self, frame: i64) -> usize { let keys: Vec = self .entries @@ -230,13 +658,14 @@ impl NodeCache { for k in keys { if let Some(removed) = self.entries.remove(&k) { self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes); + self.return_to_pool(&removed.tex); } } count } /// Bumps the salt on `node` (automatically invalidating `node` AND everything downstream - /// via Merkle hashing!) and evicts its existing entries. + /// via Merkle hashing!) and evicts its existing entries back into the pool. pub fn bust_subtree(&mut self, node: NodeId) -> usize { *self.node_salts.entry(node).or_insert(0) += 1; let keys: Vec = self @@ -249,6 +678,7 @@ impl NodeCache { for k in keys { if let Some(removed) = self.entries.remove(&k) { self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes); + self.return_to_pool(&removed.tex); } } count @@ -259,6 +689,167 @@ impl NodeCache { } pub fn total_mb(&self) -> f64 { - self.total_bytes as f64 / (1024.0 * 1024.0) + self.total_vram_bytes() as f64 / (1024.0 * 1024.0) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Engine; + + #[test] + fn texture_pool_recycles_after_clear_dynamic_and_bust() { + let eng = Engine::new_headless().expect("gpu"); + let device = eng.device(); + let usage = NodeCache::default_texture_usage(); + let mut cache = NodeCache::new(DEFAULT_VRAM_BUDGET_MB); + + // Initial acquire misses pool and allocates a 512x512 RGBA8 texture (1 MiB). + let t1 = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage); + let ptr1 = Arc::as_ptr(&t1.texture); + assert_eq!(t1.bytes, 1024 * 1024); + assert_eq!(cache.pool_stats().misses, 1); + assert_eq!(cache.pool_stats().hits, 0); + + cache.insert(101, t1, NodeId(1), 0); + assert_eq!(cache.live_bytes(), 1024 * 1024); + assert_eq!(cache.pooled_bytes(), 0); + + // clear_dynamic returns unshared texture to pool without freeing GPU allocation. + let cleared = cache.clear_dynamic(); + assert_eq!(cleared, 1); + assert_eq!(cache.live_bytes(), 0); + assert_eq!(cache.pooled_bytes(), 1024 * 1024); + assert_eq!(cache.pool_stats().pooled_count, 1); + + // Acquiring same (w, h, format, usage) reuses the exact same wgpu::Texture allocation! + let t2 = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage); + assert_eq!(Arc::as_ptr(&t2.texture), ptr1); + assert_eq!(cache.pool_stats().hits, 1); + assert_eq!(cache.pool_stats().misses, 1); + assert_eq!(cache.pooled_bytes(), 0); + + // Different format must miss pool and allocate separately. + let t3 = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba16Float, usage); + assert_ne!(Arc::as_ptr(&t3.texture), ptr1); + assert_eq!(cache.pool_stats().misses, 2); + + // Insert both and bust_frame(5) -> returns only frame 5 texture to pool. + cache.insert(201, t2, NodeId(1), 5); + cache.insert(202, t3, NodeId(2), 6); + assert_eq!(cache.bust_frame(5), 1); + assert_eq!(cache.pooled_bytes(), 1024 * 1024); + assert_eq!(cache.live_bytes(), 2 * 1024 * 1024); + + let t4 = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage); + assert_eq!(Arc::as_ptr(&t4.texture), ptr1); + assert_eq!(cache.pool_stats().hits, 2); + } + + #[test] + fn texture_pool_never_aliases_shared_arc() { + let eng = Engine::new_headless().expect("gpu"); + let device = eng.device(); + let usage = NodeCache::default_texture_usage(); + let mut cache = NodeCache::new(16); + + let t1 = cache.acquire_texture(device, 256, 256, wgpu::TextureFormat::Rgba8Unorm, usage); + let pinned = t1.clone(); // External holder keeps strong_count > 1! + let ptr1 = Arc::as_ptr(&t1.texture); + cache.insert(1, t1, NodeId(0), 0); + cache.bust_all(); + + // While `pinned` is still alive, acquire_texture must NOT alias `t1`. + let t2 = cache.acquire_texture(device, 256, 256, wgpu::TextureFormat::Rgba8Unorm, usage); + assert_ne!(Arc::as_ptr(&t2.texture), ptr1); + assert_eq!(cache.pool_stats().hits, 0); + drop(pinned); + } + + #[test] + fn vram_budget_enforces_live_plus_pooled_cap_and_lru_eviction() { + let eng = Engine::new_headless().expect("gpu"); + let device = eng.device(); + let usage = NodeCache::default_texture_usage(); + // 8 MiB budget; each 1024x1024 RGBA8 texture is 4 MiB. + let mut cache = NodeCache::new(8); + let budget = 8 * 1024 * 1024; + + let a = cache.acquire_texture(device, 1024, 1024, wgpu::TextureFormat::Rgba8Unorm, usage); + let b = cache.acquire_texture(device, 1024, 1024, wgpu::TextureFormat::Rgba8Unorm, usage); + cache.insert(1, a, NodeId(0), 0); + cache.insert(2, b, NodeId(1), 0); + assert_eq!(cache.total_vram_bytes(), 8 * 1024 * 1024); + + // Bust both into pool: live=0, pooled=8 MiB <= 8 MiB. + cache.bust_all(); + assert_eq!(cache.live_bytes(), 0); + assert_eq!(cache.pooled_bytes(), 8 * 1024 * 1024); + + // Inserting a 1024x1024 RGBA16F (8 MiB) must evict ALL pooled RGBA8 textures so live + pooled <= 8 MiB. + let c = cache.acquire_texture(device, 1024, 1024, wgpu::TextureFormat::Rgba16Float, usage); + assert!(cache.total_vram_bytes() <= budget); + cache.insert(3, c, NodeId(2), 1); + assert!(cache.total_vram_bytes() <= budget); + assert_eq!(cache.pooled_bytes(), 0); + assert!(cache.pool_stats().evictions >= 2); + + // Verify deterministic LRU eviction order in pool within 8 MiB. + let mut cache3 = NodeCache::new(8); + let first = cache3.acquire_texture(device, 1024, 1024, wgpu::TextureFormat::Rgba8Unorm, usage); // 4 MiB + let second = cache3.acquire_texture(device, 512, 1024, wgpu::TextureFormat::Rgba8Unorm, usage); // 2 MiB + let third = cache3.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage); // 1 MiB + let ptr_second = Arc::as_ptr(&second.texture); + cache3.insert(1, first, NodeId(0), 1); + cache3.insert(2, second, NodeId(1), 2); + cache3.insert(3, third, NodeId(2), 3); + assert!(cache3.total_vram_bytes() <= budget); + + // Bust in deterministic order: frame 1 (4 MiB) oldest, then frame 2 (2 MiB), then frame 3 (1 MiB) => 7 MiB pooled. + assert_eq!(cache3.bust_frame(1), 1); + assert_eq!(cache3.bust_frame(2), 1); + assert_eq!(cache3.bust_frame(3), 1); + assert_eq!(cache3.pooled_bytes(), 7 * 1024 * 1024); + + // Acquiring a 4 MiB Rgba16Float (512x1024x8 = 4 MiB) misses pool and must evict oldest (frame 1's 4 MiB), + // leaving frame 2 (2 MiB) + frame 3 (1 MiB) intact! + let _new_f16 = cache3.acquire_texture(device, 512, 1024, wgpu::TextureFormat::Rgba16Float, usage); + assert_eq!(cache3.pooled_bytes(), 3 * 1024 * 1024); + let reused_second = cache3.acquire_texture(device, 512, 1024, wgpu::TextureFormat::Rgba8Unorm, usage); + assert_eq!(Arc::as_ptr(&reused_second.texture), ptr_second); + } + + #[test] + fn default_budget_is_768_mb_and_profiler_records_hits_misses() { + let eng = Engine::new_headless().expect("gpu"); + let device = eng.device(); + let usage = NodeCache::default_texture_usage(); + let mut cache = NodeCache::new(DEFAULT_VRAM_BUDGET_MB); + assert_eq!(cache.budget_mb(), 768); + assert_eq!(cache.budget_bytes, 768 * 1024 * 1024); + + // Cold profile: 1 miss + insert + cache.begin_frame_profile(); + assert!(cache.get(42, NodeId(7), 10).is_none()); + let t = cache.acquire_texture(device, 640, 360, wgpu::TextureFormat::Rgba8Unorm, usage); + cache.insert(42, t, NodeId(7), 10); + let p_cold = cache.take_frame_profile().expect("profile"); + assert_eq!(p_cold.cache_hits, 0); + assert_eq!(p_cold.cache_misses, 1); + assert_eq!(p_cold.pool_misses, 1); + assert_eq!(p_cold.pool_hits, 0); + assert_eq!(p_cold.entries.len(), 1); + assert_eq!(p_cold.entries[0].width, 640); + assert_eq!(p_cold.entries[0].height, 360); + + // Warm profile: 1 hit + cache.begin_frame_profile(); + assert!(cache.get(42, NodeId(7), 10).is_some()); + let p_warm = cache.take_frame_profile().expect("profile"); + assert_eq!(p_warm.cache_hits, 1); + assert_eq!(p_warm.cache_misses, 0); + assert_eq!(p_warm.entries.len(), 1); + assert!(p_warm.entries[0].cache_hit); } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 1b17f89c1ee4b1f643d5962cfd71b8669c781745..cbc394ec8f3912cb7479dd7354f2a43cfdedffe9 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -7,13 +7,18 @@ pub mod export; pub mod media; pub mod optflow; pub mod particles; +pub mod profile; pub mod ram_cache; pub mod scene3d; pub use audio::{AudioPlayer, AudioTrack}; -pub use cache::{CacheMode, CachedTexture, DEFAULT_VRAM_BUDGET_MB, EvalStats, NodeCache}; +pub use cache::{ + CacheMode, CachedTexture, DEFAULT_VRAM_BUDGET_MB, EvalStats, GpuCache, NodeCache, TexturePool, + TexturePoolKey, TexturePoolStats, +}; pub use eval::{DisplaySettings, Engine, create_texture}; pub use export::{ExportOptions, ExportProgress, ExportSummary, export_saver_png_sequence, select_saver}; +pub use profile::{FrameProfile, NodeProfileEntry}; pub use ram_cache::{ DEFAULT_RAM_CACHE_MB, PrefetchJob, RamFrame, RamFrameCache, RamFrameKey, RamPrefetcher, }; diff --git a/crates/engine/src/profile.rs b/crates/engine/src/profile.rs new file mode 100644 index 0000000000000000000000000000000000000000..6a85390016d42dc689646c5ea1066fe8b4362fce --- /dev/null +++ b/crates/engine/src/profile.rs @@ -0,0 +1,327 @@ +//! Per-node GPU evaluation profiling and frame telemetry. + +use model::{Comp, NodeId}; +use std::collections::HashMap; +use std::fmt::Write as _; +use std::time::Instant; + +/// Profiling telemetry for a single node lookup or evaluation within a frame. +#[derive(Clone, Debug, PartialEq)] +pub struct NodeProfileEntry { + pub node_id: NodeId, + pub node_name: String, + pub kind: String, + pub eval_ms: f64, + pub cache_hit: bool, + pub width: u32, + pub height: u32, + pub vram_bytes: u64, +} + +/// Aggregated per-frame render telemetry captured across `NodeCache` lookups/inserts. +#[derive(Clone, Debug, Default)] +pub struct FrameProfile { + pub entries: Vec, + pub total_eval_ms: f64, + pub total_vram_bytes: u64, + pub live_vram_bytes: u64, + pub pooled_vram_bytes: u64, + pub cache_hits: usize, + pub cache_misses: usize, + pub pool_hits: u64, + pub pool_misses: u64, +} + +impl FrameProfile { + pub fn new() -> Self { + Self::default() + } + + /// Resolves `node_name` and `kind` for each entry using `comp.nodes`. + pub fn populate_names_from_comp(&mut self, comp: &Comp) { + for entry in &mut self.entries { + let node_opt = comp + .nodes + .get(entry.node_id.0) + .filter(|n| n.id == entry.node_id) + .or_else(|| comp.nodes.iter().find(|n| n.id == entry.node_id)); + if let Some(node) = node_opt { + entry.node_name = node.name.clone(); + entry.kind = node.kind.clone(); + } + } + } + + /// Sum of exclusive `eval_ms` across all profiled node entries. + pub fn total_node_eval_ms(&self) -> f64 { + self.entries.iter().map(|e| e.eval_ms).sum() + } + + /// Texture pool hit ratio in `[0.0, 1.0]`. + pub fn pool_reuse_rate(&self) -> f64 { + let total = self.pool_hits.saturating_add(self.pool_misses); + if total == 0 { + 0.0 + } else { + self.pool_hits as f64 / total as f64 + } + } + + /// Node cache hit ratio in `[0.0, 1.0]`. + pub fn cache_hit_rate(&self) -> f64 { + let total = self.cache_hits.saturating_add(self.cache_misses); + if total == 0 { + 0.0 + } else { + self.cache_hits as f64 / total as f64 + } + } + + /// Returns up to `limit` hottest nodes sorted by `eval_ms` descending (tie-broken by VRAM). + pub fn hot_nodes(&self, limit: usize) -> Vec<&NodeProfileEntry> { + let mut refs: Vec<&NodeProfileEntry> = self.entries.iter().collect(); + refs.sort_by(|a, b| { + b.eval_ms + .total_cmp(&a.eval_ms) + .then_with(|| b.vram_bytes.cmp(&a.vram_bytes)) + .then_with(|| a.node_name.cmp(&b.node_name)) + }); + refs.truncate(limit); + refs + } + + /// Returns up to `limit` heaviest nodes sorted by `vram_bytes` descending (tie-broken by `eval_ms`). + pub fn hot_nodes_by_vram(&self, limit: usize) -> Vec<&NodeProfileEntry> { + let mut refs: Vec<&NodeProfileEntry> = self.entries.iter().collect(); + refs.sort_by(|a, b| { + b.vram_bytes + .cmp(&a.vram_bytes) + .then_with(|| b.eval_ms.total_cmp(&a.eval_ms)) + .then_with(|| a.node_name.cmp(&b.node_name)) + }); + refs.truncate(limit); + refs + } + + /// Formats a human-readable summary and top-`limit` hot nodes table. + pub fn format_top_nodes(&self, limit: usize) -> String { + let mut out = String::new(); + let total_mb = self.total_vram_bytes as f64 / (1024.0 * 1024.0); + let live_mb = self.live_vram_bytes as f64 / (1024.0 * 1024.0); + let pool_mb = self.pooled_vram_bytes as f64 / (1024.0 * 1024.0); + let _ = writeln!( + out, + "Profile: eval={:.2}ms (nodes={:.2}ms) | vram={:.1}MB (live={:.1}MB, pool={:.1}MB) | cache={}/{} ({:.1}%) | pool={}/{} (reuse {:.1}%)", + self.total_eval_ms, + self.total_node_eval_ms(), + total_mb, + live_mb, + pool_mb, + self.cache_hits, + self.cache_hits + self.cache_misses, + self.cache_hit_rate() * 100.0, + self.pool_hits, + self.pool_hits + self.pool_misses, + self.pool_reuse_rate() * 100.0, + ); + + let top = self.hot_nodes(limit); + if top.is_empty() { + let _ = writeln!(out, " (no node cache evaluations recorded)"); + return out; + } + + let _ = writeln!( + out, + "{:<4} {:<24} {:<20} {:<6} {:>11} {:>9} {:>10}", + "#", "NODE", "KIND", "CACHE", "RES", "VRAM_MB", "EVAL_MS" + ); + let _ = writeln!(out, "{}", "-".repeat(90)); + for (idx, e) in top.iter().enumerate() { + let res = format!("{}x{}", e.width, e.height); + let mb = e.vram_bytes as f64 / (1024.0 * 1024.0); + let name = truncate_label(&e.node_name, 24); + let kind = truncate_label(&e.kind, 20); + let _ = writeln!( + out, + "{:<4} {:<24} {:<20} {:<6} {:>11} {:>9.2} {:>9.2}ms", + idx + 1, + name, + kind, + if e.cache_hit { "HIT" } else { "MISS" }, + res, + mb, + e.eval_ms, + ); + } + out + } +} + +fn truncate_label(s: &str, max_chars: usize) -> String { + let count = s.chars().count(); + if count <= max_chars { + s.to_owned() + } else if max_chars <= 3 { + s.chars().take(max_chars).collect() + } else { + let mut t: String = s.chars().take(max_chars - 3).collect(); + t.push_str("..."); + t + } +} + +#[derive(Debug)] +pub(crate) struct ProfileRecorder { + started_at: Instant, + last_event: Instant, + pool_hits_start: u64, + pool_misses_start: u64, + node_meta: HashMap, + entries: Vec, +} + +impl ProfileRecorder { + pub(crate) fn new(pool_hits_start: u64, pool_misses_start: u64) -> Self { + let now = Instant::now(); + Self { + started_at: now, + last_event: now, + pool_hits_start, + pool_misses_start, + node_meta: HashMap::new(), + entries: Vec::new(), + } + } + + pub(crate) fn with_comp(comp: &Comp, pool_hits_start: u64, pool_misses_start: u64) -> Self { + let mut rec = Self::new(pool_hits_start, pool_misses_start); + rec.node_meta.reserve(comp.nodes.len()); + for node in &comp.nodes { + rec.node_meta + .insert(node.id, (node.name.clone(), node.kind.clone())); + } + rec + } + + pub(crate) fn record( + &mut self, + node_id: NodeId, + cache_hit: bool, + size: [u32; 2], + vram_bytes: u64, + ) { + let now = Instant::now(); + let eval_ms = now.duration_since(self.last_event).as_secs_f64() * 1000.0; + self.last_event = now; + let (node_name, kind) = self + .node_meta + .get(&node_id) + .cloned() + .unwrap_or_else(|| (format!("Node#{}", node_id.0), "Unknown".to_owned())); + self.entries.push(NodeProfileEntry { + node_id, + node_name, + kind, + eval_ms, + cache_hit, + width: size[0], + height: size[1], + vram_bytes, + }); + } + + pub(crate) fn finish( + self, + live_vram_bytes: u64, + pooled_vram_bytes: u64, + pool_hits_now: u64, + pool_misses_now: u64, + ) -> FrameProfile { + let total_eval_ms = self.started_at.elapsed().as_secs_f64() * 1000.0; + let mut cache_hits = 0usize; + let mut cache_misses = 0usize; + for e in &self.entries { + if e.cache_hit { + cache_hits += 1; + } else { + cache_misses += 1; + } + } + FrameProfile { + entries: self.entries, + total_eval_ms, + total_vram_bytes: live_vram_bytes.saturating_add(pooled_vram_bytes), + live_vram_bytes, + pooled_vram_bytes, + cache_hits, + cache_misses, + pool_hits: pool_hits_now.saturating_sub(self.pool_hits_start), + pool_misses: pool_misses_now.saturating_sub(self.pool_misses_start), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn entry(id: usize, name: &str, kind: &str, eval_ms: f64, hit: bool, bytes: u64) -> NodeProfileEntry { + NodeProfileEntry { + node_id: NodeId(id), + node_name: name.to_owned(), + kind: kind.to_owned(), + eval_ms, + cache_hit: hit, + width: 1920, + height: 1080, + vram_bytes: bytes, + } + } + + #[test] + fn hot_nodes_sorts_by_duration_and_limits() { + let profile = FrameProfile { + entries: vec![ + entry(0, "BG", "Background", 1.2, false, 8 * 1024 * 1024), + entry(1, "Blur1", "Blur", 14.5, false, 16 * 1024 * 1024), + entry(2, "Loader1", "Loader", 22.0, false, 32 * 1024 * 1024), + entry(3, "CC1", "ColorCorrector", 0.05, true, 8 * 1024 * 1024), + ], + total_eval_ms: 37.75, + total_vram_bytes: 64 * 1024 * 1024, + live_vram_bytes: 56 * 1024 * 1024, + pooled_vram_bytes: 8 * 1024 * 1024, + cache_hits: 1, + cache_misses: 3, + pool_hits: 3, + pool_misses: 1, + }; + + let top2 = profile.hot_nodes(2); + assert_eq!(top2.len(), 2); + assert_eq!(top2[0].node_name, "Loader1"); + assert_eq!(top2[1].node_name, "Blur1"); + + let top_vram = profile.hot_nodes_by_vram(1); + assert_eq!(top_vram[0].node_name, "Loader1"); + assert!((profile.pool_reuse_rate() - 0.75).abs() < 1e-6); + assert!((profile.cache_hit_rate() - 0.25).abs() < 1e-6); + assert!((profile.total_node_eval_ms() - 37.75).abs() < 1e-6); + + let table = profile.format_top_nodes(15); + assert!(table.contains("Loader1")); + assert!(table.contains("Blur1")); + assert!(table.contains("reuse 75.0%")); + assert!(table.contains("64.0MB")); + } + + #[test] + fn zero_pool_and_cache_counts_handle_division_by_zero() { + let profile = FrameProfile::new(); + assert_eq!(profile.pool_reuse_rate(), 0.0); + assert_eq!(profile.cache_hit_rate(), 0.0); + let formatted = profile.format_top_nodes(15); + assert!(formatted.contains("no node cache evaluations recorded")); + } +} -- 2.54.1