From ab95abe1b2fb5c50b8a5916097ef51c46491351c Mon Sep 17 00:00:00 2001 From: NimaJafariComp Date: Thu, 19 Nov 2026 14:31:32 -0600 Subject: [PATCH 01/14] test: cover memory reporting across stream lifetimes The new stream test fails to compile against the existing EngineReport because the memory breakdown is missing. --- crates/flyhigh-engine/tests/stream.rs | 47 +++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/crates/flyhigh-engine/tests/stream.rs b/crates/flyhigh-engine/tests/stream.rs index 6e230b7..3fb63b8 100644 --- a/crates/flyhigh-engine/tests/stream.rs +++ b/crates/flyhigh-engine/tests/stream.rs @@ -49,6 +49,53 @@ fn engine() -> Option { } } +#[test] +#[ignore = "requires a GPU"] +fn memory_returns_to_baseline_after_stream_drop() { + let e = engine().expect("a GPU is required for this test"); + let core = flyhigh_engine::Engine::from_shared(e.gpu.clone()); + let baseline = core.report().memory; + let open = |mode, cadence| { + let opts = StreamOptions { mode, cadence, ..Default::default() }; + Stream::new(&e.gpu, &e.blob, &e.ops, TexOptions::new(W, H), &opts, None).unwrap() + }; + + let realtime = open(Mode::Realtime, false); + let real = core.report().memory; + let slot_bytes = u64::from(W) * u64::from(H) * 4; + assert_eq!( + real.frame_textures.live_bytes, + slot_bytes * (realtime.report().inputs + realtime.report().outputs) as u64 + ); + assert!(real.tensors.live_bytes > 0); + assert_eq!(real.cadence_scratch.live_bytes, 0); + drop(realtime); + assert_eq!(core.report().memory.live_bytes, baseline.live_bytes); + + let video = open(Mode::Video, false); + let video_mem = core.report().memory; + assert_eq!(video_mem.cadence_scratch.live_bytes, 0); + assert!(video_mem.tensors.live_bytes > real.tensors.live_bytes); + drop(video); + + let mut anime = open(Mode::Video, true); + anime.warm_up(&e.gpu).unwrap(); + let active = core.report().memory; + assert!(active.cadence_scratch.live_bytes > 0); + assert!(active.live_bytes > video_mem.live_bytes); + anime.reset(); + assert_eq!(core.report().memory.live_bytes, active.live_bytes); + anime.add_input_texture(e.gpu.input_texture(W, H)).unwrap(); + assert_eq!(core.report().memory.live_bytes, active.live_bytes); + drop(anime); + let stopped = core.report().memory; + assert_eq!(stopped.live_bytes, baseline.live_bytes); + assert_eq!(stopped.frame_textures.live_bytes, 0); + assert_eq!(stopped.cadence_scratch.live_bytes, 0); + assert_eq!(stopped.peak_bytes, active.peak_bytes); + assert!(stopped.peak_bytes >= active.live_bytes); +} + // a soft pattern shifted `dx` px to the right fn frame(dx: f32) -> Vec { let mut v = vec![0u8; (W * H * 4) as usize]; From 630a81462d1ac2eb64ac905c5d98a648b4dfc668 Mon Sep 17 00:00:00 2001 From: NimaJafariComp Date: Thu, 19 Nov 2026 14:31:32 -0600 Subject: [PATCH 02/14] Report live and peak GPU allocations per engine Track allocation lifetimes through stream slots, the tensor arena, and plan bindings. Keep the cumulative counter for existing hosts and split out cadence scratch so its cost can be isolated from the three video pair plans. Verified with native stream and arena tests and the browser WASM build on Apple M5. Opening and freeing realtime, video, and cadence streams at 1920x1080 returned the portable-f16 engine to its 3 KiB baseline. --- ARCHITECTURE.md | 19 +- CHANGELOG.md | 5 + crates/flyhigh-engine/src/engine.rs | 4 + crates/flyhigh-engine/src/gen_tex.rs | 5 + crates/flyhigh-engine/src/gmhs.rs | 32 ++-- crates/flyhigh-engine/src/gpu/alloc.rs | 49 +++-- crates/flyhigh-engine/src/gpu/device.rs | 16 +- crates/flyhigh-engine/src/gpu/memory.rs | 177 ++++++++++++++++++ crates/flyhigh-engine/src/gpu/mod.rs | 22 ++- crates/flyhigh-engine/src/gpu/readback.rs | 8 +- crates/flyhigh-engine/src/net/build.rs | 32 ++-- crates/flyhigh-engine/src/net/session.rs | 9 +- crates/flyhigh-engine/src/net/session_ext.rs | 22 ++- crates/flyhigh-engine/src/net/session_tex.rs | 4 + .../flyhigh-engine/src/ops/conv/autotune.rs | 5 +- crates/flyhigh-engine/src/ops/conv/kernels.rs | 15 +- crates/flyhigh-engine/src/ops/elementwise.rs | 5 +- crates/flyhigh-engine/src/ops/render.rs | 3 +- crates/flyhigh-engine/src/ops/step.rs | 41 ++-- crates/flyhigh-engine/src/ops/tensor.rs | 3 +- crates/flyhigh-engine/src/ops/texture.rs | 9 +- crates/flyhigh-engine/src/session.rs | 6 +- crates/flyhigh-engine/src/stream/classify.rs | 20 +- crates/flyhigh-engine/src/warp/gpu.rs | 48 ++--- docs/api-c.md | 3 +- docs/api-js.md | 6 +- docs/api-rust.md | 4 +- 27 files changed, 426 insertions(+), 146 deletions(-) create mode 100644 crates/flyhigh-engine/src/gpu/memory.rs diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 7a41a35..1aed3bb 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -311,13 +311,30 @@ that into `OptionInfo`; a field without a doc comment does not compile. `flyhigh needs the fast render, tensor cores need f16) are resolved there and the resolution is reported, not silent. Pacer options may change live (`set_options`); Session and Stream options rebuild the object. -Each layer reports what it did: `engine.report()` (kernels compiled, autotune entries, tensor bytes), +Each layer reports what it did: `engine.report()` (kernels compiled, autotune entries, memory), `session.report()` and `stream.report()` (sizes, slots, counters), `pacer.report()` (the display and source estimates, the plan with its clamp reason and warning, the factor, penalties and pressure, delay and lateness, the measured costs, the queue, the counters of presents and drops by cause). Counters are monotonic since creation; a host diffs them for rates. The `FH_*` developer variables ([docs/development.md](docs/development.md)) are for the CLI and the kernel builders only; library hosts set options through the API. +`engine.report().memory` reports requested GPU bytes across all live sessions and streams sharing the engine. +It gives live totals and lifetime high-water marks, both overall and for each category: + +- `tensors`: network and render buffers, including arena buffers counted once even when reused. +- `initialized_buffers`: model weights, initialized network state and engine constants. +- `cadence_scratch`: the separate re-timing composite buffers. The three video pair plans and their retained maps + are counted in the plan categories, so compare realtime, video, and video with cadence at the same settings. +- `frame_textures`: input and output slots allocated by the engine. +- `auxiliary_buffers`, `auxiliary_textures`: plan uniforms, classifier, camera warp, and tracked readbacks. + +Compare `live_bytes` before opening, during playback, and after dropping the stream and completing any pending +calls. Resetting a stream keeps its allocations. `peak_bytes` is updated when an allocation is made, even if no +report was read then. The total peak is not the sum of category peaks, which can occur at different times. +`tensor_bytes` remains the cumulative allocation counter for compatibility. The report excludes imported and +other host-owned resources, standalone diagnostic staging, driver padding and caches, and buffers retained only +for GPU work in flight. It is not a measure of resident VRAM. + Open: named presets across the layers, and a single report tree with `to_json()` instead of one per layer. ## Errors diff --git a/CHANGELOG.md b/CHANGELOG.md index f2c6ecf..1b91880 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,11 @@ follow semantic versioning as described in [CONTRIBUTING.md](CONTRIBUTING.md). ## [Unreleased] +### Added + +- Engine reports include live and peak GPU allocation bytes, with separate totals for frame slots, network buffers, + cadence scratch, and auxiliary resources. + ## [0.5.0] - 2026-11-18 ### Added diff --git a/crates/flyhigh-engine/src/engine.rs b/crates/flyhigh-engine/src/engine.rs index 3c17f7e..09c6f16 100644 --- a/crates/flyhigh-engine/src/engine.rs +++ b/crates/flyhigh-engine/src/engine.rs @@ -1,6 +1,7 @@ //! `Engine`: the device the engine runs on, its compiled kernels and its autotune table (ARCHITECTURE.md). One per device; //! models and sessions share it. Create one, or bring the device an application already has. use crate::gpu::dxc::ShaderCompiler; +use crate::gpu::memory::MemoryReport; use crate::{EngineOptions, Gpu}; use anyhow::Result; use serde::Serialize; @@ -41,6 +42,8 @@ pub struct EngineReport { pub tune_entries: usize, /// Bytes of tensor buffers created so far. pub tensor_bytes: u64, + /// Live and peak requested buffer and texture bytes. Not driver VRAM usage. + pub memory: MemoryReport, } pub struct Engine { @@ -132,6 +135,7 @@ impl Engine { kernels_compiled: self.gpu.p.borrow().len(), tune_entries: self.gpu.tune.borrow().len(), tensor_bytes: self.gpu.alloc_bytes.get(), + memory: self.gpu.memory.report(), } } } diff --git a/crates/flyhigh-engine/src/gen_tex.rs b/crates/flyhigh-engine/src/gen_tex.rs index 595e1fb..ed0e925 100644 --- a/crates/flyhigh-engine/src/gen_tex.rs +++ b/crates/flyhigh-engine/src/gen_tex.rs @@ -11,6 +11,7 @@ //! Statistics come back through an async readback (`StatsRun`): native hosts block on it inside `push_slot`, the //! browser host awaits the promise of `fh_vid_stats` before the first `generate` of the interval (the lookahead hides it). use crate::gmhs::{CadenceScratch, PairStats, StatsRun}; +use crate::gpu::memory::Charge; use crate::{gmhs, Blob, Gpu, NetOpts, SessionExt, Step, TimedRun}; use anyhow::{Context, Result}; use serde_json::Value; @@ -99,6 +100,7 @@ pub struct GenTex { pub sess: Vec, pub ins: Vec<(wgpu::Texture, wgpu::TextureView)>, pub outs: Vec<(wgpu::Texture, wgpu::TextureView)>, + owned_slots: Vec, order: [usize; 3], stats: [PairStats; 3], scratch: Option, @@ -245,6 +247,7 @@ impl GenTex { sess, ins: Vec::new(), outs: Vec::new(), + owned_slots: Vec::new(), order: [0, 1, 2], stats: [PairStats::default(); 3], scratch, @@ -257,6 +260,7 @@ impl GenTex { } pub fn add_input(&mut self, gpu: &Gpu) -> usize { let t = gpu.input_texture_l(self.opts.w, self.opts.h, &format!("fh_vin_{}", self.ins.len())); + self.owned_slots.push(gpu.memory.rgba8_slot(&t)); let v = t.create_view(&wgpu::TextureViewDescriptor::default()); self.ins.push((t, v)); self.ins.len() - 1 @@ -284,6 +288,7 @@ impl GenTex { } pub fn add_output(&mut self, gpu: &Gpu) -> usize { let t = gpu.output_texture_l(self.opts.w, self.opts.h, &format!("fh_vout_{}", self.outs.len())); + self.owned_slots.push(gpu.memory.rgba8_slot(&t)); let v = t.create_view(&wgpu::TextureViewDescriptor::default()); self.outs.push((t, v)); self.outs.len() - 1 diff --git a/crates/flyhigh-engine/src/gmhs.rs b/crates/flyhigh-engine/src/gmhs.rs index af44031..7453e2f 100644 --- a/crates/flyhigh-engine/src/gmhs.rs +++ b/crates/flyhigh-engine/src/gmhs.rs @@ -13,6 +13,7 @@ //! The same maps feed cadence smoothing (`api::Mode::Video`): the displacement-difference channel is the motion of //! an element against the global motion, which classifies a pair as a jump / hold of an element animated on 2s and //! gives the mask for the re-timed composite (`pair_stats`, `composite_frame`). +use crate::gpu::memory::Buffer; use crate::{clone_step, workgroups_2d, Gpu, SessionExt, Step, Tensor}; use bytemuck::{Pod, Zeroable}; use std::cell::RefCell; @@ -240,13 +241,13 @@ pub const CHANGE_THR: f32 = 0.02; /// Buffers for the re-timed composite, sized for one session's frame size, and the cadence steps built from them /// (cached: their uniforms never change, and building one allocates GPU objects). pub struct CadenceScratch { - pub bg_copy: Rc, - pub mask_a: Rc, - pub mask_b: Rc, - pub trust_a: Rc, - pub trust_b: Rc, + pub bg_copy: Rc, + pub mask_a: Rc, + pub mask_b: Rc, + pub trust_a: Rc, + pub trust_b: Rc, pub out: Tensor, - pub part: Rc, + pub part: Rc, steps: RefCell>>, } pub const STAT_WG: u32 = 32; @@ -267,15 +268,16 @@ impl CadenceScratch { let (m, _, _) = maps_of(sess)?; let r = &sess.render; let n = (r.c * r.h * r.w) as usize; - let out = Tensor { buf: gpu.alloc(n), c: r.c, h: r.h, w: r.w, c0: 0, scale: 1.0 }; + let out = + Tensor { buf: gpu.alloc_cadence((n * gpu.esize()) as u64), c: r.c, h: r.h, w: r.w, c0: 0, scale: 1.0 }; Some(CadenceScratch { - bg_copy: gpu.alloc(n), - mask_a: gpu.alloc_f32((m.h * m.w) as usize), - mask_b: gpu.alloc_f32((m.h * m.w) as usize), - trust_a: gpu.alloc_f32((m.h * m.w) as usize), - trust_b: gpu.alloc_f32((m.h * m.w) as usize), + bg_copy: gpu.alloc_cadence((n * gpu.esize()) as u64), + mask_a: gpu.alloc_cadence(u64::from(m.h * m.w) * 4), + mask_b: gpu.alloc_cadence(u64::from(m.h * m.w) * 4), + trust_a: gpu.alloc_cadence(u64::from(m.h * m.w) * 4), + trust_b: gpu.alloc_cadence(u64::from(m.h * m.w) * 4), out, - part: gpu.alloc_f32((STAT_WG * 4) as usize), + part: gpu.alloc_cadence(u64::from(STAT_WG * 4 * 4)), steps: RefCell::new(HashMap::new()), }) } @@ -288,7 +290,7 @@ impl CadenceScratch { /// A submitted statistics reduction whose 64-float readback is still in flight (`finish` awaits the mapping; on /// native poll the device first, in the browser the mapAsync promise resolves it). pub struct StatsRun { - stage: wgpu::Buffer, + stage: Buffer, fut: crate::MapWait, s: f32, n: u32, @@ -329,7 +331,7 @@ pub fn pair_stats_begin(gpu: &Gpu, sess: &SessionExt, sc: &CadenceScratch) -> an vec![gpu.compute_step("gm_stats", &[&m.buf], bytemuck::bytes_of(&p), &sc.part, (STAT_WG, 1, 1))] }); gpu.replay(&st); - let stage = gpu.device.create_buffer(&wgpu::BufferDescriptor { + let stage = gpu.buffer(&wgpu::BufferDescriptor { label: Some("fh_gm_stats"), size: (STAT_WG * 4 * 4) as u64, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, diff --git a/crates/flyhigh-engine/src/gpu/alloc.rs b/crates/flyhigh-engine/src/gpu/alloc.rs index 86edb3b..81adf88 100644 --- a/crates/flyhigh-engine/src/gpu/alloc.rs +++ b/crates/flyhigh-engine/src/gpu/alloc.rs @@ -1,5 +1,6 @@ //! Tensor buffers: creation, the per-plan arena that reuses dead tensors' buffers, scratch release, memory accounting. +use super::memory::{Buffer, Kind}; use crate::Gpu; use std::rc::Rc; use wgpu::util::DeviceExt; @@ -10,33 +11,33 @@ pub(crate) fn arena_trace() -> bool { } impl Gpu { - pub fn buf(&self, data: &[f32]) -> Rc { + pub fn buf(&self, data: &[f32]) -> Rc { // f16 storage let h: Vec = if self.f32_mode { Vec::new() } else { data.iter().map(|&x| half::f16::from_f32(x).to_bits()).collect() }; let bytes: &[u8] = if self.f32_mode { bytemuck::cast_slice(data) } else { bytemuck::cast_slice(&h) }; - Rc::new(self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + let raw = self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("fh_const"), contents: bytes, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST, - })) + }); + Rc::new(self.memory.buffer(Kind::InitializedBuffers, raw)) } /// Bytes of tensor buffers still alive (the engine's own video memory, without textures). pub fn live_bytes(&self) -> u64 { - let mut v = self.live.borrow_mut(); - v.retain(|w| w.strong_count() > 0); - v.iter().filter_map(|w| w.upgrade()).map(|b| b.size()).sum() + let report = self.memory.report(); + report.tensors.live_bytes + report.cadence_scratch.live_bytes } /// Sizes of the live tensor buffers, largest first (diagnostics). pub fn live_sizes(&self) -> Vec { - let mut v: Vec = self.live.borrow().iter().filter_map(|w| w.upgrade()).map(|b| b.size()).collect(); + let mut v: Vec = self.live.borrow().iter().filter_map(|w| w.upgrade()).map(|b| b.bytes).collect(); v.sort_unstable_by(|a, b| b.cmp(a)); v } } impl Gpu { - pub fn alloc(&self, n: usize) -> Rc { + pub fn alloc(&self, n: usize) -> Rc { self.alloc_raw((n * self.esize()) as u64) } // n tensor elements /// bytes per tensor element: 2 (f16) or 4 (the f32 path) @@ -47,12 +48,12 @@ impl Gpu { 2 } } - pub fn alloc_f32(&self, n: usize) -> Rc { + pub fn alloc_f32(&self, n: usize) -> Rc { self.alloc_raw((n * 4) as u64) } // n f32 elements (split-K partials) // kernel scratch (shifted copies, split-K partials, materialized views) lives only inside one op: note it here and // `release_scratch` hands it to the arena once the op is built - pub fn note_scratch(&self, b: &Rc) { + pub fn note_scratch(&self, b: &Rc) { if self.arena.borrow().is_some() { self.scratch.borrow_mut().push(b.clone()); } @@ -63,7 +64,7 @@ impl Gpu { self.release(b); } } - pub fn alloc_raw(&self, size: u64) -> Rc { + pub fn alloc_raw(&self, size: u64) -> Rc { if let Some(free) = self.arena.borrow_mut().as_mut() { // smallest released buffer that fits (exact size first); kernels address `n` elements, not the buffer size if let Some(i) = free.iter().position(|b| b.size() == size).or_else(|| { @@ -82,22 +83,36 @@ impl Gpu { eprintln!("arena: alloc {size} <- new (free: {:?})", free.iter().map(|b| b.size()).collect::>()); } } + let b = self.create_tensor(size, Kind::Tensors); + if self.arena.borrow().is_some() { + self.arena_ids.borrow_mut().insert(Rc::as_ptr(&b) as usize, Rc::downgrade(&b)); + } + b + } + + pub(crate) fn alloc_cadence(&self, size: u64) -> Rc { + self.create_tensor(size, Kind::CadenceScratch) + } + + fn create_tensor(&self, size: u64, kind: Kind) -> Rc { self.alloc_bytes.set(self.alloc_bytes.get() + size); - let b = Rc::new(self.device.create_buffer(&wgpu::BufferDescriptor { + let raw = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("fh_tensor"), size, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, - })); - if self.arena.borrow().is_some() { - self.arena_ids.borrow_mut().insert(Rc::as_ptr(&b) as usize, Rc::downgrade(&b)); + }); + let b = Rc::new(self.memory.buffer(kind, raw)); + let mut live = self.live.borrow_mut(); + if live.len() == live.capacity() { + live.retain(|w| w.strong_count() > 0); } - self.live.borrow_mut().push(Rc::downgrade(&b)); + live.push(Rc::downgrade(&b.charge)); b } // give a dead tensor's buffer back to the arena (only `alloc` buffers, and only when nothing else holds the Rc: // views, aliases, copy steps). Constant buffers (`buf`) never enter: they are written once and read every frame. - pub fn release(&self, b: Rc) { + pub fn release(&self, b: Rc) { let (count, known) = ( Rc::strong_count(&b), self.arena_ids.borrow().get(&(Rc::as_ptr(&b) as usize)).is_some_and(|w| w.as_ptr() == Rc::as_ptr(&b)), diff --git a/crates/flyhigh-engine/src/gpu/device.rs b/crates/flyhigh-engine/src/gpu/device.rs index 42c0af0..507074a 100644 --- a/crates/flyhigh-engine/src/gpu/device.rs +++ b/crates/flyhigh-engine/src/gpu/device.rs @@ -1,5 +1,6 @@ //! Adapter selection and device creation: features, limits, the f16 / f32 decision; or a device the host already has. +use super::memory::{Kind, Memory}; use crate::{parse_tune, EngineOptions, Gpu, Precision}; use anyhow::Result; use std::collections::HashMap; @@ -218,11 +219,12 @@ impl Gpu { let shader_compiler = (info.backend == wgpu::Backend::Dx12).then(super::dxc::loaded); #[cfg(not(windows))] let shader_compiler = None; - let zero = Rc::new(device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + let memory = Memory::default(); + let zero = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("fh_zero"), contents: bytemuck::cast_slice(&[0f32; 256]), usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST, - })); + }); // f16 ones: PReLU slope of 1 turns the fused epilogue into identity, so no-activation convs // (conv2d heads, up.w) run through the same Tensor-Core kernel instead of the naive conv. let ones_bytes: Vec = if caps.f32_mode { @@ -230,11 +232,11 @@ impl Gpu { } else { bytemuck::cast_slice(&vec![half::f16::from_f32(1.0).to_bits(); 1024]).to_vec() }; - let ones = Rc::new(device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + let ones = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("fh_ones"), contents: &ones_bytes, usage: wgpu::BufferUsages::STORAGE, - })); + }); // the choices depend on the GPU, its driver, the kernel set (precision, tensor cores) and the engine's kernels let tune_file = opts.tune_cache.as_ref().map(|d| { let drv: u32 = format!("{} {}", info.driver, info.driver_info) @@ -262,8 +264,9 @@ impl Gpu { device, queue, p: std::cell::RefCell::new(HashMap::new()), - zero, - ones, + zero: Rc::new(memory.buffer(Kind::InitializedBuffers, zero)), + ones: Rc::new(memory.buffer(Kind::InitializedBuffers, ones)), + memory, name, coop: caps.coop, autotune: opts.autotune, @@ -278,7 +281,6 @@ impl Gpu { arena_ids: std::cell::RefCell::new(HashMap::new()), scratch: std::cell::RefCell::new(Vec::new()), alloc_bytes: std::cell::Cell::new(0), - last_pb: std::cell::RefCell::new(None), pass_split: std::cell::Cell::new(0), submit_split: std::cell::Cell::new(0), } diff --git a/crates/flyhigh-engine/src/gpu/memory.rs b/crates/flyhigh-engine/src/gpu/memory.rs new file mode 100644 index 0000000..8a51ffd --- /dev/null +++ b/crates/flyhigh-engine/src/gpu/memory.rs @@ -0,0 +1,177 @@ +//! Logical allocation sizes, independent of wgpu's allocator and GPU submission lifetimes. +use serde::Serialize; +use std::{cell::Cell, ops::Deref, rc::Rc}; +use wgpu::util::DeviceExt; + +/// Live and lifetime peak requested bytes for one resource category. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)] +pub struct MemoryUsage { + pub live_bytes: u64, + pub peak_bytes: u64, +} + +/// Logical GPU allocation sizes for this engine, excluding allocations owned by the host or driver. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)] +pub struct MemoryReport { + pub live_bytes: u64, + pub peak_bytes: u64, + pub tensors: MemoryUsage, + pub initialized_buffers: MemoryUsage, + pub cadence_scratch: MemoryUsage, + pub frame_textures: MemoryUsage, + pub auxiliary_buffers: MemoryUsage, + pub auxiliary_textures: MemoryUsage, +} + +#[derive(Clone, Copy)] +pub(crate) enum Kind { + Tensors, + InitializedBuffers, + CadenceScratch, + FrameTextures, + AuxiliaryBuffers, + AuxiliaryTextures, +} + +#[derive(Clone, Default)] +pub(crate) struct Memory(Rc); + +#[derive(Default)] +struct State { + total: Cell, + categories: [Cell; Kind::AuxiliaryTextures as usize + 1], +} + +impl Memory { + pub(crate) fn report(&self) -> MemoryReport { + let total = self.0.total.get(); + let usage = |kind: Kind| self.0.categories[kind as usize].get(); + MemoryReport { + live_bytes: total.live_bytes, + peak_bytes: total.peak_bytes, + tensors: usage(Kind::Tensors), + initialized_buffers: usage(Kind::InitializedBuffers), + cadence_scratch: usage(Kind::CadenceScratch), + frame_textures: usage(Kind::FrameTextures), + auxiliary_buffers: usage(Kind::AuxiliaryBuffers), + auxiliary_textures: usage(Kind::AuxiliaryTextures), + } + } + + pub(crate) fn charge(&self, kind: Kind, bytes: u64) -> Charge { + for counter in [&self.0.total, &self.0.categories[kind as usize]] { + let mut usage = counter.get(); + usage.live_bytes += bytes; + usage.peak_bytes = usage.peak_bytes.max(usage.live_bytes); + counter.set(usage); + } + Charge { memory: self.clone(), kind, bytes } + } + + pub(crate) fn buffer(&self, kind: Kind, raw: wgpu::Buffer) -> Buffer { + let charge = self.charge(kind, raw.size()); + Buffer { raw, charge: Rc::new(charge) } + } + + pub(crate) fn rgba8_slot(&self, texture: &wgpu::Texture) -> Charge { + self.charge(Kind::FrameTextures, u64::from(texture.width()) * u64::from(texture.height()) * 4) + } +} + +pub(crate) struct Charge { + memory: Memory, + kind: Kind, + pub(crate) bytes: u64, +} + +impl Drop for Charge { + fn drop(&mut self) { + let state = &self.memory.0; + for counter in [&state.total, &state.categories[self.kind as usize]] { + let mut usage = counter.get(); + usage.live_bytes -= self.bytes; + counter.set(usage); + } + } +} + +/// An engine buffer. Dereferences to the underlying wgpu buffer for copies and bindings. +pub struct Buffer { + raw: wgpu::Buffer, + // Plan steps share this charge without changing the arena's Rc liveness checks. + pub(crate) charge: Rc, +} + +impl Deref for Buffer { + type Target = wgpu::Buffer; + + fn deref(&self) -> &wgpu::Buffer { + &self.raw + } +} + +impl super::Gpu { + pub(crate) fn buffer(&self, desc: &wgpu::BufferDescriptor<'_>) -> Buffer { + self.memory.buffer(Kind::AuxiliaryBuffers, self.device.create_buffer(desc)) + } + + pub(crate) fn buffer_init(&self, desc: &wgpu::util::BufferInitDescriptor<'_>) -> Buffer { + self.memory.buffer(Kind::AuxiliaryBuffers, self.device.create_buffer_init(desc)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn peak_is_the_maximum_overlapping_usage_even_without_sampling() { + let memory = Memory::default(); + let first = Rc::new(memory.charge(Kind::Tensors, 10)); + let alias = first.clone(); + let scratch = memory.charge(Kind::CadenceScratch, 4); + drop(first); + drop(alias); + assert_eq!(memory.report().live_bytes, 4); + let slots = memory.charge(Kind::FrameTextures, 7); + drop(scratch); + drop(slots); + let stopped = memory.report(); + assert_eq!(stopped.live_bytes, 0); + assert_eq!(stopped.peak_bytes, 14); + assert_eq!(stopped.frame_textures.peak_bytes, 7); + assert_eq!(stopped.cadence_scratch.peak_bytes, 4); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + #[ignore = "requires a GPU"] + fn plan_bindings_keep_one_charge_without_blocking_arena_reuse() { + use crate::{Engine, EngineOptions, Tensor}; + + let engine = Engine::new(&EngineOptions::default()).unwrap(); + let gpu = engine.gpu(); + let baseline = engine.report().memory; + + *gpu.arena.borrow_mut() = Some(Vec::new()); + let src = Tensor { buf: gpu.alloc(64), c: 1, h: 8, w: 8, c0: 0, scale: 1.0 }; + let (dst, plan) = gpu.unary(&src, 0, 1.0, 0.0); + let bytes = src.buf.size(); + let address = Rc::as_ptr(&src.buf); + gpu.release(src.buf); + let reused = gpu.alloc(64); + assert_eq!(Rc::as_ptr(&reused), address); + drop(reused); + drop(dst); + gpu.arena.borrow_mut().take(); + gpu.arena_ids.borrow_mut().clear(); + assert_eq!(engine.report().memory.tensors.live_bytes, bytes * 2); + assert_eq!(gpu.live_sizes(), vec![bytes, bytes]); + + drop(plan); + let stopped = engine.report().memory; + assert_eq!(stopped.live_bytes, baseline.live_bytes); + assert_eq!(stopped.tensors.peak_bytes, bytes * 2); + assert!(gpu.live_sizes().is_empty()); + } +} diff --git a/crates/flyhigh-engine/src/gpu/mod.rs b/crates/flyhigh-engine/src/gpu/mod.rs index e7c8782..00d0034 100644 --- a/crates/flyhigh-engine/src/gpu/mod.rs +++ b/crates/flyhigh-engine/src/gpu/mod.rs @@ -4,11 +4,13 @@ pub mod alloc; pub mod device; pub mod dxc; pub mod exec; +pub mod memory; pub mod pipeline; pub mod readback; pub mod timing; use crate::TuneTable; +use memory::{Buffer, Charge, Memory}; use std::collections::HashMap; use std::rc::Rc; @@ -19,27 +21,27 @@ pub struct Gpu { pub device: wgpu::Device, pub queue: wgpu::Queue, pub p: std::cell::RefCell>>, // compiled kernels, see `pipeline` - pub zero: Rc, - pub ones: Rc, + pub zero: Rc, + pub ones: Rc, pub name: String, pub coop: bool, pub autotune: bool, // EngineOptions::autotune (native build-time conv autotune) pub tune: std::cell::RefCell, // conv choices of every build so far pub tune_file: Option, // EngineOptions::tune_cache: where `tune` persists - pub(crate) live: std::cell::RefCell>>, // tensor buffers, for live_bytes + pub(crate) memory: Memory, + pub(crate) live: std::cell::RefCell>>, // tensor buffers, for live_sizes pub bgra_storage: bool, // BGRA8UNORM_STORAGE: canvases that prefer bgra8unorm can be written directly - pub timestamps: bool, // TIMESTAMP_QUERY: gpu_time_ms works (pass-level timestamps, WebGPU-standard) - pub ts_inside: bool, // + TIMESTAMP_QUERY_INSIDE_ENCODERS (native): per-step profile_plan + pub timestamps: bool, // TIMESTAMP_QUERY: gpu_time_ms works (pass-level timestamps, WebGPU-standard) + pub ts_inside: bool, // + TIMESTAMP_QUERY_INSIDE_ENCODERS (native): per-step profile_plan pub shader_compiler: Option, // DX12: the HLSL compiler wgpu loaded (None on other backends) // buffer arena (Some while a plan is being built): tensors whose last reader has been built release their // buffer here and later tensors of the same plan reuse it — a static in-order plan makes this safe - pub arena: std::cell::RefCell>>>, + pub arena: std::cell::RefCell>>>, // buffers that came from `alloc` (the only ones `release` takes), by address; the Weak keeps the Rc allocation // reserved, so a dropped buffer's address cannot be reused by a buffer that never came from the arena - pub arena_ids: std::cell::RefCell>>, - pub scratch: std::cell::RefCell>>, // per-op kernel scratch awaiting `release_scratch` - pub alloc_bytes: std::cell::Cell, // bytes of tensor buffers actually created - pub last_pb: std::cell::RefCell>>, // uniform buffer of the last `bind` (t-dependent steps) + pub arena_ids: std::cell::RefCell>>, + pub scratch: std::cell::RefCell>>, // per-op kernel scratch awaiting `release_scratch` + pub alloc_bytes: std::cell::Cell, // bytes of tensor buffers actually created // Frame encoding knobs (experiments on a shared GPU): 0 = one compute pass / one submit per plan (the default); // n = a new compute pass every n dispatches / a new command buffer every n dispatches pub pass_split: std::cell::Cell, diff --git a/crates/flyhigh-engine/src/gpu/readback.rs b/crates/flyhigh-engine/src/gpu/readback.rs index 4319a8e..fd6963d 100644 --- a/crates/flyhigh-engine/src/gpu/readback.rs +++ b/crates/flyhigh-engine/src/gpu/readback.rs @@ -84,6 +84,7 @@ pub struct Readback { fut: MapWait, decode: Decode, done: Option, + _allocation: Option>, } /// Turns the mapped bytes into the result. pub type Decode = Box T>; @@ -93,7 +94,12 @@ impl Readback { /// `stage` must be `MAP_READ` and already the destination of a submitted copy; `done` runs after the decode. pub fn new(stage: wgpu::Buffer, decode: Decode, done: Option) -> Self { let fut = map_read(&stage); - Readback { stage, fut, decode, done } + Readback { stage, fut, decode, done, _allocation: None } + } + pub(crate) fn tracked(stage: &super::memory::Buffer, decode: Decode, done: Option) -> Self { + let mut readback = Self::new((**stage).clone(), decode, done); + readback._allocation = Some(stage.charge.clone()); + readback } pub async fn finish(self) -> Result { self.fut.await.map_err(|e| anyhow::anyhow!("map_async: {e:?}"))?; diff --git a/crates/flyhigh-engine/src/net/build.rs b/crates/flyhigh-engine/src/net/build.rs index 442d534..3788158 100644 --- a/crates/flyhigh-engine/src/net/build.rs +++ b/crates/flyhigh-engine/src/net/build.rs @@ -1,6 +1,7 @@ //! Graph to plan: the build context (caches, liveness, pinning), `build`, `build_network` and the pair / mid split. use crate::gmhs; +use crate::gpu::memory::Buffer; use crate::model::graph::count_uses; use crate::model::graph::count_uses_unrolled; use crate::{ @@ -12,7 +13,7 @@ use std::collections::HashMap; use std::rc::Rc; // a buffer whose contents depend on the phase t (a `mul_t` scale uniform, the FiLM MLP output): `f(t)` gives the bytes -pub type PhaseDep = (Rc, Box Vec>); +pub type PhaseDep = (Rc, Box Vec>); pub fn set_t(gpu: &Gpu, deps: &[PhaseDep], t: f32) { for (b, f) in deps { gpu.queue.write_buffer(b, 0, &f(t)); @@ -22,9 +23,9 @@ pub fn set_t(gpu: &Gpu, deps: &[PhaseDep], t: f32) { pub struct BuildCtx<'a> { pub gpu: &'a Gpu, pub blob: &'a Blob, - pub wcache: HashMap>, - pub bcache: HashMap, u32, u32)>, - pub bcache4: HashMap, u32, u32, u32)>, + pub wcache: HashMap>, + pub bcache: HashMap, u32, u32)>, + pub bcache4: HashMap, u32, u32, u32)>, pub k: u32, pub t: f32, pub hs: u32, @@ -34,12 +35,12 @@ pub struct BuildCtx<'a> { pub remaining: HashMap, // reads still to come in the UNROLLED plan (buffer liveness) // buffers never released to the arena (inputs, outputs, stage exports), by address; the Weak reserves the // address (see `Gpu::arena_ids`), otherwise a freed pinned buffer's address could pin an unrelated new one - pub pinned: HashMap>, - pub t_deps: Vec, // t-dependent buffers of the plan (see `set_t`) - pub keep_all: bool, // FH_ALL_OUTPUTS=1: also compute oracle-only outputs - pub cubic: bool, // render_pix source sampler (NetOpts::cubic) - pub render_flags: u32, // render_pix mode word (NetOpts::render_flags) - pub static_age: Option<(Rc, u32)>, // static protection age and protecting age (NetOpts::keep_static) + pub pinned: HashMap>, + pub t_deps: Vec, // t-dependent buffers of the plan (see `set_t`) + pub keep_all: bool, // FH_ALL_OUTPUTS=1: also compute oracle-only outputs + pub cubic: bool, // render_pix source sampler (NetOpts::cubic) + pub render_flags: u32, // render_pix mode word (NetOpts::render_flags) + pub static_age: Option<(Rc, u32)>, // static protection age and protecting age (NetOpts::keep_static) pub discover: Option>, } // Some: record conv shapes, pick fixed kernels (autotune discovery) @@ -70,7 +71,7 @@ impl<'a> BuildCtx<'a> { pub fn pin(&mut self, t: &Tensor) { self.pinned.insert(Rc::as_ptr(&t.buf) as usize, Rc::downgrade(&t.buf)); } - pub fn is_pinned(&self, b: &Rc) -> bool { + pub fn is_pinned(&self, b: &Rc) -> bool { self.pinned.get(&(Rc::as_ptr(b) as usize)).is_some_and(|w| w.as_ptr() == Rc::as_ptr(b)) } // one op has been built: its inputs were read. Drop names whose last read this was and hand dead buffers to the arena. @@ -97,7 +98,7 @@ impl<'a> BuildCtx<'a> { } impl<'a> BuildCtx<'a> { - pub fn wb(&mut self, name: &str) -> Rc { + pub fn wb(&mut self, name: &str) -> Rc { if let Some(b) = self.wcache.get(name) { return b.clone(); } @@ -105,7 +106,7 @@ impl<'a> BuildCtx<'a> { self.wcache.insert(name.to_string(), b.clone()); b } - pub fn bbuf(&mut self, name: &str, cin: u32, cout: u32) -> (Rc, u32, u32) { + pub fn bbuf(&mut self, name: &str, cin: u32, cout: u32) -> (Rc, u32, u32) { if let Some(b) = self.bcache.get(name) { return b.clone(); } @@ -113,7 +114,7 @@ impl<'a> BuildCtx<'a> { self.bcache.insert(name.to_string(), b.clone()); b } - pub fn bbuf_tap(&mut self, name: &str, cin: u32, cout: u32) -> (Rc, u32, u32, u32) { + pub fn bbuf_tap(&mut self, name: &str, cin: u32, cout: u32) -> (Rc, u32, u32, u32) { if let Some(b) = self.bcache4.get(name) { return b.clone(); } @@ -274,7 +275,8 @@ pub fn build(ops: &[Value], env: &mut HashMap, plan: &mut Vec, - pub in_b: Rc, - pub out_rgba: Rc, + pub in_a: Rc, + pub in_b: Rc, + pub out_rgba: Rc, pub plan: Vec, pub env: HashMap, } @@ -43,7 +44,7 @@ impl Session { ) -> Session { let (hp, wp) = (h.div_ceil(32) * 32, w.div_ceil(32) * 32); let u32buf = |n: u64| { - Rc::new(gpu.device.create_buffer(&wgpu::BufferDescriptor { + Rc::new(gpu.buffer(&wgpu::BufferDescriptor { label: Some("fh_rgba"), size: n * 4, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC, diff --git a/crates/flyhigh-engine/src/net/session_ext.rs b/crates/flyhigh-engine/src/net/session_ext.rs index 01f70b9..81d9143 100644 --- a/crates/flyhigh-engine/src/net/session_ext.rs +++ b/crates/flyhigh-engine/src/net/session_ext.rs @@ -1,5 +1,6 @@ //! `SessionExt`: the texture path with input / output slots, a pair plan, a mid plan and the fast render. +use crate::gpu::memory::{Buffer, Charge}; use crate::ops::step::meta; use crate::{ build_network_ex, clone_step, set_t, workgroups_2d, Binding, Blob, Gpu, NetOpts, PhaseDep, StaticParams, Step, @@ -8,7 +9,6 @@ use crate::{ use bytemuck::{Pod, Zeroable}; use serde_json::Value; use std::collections::HashMap; -use wgpu::util::DeviceExt; // Host-pool session (the browser extension's shape): the host owns N input frame textures (a history ring it also // presents from) and M output textures; the runtime runs the pair stage on any two input slots and then any number of @@ -23,6 +23,7 @@ pub struct SessionExt { pub k: u32, pub ins: Vec<(wgpu::Texture, wgpu::TextureView)>, pub outs: Vec<(wgpu::Texture, wgpu::TextureView)>, + owned_slots: Vec, pub a: Tensor, pub b: Tensor, pub plan_pair: Vec, @@ -39,7 +40,7 @@ pub struct SessionExt { age_steps: std::cell::RefCell>, // fast render + static: (slot A, slot B) -> age pass } // the cached render_tex step of a (slot A, slot B, out) triple with its uniform buffer and the parameters it holds -type FastRenderCache = HashMap<(usize, usize, usize), (Step, wgpu::Buffer, RenderTexParams)>; +type FastRenderCache = HashMap<(usize, usize, usize), (Step, Buffer, RenderTexParams)>; #[repr(C)] #[derive(Clone, Copy, Pod, Zeroable)] struct RenderTexParams { @@ -105,6 +106,7 @@ impl SessionExt { k, ins: Vec::new(), outs: Vec::new(), + owned_slots: Vec::new(), a, b, plan_pair, @@ -193,7 +195,7 @@ impl SessionExt { _b: 0, _c: 0, }; - let pb = gpu.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + let pb = gpu.buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("fh_render_tex_params"), contents: bytemuck::bytes_of(&p), usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, @@ -227,6 +229,8 @@ impl SessionExt { Binding::Params, ], bytemuck::bytes_of(&p), + [&*ftq.buf, &*vtq.buf, &*rt.buf, &**age_buf, &pb], + None, ); (Step::Compute { pipe: "render_tex", bg, groups: workgroups_2d(self.w, self.h, 1), meta: m }, pb, p) }); @@ -260,12 +264,14 @@ impl SessionExt { } pub fn add_input(&mut self, gpu: &Gpu) -> usize { let t = gpu.input_texture_l(self.w, self.h, &format!("fh_in_{}", self.ins.len())); + self.owned_slots.push(gpu.memory.rgba8_slot(&t)); let v = t.create_view(&wgpu::TextureViewDescriptor::default()); self.ins.push((t, v)); self.ins.len() - 1 } pub fn add_output(&mut self, gpu: &Gpu) -> usize { let t = gpu.output_texture_l(self.w, self.h, &format!("fh_out_{}", self.outs.len())); + self.owned_slots.push(gpu.memory.rgba8_slot(&t)); let v = t.create_view(&wgpu::TextureViewDescriptor::default()); self.outs.push((t, v)); self.outs.len() - 1 @@ -296,7 +302,7 @@ impl SessionExt { } let p = DownsampleParams { w: self.w, h: self.h, iw: self.wp, ih: self.hp, ow: dst.w, oh: dst.h, _a: 0, _b: 0 }; - let pb = gpu.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + let pb = gpu.buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("fh_tex_down_params"), contents: bytemuck::bytes_of(&p), usage: wgpu::BufferUsages::UNIFORM, @@ -317,6 +323,8 @@ impl SessionExt { meta: meta( vec![Binding::Texture(self.w, self.h), Binding::Buffer(dst.buf.size()), Binding::Params], bytemuck::bytes_of(&p), + [&*dst.buf, &pb], + None, ), } })) @@ -351,9 +359,9 @@ impl SessionExt { let mut c = self.age_steps.borrow_mut(); let step = c.entry((a.0, b.0)).or_insert_with(|| { let p = StaticParams::new(&self.net, self.w, self.h, self.wp, self.hp); - let mask: &wgpu::Buffer = self.env.get("mask").map_or(&gpu.zero, |m| &m.buf); + let mask = self.env.get("mask").map_or(&gpu.zero, |m| &m.buf); let state = &self.env["static:state"].buf; - let pb = gpu.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + let pb = gpu.buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("fh_age_params"), contents: bytemuck::bytes_of(&p), usage: wgpu::BufferUsages::UNIFORM, @@ -384,6 +392,8 @@ impl SessionExt { Binding::Buffer(state.size()), ], bytemuck::bytes_of(&p), + [&*age.buf, &**mask, &**state, &pb], + None, ), } }); diff --git a/crates/flyhigh-engine/src/net/session_tex.rs b/crates/flyhigh-engine/src/net/session_tex.rs index a08a3b9..f40d9b3 100644 --- a/crates/flyhigh-engine/src/net/session_tex.rs +++ b/crates/flyhigh-engine/src/net/session_tex.rs @@ -1,5 +1,6 @@ //! `SessionTex`: the two-texture ping-pong session of the browser canvas path. +use crate::gpu::memory::Charge; use crate::{build_network, clone_step, Blob, Gpu, NetOpts, Step, Tensor, TuneTable}; use serde_json::Value; @@ -23,6 +24,7 @@ pub struct SessionTex { pub plan: Vec, pub render: Tensor, in_steps: [[Step; 2]; 2], + _owned_slots: [Charge; 2], } // [texture][0 = as A, 1 = as B]: built once, the ping-pong only swaps them impl SessionTex { #[allow(clippy::too_many_arguments)] // the Core `Session` is the public constructor; the tools and the plan tests call this @@ -41,6 +43,7 @@ impl SessionTex { ) -> SessionTex { let (hp, wp) = (h.div_ceil(32) * 32, w.div_ceil(32) * 32); let tex = [gpu.input_texture(w, h), gpu.input_texture(w, h)]; + let owned_slots = [&tex[0], &tex[1]].map(|t| gpu.memory.rgba8_slot(t)); let view = [ tex[0].create_view(&wgpu::TextureViewDescriptor::default()), tex[1].create_view(&wgpu::TextureViewDescriptor::default()), @@ -66,6 +69,7 @@ impl SessionTex { plan, render, in_steps, + _owned_slots: owned_slots, } } // the texture to fill with the newest frame; call `commit()` after copying into it diff --git a/crates/flyhigh-engine/src/ops/conv/autotune.rs b/crates/flyhigh-engine/src/ops/conv/autotune.rs index e4d2201..7d91af6 100644 --- a/crates/flyhigh-engine/src/ops/conv/autotune.rs +++ b/crates/flyhigh-engine/src/ops/conv/autotune.rs @@ -1,5 +1,6 @@ //! Per-shape kernel choice at build time (`BuildCtx::conv_pick`) and the asynchronous discovery autotune. +use crate::gpu::memory::Buffer; use crate::model::graph::count_uses; use crate::{ build, cand_list, cand_name, Blob, BuildCtx, ConvArgs, Gpu, OpOutput, Tensor, TiledOpts, TuneTable, CAND_DIRECT, @@ -15,8 +16,8 @@ use std::collections::HashMap; pub struct ConvOp<'a> { pub x: &'a Tensor, pub weight: &'a str, - pub bias: &'a wgpu::Buffer, - pub slope: &'a wgpu::Buffer, + pub bias: &'a Buffer, + pub slope: &'a Buffer, pub cin: u32, pub cout: u32, pub stride: u32, diff --git a/crates/flyhigh-engine/src/ops/conv/kernels.rs b/crates/flyhigh-engine/src/ops/conv/kernels.rs index 7505945..6120543 100644 --- a/crates/flyhigh-engine/src/ops/conv/kernels.rs +++ b/crates/flyhigh-engine/src/ops/conv/kernels.rs @@ -1,5 +1,6 @@ //! The conv kernels: naive, cooperative-matrix (tensor cores), portable tiled FMA with split-K, direct. +use crate::gpu::memory::Buffer; use crate::{workgroups_2d, ConvParams, Gpu, ImplicitGemmParams, OpOutput, ShiftParams, SplitKParams, Step, Tensor}; use std::rc::Rc; @@ -9,9 +10,9 @@ use std::rc::Rc; #[derive(Clone, Copy)] pub struct ConvArgs<'a> { pub x: &'a Tensor, - pub weights: &'a wgpu::Buffer, - pub bias: &'a wgpu::Buffer, - pub slope: &'a wgpu::Buffer, + pub weights: &'a Buffer, + pub bias: &'a Buffer, + pub slope: &'a Buffer, pub cin: u32, pub cout: u32, pub kp: u32, @@ -62,7 +63,7 @@ impl Gpu { impl Gpu { /// Pack torch `[cout][cin][3][3]` weights as the implicit-GEMM B matrix `[kp][np]` (ci-major K padded to 16, N padded /// to 32 or 64); returns the buffer and the paddings. - pub fn buildb(&self, wf: &[f32], cin: u32, cout: u32) -> (Rc, u32, u32) { + pub fn buildb(&self, wf: &[f32], cin: u32, cout: u32) -> (Rc, u32, u32) { let k = cin * 9; let kp = k.div_ceil(16) * 16; let nblk = if cout <= 32 { 32 } else { 64 }; @@ -129,7 +130,7 @@ impl Gpu { debug_assert!(res.is_none_or(|r| r.is_plain() && r.c == cout && r.h == hout && r.w == wout)); // dummy for the unused residual must differ from the `part` dummy: one buffer cannot be bound read-only and // read-write in the same bind group - let resb: &wgpu::Buffer = res.map(|r| &*r.buf).unwrap_or(&self.ones); + let resb: &Buffer = res.map(|r| &*r.buf).unwrap_or(&self.ones); let res_on = res.is_some() as u32; let (ker, tm, tn) = if cout <= 32 { ( @@ -190,7 +191,7 @@ impl Gpu { } /// Pack weights tap-major for the direct kernels: kcol = tap * cinp + ci with cinp = ceil16(cin), so a 16-wide K /// block never straddles a (ky, kx) tap; N padded to the 64-channel tile. Returns the buffer, kp, np and cinp. - pub fn buildb_tap(&self, wf: &[f32], cin: u32, cout: u32) -> (Rc, u32, u32, u32) { + pub fn buildb_tap(&self, wf: &[f32], cin: u32, cout: u32) -> (Rc, u32, u32, u32) { let cinp = cin.div_ceil(16) * 16; let kp = 9 * cinp; let np = cout.div_ceil(64) * 64; @@ -222,7 +223,7 @@ impl Gpu { } // three x-shifted, y-padded copies of x ([3][cinp][h+2][w]) for the direct conv kernel; the kernel writes the // padding too (arena buffers are not zeroed) - pub fn xshift3(&self, x: &Tensor, cinp: u32) -> (Rc, Step) { + pub fn xshift3(&self, x: &Tensor, cinp: u32) -> (Rc, Step) { let out = self.alloc((3 * cinp * (x.h + 2) * x.w) as usize); self.note_scratch(&out); let sp = ShiftParams { cin: x.c, cinp, h: x.h, w: x.w }; diff --git a/crates/flyhigh-engine/src/ops/elementwise.rs b/crates/flyhigh-engine/src/ops/elementwise.rs index dca758b..5f5623e 100644 --- a/crates/flyhigh-engine/src/ops/elementwise.rs +++ b/crates/flyhigh-engine/src/ops/elementwise.rs @@ -1,5 +1,6 @@ //! Binary and unary kernels, channel copies (views materialised), concat, zeros. +use crate::gpu::memory::Buffer; use crate::{workgroups_2d, BinaryParams, ChannelCopyParams, Gpu, OpOutput, Step, Tensor, UnaryParams}; use std::rc::Rc; @@ -36,7 +37,7 @@ impl Gpu { // channel-range copy into `out` at channel dst0 from up to 7 inputs (input 0 starting at channel off0), as one // `chcopy` dispatch — keeps the whole frame inside one compute pass (buffer copies split passes: ~10% of K=2 time) // `first`: (channel offset, channel count) read from input 0; `size`: (h, w) of every input - fn chcopy(&self, ins: &[&Tensor], first: (u32, u32), out: &Rc, dst0: u32, size: (u32, u32)) -> Step { + fn chcopy(&self, ins: &[&Tensor], first: (u32, u32), out: &Rc, dst0: u32, size: (u32, u32)) -> Step { let ((off0, nch0), (h, w)) = (first, size); debug_assert!(!ins.is_empty() && ins.len() <= 7 && (h * w).is_multiple_of(2)); let hw2 = h * w / 2; @@ -54,7 +55,7 @@ impl Gpu { *e = acc; } let p = ChannelCopyParams { hw2, ctot: acc, e: ends, o: offs, dst0, s: scl, _a: 0, _b: 0, _c: 0, _d: 0 }; - let bufs: Vec<&wgpu::Buffer> = (0..7).map(|k| if k < ins.len() { &*ins[k].buf } else { &*self.zero }).collect(); + let bufs: Vec<&Buffer> = (0..7).map(|k| if k < ins.len() { &*ins[k].buf } else { &*self.zero }).collect(); self.compute_step("chcopy", &bufs, bytemuck::bytes_of(&p), out, ((acc * hw2).div_ceil(256), 1, 1)) } pub fn slice(&self, x: &Tensor, a: u32, b: u32) -> OpOutput { diff --git a/crates/flyhigh-engine/src/ops/render.rs b/crates/flyhigh-engine/src/ops/render.rs index 7b1ab4d..2812deb 100644 --- a/crates/flyhigh-engine/src/ops/render.rs +++ b/crates/flyhigh-engine/src/ops/render.rs @@ -1,5 +1,6 @@ //! The final render: warped sources, visibility, residual, optional static protection; blend mixing. +use crate::gpu::memory::Buffer; use crate::{workgroups_2d, Gpu, LumaParams, NearKParams, NearParams, OpOutput, RenderParams, Tensor}; /// What the render reads: the two source frames (plain, full resolution), the flow and visibility maps of the phase @@ -24,7 +25,7 @@ pub struct RenderOpts<'a> { pub cubic: bool, /// render.wgsl's mode word: bit 0 decisive blend, bit 1 still test (`NetOpts::render_flags`) pub flags: u32, - pub static_age: Option<(&'a wgpu::Buffer, u32)>, + pub static_age: Option<(&'a Buffer, u32)>, } impl Gpu { diff --git a/crates/flyhigh-engine/src/ops/step.rs b/crates/flyhigh-engine/src/ops/step.rs index 7576627..65a8586 100644 --- a/crates/flyhigh-engine/src/ops/step.rs +++ b/crates/flyhigh-engine/src/ops/step.rs @@ -1,12 +1,12 @@ //! `Step`: one dispatch or copy of a plan, its bind group and metadata; plan dumps for the golden tests. +use crate::gpu::memory::{Buffer, Charge}; use crate::{Gpu, Tensor}; use std::rc::Rc; -use wgpu::util::DeviceExt; pub enum Step { Compute { pipe: &'static str, bg: wgpu::BindGroup, groups: (u32, u32, u32), meta: Rc }, - Copy { src: Rc, so: u64, dst: Rc, dof: u64, size: u64 }, + Copy { src: Rc, so: u64, dst: Rc, dof: u64, size: u64 }, } pub type OpOutput = (Tensor, Vec); @@ -15,6 +15,8 @@ pub type OpOutput = (Tensor, Vec); pub struct StepMeta { pub bindings: Vec, pub params: Vec, + pub(crate) params_buffer: Option>, + _allocations: Vec>, } pub enum Binding { Buffer(u64), @@ -22,8 +24,18 @@ pub enum Binding { Sampler, Params, } -pub(crate) fn meta(bindings: Vec, params: &[u8]) -> Rc { - Rc::new(StepMeta { bindings, params: params.to_vec() }) +pub(crate) fn meta<'a>( + bindings: Vec, + params: &[u8], + buffers: impl IntoIterator, + params_buffer: Option>, +) -> Rc { + Rc::new(StepMeta { + bindings, + params: params.to_vec(), + params_buffer, + _allocations: buffers.into_iter().map(|b| b.charge.clone()).collect(), + }) } /// One line per step: pipeline, workgroup counts, every binding (buffer size, texture size, sampler, the parameter /// uniform) and the parameter bytes as u32 words. The same plan always dumps the same text, so a dump is a golden. @@ -75,17 +87,16 @@ impl Gpu { pub fn bind( &self, pipe: &'static str, - ins: &[&wgpu::Buffer], + ins: &[&Buffer], params: &[u8], - out: &wgpu::Buffer, - extra: &[&wgpu::Buffer], + out: &Buffer, + extra: &[&Buffer], ) -> (wgpu::BindGroup, Rc) { - let pb = Rc::new(self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + let pb = Rc::new(self.buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("fh_params"), contents: params, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, })); - *self.last_pb.borrow_mut() = Some(pb.clone()); let mut e: Vec = ins .iter() .enumerate() @@ -107,15 +118,15 @@ impl Gpu { layout: &self.pipeline(pipe).get_bind_group_layout(0), entries: &e, }), - meta(bindings, params), + meta(bindings, params, ins.iter().copied().chain([out]).chain(extra.iter().copied()), Some(pb)), ) } pub fn compute_step( &self, pipe: &'static str, - ins: &[&wgpu::Buffer], + ins: &[&Buffer], params: &[u8], - out: &wgpu::Buffer, + out: &Buffer, groups: (u32, u32, u32), ) -> Step { let (bg, meta) = self.bind(pipe, ins, params, out, &[]); @@ -124,10 +135,10 @@ impl Gpu { pub fn compute_step_ex( &self, pipe: &'static str, - ins: &[&wgpu::Buffer], + ins: &[&Buffer], params: &[u8], - out: &wgpu::Buffer, - extra: &[&wgpu::Buffer], + out: &Buffer, + extra: &[&Buffer], groups: (u32, u32, u32), ) -> Step { let (bg, meta) = self.bind(pipe, ins, params, out, extra); diff --git a/crates/flyhigh-engine/src/ops/tensor.rs b/crates/flyhigh-engine/src/ops/tensor.rs index 4c49930..6dfb589 100644 --- a/crates/flyhigh-engine/src/ops/tensor.rs +++ b/crates/flyhigh-engine/src/ops/tensor.rs @@ -1,5 +1,6 @@ //! `Tensor`: a buffer with its channel / height / width shape, channel offset and scale (views). +use crate::gpu::memory::Buffer; use std::rc::Rc; #[derive(Clone)] @@ -7,7 +8,7 @@ use std::rc::Rc; // Views make slice / scale / neg / mul_t free (no dispatch): kernels that understand them read with the offset and // multiply on load; kernels that do not get a materialized copy (Gpu::mat) first. pub struct Tensor { - pub buf: Rc, + pub buf: Rc, pub c: u32, pub h: u32, pub w: u32, diff --git a/crates/flyhigh-engine/src/ops/texture.rs b/crates/flyhigh-engine/src/ops/texture.rs index eae6ae7..4204861 100644 --- a/crates/flyhigh-engine/src/ops/texture.rs +++ b/crates/flyhigh-engine/src/ops/texture.rs @@ -2,13 +2,12 @@ use crate::ops::step::meta; use crate::{workgroups_2d, Binding, Gpu, RgbaParams, Step, Tensor}; -use wgpu::util::DeviceExt; impl Gpu { // texture-input step: rgba8unorm texture view -> padded f16 CHW tensor pub fn tex_in_step(&self, view: &wgpu::TextureView, dst: &Tensor, w: u32, h: u32) -> Step { let rp = RgbaParams { w, h, wp: dst.w, hp: dst.h }; - let pb = self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + let pb = self.buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("fh_tex_in_params"), contents: bytemuck::bytes_of(&rp), usage: wgpu::BufferUsages::UNIFORM, @@ -29,6 +28,8 @@ impl Gpu { meta: meta( vec![Binding::Texture(w, h), Binding::Buffer(dst.buf.size()), Binding::Params], bytemuck::bytes_of(&rp), + [&*dst.buf, &pb], + None, ), } } @@ -36,7 +37,7 @@ impl Gpu { pub fn tex_out_step(&self, src: &Tensor, view: &wgpu::TextureView, w: u32, h: u32, bgra: bool) -> Step { let pipe: &'static str = if bgra { "tex_out_bgra" } else { "tex_out" }; let rp = RgbaParams { w, h, wp: src.w, hp: src.h }; - let pb = self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + let pb = self.buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("fh_tex_out_params"), contents: bytemuck::bytes_of(&rp), usage: wgpu::BufferUsages::UNIFORM, @@ -57,6 +58,8 @@ impl Gpu { meta: meta( vec![Binding::Buffer(src.buf.size()), Binding::Texture(w, h), Binding::Params], bytemuck::bytes_of(&rp), + [&*src.buf, &pb], + None, ), } } diff --git a/crates/flyhigh-engine/src/session.rs b/crates/flyhigh-engine/src/session.rs index 5b00e2f..28e267e 100644 --- a/crates/flyhigh-engine/src/session.rs +++ b/crates/flyhigh-engine/src/session.rs @@ -427,7 +427,7 @@ impl Session { self.check_out(slot)?; let (w, h) = (self.opts.width, self.opts.height); let bpr = (w * 4).div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; - let stage = self.gpu.device.create_buffer(&wgpu::BufferDescriptor { + let stage = self.gpu.buffer(&wgpu::BufferDescriptor { label: Some("fh_read_rgba"), size: (bpr * h) as u64, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, @@ -448,8 +448,8 @@ impl Session { wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, ); self.gpu.queue.submit(Some(enc.finish())); - Ok(Readback::new( - stage, + Ok(Readback::tracked( + &stage, Box::new(move |d: &[u8]| { let row = (w * 4) as usize; let mut v = Vec::with_capacity(row * h as usize); diff --git a/crates/flyhigh-engine/src/stream/classify.rs b/crates/flyhigh-engine/src/stream/classify.rs index 6333708..695a7fc 100644 --- a/crates/flyhigh-engine/src/stream/classify.rs +++ b/crates/flyhigh-engine/src/stream/classify.rs @@ -2,6 +2,7 @@ //! compute pass over the two textures (classify.wgsl) and an 8-byte readback; the decision lands asynchronously, //! before the interval's first mid is due. use super::IntervalKind; +use crate::gpu::memory::Buffer; use crate::gpu::readback::Readback; use crate::Gpu; use bytemuck::{Pod, Zeroable}; @@ -98,9 +99,9 @@ impl Classification { pub struct Classifier { sampler: wgpu::Sampler, - stats: wgpu::Buffer, - params: wgpu::Buffer, - stages: Vec<(wgpu::Buffer, Rc>)>, + stats: Buffer, + params: Buffer, + stages: Vec<(Rc, Rc>)>, bind_groups: HashMap<(usize, usize), wgpu::BindGroup>, thresholds: Thresholds, /// The mean difference of the last pair that was not a hold, as its readback landed. @@ -110,33 +111,32 @@ pub struct Classifier { impl Classifier { pub fn new(gpu: &Gpu, thresholds: Thresholds) -> Classifier { - use wgpu::util::DeviceExt; let sampler = gpu.device.create_sampler(&wgpu::SamplerDescriptor { label: Some("fh_classify"), mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear, ..Default::default() }); - let stats = gpu.device.create_buffer(&wgpu::BufferDescriptor { + let stats = gpu.buffer(&wgpu::BufferDescriptor { label: Some("fh_classify_stats"), size: 8, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); - let params = gpu.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + let params = gpu.buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("fh_classify_params"), contents: bytemuck::bytes_of(&ClassifyParams { gw: GRID.0, gh: GRID.1, _a: 0, _b: 0 }), usage: wgpu::BufferUsages::UNIFORM, }); let stages = (0..IN_FLIGHT) .map(|_| { - let b = gpu.device.create_buffer(&wgpu::BufferDescriptor { + let b = gpu.buffer(&wgpu::BufferDescriptor { label: Some("fh_classify_stage"), size: 8, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); - (b, Rc::new(Cell::new(false))) + (Rc::new(b), Rc::new(Cell::new(false))) }) .collect(); Classifier { @@ -195,8 +195,8 @@ impl Classifier { let cells = GRID.0 * GRID.1; let last_moving = self.last_moving.clone(); let last_held = self.last_held.clone(); - Some(Readback::new( - stage, + Some(Readback::tracked( + &stage, Box::new(move |d: &[u8]| { let s: &[u32] = bytemuck::cast_slice(&d[..8]); let c = Classification::from_stats(s[0], s[1], cells, &th).after(last_moving.get(), &th); diff --git a/crates/flyhigh-engine/src/warp/gpu.rs b/crates/flyhigh-engine/src/warp/gpu.rs index f3aefa2..a3635f5 100644 --- a/crates/flyhigh-engine/src/warp/gpu.rs +++ b/crates/flyhigh-engine/src/warp/gpu.rs @@ -4,6 +4,7 @@ //! (warp_refine), the minimum of each taken by warp_best. It reaches the calibrator through a 16-byte readback a frame //! or so later; nothing here waits on the GPU. use super::calib::{CalibOptions, Calibration, InputCalibrator}; +use crate::gpu::memory::{Buffer, Charge, Kind}; use crate::gpu::readback::Readback; use crate::Gpu; use bytemuck::{Pod, Zeroable}; @@ -152,11 +153,11 @@ type Shift = Option<(f64, f64)>; /// One pyramid level's buffers: the cell grids of the last two frames (`CameraWarp::cur` is the newer one's), its /// search result and the minimum taken from it. struct LevelBufs { - cells: [wgpu::Buffer; 2], - p_cells: wgpu::Buffer, - p_search: wgpu::Buffer, - p_best: wgpu::Buffer, - best: wgpu::Buffer, + cells: [Buffer; 2], + p_cells: Buffer, + p_search: Buffer, + p_best: Buffer, + best: Buffer, bg_cells: HashMap<(usize, usize), wgpu::BindGroup>, bg_search: [Option; 2], bg_best: Option, @@ -172,16 +173,17 @@ pub struct CameraWarp { cur: usize, prev: Option<(usize, wgpu::TextureView)>, /// The search differences of the level being searched (levels run in order, so they share it). - sad: wgpu::Buffer, - zero: wgpu::Buffer, - mask: wgpu::Buffer, - grown: wgpu::Buffer, - p_lock: wgpu::Buffer, - p_grow: wgpu::Buffer, - p_render: [wgpu::Buffer; 2], + sad: Buffer, + zero: Buffer, + mask: Buffer, + grown: Buffer, + p_lock: Buffer, + p_grow: Buffer, + p_render: [Buffer; 2], out: [(wgpu::Texture, wgpu::TextureView); 2], out_i: usize, - stages: Vec<(wgpu::Buffer, Rc>)>, + stages: Vec<(Rc, Rc>)>, + _out_memory: Charge, /// Frames in arrival order with their shift on its way; the calibrator takes them in that order. pending: VecDeque<(f64, Option>)>, bg_lock: HashMap<(usize, usize), wgpu::BindGroup>, @@ -190,17 +192,16 @@ pub struct CameraWarp { last_shift: Shift, } -fn uniform(gpu: &Gpu, label: &str, v: &T) -> wgpu::Buffer { - use wgpu::util::DeviceExt; - gpu.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { +fn uniform(gpu: &Gpu, label: &str, v: &T) -> Buffer { + gpu.buffer_init(&wgpu::util::BufferInitDescriptor { label: Some(label), contents: bytemuck::bytes_of(v), usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, }) } -fn storage(gpu: &Gpu, label: &str, bytes: u64, extra: wgpu::BufferUsages) -> wgpu::Buffer { - gpu.device.create_buffer(&wgpu::BufferDescriptor { +fn storage(gpu: &Gpu, label: &str, bytes: u64, extra: wgpu::BufferUsages) -> Buffer { + gpu.buffer(&wgpu::BufferDescriptor { label: Some(label), size: bytes, usage: wgpu::BufferUsages::STORAGE | extra, @@ -283,13 +284,13 @@ impl CameraWarp { }); let stages = (0..IN_FLIGHT) .map(|_| { - let b = gpu.device.create_buffer(&wgpu::BufferDescriptor { + let b = gpu.buffer(&wgpu::BufferDescriptor { label: Some("fh_warp_stage"), size: 16, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); - (b, Rc::new(Cell::new(false))) + (Rc::new(b), Rc::new(Cell::new(false))) }) .collect(); let lock_p = LockP { w, h, gw: mgw, gh: mgh, margin: opts.lock_margin, rel: opts.lock_rel, f, _b: 0.0 }; @@ -314,6 +315,7 @@ impl CameraWarp { p_render: [0, 1].map(|_| uniform(gpu, "fh_warp_render_p", &render_p)), out, out_i: 0, + _out_memory: gpu.memory.charge(Kind::AuxiliaryTextures, u64::from(w) * u64::from(h) * 4 * 2), stages, pending: VecDeque::new(), bg_lock: HashMap::new(), @@ -428,7 +430,7 @@ impl CameraWarp { let b: &[f32] = bytemuck::cast_slice(&d[..16]); (b[2] > 0.5).then_some((b[0] as f64, b[1] as f64)) }; - Readback::new(stage, Box::new(decode), Some(Box::new(move || busy.set(false)))) + Readback::tracked(&stage, Box::new(decode), Some(Box::new(move || busy.set(false)))) }); self.pending.push_back((t, rb)); self.prev = Some((src.0, src.1.clone())); @@ -583,7 +585,7 @@ impl CameraWarp { #[cfg(not(target_arch = "wasm32"))] pub fn read_mask(&self, gpu: &Gpu) -> Vec { let bytes = (self.w.div_ceil(BLOCK) * self.h.div_ceil(BLOCK) * 4) as u64; - let stage = gpu.device.create_buffer(&wgpu::BufferDescriptor { + let stage = gpu.buffer(&wgpu::BufferDescriptor { label: None, size: bytes, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, @@ -593,7 +595,7 @@ impl CameraWarp { // the lock kernel's own mask, before growing: what was detected enc.copy_buffer_to_buffer(&self.mask, 0, &stage, 0, bytes); gpu.queue.submit(Some(enc.finish())); - let rb = Readback::new(stage, Box::new(|d: &[u8]| bytemuck::cast_slice::(d).to_vec()), None); + let rb = Readback::tracked(&stage, Box::new(|d: &[u8]| bytemuck::cast_slice::(d).to_vec()), None); rb.block(gpu).unwrap_or_default() } } diff --git a/docs/api-c.md b/docs/api-c.md index b0514f6..73be8b8 100644 --- a/docs/api-c.md +++ b/docs/api-c.md @@ -32,7 +32,8 @@ fh_session_read_rgba(s, out, rgba, 1920 * 1080 * 4); // waits for the compact memory, DXC path, as `EngineOptions`. `fh_engine_info` writes the device as JSON (name, kernel class `tc-f16` / `portable-f16` / `portable-f32`, timestamp queries, and on DX12 `shader_compiler`: `dxc`, or `fxc` when `dxcompiler.dll` was not found); `fh_engine_report_json` adds kernels compiled, autotune entries and tensor - bytes. Destroy sessions and streams before the engine. + bytes, with live and peak allocation bytes in [`memory`](../ARCHITECTURE.md#options-and-reports). + Destroy sessions and streams before the engine. - `fh_model_load(dir)` / `fh_model_from_bytes(graph, len, manifest, len, weights, len)` load and check a checkpoint (format version, tensor table); `fh_model_info` is the model as JSON. Several models may live beside one engine. - `FhSessionOptions`: `width`, `height`, `internal_w` / `internal_h` (0, 0 = automatic: the 480-line rung above diff --git a/docs/api-js.md b/docs/api-js.md index bc0b3b9..d197d93 100644 --- a/docs/api-js.md +++ b/docs/api-js.md @@ -33,7 +33,7 @@ console.log(engine.info(), model.info()); // { name, |---|---| | `await FhEngine.create(options)` | the device; `{ precision: 'auto' \| 'f16' \| 'f32', tensorCores, autotune }` | | `engine.device()` | the `GPUDevice` | -| `engine.info()`, `engine.report()` | the device, its kernel class, timestamp queries; kernels compiled so far, autotune entries, tensor bytes | +| `engine.info()`, `engine.report()` | the device, its kernel class, timestamp queries; kernels compiled, autotune entries, cumulative `tensor_bytes`, and live and peak allocation bytes in [`memory`](../ARCHITECTURE.md#options-and-reports) | | `engine.kernelSource(name)` | `{ code, entry }`, the WGSL and entry point of a kernel exactly as this device compiles it (null for an unknown name). Pass every name you will `precompile` to `device.createComputePipelineAsync({ layout: 'auto', compute: { module: device.createShaderModule({ code }), entryPoint: entry } })` at once, and await them all: the browser compiles them in parallel off the compositing thread (a cold site: about 0.5 s instead of about 2 s), and `precompile` / `stream` then find them in its cache | | `engine.compiledKernels()`, `engine.precompile(names)` | the kernels compiled so far, and compiling named ones ahead of `stream` (unknown names skipped; returns how many it compiled). Chrome compiles in the process that composites the page and caches per site, so a stream's worth at once freezes a playing video for about a second on a new site: record `compiledKernels()` once, then `precompile` two or three names per animation frame (awaiting `device.queue.onSubmittedWorkDone()` between) before opening the stream | | `engine.loadModel(graphText, manifestText, weightBytes)` | an `FhModel`; the loader checks the format version and the tensor table. `model.info()`: name, training step, graph size, render sampler | @@ -41,6 +41,10 @@ console.log(engine.info(), model.info()); // { name, | `engine.stream(model, sessionOptions, streamOptions)` | an `FhStream` | | `await engine.autotune(model, sessionOptions)` | times the conv kernels of that configuration (5 to 15 s of GPU time; run it idle, once per GPU and size) and resolves with the table as text: store it (for example in `localStorage`, keyed by GPU, size and `k`) and pass it as the `tune` session option. Resolves with an empty string on a device without timestamp queries | +To check release, compare `engine.report().memory.live_bytes` before opening a stream, during playback, and +after outstanding stream calls settle and you call `stream.free()`. `memory.peak_bytes` keeps the high-water mark +for the engine's lifetime. + Session options: `{ width, height, internal: 'auto' | 'frame' | [w, h], k, repair, render: 'model' | 'bilinear' | 'bicubic', staticProtection: false | true | { frames, tolerance }, fastRender, linearT, keepMaps, protectionMask, nearestSource, preciseMotion, tune }`. Only `width` and `height` are required; the defaults are those of [options.md](options.md) (`internal` auto = diff --git a/docs/api-rust.md b/docs/api-rust.md index 54872e4..59057ef 100644 --- a/docs/api-rust.md +++ b/docs/api-rust.md @@ -29,7 +29,9 @@ let rgba = s.read_rgba(out)?.block(engine.gpu())?; // or present s.ou the device was created with them). `engine.info()` names the device, its kernel class (`tc-f16`, `portable-f16`, `portable-f32`) and, on DX12, the HLSL compiler wgpu loaded (`shader_compiler`: `dxc`, or `fxc` without `dxcompiler.dll`, see `EngineOptions::dxc_path`); `engine.report()` counts compiled kernels, autotune - entries and tensor bytes. + entries, cumulative `tensor_bytes`, and live and peak GPU allocation bytes in + [`memory`](../ARCHITECTURE.md#options-and-reports). Kernel-level tensor buffers use + `gpu::memory::Buffer`, which dereferences to `wgpu::Buffer` for queue operations. `engine.gpu()` is the wgpu context for the host's own surfaces and copies. - `Model::from_dir(dir)` / `Model::from_bytes(graph, manifest, weights)` load and validate a checkpoint (`model.info()`: name, training step, graph size, render sampler, format version). Several models may live beside From 4338f7f0cb071bac523566139d2775bd63990fbb Mon Sep 17 00:00:00 2001 From: NimaJafariComp Date: Thu, 19 Nov 2026 15:57:06 -0600 Subject: [PATCH 03/14] test: capture cadence parity and identify duplicated plan weights --- crates/flyhigh-engine/src/gen_tex.rs | 4 + crates/flyhigh-engine/src/gen_tex_tests.rs | 185 +++++++++++++++++++++ crates/flyhigh-engine/src/net/build.rs | 39 +++++ crates/flyhigh-engine/src/ops/step.rs | 12 ++ 4 files changed, 240 insertions(+) create mode 100644 crates/flyhigh-engine/src/gen_tex_tests.rs diff --git a/crates/flyhigh-engine/src/gen_tex.rs b/crates/flyhigh-engine/src/gen_tex.rs index ed0e925..f200361 100644 --- a/crates/flyhigh-engine/src/gen_tex.rs +++ b/crates/flyhigh-engine/src/gen_tex.rs @@ -17,6 +17,10 @@ use anyhow::{Context, Result}; use serde_json::Value; use std::collections::VecDeque; +#[cfg(all(test, not(target_arch = "wasm32")))] +#[path = "gen_tex_tests.rs"] +mod tests; + /// Still shot: some pair of the window changed less than this share of cells (held drawing, maybe with twinkling /// effects); a camera move changes most of the frame in every pair. const STILL_MAX: f32 = 0.01; diff --git a/crates/flyhigh-engine/src/gen_tex_tests.rs b/crates/flyhigh-engine/src/gen_tex_tests.rs new file mode 100644 index 0000000..83c8159 --- /dev/null +++ b/crates/flyhigh-engine/src/gen_tex_tests.rs @@ -0,0 +1,185 @@ +use super::*; +use crate::api::Engine; +use crate::gpu::readback::Readback; +use std::path::Path; + +const W: u32 = 256; +const H: u32 = 192; + +fn engine() -> Engine { + Engine::load_with(&Path::new(env!("CARGO_MANIFEST_DIR")).join("../../models"), &crate::EngineOptions::from_env()) + .expect("FlyHigh model and native GPU") +} + +fn anime(e: &Engine, w: u32, h: u32) -> GenTex { + let mut opts = TexOptions::new(w, h); + opts.mode = TexMode::Video; + opts.cadence = true; + opts.protection_mask = true; + GenTex::new(&e.gpu, &e.blob, &e.ops, opts, None).unwrap() +} + +fn cel(draw: u32, pan: u32, cut: bool) -> Vec { + let mut rgba = Vec::with_capacity((W * H * 4) as usize); + for y in 0..H { + for x in 0..W { + let bx = x + pan; + let wall = (bx / 17 + y / 23) % 3; + let ink = if (bx % 17 == 0) || (y % 23 == 0) { 12 } else { 52 + wall as u8 * 23 }; + let cx = 75 + ((draw % 4) * 31) as i32; + let dx = (x as i32 - cx).abs(); + let px = if cut { + [242, 229, 215, 255] + } else if dx < 27 && (58..136).contains(&y) { + if dx > 23 || (58..62).contains(&y) || (132..136).contains(&y) { + [17, 12, 23, 255] + } else if (80..99).contains(&y) && (10..17).contains(&dx) { + [250, 220, 160, 255] + } else { + [196, 57, 78, 255] + } + } else { + [ink, ink + 23, ink + 44, 255] + }; + rgba.extend_from_slice(&px); + } + } + rgba +} + +fn write(gpu: &Gpu, gen: &GenTex, slot: usize, rgba: &[u8]) { + gpu.queue.write_texture( + gen.ins[slot].0.as_image_copy(), + rgba, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(W * 4), rows_per_image: Some(H) }, + wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 1 }, + ); +} + +fn fingerprint(gpu: &Gpu, t: &wgpu::Texture) -> u64 { + let stage = gpu.device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: u64::from(W * H * 4), + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let mut enc = gpu.device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default()); + enc.copy_texture_to_buffer( + t.as_image_copy(), + wgpu::TexelCopyBufferInfo { + buffer: &stage, + layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(W * 4), rows_per_image: Some(H) }, + }, + wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 1 }, + ); + gpu.queue.submit(Some(enc.finish())); + Readback::new( + stage, + Box::new(|d: &[u8]| { + d.iter().fold(0xcbf29ce484222325_u64, |h, x| (h ^ u64::from(*x)).wrapping_mul(0x100000001b3)) + }), + None, + ) + .block(gpu) + .unwrap() +} + +#[test] +#[ignore = "requires a GPU"] +fn cadence_pixels_and_decisions() { + let e = engine(); + let gpu = &e.gpu; + let mut gen = anime(&e, W, H); + gen.write_mask(gpu, &(0..W * H).map(|i| u8::from(i % W < 21)).collect::>()).unwrap(); + for _ in 0..4 { + gen.add_input(gpu); + } + for _ in 0..2 { + gen.add_output(gpu); + } + let mut report = String::new(); + for (hold, pan) in [(2, false), (3, false), (2, true), (3, true)] { + gen.reset_history(); + let mut retimed = 0; + for i in 0..22 { + let slot = i % 4; + let cut = (13..15).contains(&i); + if i == 15 { + gen.reset_history(); + } + let image = cel((i / hold) as u32, if pan { 3 * i as u32 } else { 0 }, cut); + write(gpu, &gen, slot, &image); + let pushed = gen.push_slot(gpu, slot).unwrap(); + gen.resolve_stats(gpu).unwrap(); + assert_eq!(pushed.ready, i >= 2 && !(15..17).contains(&i)); + if i == 13 { + assert!(gen.stats()[2].cut); + } + if !pushed.ready { + continue; + } + for t in [0.0, 0.25, 0.5, 0.75] { + let decision = gen.retime(t); + if cut { + assert!(decision.is_none(), "never retime through a detected cut"); + } + retimed += usize::from(decision.is_some()); + let written = gen.generate(gpu, t, 0).unwrap(); + assert_eq!(written, t > 0.0 || decision.is_some()); + let pixels = written.then(|| fingerprint(gpu, &gen.outs[0].0)); + report.push_str(&format!("{hold} {pan} {i} {t} {decision:?} {pixels:016x?}\n")); + } + if i == 7 { + let sc = gen.scratch.as_ref().unwrap(); + let bg = &gen.sess[gen.order[1]]; + for (full, which, out) in [(true, 1, 0), (false, 0, 1), (false, 2, 0)] { + let elem = &gen.sess[gen.order[which]]; + gmhs::composite_frame(gpu, sc, (bg, 0.25), (elem, 0.75), (elem, full), out, &gen.outs[out].1) + .unwrap(); + report.push_str(&format!( + "composite {hold} {pan} {full} {which} {:016x}\n", + fingerprint(gpu, &gen.outs[out].0) + )); + } + } + } + if !pan { + assert!(retimed > 0, "held drawings must exercise retiming"); + } + } + if let Some(path) = std::env::var_os("FH_CADENCE_CAPTURE") { + std::fs::write(path, &report).unwrap(); + } +} + +#[test] +#[ignore = "requires a GPU"] +fn cadence_1080p_memory() { + let e = engine(); + let core = crate::Engine::from_shared(e.gpu.clone()); + let before = core.report().memory; + let mut gen = anime(&e, 1920, 1080); + for _ in 0..4 { + gen.add_input(&e.gpu); + } + for _ in 0..2 { + gen.add_output(&e.gpu); + } + let active = core.report().memory; + eprintln!("1080p cadence memory: {}", serde_json::to_string(&active).unwrap()); + drop(gen); + assert_eq!(core.report().memory.live_bytes, before.live_bytes); +} + +#[test] +#[ignore = "requires a GPU"] +fn video_plans_share_immutable_convolution_weights() { + let e = engine(); + let generator = anime(&e, W, H); + let first_conv_weights: Vec<_> = generator.sess.iter().map(|s| { + let conv = s.plan_pair.iter().find(|s| matches!(s, Step::Compute { pipe, .. } + if ["conv", "implicit", "fused", "tconv", "fdirect"].iter().any(|prefix| pipe.starts_with(prefix)))).unwrap(); + conv.allocations().nth(1).unwrap().clone() + }).collect(); + assert!(first_conv_weights.iter().all(|w| std::rc::Rc::ptr_eq(w, &first_conv_weights[0]))); +} diff --git a/crates/flyhigh-engine/src/net/build.rs b/crates/flyhigh-engine/src/net/build.rs index 3788158..1a25ebc 100644 --- a/crates/flyhigh-engine/src/net/build.rs +++ b/crates/flyhigh-engine/src/net/build.rs @@ -617,6 +617,20 @@ pub fn build_network_ex( }), } } + #[cfg(test)] + let (retained, pair_buffers) = if net.keep_maps && std::env::var_os("FH_CADENCE_DIAGNOSTICS").is_some() { + let retained = env + .values() + .map(|t| &t.buf) + .chain([&a.buf, &b.buf]) + .chain(static_age.iter()) + .map(|b| Rc::as_ptr(&b.charge)) + .collect::>(); + let pair = plan.iter().flat_map(Step::allocations).map(|a| (Rc::as_ptr(a), a.bytes)).collect::>(); + (retained, pair) + } else { + Default::default() + }; let tail: &mut Vec = match plan_mid { Some(pm) => { for v in env.values() { @@ -681,6 +695,31 @@ pub fn build_network_ex( workgroups_2d(wp, hp, 1), )); } + #[cfg(test)] + if !retained.is_empty() { + let weights = cx + .wcache + .values() + .chain(cx.bcache.values().map(|b| &b.0)) + .chain(cx.bcache4.values().map(|b| &b.0)) + .map(|b| Rc::as_ptr(&b.charge)) + .collect::>(); + let mut bytes = pair_buffers; + bytes.extend(tail.iter().flat_map(Step::allocations).map(|a| (Rc::as_ptr(a), a.bytes))); + bytes.remove(&Rc::as_ptr(&gpu.zero.charge)); + bytes.remove(&Rc::as_ptr(&gpu.ones.charge)); + let (mut w, mut r, mut tmp) = (0, 0, 0); + for (id, size) in bytes { + if weights.contains(&id) { + w += size; + } else if retained.contains(&id) { + r += size; + } else { + tmp += size; + } + } + eprintln!("plan {wp}x{hp}: weights={w}, retained={r}, workspace={tmp}"); + } gpu.remember_tune(&cx.tune); *gpu.arena.borrow_mut() = arena_was; // released scratch that nobody took is dropped here (VRAM freed) gpu.arena_ids.borrow_mut().clear(); diff --git a/crates/flyhigh-engine/src/ops/step.rs b/crates/flyhigh-engine/src/ops/step.rs index 65a8586..a5f1244 100644 --- a/crates/flyhigh-engine/src/ops/step.rs +++ b/crates/flyhigh-engine/src/ops/step.rs @@ -8,6 +8,18 @@ pub enum Step { Compute { pipe: &'static str, bg: wgpu::BindGroup, groups: (u32, u32, u32), meta: Rc }, Copy { src: Rc, so: u64, dst: Rc, dof: u64, size: u64 }, } +#[cfg(test)] +impl Step { + pub(crate) fn allocations(&self) -> impl Iterator> { + match self { + Self::Compute { meta, .. } => { + meta._allocations.iter().chain(meta.params_buffer.iter().map(|p| &p.charge)).collect::>() + } + Self::Copy { src, dst, .. } => vec![&src.charge, &dst.charge], + } + .into_iter() + } +} pub type OpOutput = (Tensor, Vec); /// What a compute step binds and its parameter bytes: a bind group is opaque once built, and the golden-plan tests From fbfd437b07613f2490ce3d61269312978462c15e Mon Sep 17 00:00:00 2001 From: NimaJafariComp Date: Thu, 19 Nov 2026 15:57:59 -0600 Subject: [PATCH 04/14] =?UTF-8?q?Share=20immutable=20packed=20weights=20ac?= =?UTF-8?q?ross=20a=20video=20stream=E2=80=99s=20pair=20plans?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/flyhigh-engine/src/gen_tex.rs | 16 ++++- crates/flyhigh-engine/src/gen_tex_tests.rs | 20 ++++-- crates/flyhigh-engine/src/net/build.rs | 70 +++++++++++++++----- crates/flyhigh-engine/src/net/session_ext.rs | 39 +++++++++-- 4 files changed, 118 insertions(+), 27 deletions(-) diff --git a/crates/flyhigh-engine/src/gen_tex.rs b/crates/flyhigh-engine/src/gen_tex.rs index f200361..a980d4a 100644 --- a/crates/flyhigh-engine/src/gen_tex.rs +++ b/crates/flyhigh-engine/src/gen_tex.rs @@ -12,6 +12,7 @@ //! browser host awaits the promise of `fh_vid_stats` before the first `generate` of the interval (the lookahead hides it). use crate::gmhs::{CadenceScratch, PairStats, StatsRun}; use crate::gpu::memory::Charge; +use crate::net::build::PlanResources; use crate::{gmhs, Blob, Gpu, NetOpts, SessionExt, Step, TimedRun}; use anyhow::{Context, Result}; use serde_json::Value; @@ -238,8 +239,21 @@ impl GenTex { cascade_iters: crate::options::cascade_for(opts.precise).1, }; let mut sess = Vec::new(); + let mut resources = PlanResources::default(); for _ in 0..n_sess { - sess.push(SessionExt::new(gpu, blob, ops, opts.w, opts.h, opts.k, opts.iw, opts.ih, tune, &net)); + sess.push(SessionExt::new_with( + gpu, + blob, + ops, + opts.w, + opts.h, + opts.k, + opts.iw, + opts.ih, + tune, + &net, + &mut resources, + )); } let scratch = if cadence { Some(CadenceScratch::new(gpu, &sess[0]).context("cadence: GMHS maps missing")?) diff --git a/crates/flyhigh-engine/src/gen_tex_tests.rs b/crates/flyhigh-engine/src/gen_tex_tests.rs index 83c8159..6f57be8 100644 --- a/crates/flyhigh-engine/src/gen_tex_tests.rs +++ b/crates/flyhigh-engine/src/gen_tex_tests.rs @@ -176,10 +176,20 @@ fn cadence_1080p_memory() { fn video_plans_share_immutable_convolution_weights() { let e = engine(); let generator = anime(&e, W, H); - let first_conv_weights: Vec<_> = generator.sess.iter().map(|s| { - let conv = s.plan_pair.iter().find(|s| matches!(s, Step::Compute { pipe, .. } - if ["conv", "implicit", "fused", "tconv", "fdirect"].iter().any(|prefix| pipe.starts_with(prefix)))).unwrap(); - conv.allocations().nth(1).unwrap().clone() - }).collect(); + let first_conv_weights: Vec<_> = generator + .sess + .iter() + .map(|s| { + let conv = s + .plan_pair + .iter() + .find(|s| { + matches!(s, Step::Compute { pipe, .. } + if ["conv", "implicit", "fused", "tconv", "fdirect"].iter().any(|prefix| pipe.starts_with(prefix))) + }) + .unwrap(); + conv.allocations().nth(1).unwrap().clone() + }) + .collect(); assert!(first_conv_weights.iter().all(|w| std::rc::Rc::ptr_eq(w, &first_conv_weights[0]))); } diff --git a/crates/flyhigh-engine/src/net/build.rs b/crates/flyhigh-engine/src/net/build.rs index 1a25ebc..1c8fd3b 100644 --- a/crates/flyhigh-engine/src/net/build.rs +++ b/crates/flyhigh-engine/src/net/build.rs @@ -20,12 +20,24 @@ pub fn set_t(gpu: &Gpu, deps: &[PhaseDep], t: f32) { } } +type PackKey = (String, u32, u32); + +#[derive(Default)] +pub(crate) struct PlanResources { + weights: Weights, +} + +#[derive(Default)] +struct Weights { + raw: HashMap>, + gemm: HashMap, u32, u32)>, + tap: HashMap, u32, u32, u32)>, +} + pub struct BuildCtx<'a> { pub gpu: &'a Gpu, pub blob: &'a Blob, - pub wcache: HashMap>, - pub bcache: HashMap, u32, u32)>, - pub bcache4: HashMap, u32, u32, u32)>, + weights: Weights, pub k: u32, pub t: f32, pub hs: u32, @@ -49,9 +61,7 @@ impl<'a> BuildCtx<'a> { BuildCtx { gpu, blob, - wcache: HashMap::new(), - bcache: HashMap::new(), - bcache4: HashMap::new(), + weights: Weights::default(), k, t, hs, @@ -99,27 +109,29 @@ impl<'a> BuildCtx<'a> { impl<'a> BuildCtx<'a> { pub fn wb(&mut self, name: &str) -> Rc { - if let Some(b) = self.wcache.get(name) { + if let Some(b) = self.weights.raw.get(name) { return b.clone(); } let b = self.gpu.buf(&self.blob.weight(name)); - self.wcache.insert(name.to_string(), b.clone()); + self.weights.raw.insert(name.to_string(), b.clone()); b } pub fn bbuf(&mut self, name: &str, cin: u32, cout: u32) -> (Rc, u32, u32) { - if let Some(b) = self.bcache.get(name) { + let key = (name.to_owned(), cin, cout); + if let Some(b) = self.weights.gemm.get(&key) { return b.clone(); } let b = self.gpu.buildb(&self.blob.weight(name), cin, cout); - self.bcache.insert(name.to_string(), b.clone()); + self.weights.gemm.insert(key, b.clone()); b } pub fn bbuf_tap(&mut self, name: &str, cin: u32, cout: u32) -> (Rc, u32, u32, u32) { - if let Some(b) = self.bcache4.get(name) { + let key = (name.to_owned(), cin, cout); + if let Some(b) = self.weights.tap.get(&key) { return b.clone(); } let b = self.gpu.buildb_tap(&self.blob.weight(name), cin, cout); - self.bcache4.insert(name.to_string(), b.clone()); + self.weights.tap.insert(key, b.clone()); b } } @@ -505,6 +517,26 @@ pub fn build_network_ex( plan_mid: Option<&mut Vec>, tune: Option<&TuneTable>, net: &NetOpts, +) -> (Tensor, HashMap, Vec) { + build_network_with(gpu, blob, ops, a, b, k, t, iw, ih, plan, plan_mid, tune, net, &mut PlanResources::default()) +} + +#[allow(clippy::too_many_arguments)] +pub(crate) fn build_network_with( + gpu: &Gpu, + blob: &Blob, + ops: &[Value], + a: &Tensor, + b: &Tensor, + k: u32, + t: f32, + iw: u32, + ih: u32, + plan: &mut Vec, + plan_mid: Option<&mut Vec>, + tune: Option<&TuneTable>, + net: &NetOpts, + resources: &mut PlanResources, ) -> (Tensor, HashMap, Vec) { let (hp, wp) = (a.h, a.w); let (ihp, iwp) = (ih.div_ceil(32) * 32, iw.div_ceil(32) * 32); @@ -527,6 +559,7 @@ pub fn build_network_ex( gpu.arena_ids.borrow_mut().clear(); let mut env: HashMap = HashMap::new(); let mut cx = BuildCtx::new(gpu, blob, k, t, ihp, iwp); + cx.weights = std::mem::take(&mut resources.weights); cx.cubic = net.cubic; cx.render_flags = net.render_flags(); cx.pin(a); @@ -661,7 +694,8 @@ pub fn build_network_ex( *gpu.arena.borrow_mut() = arena_was; gpu.arena_ids.borrow_mut().clear(); let r = env["render"].clone(); - return (r, env, std::mem::take(&mut cx.t_deps)); + resources.weights = cx.weights; + return (r, env, cx.t_deps); } if let Some(op) = rop { let ins = names(op, "in"); // A, B, flow_tq, vis_tq, R_t @@ -698,10 +732,11 @@ pub fn build_network_ex( #[cfg(test)] if !retained.is_empty() { let weights = cx - .wcache + .weights + .raw .values() - .chain(cx.bcache.values().map(|b| &b.0)) - .chain(cx.bcache4.values().map(|b| &b.0)) + .chain(cx.weights.gemm.values().map(|b| &b.0)) + .chain(cx.weights.tap.values().map(|b| &b.0)) .map(|b| Rc::as_ptr(&b.charge)) .collect::>(); let mut bytes = pair_buffers; @@ -724,5 +759,6 @@ pub fn build_network_ex( *gpu.arena.borrow_mut() = arena_was; // released scratch that nobody took is dropped here (VRAM freed) gpu.arena_ids.borrow_mut().clear(); let r = env["render"].clone(); - (r, env, std::mem::take(&mut cx.t_deps)) + resources.weights = cx.weights; + (r, env, cx.t_deps) } diff --git a/crates/flyhigh-engine/src/net/session_ext.rs b/crates/flyhigh-engine/src/net/session_ext.rs index 81d9143..df09bc1 100644 --- a/crates/flyhigh-engine/src/net/session_ext.rs +++ b/crates/flyhigh-engine/src/net/session_ext.rs @@ -1,10 +1,10 @@ //! `SessionExt`: the texture path with input / output slots, a pair plan, a mid plan and the fast render. use crate::gpu::memory::{Buffer, Charge}; +use crate::net::build::{build_network_with, PlanResources}; use crate::ops::step::meta; use crate::{ - build_network_ex, clone_step, set_t, workgroups_2d, Binding, Blob, Gpu, NetOpts, PhaseDep, StaticParams, Step, - Tensor, TuneTable, + clone_step, set_t, workgroups_2d, Binding, Blob, Gpu, NetOpts, PhaseDep, StaticParams, Step, Tensor, TuneTable, }; use bytemuck::{Pod, Zeroable}; use serde_json::Value; @@ -78,6 +78,23 @@ impl SessionExt { ih: u32, tune: Option<&TuneTable>, net: &NetOpts, + ) -> SessionExt { + Self::new_with(gpu, blob, ops, w, h, k, iw, ih, tune, net, &mut PlanResources::default()) + } + + #[allow(clippy::too_many_arguments)] + pub(crate) fn new_with( + gpu: &Gpu, + blob: &Blob, + ops: &[Value], + w: u32, + h: u32, + k: u32, + iw: u32, + ih: u32, + tune: Option<&TuneTable>, + net: &NetOpts, + resources: &mut PlanResources, ) -> SessionExt { let (hp, wp) = (h.div_ceil(32) * 32, w.div_ceil(32) * 32); // fast render reads the source textures directly: the full-resolution input tensors keep only their shape @@ -86,8 +103,22 @@ impl SessionExt { let a = Tensor { buf: gpu.alloc(n), c: 3, h: hp, w: wp, c0: 0, scale: 1.0 }; let b = Tensor { buf: gpu.alloc(n), c: 3, h: hp, w: wp, c0: 0, scale: 1.0 }; let (mut plan_pair, mut plan_mid) = (Vec::new(), Vec::new()); - let (render, env, t_deps) = - build_network_ex(gpu, blob, ops, &a, &b, k, 0.5, iw, ih, &mut plan_pair, Some(&mut plan_mid), tune, net); + let (render, env, t_deps) = build_network_with( + gpu, + blob, + ops, + &a, + &b, + k, + 0.5, + iw, + ih, + &mut plan_pair, + Some(&mut plan_mid), + tune, + net, + resources, + ); let fast = env.get("fast:ftq").map(|ftq| { let (ihp, iwp) = (ih.div_ceil(32) * 32, iw.div_ceil(32) * 32); let samp = gpu.device.create_sampler(&wgpu::SamplerDescriptor { From 28a770b5df49db73424ed8d983a99fa136f78fc6 Mon Sep 17 00:00:00 2001 From: NimaJafariComp Date: Thu, 19 Nov 2026 15:58:24 -0600 Subject: [PATCH 05/14] test: require the cadence plans to share one render target --- crates/flyhigh-engine/src/gen_tex_tests.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/crates/flyhigh-engine/src/gen_tex_tests.rs b/crates/flyhigh-engine/src/gen_tex_tests.rs index 6f57be8..a5e46f4 100644 --- a/crates/flyhigh-engine/src/gen_tex_tests.rs +++ b/crates/flyhigh-engine/src/gen_tex_tests.rs @@ -159,6 +159,7 @@ fn cadence_1080p_memory() { let core = crate::Engine::from_shared(e.gpu.clone()); let before = core.report().memory; let mut gen = anime(&e, 1920, 1080); + assert_render_shared(&gen); for _ in 0..4 { gen.add_input(&e.gpu); } @@ -171,6 +172,16 @@ fn cadence_1080p_memory() { assert_eq!(core.report().memory.live_bytes, before.live_bytes); } +fn assert_render_shared(gen: &GenTex) { + assert!(gen.sess.iter().all(|s| std::rc::Rc::ptr_eq(&s.render.buf, &gen.sess[0].render.buf))); +} + +#[test] +#[ignore = "requires a GPU"] +fn cadence_shares_render_at_native_resolution() { + assert_render_shared(&anime(&engine(), W, H)); +} + #[test] #[ignore = "requires a GPU"] fn video_plans_share_immutable_convolution_weights() { From 03f0f63d500fc0122682c3032be5ddd3aa9a12b3 Mon Sep 17 00:00:00 2001 From: NimaJafariComp Date: Thu, 19 Nov 2026 15:59:38 -0600 Subject: [PATCH 06/14] Reuse a single render target for cadence synthesis --- crates/flyhigh-engine/src/gen_tex.rs | 4 ++++ crates/flyhigh-engine/src/net/build.rs | 10 ++++++++-- crates/flyhigh-engine/src/ops/render.rs | 6 +++++- 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/crates/flyhigh-engine/src/gen_tex.rs b/crates/flyhigh-engine/src/gen_tex.rs index a980d4a..d8559c9 100644 --- a/crates/flyhigh-engine/src/gen_tex.rs +++ b/crates/flyhigh-engine/src/gen_tex.rs @@ -240,6 +240,10 @@ impl GenTex { }; let mut sess = Vec::new(); let mut resources = PlanResources::default(); + // Every mid consumes the render before the next one, including the compositor's saved background. + if cadence { + resources.render = Some(gpu.alloc((3 * (opts.w.div_ceil(32) * 32) * (opts.h.div_ceil(32) * 32)) as usize)); + } for _ in 0..n_sess { sess.push(SessionExt::new_with( gpu, diff --git a/crates/flyhigh-engine/src/net/build.rs b/crates/flyhigh-engine/src/net/build.rs index 1c8fd3b..1d3a62d 100644 --- a/crates/flyhigh-engine/src/net/build.rs +++ b/crates/flyhigh-engine/src/net/build.rs @@ -25,6 +25,7 @@ type PackKey = (String, u32, u32); #[derive(Default)] pub(crate) struct PlanResources { weights: Weights, + pub(crate) render: Option>, } #[derive(Default)] @@ -38,6 +39,7 @@ pub struct BuildCtx<'a> { pub gpu: &'a Gpu, pub blob: &'a Blob, weights: Weights, + render_target: Option>, pub k: u32, pub t: f32, pub hs: u32, @@ -62,6 +64,7 @@ impl<'a> BuildCtx<'a> { gpu, blob, weights: Weights::default(), + render_target: None, k, t, hs, @@ -358,7 +361,7 @@ pub fn build(ops: &[Value], env: &mut HashMap, plan: &mut Vec { let (a, b, rt) = (mat(t(env, 0), plan), mat(t(env, 1), plan), mat(t(env, 4), plan)); let (ftq, vtq) = (t(env, 2), t(env, 3)); - g.render_ex( + g.render_ex_to( &RenderInputs { a: &a, b: &b, flow: &ftq, vis: &vtq, residual: &rt }, &RenderOpts { fsx: ftq.scale, @@ -367,6 +370,7 @@ pub fn build(ops: &[Value], env: &mut HashMap, plan: &mut Vec { @@ -560,6 +564,7 @@ pub(crate) fn build_network_with( let mut env: HashMap = HashMap::new(); let mut cx = BuildCtx::new(gpu, blob, k, t, ihp, iwp); cx.weights = std::mem::take(&mut resources.weights); + cx.render_target = resources.render.clone(); cx.cubic = net.cubic; cx.render_flags = net.render_flags(); cx.pin(a); @@ -703,7 +708,7 @@ pub(crate) fn build_network_with( let (rt, s) = gpu.mat(&env[&ins[4]]); tail.extend(s); let (fsx, fsy) = (ftq.scale * wp as f32 / iwp as f32, ftq.scale * hp as f32 / ihp as f32); - let (o, s) = gpu.render_ex( + let (o, s) = gpu.render_ex_to( &RenderInputs { a, b, flow: &ftq, vis: &vtq, residual: &rt }, &RenderOpts { fsx, @@ -712,6 +717,7 @@ pub(crate) fn build_network_with( flags: net.render_flags(), static_age: static_age.as_deref().map(|b| (b, static_frames)), }, + cx.render_target.as_ref(), ); tail.extend(s); cx.pin(&o); diff --git a/crates/flyhigh-engine/src/ops/render.rs b/crates/flyhigh-engine/src/ops/render.rs index 2812deb..b676f8f 100644 --- a/crates/flyhigh-engine/src/ops/render.rs +++ b/crates/flyhigh-engine/src/ops/render.rs @@ -2,6 +2,7 @@ use crate::gpu::memory::Buffer; use crate::{workgroups_2d, Gpu, LumaParams, NearKParams, NearParams, OpOutput, RenderParams, Tensor}; +use std::rc::Rc; /// What the render reads: the two source frames (plain, full resolution), the flow and visibility maps of the phase /// (`flow_tq`, `vis_tq`; views allowed) and the residual `R_t` (plain). @@ -37,8 +38,11 @@ impl Gpu { ) } pub fn render_ex(&self, i: &RenderInputs, o: &RenderOpts) -> OpOutput { + self.render_ex_to(i, o, None) + } + pub(crate) fn render_ex_to(&self, i: &RenderInputs, o: &RenderOpts, target: Option<&Rc>) -> OpOutput { let (a, b, ftq, vtq, rt) = (i.a, i.b, i.flow, i.vis, i.residual); - let out = self.alloc((3 * a.h * a.w) as usize); + let out = target.cloned().unwrap_or_else(|| self.alloc((3 * a.h * a.w) as usize)); debug_assert!(a.is_plain() && b.is_plain() && rt.is_plain()); let p = RenderParams { h: a.h, From b5235a6b8ed9ea1231aedb6ceacfcff17a7a3837 Mon Sep 17 00:00:00 2001 From: NimaJafariComp Date: Thu, 19 Nov 2026 16:00:07 -0600 Subject: [PATCH 07/14] test: separate reusable inference scratch from retained cadence data --- crates/flyhigh-engine/src/gen_tex_tests.rs | 20 ++++++++++++++++++++ crates/flyhigh-engine/src/gpu/memory.rs | 7 +++++++ 2 files changed, 27 insertions(+) diff --git a/crates/flyhigh-engine/src/gen_tex_tests.rs b/crates/flyhigh-engine/src/gen_tex_tests.rs index a5e46f4..5789e90 100644 --- a/crates/flyhigh-engine/src/gen_tex_tests.rs +++ b/crates/flyhigh-engine/src/gen_tex_tests.rs @@ -204,3 +204,23 @@ fn video_plans_share_immutable_convolution_weights() { .collect(); assert!(first_conv_weights.iter().all(|w| std::rc::Rc::ptr_eq(w, &first_conv_weights[0]))); } + +#[test] +#[ignore = "requires a GPU"] +fn cadence_shares_transient_inference_buffers_but_keeps_pair_data() { + let gen = anime(&engine(), W, H); + let (a, b) = (&gen.sess[0], &gen.sess[1]); + let temps = |s: &SessionExt| { + s.plan_mid.iter().flat_map(Step::allocations) + .filter(|c| c.is_tensor() && !std::rc::Rc::ptr_eq(c, &s.render.buf.charge)) + .map(std::rc::Rc::as_ptr).collect::>() + }; + if std::env::var_os("FH_NO_ARENA").is_none() { + assert!(temps(a).intersection(&temps(b)).count() > 5, "mid kernels reuse one workspace"); + } + for field in ["gm_maps", "static:state", "mask"] { + assert!(!std::rc::Rc::ptr_eq(&a.env[field].buf.charge, &b.env[field].buf.charge)); + } + assert!(!std::rc::Rc::ptr_eq(&a.a.buf.charge, &b.a.buf.charge)); + assert!(!std::rc::Rc::ptr_eq(&a.b.buf.charge, &b.b.buf.charge)); +} diff --git a/crates/flyhigh-engine/src/gpu/memory.rs b/crates/flyhigh-engine/src/gpu/memory.rs index 8a51ffd..d29e38c 100644 --- a/crates/flyhigh-engine/src/gpu/memory.rs +++ b/crates/flyhigh-engine/src/gpu/memory.rs @@ -84,6 +84,13 @@ pub(crate) struct Charge { pub(crate) bytes: u64, } +#[cfg(test)] +impl Charge { + pub(crate) fn is_tensor(&self) -> bool { + matches!(self.kind, Kind::Tensors) + } +} + impl Drop for Charge { fn drop(&mut self) { let state = &self.memory.0; From 99c6fb41a1dbebc5e279f69161d290f304638a8c Mon Sep 17 00:00:00 2001 From: NimaJafariComp Date: Thu, 19 Nov 2026 16:02:16 -0600 Subject: [PATCH 08/14] Reuse transient cadence allocations while keeping live pairs private --- crates/flyhigh-engine/src/gen_tex.rs | 47 ++++++++++++------ crates/flyhigh-engine/src/gen_tex_tests.rs | 7 ++- crates/flyhigh-engine/src/gpu/alloc.rs | 58 +++++++++++++++++++++- crates/flyhigh-engine/src/gpu/device.rs | 1 + crates/flyhigh-engine/src/gpu/memory.rs | 1 + crates/flyhigh-engine/src/gpu/mod.rs | 1 + crates/flyhigh-engine/src/net/build.rs | 24 ++++++++- crates/flyhigh-engine/src/ops/step.rs | 13 ++--- 8 files changed, 125 insertions(+), 27 deletions(-) diff --git a/crates/flyhigh-engine/src/gen_tex.rs b/crates/flyhigh-engine/src/gen_tex.rs index d8559c9..e0378a7 100644 --- a/crates/flyhigh-engine/src/gen_tex.rs +++ b/crates/flyhigh-engine/src/gen_tex.rs @@ -244,20 +244,39 @@ impl GenTex { if cadence { resources.render = Some(gpu.alloc((3 * (opts.w.div_ceil(32) * 32) * (opts.h.div_ceil(32) * 32)) as usize)); } - for _ in 0..n_sess { - sess.push(SessionExt::new_with( - gpu, - blob, - ops, - opts.w, - opts.h, - opts.k, - opts.iw, - opts.ih, - tune, - &net, - &mut resources, - )); + let can_share_workspace = cadence && std::env::var_os("FH_NO_ARENA").is_none(); + let mut warmed_tune = None; + for attempt in 0..3 { + resources.workspace = (can_share_workspace && attempt < 2).then(Default::default); + resources.layout_mismatch = false; + for _ in 0..n_sess { + sess.push(SessionExt::new_with( + gpu, + blob, + ops, + opts.w, + opts.h, + opts.k, + opts.iw, + opts.ih, + warmed_tune.as_ref().or(tune), + &net, + &mut resources, + )); + if resources.layout_mismatch { + break; + } + } + if !resources.layout_mismatch { + break; + } + // Cold native autotune can change the allocation trace. Retry with those choices, otherwise keep private arenas. + sess.clear(); + if attempt == 0 { + let mut choices = gpu.tune.borrow().clone(); + choices.extend(tune.into_iter().flatten().map(|(k, v)| (*k, *v))); + warmed_tune = Some(choices); + } } let scratch = if cadence { Some(CadenceScratch::new(gpu, &sess[0]).context("cadence: GMHS maps missing")?) diff --git a/crates/flyhigh-engine/src/gen_tex_tests.rs b/crates/flyhigh-engine/src/gen_tex_tests.rs index 5789e90..7b0e830 100644 --- a/crates/flyhigh-engine/src/gen_tex_tests.rs +++ b/crates/flyhigh-engine/src/gen_tex_tests.rs @@ -211,9 +211,12 @@ fn cadence_shares_transient_inference_buffers_but_keeps_pair_data() { let gen = anime(&engine(), W, H); let (a, b) = (&gen.sess[0], &gen.sess[1]); let temps = |s: &SessionExt| { - s.plan_mid.iter().flat_map(Step::allocations) + s.plan_mid + .iter() + .flat_map(Step::allocations) .filter(|c| c.is_tensor() && !std::rc::Rc::ptr_eq(c, &s.render.buf.charge)) - .map(std::rc::Rc::as_ptr).collect::>() + .map(std::rc::Rc::as_ptr) + .collect::>() }; if std::env::var_os("FH_NO_ARENA").is_none() { assert!(temps(a).intersection(&temps(b)).count() > 5, "mid kernels reuse one workspace"); diff --git a/crates/flyhigh-engine/src/gpu/alloc.rs b/crates/flyhigh-engine/src/gpu/alloc.rs index 81adf88..0ccf220 100644 --- a/crates/flyhigh-engine/src/gpu/alloc.rs +++ b/crates/flyhigh-engine/src/gpu/alloc.rs @@ -1,7 +1,8 @@ //! Tensor buffers: creation, the per-plan arena that reuses dead tensors' buffers, scratch release, memory accounting. -use super::memory::{Buffer, Kind}; +use super::memory::{Buffer, Charge, Kind}; use crate::Gpu; +use std::collections::HashSet; use std::rc::Rc; use wgpu::util::DeviceExt; @@ -10,6 +11,50 @@ pub(crate) fn arena_trace() -> bool { std::env::var_os("FH_ARENA_TRACE").is_some() } +#[derive(Default)] +pub(crate) struct Workspace { + slots: Vec<(u64, Option)>, + allocated: Vec, + mismatch: bool, +} + +impl Workspace { + fn reuse(&mut self, size: u64) -> Option { + if self.slots.is_empty() || self.mismatch { + return None; + } + match self.slots.get(self.allocated.len()) { + Some((len, buf)) if *len == size => buf.clone(), + _ => { + self.mismatch = true; + None + } + } + } + + pub(crate) fn finish(&mut self, retained: &HashSet<*const Charge>, used: &HashSet<*const Charge>) -> bool { + if self.slots.is_empty() { + self.slots = self + .allocated + .drain(..) + .map(|b| { + let id = Rc::as_ptr(&b.charge); + (b.size(), (used.contains(&id) && !retained.contains(&id)).then_some(b)) + }) + .collect(); + return true; + } + // Compare the actual liveness of this build, not just its allocation sizes. + let ok = !self.mismatch + && self.slots.len() == self.allocated.len() + && self.slots.iter().zip(&self.allocated).all(|((_, shared), actual)| { + shared.as_ref().is_none_or(|_| !retained.contains(&Rc::as_ptr(&actual.charge))) + }); + self.allocated.clear(); + ok + } +} + impl Gpu { pub fn buf(&self, data: &[f32]) -> Rc { // f16 storage @@ -83,7 +128,16 @@ impl Gpu { eprintln!("arena: alloc {size} <- new (free: {:?})", free.iter().map(|b| b.size()).collect::>()); } } - let b = self.create_tensor(size, Kind::Tensors); + let mut workspace = self.workspace.borrow_mut(); + let b = workspace + .as_mut() + .and_then(|w| w.reuse(size)) + .map(Rc::new) + .unwrap_or_else(|| self.create_tensor(size, Kind::Tensors)); + if let Some(w) = workspace.as_mut() { + // Clone the raw handle, not Rc, so intra-plan last-use checks are unchanged. + w.allocated.push((*b).clone()); + } if self.arena.borrow().is_some() { self.arena_ids.borrow_mut().insert(Rc::as_ptr(&b) as usize, Rc::downgrade(&b)); } diff --git a/crates/flyhigh-engine/src/gpu/device.rs b/crates/flyhigh-engine/src/gpu/device.rs index 507074a..76d580f 100644 --- a/crates/flyhigh-engine/src/gpu/device.rs +++ b/crates/flyhigh-engine/src/gpu/device.rs @@ -278,6 +278,7 @@ impl Gpu { ts_inside: caps.ts_inside, shader_compiler, arena: std::cell::RefCell::new(None), + workspace: std::cell::RefCell::new(None), arena_ids: std::cell::RefCell::new(HashMap::new()), scratch: std::cell::RefCell::new(Vec::new()), alloc_bytes: std::cell::Cell::new(0), diff --git a/crates/flyhigh-engine/src/gpu/memory.rs b/crates/flyhigh-engine/src/gpu/memory.rs index d29e38c..9eb650a 100644 --- a/crates/flyhigh-engine/src/gpu/memory.rs +++ b/crates/flyhigh-engine/src/gpu/memory.rs @@ -103,6 +103,7 @@ impl Drop for Charge { } /// An engine buffer. Dereferences to the underlying wgpu buffer for copies and bindings. +#[derive(Clone)] pub struct Buffer { raw: wgpu::Buffer, // Plan steps share this charge without changing the arena's Rc liveness checks. diff --git a/crates/flyhigh-engine/src/gpu/mod.rs b/crates/flyhigh-engine/src/gpu/mod.rs index 00d0034..f426a2c 100644 --- a/crates/flyhigh-engine/src/gpu/mod.rs +++ b/crates/flyhigh-engine/src/gpu/mod.rs @@ -37,6 +37,7 @@ pub struct Gpu { // buffer arena (Some while a plan is being built): tensors whose last reader has been built release their // buffer here and later tensors of the same plan reuse it — a static in-order plan makes this safe pub arena: std::cell::RefCell>>>, + pub(crate) workspace: std::cell::RefCell>, // buffers that came from `alloc` (the only ones `release` takes), by address; the Weak keeps the Rc allocation // reserved, so a dropped buffer's address cannot be reused by a buffer that never came from the arena pub arena_ids: std::cell::RefCell>>, diff --git a/crates/flyhigh-engine/src/net/build.rs b/crates/flyhigh-engine/src/net/build.rs index 1d3a62d..fe04eb0 100644 --- a/crates/flyhigh-engine/src/net/build.rs +++ b/crates/flyhigh-engine/src/net/build.rs @@ -1,6 +1,7 @@ //! Graph to plan: the build context (caches, liveness, pinning), `build`, `build_network` and the pair / mid split. use crate::gmhs; +use crate::gpu::alloc::Workspace; use crate::gpu::memory::Buffer; use crate::model::graph::count_uses; use crate::model::graph::count_uses_unrolled; @@ -9,7 +10,7 @@ use crate::{ RenderOpts, StaticParams, Step, Tensor, TuneTable, UnaryParams, }; use serde_json::Value; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::rc::Rc; // a buffer whose contents depend on the phase t (a `mul_t` scale uniform, the FiLM MLP output): `f(t)` gives the bytes @@ -26,6 +27,8 @@ type PackKey = (String, u32, u32); pub(crate) struct PlanResources { weights: Weights, pub(crate) render: Option>, + pub(crate) workspace: Option, + pub(crate) layout_mismatch: bool, } #[derive(Default)] @@ -561,6 +564,7 @@ pub(crate) fn build_network_with( // buffers, so stale ids let a buffer that never came from the arena enter the free list (which also made the plan's // buffer assignment depend on allocator luck) gpu.arena_ids.borrow_mut().clear(); + let workspace_was = gpu.workspace.replace(resources.workspace.take()); let mut env: HashMap = HashMap::new(); let mut cx = BuildCtx::new(gpu, blob, k, t, ihp, iwp); cx.weights = std::mem::take(&mut resources.weights); @@ -655,6 +659,14 @@ pub(crate) fn build_network_with( }), } } + let (pair_live, pair_used): (HashSet<_>, HashSet<_>) = if gpu.workspace.borrow().is_some() { + ( + env.values().map(|t| Rc::as_ptr(&t.buf.charge)).collect(), + plan.iter().flat_map(Step::allocations).map(Rc::as_ptr).collect(), + ) + } else { + Default::default() + }; #[cfg(test)] let (retained, pair_buffers) = if net.keep_maps && std::env::var_os("FH_CADENCE_DIAGNOSTICS").is_some() { let retained = env @@ -699,6 +711,7 @@ pub(crate) fn build_network_with( *gpu.arena.borrow_mut() = arena_was; gpu.arena_ids.borrow_mut().clear(); let r = env["render"].clone(); + resources.workspace = gpu.workspace.replace(workspace_was); resources.weights = cx.weights; return (r, env, cx.t_deps); } @@ -735,6 +748,15 @@ pub(crate) fn build_network_with( workgroups_2d(wp, hp, 1), )); } + resources.workspace = gpu.workspace.replace(workspace_was); + if let Some(workspace) = resources.workspace.as_mut() { + // Only data that crosses the pair/mid boundary or feeds the GMHS stats/composite must remain pair-local. + let mid: HashSet<_> = tail.iter().flat_map(Step::allocations).map(Rc::as_ptr).collect(); + let mut retained: HashSet<_> = pair_live.intersection(&mid).copied().collect(); + retained.extend(env.get("gm_maps").map(|m| Rc::as_ptr(&m.buf.charge))); + let used = mid.into_iter().chain(pair_used).collect(); + resources.layout_mismatch = !workspace.finish(&retained, &used); + } #[cfg(test)] if !retained.is_empty() { let weights = cx diff --git a/crates/flyhigh-engine/src/ops/step.rs b/crates/flyhigh-engine/src/ops/step.rs index a5f1244..446607e 100644 --- a/crates/flyhigh-engine/src/ops/step.rs +++ b/crates/flyhigh-engine/src/ops/step.rs @@ -8,16 +8,13 @@ pub enum Step { Compute { pipe: &'static str, bg: wgpu::BindGroup, groups: (u32, u32, u32), meta: Rc }, Copy { src: Rc, so: u64, dst: Rc, dof: u64, size: u64 }, } -#[cfg(test)] impl Step { pub(crate) fn allocations(&self) -> impl Iterator> { - match self { - Self::Compute { meta, .. } => { - meta._allocations.iter().chain(meta.params_buffer.iter().map(|p| &p.charge)).collect::>() - } - Self::Copy { src, dst, .. } => vec![&src.charge, &dst.charge], - } - .into_iter() + let (allocs, params, copies): (&[_], _, [_; 2]) = match self { + Self::Compute { meta, .. } => (&meta._allocations, meta.params_buffer.as_ref(), [None, None]), + Self::Copy { src, dst, .. } => (&[], None, [Some(&src.charge), Some(&dst.charge)]), + }; + allocs.iter().chain(params.map(|p| &p.charge)).chain(copies.into_iter().flatten()) } } pub type OpOutput = (Tensor, Vec); From 9e4cd12cd5cc7c823ad773cc7b1b0eca62b3c590 Mon Sep 17 00:00:00 2001 From: NimaJafariComp Date: Thu, 19 Nov 2026 16:02:46 -0600 Subject: [PATCH 09/14] Update the f16 cadence plan fixture for the shared render target --- .../tests/golden/video-720p-cadence.portable-f16.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/flyhigh-engine/tests/golden/video-720p-cadence.portable-f16.txt b/crates/flyhigh-engine/tests/golden/video-720p-cadence.portable-f16.txt index 266e7b9..8cd6d17 100644 --- a/crates/flyhigh-engine/tests/golden/video-720p-cadence.portable-f16.txt +++ b/crates/flyhigh-engine/tests/golden/video-720p-cadence.portable-f16.txt @@ -105,4 +105,4 @@ 28 tconv32 (1,203,3) [buf4976640 buf14336 buf8 buf2048 buf158760 params buf2008800 buf2048] 00000018 00000078 000000d8 00000078 000000d8 00000001 00000001 000000d8 000000e0 00000003 00000020 00006540 00000000 00000003 00000000 00000000 29 skreduce (76,1,1) [buf2008800 buf8 buf2048 buf158760 params buf2048] 00000003 00006540 00000003 00000000 30 unary (27,15,3) [buf158760 buf324000 params] 00000003 00000078 000000d8 00000002 00000000 00000000 00000000 3f800000 - 31 render (160,92,1) [buf5652480 buf5652480 buf4976640 buf4976640 buf324000 buf7464960 params] 000002e0 00000500 00000078 000000d8 00000000 00000004 3fbda12f 3fc44444 3f800000 00000001 00000000 00000000 + 31 render (160,92,1) [buf5652480 buf5652480 buf4976640 buf4976640 buf324000 buf5652480 params] 000002e0 00000500 00000078 000000d8 00000000 00000004 3fbda12f 3fc44444 3f800000 00000001 00000000 00000000 From 549fdd6a181d3f80cf87761ba47eb4e86069c181 Mon Sep 17 00:00:00 2001 From: NimaJafariComp Date: Thu, 19 Nov 2026 16:02:46 -0600 Subject: [PATCH 10/14] test: account for cadence scratch without a composite intermediate --- crates/flyhigh-engine/src/gen_tex_tests.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/crates/flyhigh-engine/src/gen_tex_tests.rs b/crates/flyhigh-engine/src/gen_tex_tests.rs index 7b0e830..d579a48 100644 --- a/crates/flyhigh-engine/src/gen_tex_tests.rs +++ b/crates/flyhigh-engine/src/gen_tex_tests.rs @@ -167,6 +167,13 @@ fn cadence_1080p_memory() { gen.add_output(&e.gpu); } let active = core.report().memory; + let scratch = gen.scratch.as_ref().unwrap(); + assert_eq!( + active.cadence_scratch.live_bytes, + [&scratch.bg_copy, &scratch.mask_a, &scratch.mask_b, &scratch.trust_a, &scratch.trust_b, &scratch.part] + .iter().map(|b| b.size()).sum::(), + "no full-size composite intermediate" + ); eprintln!("1080p cadence memory: {}", serde_json::to_string(&active).unwrap()); drop(gen); assert_eq!(core.report().memory.live_bytes, before.live_bytes); From cfc02c5d60f1b2987e079c2d6e652a7bab7247a3 Mon Sep 17 00:00:00 2001 From: NimaJafariComp Date: Thu, 19 Nov 2026 16:04:33 -0600 Subject: [PATCH 11/14] Composite cadence frames directly into the output texture --- crates/flyhigh-engine/src/gen_tex_tests.rs | 4 +- crates/flyhigh-engine/src/gmhs.rs | 54 ++++++++++++++-------- shaders/gm_composite.wgsl | 12 +++-- 3 files changed, 46 insertions(+), 24 deletions(-) diff --git a/crates/flyhigh-engine/src/gen_tex_tests.rs b/crates/flyhigh-engine/src/gen_tex_tests.rs index d579a48..6b61282 100644 --- a/crates/flyhigh-engine/src/gen_tex_tests.rs +++ b/crates/flyhigh-engine/src/gen_tex_tests.rs @@ -171,7 +171,9 @@ fn cadence_1080p_memory() { assert_eq!( active.cadence_scratch.live_bytes, [&scratch.bg_copy, &scratch.mask_a, &scratch.mask_b, &scratch.trust_a, &scratch.trust_b, &scratch.part] - .iter().map(|b| b.size()).sum::(), + .iter() + .map(|b| b.size()) + .sum::(), "no full-size composite intermediate" ); eprintln!("1080p cadence memory: {}", serde_json::to_string(&active).unwrap()); diff --git a/crates/flyhigh-engine/src/gmhs.rs b/crates/flyhigh-engine/src/gmhs.rs index 7453e2f..ec3f337 100644 --- a/crates/flyhigh-engine/src/gmhs.rs +++ b/crates/flyhigh-engine/src/gmhs.rs @@ -14,7 +14,8 @@ //! an element against the global motion, which classifies a pair as a jump / hold of an element animated on 2s and //! gives the mask for the re-timed composite (`pair_stats`, `composite_frame`). use crate::gpu::memory::Buffer; -use crate::{clone_step, workgroups_2d, Gpu, SessionExt, Step, Tensor}; +use crate::ops::step::meta; +use crate::{clone_step, workgroups_2d, Binding, Gpu, SessionExt, Step, Tensor}; use bytemuck::{Pod, Zeroable}; use std::cell::RefCell; use std::collections::HashMap; @@ -113,8 +114,8 @@ pub struct CompP { pub wc: u32, pub sx: f32, pub sy: f32, - pub _a: u32, - pub _b: u32, + pub w: u32, + pub h: u32, } /// cost-map grid: `DS` network px per cell (the decision is smoothed over ~60 px anyway; 2 keeps the stage ~0.2 ms) @@ -246,7 +247,6 @@ pub struct CadenceScratch { pub mask_b: Rc, pub trust_a: Rc, pub trust_b: Rc, - pub out: Tensor, pub part: Rc, steps: RefCell>>, } @@ -254,7 +254,6 @@ pub const STAT_WG: u32 = 32; const K_STATS: u8 = 0; const K_MASK: u8 = 1; const K_COMP: u8 = 2; -const K_OUT: u8 = 3; const K_TRUST: u8 = 4; /// Model cost (box-filtered luma mismatch, 0..1) above which the transition pair's render is a guess. Measured on the /// tunnel clip (a disoccluded arm), walk and fence: 0.03 keeps the real drawing there with 2 to 4 % stopped steps, @@ -268,15 +267,12 @@ impl CadenceScratch { let (m, _, _) = maps_of(sess)?; let r = &sess.render; let n = (r.c * r.h * r.w) as usize; - let out = - Tensor { buf: gpu.alloc_cadence((n * gpu.esize()) as u64), c: r.c, h: r.h, w: r.w, c0: 0, scale: 1.0 }; Some(CadenceScratch { bg_copy: gpu.alloc_cadence((n * gpu.esize()) as u64), mask_a: gpu.alloc_cadence(u64::from(m.h * m.w) * 4), mask_b: gpu.alloc_cadence(u64::from(m.h * m.w) * 4), trust_a: gpu.alloc_cadence(u64::from(m.h * m.w) * 4), trust_b: gpu.alloc_cadence(u64::from(m.h * m.w) * 4), - out, part: gpu.alloc_cadence(u64::from(STAT_WG * 4 * 4)), steps: RefCell::new(HashMap::new()), }) @@ -443,7 +439,7 @@ pub fn composite_frame( ), ] })); - st.extend(sc.cached((K_COMP, sid(elem), 0), || { + st.extend(sc.cached((K_COMP, Rc::as_ptr(&elem.render.buf) as usize, slot), || { let cp = CompP { hp: bg.render.h, wp: bg.render.w, @@ -451,18 +447,38 @@ pub fn composite_frame( wc: m.w, sx: iw as f32 / (bg.render.w as f32 * DS as f32), sy: ih as f32 / (bg.render.h as f32 * DS as f32), - _a: 0, - _b: 0, + w: bg.w, + h: bg.h, }; - vec![gpu.compute_step( - "gm_composite", - &[&sc.bg_copy, &elem.render.buf, &sc.mask_a], - bytemuck::bytes_of(&cp), - &sc.out.buf, - workgroups_2d(bg.render.w, bg.render.h, 1), - )] + let params = bytemuck::bytes_of(&cp); + let uniform = gpu.buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("fh_gm_composite_params"), + contents: params, + usage: wgpu::BufferUsages::UNIFORM, + }); + let inputs = [&*sc.bg_copy, &*elem.render.buf, &*sc.mask_a]; + let mut entries: Vec<_> = inputs + .iter() + .enumerate() + .map(|(i, b)| wgpu::BindGroupEntry { binding: i as u32, resource: b.as_entire_binding() }) + .collect(); + entries.push(wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(out_view) }); + entries.push(wgpu::BindGroupEntry { binding: 4, resource: uniform.as_entire_binding() }); + let pipe = "gm_composite"; + let bind_group = gpu.device.create_bind_group(&wgpu::BindGroupDescriptor { + label: None, + layout: &gpu.pipeline(pipe).get_bind_group_layout(0), + entries: &entries, + }); + let mut bindings: Vec<_> = inputs.iter().map(|b| Binding::Buffer(b.size())).collect(); + bindings.extend([Binding::Texture(bg.w, bg.h), Binding::Params]); + vec![Step::Compute { + pipe, + bg: bind_group, + groups: workgroups_2d(bg.w, bg.h, 1), + meta: meta(bindings, params, inputs.into_iter().chain([&uniform]), None), + }] })); - st.extend(sc.cached((K_OUT, slot, 0), || vec![gpu.tex_out_step(&sc.out, out_view, bg.w, bg.h, false)])); gpu.replay(&st); Ok(()) } diff --git a/shaders/gm_composite.wgsl b/shaders/gm_composite.wgsl index 8eac8c9..124d44f 100644 --- a/shaders/gm_composite.wgsl +++ b/shaders/gm_composite.wgsl @@ -2,11 +2,11 @@ enable f16; // Cadence composite: out = bg * (1 - m) + elem * m over the 3 image channels of two rendered frames ([3][hp][wp] f16), // with the element mask m (f32, cost grid hc x wc covering the network frame) sampled bilinearly at the full-frame // pixel's position in the network frame. -struct Par { hp: u32, wp: u32, hc: u32, wc: u32, sx: f32, sy: f32, _a: u32, _b: u32 }; // sx, sy: cost-grid cells per full-frame px +struct Par { hp: u32, wp: u32, hc: u32, wc: u32, sx: f32, sy: f32, w: u32, h: u32 }; // sx, sy: cost-grid cells per full-frame px @group(0) @binding(0) var bg: array; @group(0) @binding(1) var elem: array; @group(0) @binding(2) var mask: array; -@group(0) @binding(3) var outp: array; +@group(0) @binding(3) var dst: texture_storage_2d; @group(0) @binding(4) var pp: Par; fn clampi(v: i32, lo: i32, hi: i32) -> i32 { return max(lo, min(v, hi)); } @@ -14,7 +14,7 @@ fn clampi(v: i32, lo: i32, hi: i32) -> i32 { return max(lo, min(v, hi)); } @compute @workgroup_size(8, 8, 1) fn main(@builtin(global_invocation_id) gid: vec3) { let x = gid.x; let y = gid.y; - if (x >= pp.wp || y >= pp.hp) { return; } + if (x >= pp.w || y >= pp.h) { return; } let cx = (f32(x) + 0.5) * pp.sx - 0.5; let cy = (f32(y) + 0.5) * pp.sy - 0.5; let x0 = i32(floor(cx)); let y0 = i32(floor(cy)); let fx = cx - f32(x0); let fy = cy - f32(y0); let x0c = u32(clampi(x0, 0, i32(pp.wc) - 1)); let x1c = u32(clampi(x0 + 1, 0, i32(pp.wc) - 1)); @@ -23,8 +23,12 @@ fn main(@builtin(global_invocation_id) gid: vec3) { let bot = mask[y1c * pp.wc + x0c] * (1.0 - fx) + mask[y1c * pp.wc + x1c] * fx; let m = clamp(top * (1.0 - fy) + bot * fy, 0.0, 1.0); let plane = pp.hp * pp.wp; let i = y * pp.wp + x; + // Preserve the old planar buffer's precision rounding before RGBA8 quantization. + var bgr: vec3; for (var c: u32 = 0u; c < 3u; c = c + 1u) { let o = c * plane + i; - outp[o] = f16(f32(bg[o]) * (1.0 - m) + f32(elem[o]) * m); + bgr[c] = f16(f32(bg[o]) * (1.0 - m) + f32(elem[o]) * m); } + let rgba = vec4(clamp(vec3(bgr.zyx), vec3(0.0), vec3(1.0)), 1.0); + textureStore(dst, vec2(i32(x), i32(y)), rgba); } From efe035ca87c945c54cc97ec3f0b82d0d4bc22f79 Mon Sep 17 00:00:00 2001 From: NimaJafariComp Date: Thu, 19 Nov 2026 16:05:07 -0600 Subject: [PATCH 12/14] test: reproduce out-of-order and post-seek cadence statistics --- crates/flyhigh-engine/src/gen_tex_tests.rs | 48 ++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/crates/flyhigh-engine/src/gen_tex_tests.rs b/crates/flyhigh-engine/src/gen_tex_tests.rs index 6b61282..082d721 100644 --- a/crates/flyhigh-engine/src/gen_tex_tests.rs +++ b/crates/flyhigh-engine/src/gen_tex_tests.rs @@ -236,3 +236,51 @@ fn cadence_shares_transient_inference_buffers_but_keeps_pair_data() { assert!(!std::rc::Rc::ptr_eq(&a.a.buf.charge, &b.a.buf.charge)); assert!(!std::rc::Rc::ptr_eq(&a.b.buf.charge, &b.b.buf.charge)); } + +#[test] +#[ignore = "requires a GPU"] +fn cadence_readbacks_follow_their_pair_and_reset_generation() { + let e = engine(); + let gpu = &e.gpu; + let mut generator = anime(&e, W, H); + for _ in 0..4 { + generator.add_input(gpu); + } + let cel_a = cel(0, 0, false); + let cut = cel(0, 0, true); + let push = |g: &mut GenTex, slot, data| { + write(gpu, g, slot, data); + g.push_slot(gpu, slot).unwrap(); + }; + let poll = || gpu.device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None }).unwrap(); + + push(&mut generator, 0, &cel_a); + push(&mut generator, 1, &cut); + let older_cut = generator.take_stats().unwrap(); + push(&mut generator, 2, &cut); + generator.resolve_stats(gpu).unwrap(); + poll(); + generator.set_stats(pollster::block_on(older_cut.finish()).unwrap()); + assert!(generator.stats()[1].cut && !generator.stats()[2].cut, "a late cut belongs to its older interval"); + + for reset in [true, false] { + generator.reset_history(); + push(&mut generator, 0, &cel_a); + push(&mut generator, 1, &cut); + let discarded_cut = generator.take_stats().unwrap(); + if reset { + generator.reset_history(); + push(&mut generator, 0, &cut); + push(&mut generator, 1, &cut); + } else { + for i in 0..=HIST { + push(&mut generator, (i + 2) % 4, &cut); + generator.resolve_stats(gpu).unwrap(); + } + } + generator.resolve_stats(gpu).unwrap(); + poll(); + generator.set_stats(pollster::block_on(discarded_cut.finish()).unwrap()); + assert!(generator.stats().iter().all(|s| !s.cut), "seek and evicted intervals must discard stale cuts"); + } +} From b26c0d9d8c2fc4930114560c09e5f6e36acf91b3 Mon Sep 17 00:00:00 2001 From: NimaJafariComp Date: Thu, 19 Nov 2026 16:10:13 -0600 Subject: [PATCH 13/14] Assert memory lifecycle without assuming cadence costs more than video --- crates/flyhigh-engine/tests/stream.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/flyhigh-engine/tests/stream.rs b/crates/flyhigh-engine/tests/stream.rs index 3fb63b8..c243671 100644 --- a/crates/flyhigh-engine/tests/stream.rs +++ b/crates/flyhigh-engine/tests/stream.rs @@ -82,7 +82,7 @@ fn memory_returns_to_baseline_after_stream_drop() { anime.warm_up(&e.gpu).unwrap(); let active = core.report().memory; assert!(active.cadence_scratch.live_bytes > 0); - assert!(active.live_bytes > video_mem.live_bytes); + assert_eq!(active.frame_textures.live_bytes, video_mem.frame_textures.live_bytes); anime.reset(); assert_eq!(core.report().memory.live_bytes, active.live_bytes); anime.add_input_texture(e.gpu.input_texture(W, H)).unwrap(); From 58451dd8404bae1935ea61b50ba5377264ebcb2d Mon Sep 17 00:00:00 2001 From: NimaJafariComp Date: Thu, 19 Nov 2026 16:10:13 -0600 Subject: [PATCH 14/14] Apply asynchronous cadence statistics only to their original interval --- crates/flyhigh-engine/src/gen_tex.rs | 56 ++++++++++++++++++---- crates/flyhigh-engine/src/gen_tex_tests.rs | 7 ++- crates/flyhigh-engine/src/stream/mod.rs | 7 ++- crates/flyhigh-web/src/core.rs | 10 ++-- 4 files changed, 60 insertions(+), 20 deletions(-) diff --git a/crates/flyhigh-engine/src/gen_tex.rs b/crates/flyhigh-engine/src/gen_tex.rs index e0378a7..fc635a4 100644 --- a/crates/flyhigh-engine/src/gen_tex.rs +++ b/crates/flyhigh-engine/src/gen_tex.rs @@ -8,8 +8,7 @@ //! slot of the interval is then synthesised too (`generate(0.0, out)` returns true) and the host must present that //! output instead of its source frame. //! -//! Statistics come back through an async readback (`StatsRun`): native hosts block on it inside `push_slot`, the -//! browser host awaits the promise of `fh_vid_stats` before the first `generate` of the interval (the lookahead hides it). +//! Statistics come back through a tagged async readback. Hosts resolve it before the interval's first `generate`. use crate::gmhs::{CadenceScratch, PairStats, StatsRun}; use crate::gpu::memory::Charge; use crate::net::build::PlanResources; @@ -17,6 +16,7 @@ use crate::{gmhs, Blob, Gpu, NetOpts, SessionExt, Step, TimedRun}; use anyhow::{Context, Result}; use serde_json::Value; use std::collections::VecDeque; +use std::rc::Rc; #[cfg(all(test, not(target_arch = "wasm32")))] #[path = "gen_tex_tests.rs"] @@ -111,11 +111,35 @@ pub struct GenTex { scratch: Option, slots: Vec, // last pushed input slots, newest last (<= 3) n_pushed: u64, - pending: Option, // statistics of the newest pair, not yet read back + pending: Option, + generation: Rc<()>, hist: VecDeque, // per-pair statistics, oldest first; back = the "next" pair (lookahead) half_done: bool, // linear_t: the t = 0.5 maps of the current pair are computed } +struct PairKey { + generation: Rc<()>, + sequence: u64, +} + +/// In-flight readback for one cadence pair. Finish it before passing it back to the stream. +pub struct PendingPairStats { + key: PairKey, + run: StatsRun, +} + +/// Completed statistics bound to their original stream generation and pair. +pub struct FinishedPairStats { + key: PairKey, + stats: PairStats, +} + +impl PendingPairStats { + pub async fn finish(self) -> Result { + Ok(FinishedPairStats { key: self.key, stats: self.run.finish().await? }) + } +} + /// What the host can do after a push. #[derive(Clone, Copy, Debug, Default)] pub struct PushInfo { @@ -295,6 +319,7 @@ impl GenTex { slots: Vec::new(), n_pushed: 0, pending: None, + generation: Rc::new(()), hist: VecDeque::new(), half_done: false, }) @@ -351,6 +376,7 @@ impl GenTex { self.n_pushed = 0; self.stats = [PairStats::default(); 3]; self.pending = None; + self.generation = Rc::new(()); self.hist.clear(); } pub fn stats(&self) -> [PairStats; 3] { @@ -402,7 +428,9 @@ impl GenTex { self.hist.pop_front(); } if let Some(sc) = &self.scratch { - self.pending = Some(gmhs::pair_stats_begin(gpu, &self.sess[sn], sc)?); + let key = PairKey { generation: self.generation.clone(), sequence: self.n_pushed }; + self.pending = + Some(PendingPairStats { key, run: gmhs::pair_stats_begin(gpu, &self.sess[sn], sc)? }); } let ready = self.slots.len() >= 3; Ok((PushInfo { ready, base_slot: if ready { self.slots[0] } else { slot }, real_replaced: false }, run)) @@ -410,16 +438,26 @@ impl GenTex { } } /// Take the pending statistics readback (Video + cadence); the caller awaits `finish` and passes the result to `set_stats`. - pub fn take_stats(&mut self) -> Option { + pub fn take_stats(&mut self) -> Option { self.pending.take() } pub fn has_pending_stats(&self) -> bool { self.pending.is_some() } - pub fn set_stats(&mut self, st: PairStats) { - self.stats[2] = st; - if let Some(b) = self.hist.back_mut() { - *b = st; + /// Ignore completions from another generation or a pair that has left history. + pub fn set_stats(&mut self, st: FinishedPairStats) { + if !Rc::ptr_eq(&st.key.generation, &self.generation) { + return; + } + let Some(age) = self.n_pushed.checked_sub(st.key.sequence) else { return }; + if age >= self.hist.len() as u64 { + return; + } + let i = self.hist.len() - 1 - age as usize; + self.hist[i] = st.stats; + if age < self.stats.len() as u64 { + let i = self.stats.len() - 1 - age as usize; + self.stats[i] = st.stats; } } /// Native convenience: block for the pending statistics. diff --git a/crates/flyhigh-engine/src/gen_tex_tests.rs b/crates/flyhigh-engine/src/gen_tex_tests.rs index 082d721..ed15dda 100644 --- a/crates/flyhigh-engine/src/gen_tex_tests.rs +++ b/crates/flyhigh-engine/src/gen_tex_tests.rs @@ -25,7 +25,7 @@ fn cel(draw: u32, pan: u32, cut: bool) -> Vec { for x in 0..W { let bx = x + pan; let wall = (bx / 17 + y / 23) % 3; - let ink = if (bx % 17 == 0) || (y % 23 == 0) { 12 } else { 52 + wall as u8 * 23 }; + let ink = if bx.is_multiple_of(17) || y.is_multiple_of(23) { 12 } else { 52 + wall as u8 * 23 }; let cx = 75 + ((draw % 4) * 31) as i32; let dx = (x as i32 - cx).abs(); let px = if cut { @@ -217,7 +217,9 @@ fn video_plans_share_immutable_convolution_weights() { #[test] #[ignore = "requires a GPU"] fn cadence_shares_transient_inference_buffers_but_keeps_pair_data() { - let gen = anime(&engine(), W, H); + let e = engine(); + let gen = anime(&e, W, H); + let other = anime(&e, W, H); let (a, b) = (&gen.sess[0], &gen.sess[1]); let temps = |s: &SessionExt| { s.plan_mid @@ -230,6 +232,7 @@ fn cadence_shares_transient_inference_buffers_but_keeps_pair_data() { if std::env::var_os("FH_NO_ARENA").is_none() { assert!(temps(a).intersection(&temps(b)).count() > 5, "mid kernels reuse one workspace"); } + assert!(temps(a).is_disjoint(&temps(&other.sess[0])), "independent streams never alias workspace"); for field in ["gm_maps", "static:state", "mask"] { assert!(!std::rc::Rc::ptr_eq(&a.env[field].buf.charge, &b.env[field].buf.charge)); } diff --git a/crates/flyhigh-engine/src/stream/mod.rs b/crates/flyhigh-engine/src/stream/mod.rs index 0587ef9..b870a1a 100644 --- a/crates/flyhigh-engine/src/stream/mod.rs +++ b/crates/flyhigh-engine/src/stream/mod.rs @@ -9,8 +9,7 @@ pub mod classify; pub use classify::{Classification, Classifier, Thresholds}; -use crate::gen_tex::{GenTex, Retime, TexMode, TexOptions}; -use crate::gmhs::{PairStats, StatsRun}; +use crate::gen_tex::{FinishedPairStats, GenTex, PendingPairStats, Retime, TexMode, TexOptions}; use crate::gpu::readback::Readback; use crate::options::Options; use crate::warp::{Calibration, CameraWarp, WarpOptions}; @@ -405,11 +404,11 @@ impl Stream { } /// Video + cadence: the pending statistics readback; await `finish` and pass the result to `set_stats`. - pub fn take_stats(&mut self) -> Option { + pub fn take_stats(&mut self) -> Option { self.gen.take_stats() } - pub fn set_stats(&mut self, st: PairStats) { + pub fn set_stats(&mut self, st: FinishedPairStats) { self.gen.set_stats(st); } diff --git a/crates/flyhigh-web/src/core.rs b/crates/flyhigh-web/src/core.rs index f6c8ef8..9b231be 100644 --- a/crates/flyhigh-web/src/core.rs +++ b/crates/flyhigh-web/src/core.rs @@ -611,14 +611,14 @@ impl FhStream { } /// Video + cadence: resolves when the pending pair statistics are in (await it after a push with `statsPending`, - /// before the interval's first `generate`). + /// before the interval's first `generate`). Completions after reset or history eviction are discarded. pub fn stats(&self) -> js_sys::Promise { - let run = self.inner.borrow_mut().take_stats(); + let pending = self.inner.borrow_mut().take_stats(); let inner = self.inner.clone(); future_to_promise(async move { - if let Some(run) = run { - let s = run.finish().await.map_err(err)?; - inner.borrow_mut().set_stats(s); + if let Some(readback) = pending { + let result = readback.finish().await.map_err(err)?; + inner.borrow_mut().set_stats(result); } Ok(JsValue::UNDEFINED) })