From a02c7bd8ec57de25b9705594bff52add71bcb857 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 5 Sep 2026 06:17:03 +0300 Subject: [PATCH] perf(av1): persistent worker pools instead of per-frame and per-tile threads Every threaded stage spawned its threads per unit of work: one `thread::scope` per filter stage per frame, `EC_AV1_RECON_THREADS` workers per tile, one frame worker per coded frame -- 2363 distinct threads in a 13 s 4K decode. What died with each of them was the `thread_local!` decode scratch (planes, rows, dq, mc, wiener, sgr), re-allocated and re-faulted on every new thread. `par::Batch` submits jobs to a pool owned by the submitting thread (thread-local, joined at thread exit), growing to `busy + queued` so a job never queues behind a blocking one -- the recon wavefront's workers block on their own dependencies. `Batch`'s drop waits every job out and re-raises the first panic, which is `thread::scope`'s contract minus the spawns, so the three call sites keep their borrows. Byte-exact: all 12 sha6t hashes at (frame, filter, recon) = (1,1,1), (6,2,4) and (1,1,4). seg4k (6,2,4) best-of-2 interleaved: 13.02 s -> 12.24 s. --- crates/ec-av1/src/decode.rs | 26 +++-- crates/ec-av1/src/par.rs | 197 ++++++++++++++++++++++++++++++++++-- crates/ec-av1/src/stream.rs | 12 ++- 3 files changed, 212 insertions(+), 23 deletions(-) diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 61482e40..763f4d77 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -2425,7 +2425,13 @@ fn wave_worker(st: &WaveState) { /// Installs the wavefront for one tile and joins its workers on every exit /// from the tile decoder, including the `?` ones -- the jobs hold raw /// pointers into the tile's planes, so no worker may outlive them. -pub(crate) struct WaveGuard<'a>(&'a crate::decode::FrameCtx, Vec>); +/// (lane-pool1: the workers come from this thread's persistent pool, so a +/// tile costs a batch submit rather than `EC_AV1_RECON_THREADS` fresh threads +/// with fresh scratch.) +pub(crate) struct WaveGuard<'a>( + &'a crate::decode::FrameCtx, + Option>, +); #[allow(unsafe_code)] impl<'a> WaveGuard<'a> { @@ -2460,14 +2466,13 @@ impl<'a> WaveGuard<'a> { enable_edge_filter: fctx.enable_edge_filter.with(std::cell::Cell::get), last_col: cols - 1, }); - let workers = (0..threads) - .map(|_| { - let st = std::sync::Arc::clone(&st); - std::thread::spawn(move || wave_worker(&st)) - }) - .collect(); + let batch = crate::par::Batch::new(); + for _ in 0..threads { + let st = std::sync::Arc::clone(&st); + batch.submit(move || wave_worker(&st)); + } fctx.wave.with(|w| *w.borrow_mut() = Some(st)); - Some(Self(fctx, workers)) + Some(Self(fctx, Some(batch))) } } @@ -2478,9 +2483,8 @@ impl Drop for WaveGuard<'_> { st.q.lock().unwrap().closed = true; st.cv.notify_all(); } - for h in self.1.drain(..) { - let _ = h.join(); - } + // Dropping the batch waits every worker out, as the joins did. + drop(self.1.take()); } } diff --git a/crates/ec-av1/src/par.rs b/crates/ec-av1/src/par.rs index f77dde51..911d1009 100644 --- a/crates/ec-av1/src/par.rs +++ b/crates/ec-av1/src/par.rs @@ -122,14 +122,17 @@ where [] => {} [(a, b)] => f(*a, *b, fctx), [(a0, b0), rest @ ..] => { - std::thread::scope(|s| { - for &(a, b) in rest { - let ctx = crate::decode::filter_ctx_copy(fctx); - let f = &f; - s.spawn(move || f(a, b, &ctx)); - } - f(*a0, *b0, fctx); - }); + // lane-pool1: same shape as the `thread::scope` this replaced -- + // band 0 inline, the rest on this thread's persistent pool, all + // waited out by `batch`'s drop at the end of the block. + let batch = Batch::new(); + for &(a, b) in rest { + let ctx = crate::decode::filter_ctx_copy(fctx); + let f = &f; + batch.submit(move || f(a, b, &ctx)); + } + f(*a0, *b0, fctx); + drop(batch); } } } @@ -161,3 +164,181 @@ pub(crate) fn recon_threads() -> usize { pub(crate) fn set_recon_threads(n: usize) { RECON_THREADS.store(n.clamp(1, 64), std::sync::atomic::Ordering::Relaxed); } + +// --- lane-pool1: persistent worker pools --------------------------------- +// +// Every threaded stage of the decoder used to spawn its threads per unit of +// work: one `thread::scope` per filter STAGE per frame, `EC_AV1_RECON_THREADS` +// workers per TILE, one frame worker per coded frame -- 2363 distinct threads +// in a 13 s 4K decode. The cost is not the clone of the thread itself but what +// dies with it: every `thread_local!` scratch pool in `decode.rs` (planes, +// rows, dq, mc, wiener, sgr) is allocated and faulted in again on each new +// thread, which is where the 3.65 M page faults and the 2.7x malloc traffic of +// the composed setting came from. +// +// The replacement is one pool per POOL-OWNING THREAD, kept in a thread-local +// and joined when that thread exits: a stage submits a [`Batch`] of jobs, the +// pool hands each to an idle worker (growing to `busy + queued` so a job never +// queues behind a blocking one -- the recon wavefront's workers block on their +// dependencies), and the batch's `Drop` waits every job out. Scratch then +// lives as long as the worker, not as long as the frame. +type Job = Box; + +struct PoolQ { + jobs: std::collections::VecDeque, + /// Jobs handed to a worker and not yet finished. + busy: usize, + closed: bool, +} + +struct PoolInner { + q: std::sync::Mutex, + cv: std::sync::Condvar, +} + +struct Pool { + inner: std::sync::Arc, + handles: Vec>, +} + +fn pool_worker(inner: &PoolInner) { + let mut q = inner.q.lock().unwrap(); + loop { + if let Some(job) = q.jobs.pop_front() { + q.busy += 1; + drop(q); + // A job's own panic is captured by the batch wrapper below, so + // this only guards against a wrapper that itself unwinds. + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(job)); + q = inner.q.lock().unwrap(); + q.busy -= 1; + continue; + } + if q.closed { + return; + } + q = inner.cv.wait(q).unwrap(); + } +} + +impl Pool { + fn new() -> Self { + Self { + inner: std::sync::Arc::new(PoolInner { + q: std::sync::Mutex::new(PoolQ { + jobs: std::collections::VecDeque::new(), + busy: 0, + closed: false, + }), + cv: std::sync::Condvar::new(), + }), + handles: Vec::new(), + } + } + + /// Queues `job` and makes sure a worker is free for it: the pool grows to + /// `busy + queued` threads and never shrinks, so a submitted job always + /// starts, even when every other running job is blocked waiting for it. + fn push(&mut self, job: Job) { + let want = { + let mut q = self.inner.q.lock().unwrap(); + q.jobs.push_back(job); + q.busy + q.jobs.len() + }; + while self.handles.len() < want { + let inner = std::sync::Arc::clone(&self.inner); + self.handles + .push(std::thread::spawn(move || pool_worker(&inner))); + } + self.inner.cv.notify_one(); + } +} + +impl Drop for Pool { + fn drop(&mut self) { + self.inner.q.lock().unwrap().closed = true; + self.inner.cv.notify_all(); + for h in self.handles.drain(..) { + let _ = h.join(); + } + } +} + +thread_local! { + /// This thread's pool, created on its first [`Batch::submit`] and joined + /// when the thread exits (the process's main thread may skip that + /// destructor, in which case the idle workers die with the process). + static POOL: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +struct BatchState { + left: std::sync::Mutex, + cv: std::sync::Condvar, + panic: std::sync::Mutex>>, +} + +/// A set of jobs running on the submitting thread's pool. `Drop` waits for +/// every one of them and re-raises the first panic, which is what makes +/// [`Batch::submit`]'s borrow of non-`'static` data sound -- exactly +/// `thread::scope`'s contract, minus the spawns. +/// +/// corner-cut: soundness rests on this `Drop` running; `std::mem::forget` of a +/// `Batch` would let a job outlive its borrows. The type is crate-private and +/// every construction site below binds it to a local. Upgrade path is the +/// closure-taking `scope(|s| ...)` shape, which costs every caller a level of +/// indentation for the same guarantee. +pub(crate) struct Batch<'a> { + st: std::sync::Arc, + _p: std::marker::PhantomData<&'a ()>, +} + +impl<'a> Batch<'a> { + pub(crate) fn new() -> Self { + Self { + st: std::sync::Arc::new(BatchState { + left: std::sync::Mutex::new(0), + cv: std::sync::Condvar::new(), + panic: std::sync::Mutex::new(None), + }), + _p: std::marker::PhantomData, + } + } + + pub(crate) fn submit(&self, f: F) { + *self.st.left.lock().unwrap() += 1; + let st = std::sync::Arc::clone(&self.st); + let job: Box = Box::new(move || { + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)); + if let Err(p) = r { + let mut slot = st.panic.lock().unwrap(); + if slot.is_none() { + *slot = Some(p); + } + } + let mut left = st.left.lock().unwrap(); + *left -= 1; + st.cv.notify_all(); + }); + // SAFETY: the job is dropped before `Batch::drop` returns (it waits + // for `left == 0`), and `Batch<'a>` cannot outlive `'a`, so the + // laundered lifetime is never observed past the real one. + let job: Job = unsafe { std::mem::transmute::, Job>(job) }; + POOL.with(|p| { + let mut p = p.borrow_mut(); + p.get_or_insert_with(Pool::new).push(job); + }); + } +} + +impl Drop for Batch<'_> { + fn drop(&mut self) { + let mut left = self.st.left.lock().unwrap(); + while *left > 0 { + left = self.st.cv.wait(left).unwrap(); + } + drop(left); + if let Some(p) = self.st.panic.lock().unwrap().take() { + std::panic::resume_unwind(p); + } + } +} diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 6cb22e04..1eec8bc5 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -478,7 +478,12 @@ pub fn decode_stream_with_threads( threads: usize, mut sink: impl FnMut(&Picture, usize, bool) -> Result<()>, ) -> Result<()> { - std::thread::scope(|scope| { + // lane-pool1: this replaced a `std::thread::scope` -- frame workers now + // come from a persistent pool (one per submitting thread, workers reused + // across frames, so their `thread_local!` decode scratch survives the + // frame). `jobs` is declared here and dropped at the end of the function, + // including on `?`, so no job outlives the data it borrows. + let jobs = crate::par::Batch::new(); // lane-thread1: this stream's per-frame decode state (was 38 thread_local // statics in decode.rs) -- one object, threaded down the decode call graph. let fctx = &crate::decode::FrameCtx::new(); @@ -617,7 +622,7 @@ pub fn decode_stream_with_threads( let grain = header.film_grain; let seq = SeqFlags::read(&parser); let tx = tx.clone(); - scope.spawn(move || { + jobs.submit(move || { let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { let value = promise.wait()?; let output = if grain.apply_grain && !no_grain() { @@ -838,7 +843,7 @@ pub fn decode_stream_with_threads( } let tx = tx.clone(); let dump = final_dump.clone(); - scope.spawn(move || { + jobs.submit(move || { let promise = produces; let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { // The wait happens HERE, off the parsing thread, and only @@ -1041,7 +1046,6 @@ pub fn decode_stream_with_threads( } debug_assert!(reorder.pending.is_empty(), "a frame was never emitted"); Ok(()) - }) }