diff --git a/crates/flyhigh-engine/src/gen_tex.rs b/crates/flyhigh-engine/src/gen_tex.rs index 767f5f5..dcc6385 100644 --- a/crates/flyhigh-engine/src/gen_tex.rs +++ b/crates/flyhigh-engine/src/gen_tex.rs @@ -8,14 +8,19 @@ //! 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; 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"] +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. @@ -106,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 { @@ -234,8 +263,44 @@ impl GenTex { cascade_iters: crate::options::cascade_for(opts.precise).1, }; let mut sess = Vec::new(); - for _ in 0..n_sess { - sess.push(SessionExt::new(gpu, blob, ops, opts.w, opts.h, opts.k, opts.iw, opts.ih, tune, &net)); + 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)); + } + 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")?) @@ -254,6 +319,7 @@ impl GenTex { slots: Vec::new(), n_pushed: 0, pending: None, + generation: Rc::new(()), hist: VecDeque::new(), half_done: false, }) @@ -310,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] { @@ -361,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)) @@ -369,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 new file mode 100644 index 0000000..ed15dda --- /dev/null +++ b/crates/flyhigh-engine/src/gen_tex_tests.rs @@ -0,0 +1,289 @@ +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.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 { + [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); + assert_render_shared(&gen); + for _ in 0..4 { + gen.add_input(&e.gpu); + } + for _ in 0..2 { + 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); +} + +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() { + 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]))); +} + +#[test] +#[ignore = "requires a GPU"] +fn cadence_shares_transient_inference_buffers_but_keeps_pair_data() { + 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 + .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"); + } + 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)); + } + 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"); + } +} 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/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 d194e63..b3398ae 100644 --- a/crates/flyhigh-engine/src/gpu/device.rs +++ b/crates/flyhigh-engine/src/gpu/device.rs @@ -279,6 +279,7 @@ impl Gpu { timing: Default::default(), 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 8a51ffd..9eb650a 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; @@ -96,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 9b2a89d..cfc705c 100644 --- a/crates/flyhigh-engine/src/gpu/mod.rs +++ b/crates/flyhigh-engine/src/gpu/mod.rs @@ -38,6 +38,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 3788158..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 @@ -20,12 +21,28 @@ pub fn set_t(gpu: &Gpu, deps: &[PhaseDep], t: f32) { } } +type PackKey = (String, u32, u32); + +#[derive(Default)] +pub(crate) struct PlanResources { + weights: Weights, + pub(crate) render: Option>, + pub(crate) workspace: Option, + pub(crate) layout_mismatch: bool, +} + +#[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, + render_target: Option>, pub k: u32, pub t: f32, pub hs: u32, @@ -49,9 +66,8 @@ impl<'a> BuildCtx<'a> { BuildCtx { gpu, blob, - wcache: HashMap::new(), - bcache: HashMap::new(), - bcache4: HashMap::new(), + weights: Weights::default(), + render_target: None, k, t, hs, @@ -99,27 +115,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 } } @@ -346,7 +364,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, @@ -355,6 +373,7 @@ pub fn build(ops: &[Value], env: &mut HashMap, plan: &mut Vec { @@ -505,6 +524,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); @@ -525,8 +564,11 @@ pub fn build_network_ex( // 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); + cx.render_target = resources.render.clone(); cx.cubic = net.cubic; cx.render_flags = net.render_flags(); cx.pin(a); @@ -617,6 +659,28 @@ pub fn build_network_ex( }), } } + 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 + .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() { @@ -647,7 +711,9 @@ 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.workspace = gpu.workspace.replace(workspace_was); + 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 @@ -655,7 +721,7 @@ pub fn build_network_ex( 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, @@ -664,6 +730,7 @@ pub fn build_network_ex( 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); @@ -681,9 +748,45 @@ pub fn build_network_ex( 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 + .weights + .raw + .values() + .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; + 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(); 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 e494609..d5d727f 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 { 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, diff --git a/crates/flyhigh-engine/src/ops/step.rs b/crates/flyhigh-engine/src/ops/step.rs index 65a8586..446607e 100644 --- a/crates/flyhigh-engine/src/ops/step.rs +++ b/crates/flyhigh-engine/src/ops/step.rs @@ -8,6 +8,15 @@ 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 }, } +impl Step { + pub(crate) fn allocations(&self) -> impl Iterator> { + 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); /// What a compute step binds and its parameter bytes: a bind group is opaque once built, and the golden-plan tests 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-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 diff --git a/crates/flyhigh-engine/tests/stream.rs b/crates/flyhigh-engine/tests/stream.rs index 4df2534..9cf9538 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(); diff --git a/crates/flyhigh-web/src/core.rs b/crates/flyhigh-web/src/core.rs index d10f533..6a2aa8f 100644 --- a/crates/flyhigh-web/src/core.rs +++ b/crates/flyhigh-web/src/core.rs @@ -632,14 +632,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) }) 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); }