M13.13: gpu texture pool, Auto per-comp backend choice, warp-family GPU ports
- gpu: pooled working textures (released once every encoder that could read them is submitted), shared zero images, reused readback staging buffers, direct readback into Image; NaN-poisoned scratch images under test and NaN-aware diffs; validation errors panic under test - render: AutoPick (per comp / scale / path EWMA of CPU vs GPU frame times, warm-up and periodic re-probe) behind Backend::Auto; viewer uses it too; cached adjustment footprints (uploaded once) - gpu fx_warp: Warp, Bezier Warp, CC Bend It, CC Page Turn, Smear, Reshape, Color Emboss, Cartoon; sliding-histogram median for large radii; CC Power Pin perspective < 100 - cli: bench --gpu reports Auto and per-frame upload / readback MB Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
f5a136e346
commit
9ff0e5aa3c
@@ -0,0 +1,144 @@
|
||||
//! [`Backend::Auto`](crate::Backend::Auto)'s per-comp choice between the CPU and the GPU
|
||||
//! compositor, from measured frame times.
|
||||
//!
|
||||
//! A light comp (a couple of small layers) composites faster on the CPU, which only touches
|
||||
//! the layers' bounds, than on the GPU, which works on whole frames and reads the result back;
|
||||
//! heavy comps (many layers, 3D, GPU effects) are faster on the GPU. Neither a layer count nor
|
||||
//! a pixel count predicts the crossover across machines, so Auto measures: per comp, output
|
||||
//! scale and path (readback / viewer display), it keeps an exponentially weighted average of
|
||||
//! the CPU and GPU frame times and renders on the faster one. Each side is warmed up first
|
||||
//! (its first frame, with layer cache misses and texture uploads, is not counted; the fastest of
|
||||
//! the next ones starts the average), and the slower side is re-measured every
|
||||
//! [`AutoPick::REPROBE`] frames so the choice follows the comp as it changes.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use effectcraft_project::ItemId;
|
||||
|
||||
/// Which frames share timing history: one comp at one output scale on one path.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct AutoKey {
|
||||
pub comp: ItemId,
|
||||
/// `RenderOpts::scale` bits.
|
||||
pub scale: u64,
|
||||
/// The viewer's display path (GPU frames stay on the device) rather than a readback.
|
||||
pub display: bool,
|
||||
}
|
||||
|
||||
impl AutoKey {
|
||||
pub fn new(comp: ItemId, scale: f64, display: bool) -> AutoKey {
|
||||
AutoKey { comp, scale: scale.to_bits(), display }
|
||||
}
|
||||
}
|
||||
|
||||
/// Timing history of one [`AutoKey`].
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct AutoStats {
|
||||
/// Averaged ms/frame (`None` until a counted sample).
|
||||
pub cpu_ms: Option<f64>,
|
||||
pub gpu_ms: Option<f64>,
|
||||
/// Frames measured on each side (the first is the uncounted warm-up).
|
||||
pub cpu_frames: u32,
|
||||
pub gpu_frames: u32,
|
||||
/// Frames since the side not chosen was last measured.
|
||||
pub since_probe: u32,
|
||||
/// The GPU declined the last frame it was asked for (the CPU rendered it).
|
||||
pub declined: bool,
|
||||
}
|
||||
|
||||
/// Per-comp CPU / GPU timing history for [`Backend::Auto`](crate::Backend::Auto) (held by the
|
||||
/// accelerator, see [`Accelerator::auto_pick`](crate::Accelerator::auto_pick)).
|
||||
#[derive(Default)]
|
||||
pub struct AutoPick {
|
||||
stats: Mutex<HashMap<AutoKey, AutoStats>>,
|
||||
}
|
||||
|
||||
impl AutoPick {
|
||||
/// Frames measured on each side before choosing (the first is not counted).
|
||||
pub const WARMUP: u32 = 3;
|
||||
/// Weight of a new sample in the running average (slower / faster than the average).
|
||||
pub const ALPHA: f64 = 0.3;
|
||||
pub const ALPHA_DOWN: f64 = 0.5;
|
||||
/// Re-measure the side not chosen after this many frames.
|
||||
pub const REPROBE: u32 = 48;
|
||||
/// The CPU wins only when clearly faster (ties and noise stay on the GPU).
|
||||
pub const MARGIN: f64 = 0.85;
|
||||
/// Keys remembered before the history is reset.
|
||||
const MAX_KEYS: usize = 1024;
|
||||
|
||||
/// Render the frame for `key` on the GPU?
|
||||
pub fn choose(&self, key: AutoKey) -> bool {
|
||||
let Ok(mut m) = self.stats.lock() else { return true };
|
||||
if m.len() > Self::MAX_KEYS && !m.contains_key(&key) {
|
||||
m.clear();
|
||||
}
|
||||
let s = m.entry(key).or_default();
|
||||
// Warm up both sides, alternating, GPU first.
|
||||
let gpu_warm = s.declined || s.gpu_frames >= Self::WARMUP;
|
||||
if !gpu_warm && s.gpu_frames <= s.cpu_frames {
|
||||
return true;
|
||||
}
|
||||
if s.cpu_frames < Self::WARMUP {
|
||||
return false;
|
||||
}
|
||||
let gpu_faster = match (s.gpu_ms, s.cpu_ms) {
|
||||
(Some(g), Some(c)) => c >= g * Self::MARGIN,
|
||||
(g, _) => g.is_some(),
|
||||
};
|
||||
// Periodically re-measure the slower side.
|
||||
if s.since_probe >= Self::REPROBE {
|
||||
s.since_probe = 0;
|
||||
return !gpu_faster;
|
||||
}
|
||||
s.since_probe += 1;
|
||||
gpu_faster
|
||||
}
|
||||
|
||||
/// A frame for `key` took `ms` on the GPU (`gpu`) or the CPU.
|
||||
///
|
||||
/// The warm-up keeps the fastest of its counted frames; after that the average follows
|
||||
/// improvements quickly and slow-downs gradually, and a single frame counts at most twice
|
||||
/// the average (a stall of the machine does not flip the choice for a whole re-probe
|
||||
/// period).
|
||||
pub fn record(&self, key: AutoKey, gpu: bool, ms: f64) {
|
||||
let Ok(mut m) = self.stats.lock() else { return };
|
||||
let s = m.entry(key).or_default();
|
||||
let (avg, frames) = if gpu { (&mut s.gpu_ms, &mut s.gpu_frames) } else { (&mut s.cpu_ms, &mut s.cpu_frames) };
|
||||
*frames = frames.saturating_add(1);
|
||||
if gpu {
|
||||
s.declined = false;
|
||||
}
|
||||
if *frames < 2 {
|
||||
return;
|
||||
}
|
||||
*avg = Some(match *avg {
|
||||
None => ms,
|
||||
Some(a) if *frames <= Self::WARMUP => a.min(ms),
|
||||
Some(a) if ms < a => a + (ms - a) * Self::ALPHA_DOWN,
|
||||
Some(a) => a + (ms.min(2.0 * a) - a) * Self::ALPHA,
|
||||
});
|
||||
}
|
||||
|
||||
/// The GPU did not handle a frame for `key` (it rendered on the CPU instead).
|
||||
pub fn declined(&self, key: AutoKey) {
|
||||
if let Ok(mut m) = self.stats.lock() {
|
||||
let s = m.entry(key).or_default();
|
||||
s.declined = true;
|
||||
s.gpu_ms = None;
|
||||
s.since_probe = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// The history of `key`.
|
||||
pub fn stats(&self, key: AutoKey) -> Option<AutoStats> {
|
||||
self.stats.lock().ok()?.get(&key).copied()
|
||||
}
|
||||
|
||||
/// Forget all history (settings that change both paths' costs).
|
||||
pub fn reset(&self) {
|
||||
if let Ok(mut m) = self.stats.lock() {
|
||||
m.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -326,10 +326,20 @@ fn has_expression(g: &PropGroup) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// Cache key for an adjustment layer's footprint (its source through its masks, see
|
||||
/// `Renderer::adjustment_footprint`): the GPU compositor then uploads it once, not every frame.
|
||||
pub fn footprint_key(ctx: &EvalCtx, layer: &Layer, scale: f64, draft: bool) -> Option<u64> {
|
||||
Some(derive(key_any(ctx, layer, scale, draft, false)?, 0xf007_9417))
|
||||
}
|
||||
|
||||
fn key_with(ctx: &EvalCtx, layer: &Layer, scale: f64, draft: bool, footage: bool) -> Option<u64> {
|
||||
if layer.switches.adjustment {
|
||||
return None;
|
||||
}
|
||||
key_any(ctx, layer, scale, draft, footage)
|
||||
}
|
||||
|
||||
fn key_any(ctx: &EvalCtx, layer: &Layer, scale: f64, draft: bool, footage: bool) -> Option<u64> {
|
||||
let mut h = KeyHasher(0xcbf2_9ce4_8422_2325);
|
||||
match &layer.source {
|
||||
LayerSource::Solid { item } => {
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
//! Adjustment layers run their effects on everything below, limited by their own bounds/masks.
|
||||
|
||||
pub mod audio;
|
||||
pub mod auto;
|
||||
pub mod cache;
|
||||
pub mod color;
|
||||
pub mod disk_cache;
|
||||
@@ -20,6 +21,7 @@ pub mod three_d;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
pub use auto::{AutoKey, AutoPick};
|
||||
pub use cache::{CacheStats, LayerCache};
|
||||
use effectcraft_color::BlendMode;
|
||||
use effectcraft_effects::{Buf, EffectCtx, EffectEnv, EffectHost, LayerPixels, Params};
|
||||
@@ -283,6 +285,11 @@ pub trait Accelerator: Send + Sync {
|
||||
fn particles(&self) -> Option<&dyn effectcraft_effects::psim::ParticleSim> {
|
||||
None
|
||||
}
|
||||
/// Timing history [`Backend::Auto`] uses to send each comp's top-level frames to the
|
||||
/// faster compositor. `None` = Auto always tries the accelerator first.
|
||||
fn auto_pick(&self) -> Option<&AutoPick> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Where an effect stack runs (see [`Renderer::run_effects_on`]): a CPU buffer, or an image
|
||||
@@ -627,16 +634,43 @@ impl<'a> Renderer<'a> {
|
||||
/// Render a composition at comp time `t` (transparent background, comp size × scale).
|
||||
/// Top-level frames go to the GPU when [`Self::active_accel`] is set and handles them.
|
||||
pub fn comp_frame(&self, comp_id: ItemId, t: Tick) -> Image {
|
||||
// Classic 3D runs composite on the GPU too (M12.7), so Auto sends 3D comps there as well.
|
||||
// Classic 3D runs composite on the GPU too (M12.7), so Auto sends 3D comps there as well;
|
||||
// Auto renders each comp on whichever compositor measured faster ([`AutoPick`]).
|
||||
if self.depth == 0
|
||||
&& let Some(a) = self.active_accel()
|
||||
&& let Some(img) = a.comp_frame(self, comp_id, t)
|
||||
{
|
||||
let auto = self.frame_auto(a, comp_id, false);
|
||||
if auto.is_none_or(|(p, key)| p.choose(key)) {
|
||||
let t0 = web_time::Instant::now();
|
||||
if let Some(img) = a.comp_frame(self, comp_id, t) {
|
||||
if let Some((p, key)) = auto {
|
||||
p.record(key, true, t0.elapsed().as_secs_f64() * 1e3);
|
||||
}
|
||||
return img;
|
||||
}
|
||||
if let Some((p, key)) = auto {
|
||||
p.declined(key);
|
||||
}
|
||||
}
|
||||
let t0 = web_time::Instant::now();
|
||||
let img = self.comp_frame_cpu(comp_id, t);
|
||||
if let Some((p, key)) = auto {
|
||||
p.record(key, false, t0.elapsed().as_secs_f64() * 1e3);
|
||||
}
|
||||
return img;
|
||||
}
|
||||
self.comp_frame_cpu(comp_id, t)
|
||||
}
|
||||
|
||||
/// The Auto timing history and key for a top-level frame of `comp` (`None` unless the
|
||||
/// backend is [`Backend::Auto`] and the accelerator keeps history).
|
||||
pub fn frame_auto(&self, a: &'a dyn Accelerator, comp: ItemId, display: bool) -> Option<(&'a AutoPick, AutoKey)> {
|
||||
if self.opts.backend != Backend::Auto || self.opts.roi.is_some() {
|
||||
return None;
|
||||
}
|
||||
Some((a.auto_pick()?, AutoKey::new(comp, self.opts.scale, display)))
|
||||
}
|
||||
|
||||
/// [`Self::comp_frame`] on the CPU compositor only.
|
||||
pub fn comp_frame_cpu(&self, comp_id: ItemId, t: Tick) -> Image {
|
||||
let Some(comp) = self.project.comp(comp_id) else { return Image::new(1, 1) };
|
||||
@@ -1580,9 +1614,20 @@ impl<'a> Renderer<'a> {
|
||||
|
||||
/// An adjustment layer's footprint (its source with masks applied, layer space): where
|
||||
/// its effects show. `None` = the layer changes nothing.
|
||||
pub fn adjustment_footprint(&self, ctx: &EvalCtx, layer: &Layer) -> Option<Buf> {
|
||||
pub fn adjustment_footprint(&self, ctx: &EvalCtx, layer: &Layer) -> Option<Arc<Buf>> {
|
||||
// Cached, so an accelerator sees the same buffer (and uploads it once) every frame.
|
||||
let key = self.cache.and_then(|_| cache::footprint_key(ctx, layer, self.raster_scale(ctx, layer), self.opts.draft));
|
||||
if let (Some(c), Some(k)) = (self.cache, key)
|
||||
&& let Some(b) = c.get(k)
|
||||
{
|
||||
return Some(b);
|
||||
}
|
||||
let mut foot = self.source(ctx, layer)?;
|
||||
let _ = masks::apply(ctx, layer, &mut foot);
|
||||
let foot = Arc::new(foot);
|
||||
if let (Some(c), Some(k)) = (self.cache, key) {
|
||||
c.insert(k, foot.clone());
|
||||
}
|
||||
Some(foot)
|
||||
}
|
||||
|
||||
@@ -1735,6 +1780,8 @@ pub fn render_frame(project: &Project, comp: ItemId, t: Tick, scale: f64) -> Ima
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
mod tests_auto;
|
||||
#[cfg(test)]
|
||||
mod tests_remap;
|
||||
#[cfg(test)]
|
||||
mod tests_roi;
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
//! Backend::Auto's per-comp CPU / GPU choice (`auto.rs`), with a mock accelerator.
|
||||
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use effectcraft_color::Label;
|
||||
use effectcraft_project::build;
|
||||
use effectcraft_project::{Comp, ItemId, ItemKind, LayerSource, Project, Solid};
|
||||
use effectcraft_time::{FrameRate, Tick};
|
||||
|
||||
use crate::{Accelerator, AutoKey, AutoPick, Backend, NoFootage, RenderOpts, Renderer};
|
||||
|
||||
/// An accelerator that takes `delay` per frame (or declines with `handle = false`) and keeps
|
||||
/// Auto timing history.
|
||||
struct TimedAccel {
|
||||
delay: std::time::Duration,
|
||||
handle: bool,
|
||||
calls: AtomicUsize,
|
||||
pick: AutoPick,
|
||||
}
|
||||
|
||||
impl TimedAccel {
|
||||
fn new(ms: u64, handle: bool) -> TimedAccel {
|
||||
TimedAccel { delay: std::time::Duration::from_millis(ms), handle, calls: Default::default(), pick: Default::default() }
|
||||
}
|
||||
fn calls(&self) -> usize {
|
||||
self.calls.load(Ordering::SeqCst)
|
||||
}
|
||||
}
|
||||
|
||||
impl Accelerator for TimedAccel {
|
||||
fn name(&self) -> String {
|
||||
"timed".into()
|
||||
}
|
||||
fn comp_frame(&self, _r: &Renderer, _comp: ItemId, _t: Tick) -> Option<crate::Image> {
|
||||
self.calls.fetch_add(1, Ordering::SeqCst);
|
||||
std::thread::sleep(self.delay);
|
||||
// The centre of the comp, as the CPU draws it (a red solid).
|
||||
self.handle.then(|| {
|
||||
let mut img = crate::Image::new(200, 100);
|
||||
img.set(100, 50, [1.0, 0.0, 0.0, 1.0]);
|
||||
img
|
||||
})
|
||||
}
|
||||
fn supports_effect(&self, _id: &str) -> bool {
|
||||
false
|
||||
}
|
||||
fn effects(&self, _chain: &[crate::FxStep], _buf: &crate::Buf, _levels: Option<f32>) -> Option<crate::Buf> {
|
||||
None
|
||||
}
|
||||
fn auto_pick(&self) -> Option<&AutoPick> {
|
||||
Some(&self.pick)
|
||||
}
|
||||
}
|
||||
|
||||
fn project() -> (Project, ItemId) {
|
||||
let mut p = Project::default();
|
||||
p.settings.gpu_acceleration = true;
|
||||
let mut comp = Comp::new(200, 100, FrameRate::FPS_30, Tick::from_seconds_f64(2.0));
|
||||
let sid = p.add_item("Solid", Label::Red, None, ItemKind::Solid(Solid { color: [1.0, 0.0, 0.0], width: 50, height: 50, pixel_aspect: 1.0 }));
|
||||
let l = build::layer(&mut p, &comp, "Solid", LayerSource::Solid { item: sid }, (50, 50), None);
|
||||
comp.layers.push(l);
|
||||
let cid = p.add_item("Comp", Label::Sandstone, None, ItemKind::Comp(comp.into()));
|
||||
(p, cid)
|
||||
}
|
||||
|
||||
/// Render `n` frames with `backend`; how many the accelerator was asked for.
|
||||
fn frames(p: &Project, cid: ItemId, a: &TimedAccel, backend: Backend, n: usize) -> usize {
|
||||
let before = a.calls();
|
||||
for _ in 0..n {
|
||||
let mut r = Renderer::new(p, &NoFootage, RenderOpts { backend, ..Default::default() });
|
||||
r.accel = Some(a);
|
||||
let img = r.comp_frame(cid, Tick::ZERO);
|
||||
// Whichever compositor ran, the frame is the same.
|
||||
assert!(img.get(100, 50)[0] > 0.99 && img.get(100, 50)[3] > 0.99);
|
||||
}
|
||||
a.calls() - before
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_backend_moves_light_comps_to_the_cpu() {
|
||||
// A light comp on a slow accelerator: after the warm-up (three frames on
|
||||
// each side) Auto renders on the CPU, re-measuring the accelerator now and then.
|
||||
let (p, cid) = project();
|
||||
// Several times the CPU's frame time (unoptimised test builds are slow).
|
||||
let t0 = std::time::Instant::now();
|
||||
for _ in 0..3 {
|
||||
Renderer::new(&p, &NoFootage, RenderOpts::default()).comp_frame(cid, Tick::ZERO);
|
||||
}
|
||||
let cpu_ms = t0.elapsed().as_millis() as u64 / 3;
|
||||
let slow = TimedAccel::new((cpu_ms * 5).max(20), true);
|
||||
let n = 6 + 2 * AutoPick::REPROBE as usize;
|
||||
let asked = frames(&p, cid, &slow, Backend::Auto, n);
|
||||
assert!((3..=5).contains(&asked), "asked the slow accelerator {asked} times in {n} frames");
|
||||
let s = slow.pick.stats(AutoKey::new(cid, 1.0, false)).unwrap();
|
||||
assert!(s.gpu_ms.unwrap() > s.cpu_ms.unwrap(), "{s:?}");
|
||||
// Backend::Gpu ignores the history; Software Only never asks.
|
||||
assert_eq!(frames(&p, cid, &slow, Backend::Gpu, 3), 3);
|
||||
let mut sw = p.clone();
|
||||
sw.settings.gpu_acceleration = false;
|
||||
assert_eq!(frames(&sw, cid, &slow, Backend::Auto, 3), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_backend_keeps_fast_accelerators() {
|
||||
// As fast as the CPU (ties stay on the accelerator): every frame but the CPU warm-up and
|
||||
// re-probes.
|
||||
let (p, cid) = project();
|
||||
let fast = TimedAccel::new(0, true);
|
||||
let asked = frames(&p, cid, &fast, Backend::Auto, 40);
|
||||
assert!(asked >= 36, "asked {asked} of 40");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_backend_falls_back_when_the_accelerator_declines() {
|
||||
let (p, cid) = project();
|
||||
let declining = TimedAccel::new(0, false);
|
||||
let n = 2 * AutoPick::REPROBE as usize;
|
||||
let asked = frames(&p, cid, &declining, Backend::Auto, n);
|
||||
// Asked first, then only on the periodic re-probes.
|
||||
assert!((1..=4).contains(&asked), "asked {asked} times in {n} frames");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_pick_follows_changing_costs() {
|
||||
let pick = AutoPick::default();
|
||||
let key = AutoKey::new(ItemId(7), 0.5, true);
|
||||
let cpu = 5.0;
|
||||
let mut gpu = 10.0;
|
||||
let (mut early, mut late) = (0, 0);
|
||||
for frame in 0..400 {
|
||||
// The GPU gets faster halfway (say, its uploads became cached).
|
||||
if frame == 200 {
|
||||
gpu = 1.0;
|
||||
}
|
||||
let g = pick.choose(key);
|
||||
pick.record(key, g, if g { gpu } else { cpu });
|
||||
if (100..200).contains(&frame) && g {
|
||||
early += 1;
|
||||
}
|
||||
if frame >= 300 && g {
|
||||
late += 1;
|
||||
}
|
||||
}
|
||||
assert!(early <= 3, "{early} of 100 frames on the slower GPU");
|
||||
assert!(late >= 97, "{late} of 100 frames on the faster GPU");
|
||||
let s = pick.stats(key).unwrap();
|
||||
assert!(s.gpu_ms.unwrap() < 2.0 && s.cpu_ms.unwrap() > 4.0, "{s:?}");
|
||||
// Keys are separate per comp, scale and path.
|
||||
assert!(pick.stats(AutoKey::new(ItemId(7), 1.0, true)).is_none());
|
||||
assert!(pick.stats(AutoKey::new(ItemId(7), 0.5, false)).is_none());
|
||||
}
|
||||
Reference in New Issue
Block a user