Merge branch 'lane-memfix' (167e98e9): a pool job submits back into the pool it runs on (no nested pools: 1053 -> 59 threads), whole-plane scratch is one process-wide best-fit pool capped at 32 buffers (frame thread and filter workers share it); 4K peak RSS 10 GB -> 4.1-5.0 GB, page faults -30%, +0.1% instructions; byte-exact on 20 gate hashes + 6 film cuts; bounded-pool test added
Browse files at this commit3 changed files +194 -47
- crates/ec-av1/src/decode.rs +57 -13
- crates/ec-av1/src/par.rs +85 -34
- crates/ec-av1/src/stream.rs +52 -0
crates/ec-av1/src/decode.rsmodified+57 -13
| @@ -19366,20 +19366,59 @@ fn deblock_plane_span( | ||
| 19366 | 19366 | } }); |
| 19367 | 19367 | } |
| 19368 | 19368 | |
| 19369 | -thread_local! { | |
| 19370 | - /// lane-perf6: reused whole-plane `u16` buffers. Every frame takes a | |
| 19371 | - /// pre-CDEF snapshot of all three planes, a post-deblock snapshot when | |
| 19372 | - /// loop restoration is active, and a fresh LR destination per plane -- | |
| 19373 | - /// freshly allocated that is ~25 MB of `mmap`/`munmap` per frame at 4K, | |
| 19374 | - /// so every sample written also takes a first-touch page fault. The | |
| 19375 | - /// buffers are handed back here instead and refilled in place. | |
| 19376 | - static PLANE_SCRATCH: std::cell::RefCell<Vec<Vec<u16>>> = | |
| 19377 | - const { std::cell::RefCell::new(Vec::new()) }; | |
| 19369 | +/// lane-perf6: reused whole-plane `u16` buffers. Every frame takes a | |
| 19370 | +/// pre-CDEF snapshot of all three planes, a post-deblock snapshot when loop | |
| 19371 | +/// restoration is active, and a fresh LR destination per plane -- freshly | |
| 19372 | +/// allocated that is ~25 MB of `mmap`/`munmap` per frame at 4K, so every | |
| 19373 | +/// sample written also takes a first-touch page fault. The buffers are handed | |
| 19374 | +/// back here instead and refilled in place. | |
| 19375 | +/// | |
| 19376 | +/// lane-memfix: PROCESS-WIDE, not one stash per thread. These buffers do not | |
| 19377 | +/// stay on one thread: the frame thread allocates the snapshots and a filter | |
| 19378 | +/// worker returns them ([`pipe_run_lr`] swaps the picture's pre-LR planes | |
| 19379 | +/// into the pool from whichever worker ran it), so a per-thread pool leaked | |
| 19380 | +/// whole-plane buffers into every worker it touched -- 19 MB a set, times | |
| 19381 | +/// every pool thread the decode ever created. One shared pool with a hard | |
| 19382 | +/// entry cap bounds the retention at [`SCRATCH_CAP`] buffers no matter how | |
| 19383 | +/// many threads cycle through it; anything over the cap is freed. | |
| 19384 | +static PLANE_SCRATCH: std::sync::Mutex<Vec<Vec<u16>>> = std::sync::Mutex::new(Vec::new()); | |
| 19385 | + | |
| 19386 | +/// Most buffers the shared pool keeps. ~3 whole-plane sets per in-flight 4K | |
| 19387 | +/// frame at the shipped `EC_AV1_THREADS` ceiling; the frames actually in | |
| 19388 | +/// flight cycle through far fewer. | |
| 19389 | +const SCRATCH_CAP: usize = 32; | |
| 19390 | + | |
| 19391 | +/// Takes a pooled buffer for a caller that wants `n` samples, best-fit by | |
| 19392 | +/// CAPACITY so a chroma-sized request does not permanently promote a | |
| 19393 | +/// luma-sized allocation (every pooled buffer would drift to the largest | |
| 19394 | +/// size otherwise). `None` when the pool is empty. | |
| 19395 | +fn scratch_take(n: usize) -> Option<Vec<u16>> { | |
| 19396 | + let mut p = PLANE_SCRATCH.lock().unwrap(); | |
| 19397 | + if p.is_empty() { | |
| 19398 | + return None; | |
| 19399 | + } | |
| 19400 | + let fit = p | |
| 19401 | + .iter() | |
| 19402 | + .enumerate() | |
| 19403 | + .filter(|(_, v)| v.capacity() >= n) | |
| 19404 | + .min_by_key(|(_, v)| v.capacity()) | |
| 19405 | + .map(|(i, _)| i); | |
| 19406 | + let i = match fit { | |
| 19407 | + Some(i) => i, | |
| 19408 | + // Nothing big enough: grow the largest rather than a small one. | |
| 19409 | + None => p | |
| 19410 | + .iter() | |
| 19411 | + .enumerate() | |
| 19412 | + .max_by_key(|(_, v)| v.capacity()) | |
| 19413 | + .map(|(i, _)| i) | |
| 19414 | + .expect("the pool is not empty"), | |
| 19415 | + }; | |
| 19416 | + Some(p.swap_remove(i)) | |
| 19378 | 19417 | } |
| 19379 | 19418 | |
| 19380 | 19419 | /// A pooled buffer holding a copy of `src`. |
| 19381 | 19420 | fn scratch_from(src: &[u16]) -> Vec<u16> { |
| 19382 | - let mut v = PLANE_SCRATCH.with(|p| p.borrow_mut().pop()).unwrap_or_default(); | |
| 19421 | + let mut v = scratch_take(src.len()).unwrap_or_default(); | |
| 19383 | 19422 | v.clear(); |
| 19384 | 19423 | v.extend_from_slice(src); |
| 19385 | 19424 | v |
| @@ -19387,7 +19426,7 @@ fn scratch_from(src: &[u16]) -> Vec<u16> { | ||
| 19387 | 19426 | |
| 19388 | 19427 | /// An empty pooled buffer, for a caller that fills it itself. |
| 19389 | 19428 | fn scratch_empty() -> Vec<u16> { |
| 19390 | - let mut v = PLANE_SCRATCH.with(|p| p.borrow_mut().pop()).unwrap_or_default(); | |
| 19429 | + let mut v = scratch_take(0).unwrap_or_default(); | |
| 19391 | 19430 | v.clear(); |
| 19392 | 19431 | v |
| 19393 | 19432 | } |
| @@ -19396,7 +19435,7 @@ fn scratch_empty() -> Vec<u16> { | ||
| 19396 | 19435 | /// for a caller that writes every element it later reads (lane-copy: the |
| 19397 | 19436 | /// post-deblock snapshot writes 4 rows in 64 and reads no other). |
| 19398 | 19437 | fn scratch_sized(n: usize) -> Vec<u16> { |
| 19399 | - let mut v = PLANE_SCRATCH.with(|p| p.borrow_mut().pop()).unwrap_or_default(); | |
| 19438 | + let mut v = scratch_take(n).unwrap_or_default(); | |
| 19400 | 19439 | if v.len() > n { |
| 19401 | 19440 | v.truncate(n); |
| 19402 | 19441 | } else if v.len() < n { |
| @@ -19458,8 +19497,13 @@ fn crop_owned(plane: PlaneBuf<'_>, w: usize, h: usize) -> Vec<u16> { | ||
| 19458 | 19497 | } |
| 19459 | 19498 | |
| 19460 | 19499 | /// Hands a buffer back to the pool; the capacity is what is worth keeping. |
| 19500 | +/// Over [`SCRATCH_CAP`] the buffer is dropped (freed) instead -- the cap is | |
| 19501 | +/// what keeps a pool shared by every thread from being an unbounded stash. | |
| 19461 | 19502 | fn scratch_return(v: Vec<u16>) { |
| 19462 | - PLANE_SCRATCH.with(|p| p.borrow_mut().push(v)); | |
| 19503 | + let mut p = PLANE_SCRATCH.lock().unwrap(); | |
| 19504 | + if p.len() < SCRATCH_CAP { | |
| 19505 | + p.push(v); | |
| 19506 | + } | |
| 19463 | 19507 | } |
| 19464 | 19508 | |
| 19465 | 19509 | /// One CDEF mi-row band, as a real function rather than the body of the |
crates/ec-av1/src/par.rsmodified+85 -34
| @@ -202,6 +202,11 @@ struct PoolQ { | ||
| 202 | 202 | /// Jobs handed to a worker and not yet finished. |
| 203 | 203 | busy: usize, |
| 204 | 204 | closed: bool, |
| 205 | + /// lane-memfix: the pool's threads live behind the same lock as its | |
| 206 | + /// queue, because the thread that has to GROW the pool is whichever one | |
| 207 | + /// submits -- including one of the pool's own workers (see | |
| 208 | + /// [`pool_push`]). Joined by [`Pool::drop`] on the owning thread. | |
| 209 | + handles: Vec<std::thread::JoinHandle<()>>, | |
| 205 | 210 | } |
| 206 | 211 | |
| 207 | 212 | struct PoolInner { |
| @@ -211,10 +216,13 @@ struct PoolInner { | ||
| 211 | 216 | |
| 212 | 217 | struct Pool { |
| 213 | 218 | inner: std::sync::Arc<PoolInner>, |
| 214 | - handles: Vec<std::thread::JoinHandle<()>>, | |
| 215 | 219 | } |
| 216 | 220 | |
| 217 | -fn pool_worker(inner: &PoolInner) { | |
| 221 | +fn pool_worker(inner: &std::sync::Arc<PoolInner>) { | |
| 222 | + // lane-memfix: a job this worker runs submits its own sub-batches to THIS | |
| 223 | + // pool rather than opening a second one on the worker's thread-local -- | |
| 224 | + // see [`Batch::submit`]. | |
| 225 | + ON_POOL.with(|c| *c.borrow_mut() = Some(std::sync::Arc::clone(inner))); | |
| 218 | 226 | let mut q = inner.q.lock().unwrap(); |
| 219 | 227 | loop { |
| 220 | 228 | if let Some(job) = q.jobs.pop_front() { |
| @@ -228,6 +236,7 @@ fn pool_worker(inner: &PoolInner) { | ||
| 228 | 236 | continue; |
| 229 | 237 | } |
| 230 | 238 | if q.closed { |
| 239 | + POOL_THREADS.fetch_sub(1, std::sync::atomic::Ordering::Relaxed); | |
| 231 | 240 | return; |
| 232 | 241 | } |
| 233 | 242 | q = inner.cv.wait(q).unwrap(); |
| @@ -242,46 +251,66 @@ impl Pool { | ||
| 242 | 251 | jobs: std::collections::VecDeque::new(), |
| 243 | 252 | busy: 0, |
| 244 | 253 | closed: false, |
| 254 | + handles: Vec::new(), | |
| 245 | 255 | }), |
| 246 | 256 | cv: std::sync::Condvar::new(), |
| 247 | 257 | }), |
| 248 | - handles: Vec::new(), | |
| 249 | 258 | } |
| 250 | 259 | } |
| 260 | +} | |
| 251 | 261 | |
| 252 | - /// Queues `job` and makes sure a worker is free for it: the pool grows to | |
| 253 | - /// `busy + queued` threads and never shrinks, so a submitted job always | |
| 254 | - /// starts, even when every other running job is blocked waiting for it. | |
| 255 | - /// `class` names the submitting site of the job that grows the pool, so a | |
| 256 | - /// profiler attributes the thread to the work that created it | |
| 257 | - /// (`ec-av1-frame`, `ec-av1-recon`, `ec-av1-filter`). One pool serves | |
| 258 | - /// every class a thread submits, so later classes on the same pool reuse | |
| 259 | - /// the threads an earlier one named. | |
| 260 | - fn push(&mut self, job: Job, class: &'static str) { | |
| 261 | - let want = { | |
| 262 | - let mut q = self.inner.q.lock().unwrap(); | |
| 263 | - q.jobs.push_back(job); | |
| 264 | - q.busy + q.jobs.len() | |
| 265 | - }; | |
| 266 | - while self.handles.len() < want { | |
| 267 | - let inner = std::sync::Arc::clone(&self.inner); | |
| 268 | - let name = format!("{class}-{}", self.handles.len()); | |
| 269 | - self.handles.push( | |
| 270 | - std::thread::Builder::new() | |
| 271 | - .name(name) | |
| 272 | - .spawn(move || pool_worker(&inner)) | |
| 273 | - .expect("spawning an ec-av1 pool worker"), | |
| 274 | - ); | |
| 275 | - } | |
| 276 | - self.inner.cv.notify_one(); | |
| 262 | +/// Queues `job` on `inner` and makes sure a worker is free for it: the pool | |
| 263 | +/// grows to `busy + queued` threads, so a submitted job always starts, even | |
| 264 | +/// when every other running job is blocked waiting for it. | |
| 265 | +/// `class` names the submitting site of the job that grows the pool, so a | |
| 266 | +/// profiler attributes the thread to the work that created it | |
| 267 | +/// (`ec-av1-frame`, `ec-av1-recon`, `ec-av1-filter`). One pool serves every | |
| 268 | +/// class submitted to it, so later classes reuse the threads an earlier one | |
| 269 | +/// named. | |
| 270 | +/// | |
| 271 | +/// lane-memfix: the pool only grows for work that is queued and unserved AT | |
| 272 | +/// THAT MOMENT, and a pool worker submits back into its own pool, so the | |
| 273 | +/// process-wide thread count is the peak of `busy + queued` over the whole | |
| 274 | +/// job tree -- not the product of one pool per nesting level (a filter band | |
| 275 | +/// job used to open a third-level pool on the worker running it, and none of | |
| 276 | +/// those pools ever shrank: 1038 threads at (16,4,2)). | |
| 277 | +fn pool_push(inner: &std::sync::Arc<PoolInner>, job: Job, class: &'static str) { | |
| 278 | + let mut q = inner.q.lock().unwrap(); | |
| 279 | + q.jobs.push_back(job); | |
| 280 | + let want = q.busy + q.jobs.len(); | |
| 281 | + while q.handles.len() < want { | |
| 282 | + let inner = std::sync::Arc::clone(inner); | |
| 283 | + let name = format!("{class}-{}", q.handles.len()); | |
| 284 | + q.handles.push( | |
| 285 | + std::thread::Builder::new() | |
| 286 | + .name(name) | |
| 287 | + .spawn(move || pool_worker(&inner)) | |
| 288 | + .expect("spawning an ec-av1 pool worker"), | |
| 289 | + ); | |
| 290 | + POOL_THREADS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); | |
| 277 | 291 | } |
| 292 | + drop(q); | |
| 293 | + inner.cv.notify_one(); | |
| 294 | +} | |
| 295 | + | |
| 296 | +/// Live threads across every ec-av1 pool -- what the bounded-growth test | |
| 297 | +/// asserts on, and what a profiler counts as `ec-av1-*`. | |
| 298 | +static POOL_THREADS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); | |
| 299 | + | |
| 300 | +#[cfg(test)] | |
| 301 | +pub(crate) fn pool_threads() -> usize { | |
| 302 | + POOL_THREADS.load(std::sync::atomic::Ordering::Relaxed) | |
| 278 | 303 | } |
| 279 | 304 | |
| 280 | 305 | impl Drop for Pool { |
| 281 | 306 | fn drop(&mut self) { |
| 282 | - self.inner.q.lock().unwrap().closed = true; | |
| 307 | + let handles = { | |
| 308 | + let mut q = self.inner.q.lock().unwrap(); | |
| 309 | + q.closed = true; | |
| 310 | + std::mem::take(&mut q.handles) | |
| 311 | + }; | |
| 283 | 312 | self.inner.cv.notify_all(); |
| 284 | - for h in self.handles.drain(..) { | |
| 313 | + for h in handles { | |
| 285 | 314 | let _ = h.join(); |
| 286 | 315 | } |
| 287 | 316 | } |
| @@ -292,6 +321,12 @@ thread_local! { | ||
| 292 | 321 | /// when the thread exits (the process's main thread may skip that |
| 293 | 322 | /// destructor, in which case the idle workers die with the process). |
| 294 | 323 | static POOL: std::cell::RefCell<Option<Pool>> = const { std::cell::RefCell::new(None) }; |
| 324 | + /// lane-memfix: set on a pool WORKER for its whole life -- the pool it | |
| 325 | + /// serves. A job submitting a sub-batch (a pipeline stage banding itself | |
| 326 | + /// across the filter pool) then reuses that pool instead of opening a | |
| 327 | + /// nested one of its own. | |
| 328 | + static ON_POOL: std::cell::RefCell<Option<std::sync::Arc<PoolInner>>> = | |
| 329 | + const { std::cell::RefCell::new(None) }; | |
| 295 | 330 | } |
| 296 | 331 | |
| 297 | 332 | struct BatchState { |
| @@ -350,10 +385,26 @@ impl<'a> Batch<'a> { | ||
| 350 | 385 | // for `left == 0`), and `Batch<'a>` cannot outlive `'a`, so the |
| 351 | 386 | // laundered lifetime is never observed past the real one. |
| 352 | 387 | let job: Job = unsafe { std::mem::transmute::<Box<dyn FnOnce() + Send + 'a>, Job>(job) }; |
| 353 | - POOL.with(|p| { | |
| 354 | - let mut p = p.borrow_mut(); | |
| 355 | - p.get_or_insert_with(Pool::new).push(job, self.class); | |
| 356 | - }); | |
| 388 | + // lane-memfix: on a pool worker, back into the pool it is serving; on | |
| 389 | + // any other thread, this thread's own pool. | |
| 390 | + // | |
| 391 | + // No deadlock: a job blocked in `Batch::drop` is counted in `busy`, | |
| 392 | + // so `pool_push` grows the pool by one thread for every queued job | |
| 393 | + // that has no idle worker -- the child of a blocked parent always | |
| 394 | + // gets a thread. The only waits inside a job are on its own sub-batch | |
| 395 | + // (same rule, one level deeper) and on wavefront row atomics / | |
| 396 | + // `PipeSync` counters, which are published by jobs that are already | |
| 397 | + // running, never by a job still in the queue. | |
| 398 | + let on = ON_POOL.with(|c| c.borrow().clone()); | |
| 399 | + match on { | |
| 400 | + Some(inner) => pool_push(&inner, job, self.class), | |
| 401 | + None => POOL.with(|p| { | |
| 402 | + let mut p = p.borrow_mut(); | |
| 403 | + let inner = std::sync::Arc::clone(&p.get_or_insert_with(Pool::new).inner); | |
| 404 | + drop(p); | |
| 405 | + pool_push(&inner, job, self.class); | |
| 406 | + }), | |
| 407 | + } | |
| 357 | 408 | } |
| 358 | 409 | } |
| 359 | 410 |
crates/ec-av1/src/stream.rsmodified+52 -0
| @@ -6363,6 +6363,58 @@ mod tests { | ||
| 6363 | 6363 | } |
| 6364 | 6364 | } |
| 6365 | 6365 | |
| 6366 | + /// lane-memfix: the pool grows to the peak of `busy + queued` over the | |
| 6367 | + /// job tree and stops there. Before, a job running on a pool worker | |
| 6368 | + /// opened a SECOND pool on that worker's own thread-local -- one level | |
| 6369 | + /// per pipeline stage, none of them ever shrinking -- which is how a 4K | |
| 6370 | + /// decode at `(16, 4, 2)` reached 1038 live threads. Two decodes of the | |
| 6371 | + /// same stream: the count stays inside the composed setting and the | |
| 6372 | + /// second decode adds nothing (the ratchet is what cost the memory). | |
| 6373 | + #[test] | |
| 6374 | + fn the_worker_pool_stays_bounded_across_repeated_threaded_decodes() { | |
| 6375 | + const NAME: &str = "the_worker_pool_stays_bounded_across_repeated_threaded_decodes"; | |
| 6376 | + let _gate_lock = lock_gate_counters(); | |
| 6377 | + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) | |
| 6378 | + .join("fixtures") | |
| 6379 | + .join("superres_alltools_sb128_320x180.obu"); | |
| 6380 | + let stream = std::fs::read(&path) | |
| 6381 | + .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); | |
| 6382 | + crate::par::set_filter_threads(4); | |
| 6383 | + crate::par::set_recon_threads(2); | |
| 6384 | + let mut counts = [0usize; 2]; | |
| 6385 | + let mut frames = [0usize; 2]; | |
| 6386 | + for (i, slot) in counts.iter_mut().enumerate() { | |
| 6387 | + let mut n = 0usize; | |
| 6388 | + let r = decode_stream_with_threads(&stream, 4, |_, _, _| { | |
| 6389 | + n += 1; | |
| 6390 | + Ok(()) | |
| 6391 | + }); | |
| 6392 | + if let Err(e) = r { | |
| 6393 | + crate::par::set_filter_threads(1); | |
| 6394 | + crate::par::set_recon_threads(1); | |
| 6395 | + panic!("{NAME}: refused on decode {i}: {e}"); | |
| 6396 | + } | |
| 6397 | + frames[i] = n; | |
| 6398 | + *slot = crate::par::pool_threads(); | |
| 6399 | + } | |
| 6400 | + crate::par::set_filter_threads(1); | |
| 6401 | + crate::par::set_recon_threads(1); | |
| 6402 | + assert!(frames[0] > 1, "{NAME}: the fixture decoded {} frames, so nothing was threaded", frames[0]); | |
| 6403 | + // 4 frame workers x (recon 2 + filter 4) plus the two in-flight | |
| 6404 | + // slots `stream.rs` allows over the thread count, with room for the | |
| 6405 | + // show jobs -- 1038 was three orders past this. | |
| 6406 | + assert!( | |
| 6407 | + counts[1] <= 4 * (2 + 4) + 2 * 4, | |
| 6408 | + "{NAME}: the pool grew to {} threads at 4 frame / 4 filter / 2 recon", | |
| 6409 | + counts[1] | |
| 6410 | + ); | |
| 6411 | + assert_eq!( | |
| 6412 | + counts[0], counts[1], | |
| 6413 | + "{NAME}: a second decode of the same stream grew the pool from {} to {} threads", | |
| 6414 | + counts[0], counts[1] | |
| 6415 | + ); | |
| 6416 | + } | |
| 6417 | + | |
| 6366 | 6418 | #[test] |
| 6367 | 6419 | fn a_real_stream_filters_identically_with_one_and_four_filter_threads() { |
| 6368 | 6420 | const NAME: &str = "a_real_stream_filters_identically_with_one_and_four_filter_threads"; |