Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions crates/flyhigh-engine/src/engine.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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(),
}
}
}
5 changes: 5 additions & 0 deletions crates/flyhigh-engine/src/gen_tex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -99,6 +100,7 @@ pub struct GenTex {
pub sess: Vec<SessionExt>,
pub ins: Vec<(wgpu::Texture, wgpu::TextureView)>,
pub outs: Vec<(wgpu::Texture, wgpu::TextureView)>,
owned_slots: Vec<Charge>,
order: [usize; 3],
stats: [PairStats; 3],
scratch: Option<CadenceScratch>,
Expand Down Expand Up @@ -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,
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
32 changes: 17 additions & 15 deletions crates/flyhigh-engine/src/gmhs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<wgpu::Buffer>,
pub mask_a: Rc<wgpu::Buffer>,
pub mask_b: Rc<wgpu::Buffer>,
pub trust_a: Rc<wgpu::Buffer>,
pub trust_b: Rc<wgpu::Buffer>,
pub bg_copy: Rc<Buffer>,
pub mask_a: Rc<Buffer>,
pub mask_b: Rc<Buffer>,
pub trust_a: Rc<Buffer>,
pub trust_b: Rc<Buffer>,
pub out: Tensor,
pub part: Rc<wgpu::Buffer>,
pub part: Rc<Buffer>,
steps: RefCell<HashMap<(u8, usize, usize), Vec<Step>>>,
}
pub const STAT_WG: u32 = 32;
Expand All @@ -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()),
})
}
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
49 changes: 32 additions & 17 deletions crates/flyhigh-engine/src/gpu/alloc.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -10,33 +11,33 @@ pub(crate) fn arena_trace() -> bool {
}

impl Gpu {
pub fn buf(&self, data: &[f32]) -> Rc<wgpu::Buffer> {
pub fn buf(&self, data: &[f32]) -> Rc<Buffer> {
// f16 storage
let h: Vec<u16> =
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<u64> {
let mut v: Vec<u64> = self.live.borrow().iter().filter_map(|w| w.upgrade()).map(|b| b.size()).collect();
let mut v: Vec<u64> = 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<wgpu::Buffer> {
pub fn alloc(&self, n: usize) -> Rc<Buffer> {
self.alloc_raw((n * self.esize()) as u64)
} // n tensor elements
/// bytes per tensor element: 2 (f16) or 4 (the f32 path)
Expand All @@ -47,12 +48,12 @@ impl Gpu {
2
}
}
pub fn alloc_f32(&self, n: usize) -> Rc<wgpu::Buffer> {
pub fn alloc_f32(&self, n: usize) -> Rc<Buffer> {
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<wgpu::Buffer>) {
pub fn note_scratch(&self, b: &Rc<Buffer>) {
if self.arena.borrow().is_some() {
self.scratch.borrow_mut().push(b.clone());
}
Expand All @@ -63,7 +64,7 @@ impl Gpu {
self.release(b);
}
}
pub fn alloc_raw(&self, size: u64) -> Rc<wgpu::Buffer> {
pub fn alloc_raw(&self, size: u64) -> Rc<Buffer> {
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(|| {
Expand All @@ -82,22 +83,36 @@ impl Gpu {
eprintln!("arena: alloc {size} <- new (free: {:?})", free.iter().map(|b| b.size()).collect::<Vec<_>>());
}
}
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<Buffer> {
self.create_tensor(size, Kind::CadenceScratch)
}

fn create_tensor(&self, size: u64, kind: Kind) -> Rc<Buffer> {
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<wgpu::Buffer>) {
pub fn release(&self, b: Rc<Buffer>) {
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)),
Expand Down
16 changes: 9 additions & 7 deletions crates/flyhigh-engine/src/gpu/device.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -218,23 +219,24 @@ 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<u8> = if caps.f32_mode {
bytemuck::cast_slice(&vec![1f32; 1024]).to_vec()
} 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)
Expand Down Expand Up @@ -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,
Expand All @@ -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),
}
Expand Down
Loading
Loading