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 b92efa1..767f5f5 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 74d219c..d194e63 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, @@ -279,7 +282,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 0da6fbd..9b2a89d 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,28 +21,28 @@ 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(crate) timing: std::cell::RefCell, 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 8101cf6..e494609 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) }); @@ -263,12 +267,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 @@ -299,7 +305,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, @@ -320,6 +326,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, ), } })) @@ -354,9 +362,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, @@ -387,6 +395,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 e524f9b..d0f7ee7 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/crates/flyhigh-engine/tests/stream.rs b/crates/flyhigh-engine/tests/stream.rs index be7f087..4df2534 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]; 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 c439a28..1be0dec 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 5de520f..5c336f8 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