| 1 | //! Per-node GPU evaluation profiling and frame telemetry. |
| 2 | |
| 3 | use model::{Comp, NodeId}; |
| 4 | use std::collections::HashMap; |
| 5 | use std::fmt::Write as _; |
| 6 | #[cfg(not(target_arch = "wasm32"))] |
| 7 | use std::time::Instant; |
| 8 | #[cfg(target_arch = "wasm32")] |
| 9 | use web_time::Instant; |
| 10 | |
| 11 | /// Profiling telemetry for a single node lookup or evaluation within a frame. |
| 12 | #[derive(Clone, Debug, PartialEq)] |
| 13 | pub struct NodeProfileEntry { |
| 14 | pub node_id: NodeId, |
| 15 | pub node_name: String, |
| 16 | pub kind: String, |
| 17 | pub eval_ms: f64, |
| 18 | pub cache_hit: bool, |
| 19 | pub width: u32, |
| 20 | pub height: u32, |
| 21 | pub vram_bytes: u64, |
| 22 | } |
| 23 | |
| 24 | /// Aggregated per-frame render telemetry captured across `NodeCache` lookups/inserts. |
| 25 | #[derive(Clone, Debug, Default)] |
| 26 | pub struct FrameProfile { |
| 27 | pub entries: Vec<NodeProfileEntry>, |
| 28 | pub total_eval_ms: f64, |
| 29 | pub total_vram_bytes: u64, |
| 30 | pub live_vram_bytes: u64, |
| 31 | pub pooled_vram_bytes: u64, |
| 32 | pub cache_hits: usize, |
| 33 | pub cache_misses: usize, |
| 34 | pub pool_hits: u64, |
| 35 | pub pool_misses: u64, |
| 36 | } |
| 37 | |
| 38 | impl FrameProfile { |
| 39 | /// Per-node allocation threshold (64 MiB) above which a node is considered heavy VRAM. |
| 40 | pub const HEAVY_VRAM_NODE_BYTES: u64 = 64 * 1024 * 1024; |
| 41 | /// Frame live VRAM threshold (512 MiB) above which the Top VRAM section is always shown. |
| 42 | pub const HIGH_LIVE_VRAM_BYTES: u64 = 512 * 1024 * 1024; |
| 43 | |
| 44 | pub fn new() -> Self { |
| 45 | Self::default() |
| 46 | } |
| 47 | |
| 48 | /// Resolves `node_name` and `kind` for each entry using `comp.nodes`. |
| 49 | pub fn populate_names_from_comp(&mut self, comp: &Comp) { |
| 50 | for entry in &mut self.entries { |
| 51 | let node_opt = comp |
| 52 | .nodes |
| 53 | .get(entry.node_id.0) |
| 54 | .filter(|n| n.id == entry.node_id) |
| 55 | .or_else(|| comp.nodes.iter().find(|n| n.id == entry.node_id)); |
| 56 | if let Some(node) = node_opt { |
| 57 | entry.node_name = node.name.clone(); |
| 58 | entry.kind = node.kind.clone(); |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | /// Sum of exclusive `eval_ms` across all profiled node entries. |
| 64 | pub fn total_node_eval_ms(&self) -> f64 { |
| 65 | self.entries.iter().map(|e| e.eval_ms).sum() |
| 66 | } |
| 67 | |
| 68 | /// Texture pool hit ratio in `[0.0, 1.0]`. |
| 69 | pub fn pool_reuse_rate(&self) -> f64 { |
| 70 | let total = self.pool_hits.saturating_add(self.pool_misses); |
| 71 | if total == 0 { |
| 72 | 0.0 |
| 73 | } else { |
| 74 | self.pool_hits as f64 / total as f64 |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | /// Node cache hit ratio in `[0.0, 1.0]`. |
| 79 | pub fn cache_hit_rate(&self) -> f64 { |
| 80 | let total = self.cache_hits.saturating_add(self.cache_misses); |
| 81 | if total == 0 { |
| 82 | 0.0 |
| 83 | } else { |
| 84 | self.cache_hits as f64 / total as f64 |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | /// Returns up to `limit` hottest nodes sorted by `eval_ms` descending (tie-broken by VRAM). |
| 89 | pub fn hot_nodes(&self, limit: usize) -> Vec<&NodeProfileEntry> { |
| 90 | let mut refs: Vec<&NodeProfileEntry> = self.entries.iter().collect(); |
| 91 | refs.sort_by(|a, b| { |
| 92 | b.eval_ms |
| 93 | .total_cmp(&a.eval_ms) |
| 94 | .then_with(|| b.vram_bytes.cmp(&a.vram_bytes)) |
| 95 | .then_with(|| a.node_name.cmp(&b.node_name)) |
| 96 | }); |
| 97 | refs.truncate(limit); |
| 98 | refs |
| 99 | } |
| 100 | |
| 101 | /// Returns up to `limit` heaviest nodes sorted by `vram_bytes` descending (tie-broken by `eval_ms`). |
| 102 | pub fn hot_nodes_by_vram(&self, limit: usize) -> Vec<&NodeProfileEntry> { |
| 103 | let mut refs: Vec<&NodeProfileEntry> = self.entries.iter().collect(); |
| 104 | refs.sort_by(|a, b| { |
| 105 | b.vram_bytes |
| 106 | .cmp(&a.vram_bytes) |
| 107 | .then_with(|| b.eval_ms.total_cmp(&a.eval_ms)) |
| 108 | .then_with(|| a.node_name.cmp(&b.node_name)) |
| 109 | }); |
| 110 | refs.truncate(limit); |
| 111 | refs |
| 112 | } |
| 113 | |
| 114 | /// Returns up to `limit` heavy-VRAM nodes sorted by `vram_bytes` descending. |
| 115 | /// When `live_vram_bytes >= 512 MiB`, returns the top `limit` VRAM consumers; |
| 116 | /// otherwise returns only nodes using at least `64 MiB`. |
| 117 | pub fn heavy_vram_nodes(&self, limit: usize) -> Vec<&NodeProfileEntry> { |
| 118 | if self.live_vram_bytes >= Self::HIGH_LIVE_VRAM_BYTES { |
| 119 | return self.hot_nodes_by_vram(limit); |
| 120 | } |
| 121 | let mut refs: Vec<&NodeProfileEntry> = self |
| 122 | .entries |
| 123 | .iter() |
| 124 | .filter(|e| e.vram_bytes >= Self::HEAVY_VRAM_NODE_BYTES) |
| 125 | .collect(); |
| 126 | refs.sort_by(|a, b| { |
| 127 | b.vram_bytes |
| 128 | .cmp(&a.vram_bytes) |
| 129 | .then_with(|| b.eval_ms.total_cmp(&a.eval_ms)) |
| 130 | .then_with(|| a.node_name.cmp(&b.node_name)) |
| 131 | }); |
| 132 | refs.truncate(limit); |
| 133 | refs |
| 134 | } |
| 135 | |
| 136 | /// Formats a human-readable summary, top-`limit` hot nodes table, and (when heavy) Top VRAM table. |
| 137 | pub fn format_top_nodes(&self, limit: usize) -> String { |
| 138 | let mut out = String::new(); |
| 139 | let total_mb = self.total_vram_bytes as f64 / (1024.0 * 1024.0); |
| 140 | let live_mb = self.live_vram_bytes as f64 / (1024.0 * 1024.0); |
| 141 | let pool_mb = self.pooled_vram_bytes as f64 / (1024.0 * 1024.0); |
| 142 | let _ = writeln!( |
| 143 | out, |
| 144 | "Profile: eval={:.2}ms (nodes={:.2}ms) | vram={:.1}MB (live={:.1}MB, pool={:.1}MB) | cache={}/{} ({:.1}%) | pool={}/{} (reuse {:.1}%)", |
| 145 | self.total_eval_ms, |
| 146 | self.total_node_eval_ms(), |
| 147 | total_mb, |
| 148 | live_mb, |
| 149 | pool_mb, |
| 150 | self.cache_hits, |
| 151 | self.cache_hits + self.cache_misses, |
| 152 | self.cache_hit_rate() * 100.0, |
| 153 | self.pool_hits, |
| 154 | self.pool_hits + self.pool_misses, |
| 155 | self.pool_reuse_rate() * 100.0, |
| 156 | ); |
| 157 | |
| 158 | let top = self.hot_nodes(limit); |
| 159 | if top.is_empty() { |
| 160 | let _ = writeln!(out, " (no node cache evaluations recorded)"); |
| 161 | return out; |
| 162 | } |
| 163 | |
| 164 | write_profile_table(&mut out, &top); |
| 165 | let vram_top = self.heavy_vram_nodes(limit); |
| 166 | if !vram_top.is_empty() { |
| 167 | let _ = writeln!(out, "Top VRAM:"); |
| 168 | write_profile_table(&mut out, &vram_top); |
| 169 | } |
| 170 | out |
| 171 | } |
| 172 | |
| 173 | /// Alias for [`Self::format_top_nodes`]. |
| 174 | pub fn format_report(&self, limit: usize) -> String { |
| 175 | self.format_top_nodes(limit) |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | fn write_profile_table(out: &mut String, rows: &[&NodeProfileEntry]) { |
| 180 | let _ = writeln!( |
| 181 | out, |
| 182 | "{:<4} {:<24} {:<20} {:<6} {:>11} {:>9} {:>10}", |
| 183 | "#", "NODE", "KIND", "CACHE", "RES", "VRAM_MB", "EVAL_MS" |
| 184 | ); |
| 185 | let _ = writeln!(out, "{}", "-".repeat(90)); |
| 186 | for (idx, e) in rows.iter().enumerate() { |
| 187 | let res = format!("{}x{}", e.width, e.height); |
| 188 | let mb = e.vram_bytes as f64 / (1024.0 * 1024.0); |
| 189 | let name = truncate_label(&e.node_name, 24); |
| 190 | let kind = truncate_label(&e.kind, 20); |
| 191 | let _ = writeln!( |
| 192 | out, |
| 193 | "{:<4} {:<24} {:<20} {:<6} {:>11} {:>9.2} {:>9.2}ms", |
| 194 | idx + 1, |
| 195 | name, |
| 196 | kind, |
| 197 | if e.cache_hit { "HIT" } else { "MISS" }, |
| 198 | res, |
| 199 | mb, |
| 200 | e.eval_ms, |
| 201 | ); |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | fn truncate_label(s: &str, max_chars: usize) -> String { |
| 206 | let count = s.chars().count(); |
| 207 | if count <= max_chars { |
| 208 | s.to_owned() |
| 209 | } else if max_chars <= 3 { |
| 210 | s.chars().take(max_chars).collect() |
| 211 | } else { |
| 212 | let mut t: String = s.chars().take(max_chars - 3).collect(); |
| 213 | t.push_str("..."); |
| 214 | t |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | #[derive(Debug)] |
| 219 | pub(crate) struct ProfileRecorder { |
| 220 | started_at: Instant, |
| 221 | last_event: Instant, |
| 222 | pool_hits_start: u64, |
| 223 | pool_misses_start: u64, |
| 224 | node_meta: HashMap<NodeId, (String, String)>, |
| 225 | entries: Vec<NodeProfileEntry>, |
| 226 | } |
| 227 | |
| 228 | impl ProfileRecorder { |
| 229 | pub(crate) fn new(pool_hits_start: u64, pool_misses_start: u64) -> Self { |
| 230 | let now = Instant::now(); |
| 231 | Self { |
| 232 | started_at: now, |
| 233 | last_event: now, |
| 234 | pool_hits_start, |
| 235 | pool_misses_start, |
| 236 | node_meta: HashMap::new(), |
| 237 | entries: Vec::new(), |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | pub(crate) fn with_comp(comp: &Comp, pool_hits_start: u64, pool_misses_start: u64) -> Self { |
| 242 | let mut rec = Self::new(pool_hits_start, pool_misses_start); |
| 243 | rec.node_meta.reserve(comp.nodes.len()); |
| 244 | for node in &comp.nodes { |
| 245 | rec.node_meta |
| 246 | .insert(node.id, (node.name.clone(), node.kind.clone())); |
| 247 | } |
| 248 | rec |
| 249 | } |
| 250 | |
| 251 | pub(crate) fn record( |
| 252 | &mut self, |
| 253 | node_id: NodeId, |
| 254 | cache_hit: bool, |
| 255 | size: [u32; 2], |
| 256 | vram_bytes: u64, |
| 257 | ) { |
| 258 | let now = Instant::now(); |
| 259 | let eval_ms = now.duration_since(self.last_event).as_secs_f64() * 1000.0; |
| 260 | self.last_event = now; |
| 261 | let (node_name, kind) = self |
| 262 | .node_meta |
| 263 | .get(&node_id) |
| 264 | .cloned() |
| 265 | .unwrap_or_else(|| (format!("Node#{}", node_id.0), "Unknown".to_owned())); |
| 266 | self.entries.push(NodeProfileEntry { |
| 267 | node_id, |
| 268 | node_name, |
| 269 | kind, |
| 270 | eval_ms, |
| 271 | cache_hit, |
| 272 | width: size[0], |
| 273 | height: size[1], |
| 274 | vram_bytes, |
| 275 | }); |
| 276 | } |
| 277 | |
| 278 | pub(crate) fn finish( |
| 279 | self, |
| 280 | live_vram_bytes: u64, |
| 281 | pooled_vram_bytes: u64, |
| 282 | pool_hits_now: u64, |
| 283 | pool_misses_now: u64, |
| 284 | ) -> FrameProfile { |
| 285 | let total_eval_ms = self.started_at.elapsed().as_secs_f64() * 1000.0; |
| 286 | let mut cache_hits = 0usize; |
| 287 | let mut cache_misses = 0usize; |
| 288 | for e in &self.entries { |
| 289 | if e.cache_hit { |
| 290 | cache_hits += 1; |
| 291 | } else { |
| 292 | cache_misses += 1; |
| 293 | } |
| 294 | } |
| 295 | FrameProfile { |
| 296 | entries: self.entries, |
| 297 | total_eval_ms, |
| 298 | total_vram_bytes: live_vram_bytes.saturating_add(pooled_vram_bytes), |
| 299 | live_vram_bytes, |
| 300 | pooled_vram_bytes, |
| 301 | cache_hits, |
| 302 | cache_misses, |
| 303 | pool_hits: pool_hits_now.saturating_sub(self.pool_hits_start), |
| 304 | pool_misses: pool_misses_now.saturating_sub(self.pool_misses_start), |
| 305 | } |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | #[cfg(test)] |
| 310 | mod tests { |
| 311 | use super::*; |
| 312 | |
| 313 | fn entry(id: usize, name: &str, kind: &str, eval_ms: f64, hit: bool, bytes: u64) -> NodeProfileEntry { |
| 314 | NodeProfileEntry { |
| 315 | node_id: NodeId(id), |
| 316 | node_name: name.to_owned(), |
| 317 | kind: kind.to_owned(), |
| 318 | eval_ms, |
| 319 | cache_hit: hit, |
| 320 | width: 1920, |
| 321 | height: 1080, |
| 322 | vram_bytes: bytes, |
| 323 | } |
| 324 | } |
| 325 | |
| 326 | #[test] |
| 327 | fn hot_nodes_sorts_by_duration_and_limits() { |
| 328 | let profile = FrameProfile { |
| 329 | entries: vec![ |
| 330 | entry(0, "BG", "Background", 1.2, false, 8 * 1024 * 1024), |
| 331 | entry(1, "Blur1", "Blur", 14.5, false, 16 * 1024 * 1024), |
| 332 | entry(2, "Loader1", "Loader", 22.0, false, 32 * 1024 * 1024), |
| 333 | entry(3, "CC1", "ColorCorrector", 0.05, true, 8 * 1024 * 1024), |
| 334 | ], |
| 335 | total_eval_ms: 37.75, |
| 336 | total_vram_bytes: 64 * 1024 * 1024, |
| 337 | live_vram_bytes: 56 * 1024 * 1024, |
| 338 | pooled_vram_bytes: 8 * 1024 * 1024, |
| 339 | cache_hits: 1, |
| 340 | cache_misses: 3, |
| 341 | pool_hits: 3, |
| 342 | pool_misses: 1, |
| 343 | }; |
| 344 | |
| 345 | let top2 = profile.hot_nodes(2); |
| 346 | assert_eq!(top2.len(), 2); |
| 347 | assert_eq!(top2[0].node_name, "Loader1"); |
| 348 | assert_eq!(top2[1].node_name, "Blur1"); |
| 349 | |
| 350 | let top_vram = profile.hot_nodes_by_vram(1); |
| 351 | assert_eq!(top_vram[0].node_name, "Loader1"); |
| 352 | assert!((profile.pool_reuse_rate() - 0.75).abs() < 1e-6); |
| 353 | assert!((profile.cache_hit_rate() - 0.25).abs() < 1e-6); |
| 354 | assert!((profile.total_node_eval_ms() - 37.75).abs() < 1e-6); |
| 355 | |
| 356 | let table = profile.format_top_nodes(15); |
| 357 | assert!(table.contains("Loader1")); |
| 358 | assert!(table.contains("Blur1")); |
| 359 | assert!(table.contains("reuse 75.0%")); |
| 360 | assert!(table.contains("64.0MB")); |
| 361 | assert!(!table.contains("Top VRAM:")); |
| 362 | assert!(profile.heavy_vram_nodes(5).is_empty()); |
| 363 | } |
| 364 | |
| 365 | #[test] |
| 366 | fn heavy_vram_nodes_triggers_top_vram_section() { |
| 367 | let profile = FrameProfile { |
| 368 | entries: vec![ |
| 369 | entry(0, "BG", "Background", 1.0, false, 8 * 1024 * 1024), |
| 370 | entry(1, "CC1", "ColorCorrector", 2.0, false, 256 * 1024 * 1024), |
| 371 | entry(2, "Scale1", "Scale", 3.0, false, 144 * 1024 * 1024), |
| 372 | ], |
| 373 | total_eval_ms: 6.0, |
| 374 | total_vram_bytes: 408 * 1024 * 1024, |
| 375 | live_vram_bytes: 408 * 1024 * 1024, |
| 376 | pooled_vram_bytes: 0, |
| 377 | cache_hits: 0, |
| 378 | cache_misses: 3, |
| 379 | pool_hits: 0, |
| 380 | pool_misses: 3, |
| 381 | }; |
| 382 | let heavy = profile.heavy_vram_nodes(5); |
| 383 | assert_eq!(heavy.len(), 2); |
| 384 | assert_eq!(heavy[0].node_name, "CC1"); |
| 385 | assert_eq!(heavy[1].node_name, "Scale1"); |
| 386 | let report = profile.format_report(15); |
| 387 | assert!(report.contains("Top VRAM:")); |
| 388 | assert!(report.contains("256.00")); |
| 389 | assert!(report.contains("144.00")); |
| 390 | |
| 391 | // When live_vram_bytes >= 512 MiB, even sub-64 MiB nodes appear in Top VRAM. |
| 392 | let high_live = FrameProfile { |
| 393 | entries: vec![ |
| 394 | entry(0, "Loader1", "Loader", 1.0, false, 32 * 1024 * 1024), |
| 395 | entry(1, "BG", "Background", 2.0, false, 8 * 1024 * 1024), |
| 396 | ], |
| 397 | total_eval_ms: 3.0, |
| 398 | total_vram_bytes: 600 * 1024 * 1024, |
| 399 | live_vram_bytes: 600 * 1024 * 1024, |
| 400 | pooled_vram_bytes: 0, |
| 401 | cache_hits: 0, |
| 402 | cache_misses: 2, |
| 403 | pool_hits: 0, |
| 404 | pool_misses: 2, |
| 405 | }; |
| 406 | assert_eq!(high_live.heavy_vram_nodes(5).len(), 2); |
| 407 | assert!(high_live.format_top_nodes(15).contains("Top VRAM:")); |
| 408 | } |
| 409 | |
| 410 | #[test] |
| 411 | fn zero_pool_and_cache_counts_handle_division_by_zero() { |
| 412 | let profile = FrameProfile::new(); |
| 413 | assert_eq!(profile.pool_reuse_rate(), 0.0); |
| 414 | assert_eq!(profile.cache_hit_rate(), 0.0); |
| 415 | let formatted = profile.format_top_nodes(15); |
| 416 | assert!(formatted.contains("no node cache evaluations recorded")); |
| 417 | } |
| 418 | } |