forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-wave5' (83a87ee2): reconstruction wavefront takes jobs from per-superblock-row queues (one raster FIFO had serialised workers on one row); EC_AV1_WAVE_STATS instrument; byte-exact at all settings; 4K 32.1 fps at (16,4,2), 1080p 75 fps

Browse files at this commit

8cdbcf4dab1793e53e30c218251aa3a251aaa432Ahmet Kaan GümüşParent: f37b756bdf81cd
crates/ec-av1/src/decode.rsmodified+157 -17
@@ -93,6 +93,9 @@ pub(crate) struct FrameCtx {
93 /// lane-wave1 step (ii): the superblock wavefront this tile's recorded93 /// lane-wave1 step (ii): the superblock wavefront this tile's recorded
94 /// writes are handed to, at more than one reconstruction thread.94 /// writes are handed to, at more than one reconstruction thread.
95 pub(crate) wave: std::cell::RefCell<Option<std::sync::Arc<WaveState>>>,95 pub(crate) wave: std::cell::RefCell<Option<std::sync::Arc<WaveState>>>,
96+ /// lane-wave5 instrumentation only (`EC_AV1_WAVE_STATS`): when the parse
97+ /// thread last handed a superblock to the wavefront.
98+ pub(crate) wave_mark: std::cell::Cell<Option<std::time::Instant>>,
96 }99 }
97 100
98 impl std::fmt::Debug for FrameCtx {101 impl std::fmt::Debug for FrameCtx {
@@ -154,6 +157,7 @@ impl FrameCtx {
154 recon_spare: std::cell::RefCell::new(Vec::new()),157 recon_spare: std::cell::RefCell::new(Vec::new()),
155 recon_planes: std::cell::Cell::new(None),158 recon_planes: std::cell::Cell::new(None),
156 wave: std::cell::RefCell::new(None),159 wave: std::cell::RefCell::new(None),
160+ wave_mark: std::cell::Cell::new(None),
157 }161 }
158 }162 }
159 }163 }
@@ -2371,7 +2375,16 @@ pub(crate) struct WaveState {
2371 }2375 }
2372 2376
2373 struct WaveQueue {2377 struct WaveQueue {
2374- jobs: std::collections::VecDeque<(usize, usize, Vec<ReconOp>)>,2378+ /// Queued jobs per superblock ROW, in column order (lane-wave5). Only a
2379+ /// row's front job can ever be runnable -- a job waits on its own left
2380+ /// neighbour -- so a worker takes the lowest row whose front job's
2381+ /// dependencies are met. Popping the raster-oldest job instead (what
2382+ /// this replaced) put every worker on the SAME row, where the wavefront
2383+ /// rule serialises them, which is why 4 workers ran the tile at 1.2x.
2384+ rows: Vec<std::collections::VecDeque<(usize, Vec<ReconOp>)>>,
2385+ /// Jobs sitting in `rows`, so a worker knows the queue is empty without
2386+ /// walking it.
2387+ queued: usize,
2375 /// Per superblock row, the last column reconstructed (-1 = none yet).2388 /// Per superblock row, the last column reconstructed (-1 = none yet).
2376 done: Vec<isize>,2389 done: Vec<isize>,
2377 /// Jobs popped but not finished -- what [`wave_barrier`] waits out.2390 /// Jobs popped but not finished -- what [`wave_barrier`] waits out.
@@ -2379,32 +2392,132 @@ struct WaveQueue {
2379 closed: bool,2392 closed: bool,
2380 }2393 }
2381 2394
2395+impl WaveQueue {
2396+ /// The lowest-row queued job whose wavefront dependencies are satisfied,
2397+ /// or `None` (with the blocking condition counted when instrumented).
2398+ fn take_runnable(&mut self, last_col: usize, stats: bool) -> Option<(usize, usize, Vec<ReconOp>)> {
2399+ let mut blocked: Option<bool> = None;
2400+ for r in 0..self.rows.len() {
2401+ let Some(front) = self.rows[r].front() else {
2402+ continue;
2403+ };
2404+ let c = front.0;
2405+ let above = r == 0 || self.done[r - 1] >= (c + 1).min(last_col) as isize;
2406+ let left = c == 0 || self.done[r] >= c as isize - 1;
2407+ if above && left {
2408+ let (c, ops) = self.rows[r].pop_front().expect("front checked above");
2409+ self.queued -= 1;
2410+ return Some((r, c, ops));
2411+ }
2412+ if blocked.is_none() {
2413+ blocked = Some(above);
2414+ }
2415+ }
2416+ if stats {
2417+ match blocked {
2418+ Some(true) => WS_BLOCK_LEFT.fetch_add(1, Relaxed),
2419+ Some(false) => WS_BLOCK_ABOVE.fetch_add(1, Relaxed),
2420+ None => 0,
2421+ };
2422+ }
2423+ None
2424+ }
2425+}
2426+
2427+/// lane-wave5 instrumentation, on `EC_AV1_WAVE_STATS=1`: where a recon
2428+/// worker's time goes (busy replaying, waiting for a dependency, idle on an
2429+/// empty queue), how far ahead the parse thread is, and how often the two
2430+/// parse-time pixel reads barrier the wavefront. Cumulative for the process,
2431+/// dumped by every [`WaveGuard`] drop, so the LAST line of a decode is the
2432+/// whole run.
2433+const WS_SLOTS: usize = 16;
2434+use std::sync::atomic::AtomicU64;
2435+use std::sync::atomic::Ordering::Relaxed;
2436+static WS_JOBS: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
2437+static WS_OPS: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
2438+static WS_BUSY: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
2439+static WS_WAIT: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
2440+static WS_BLOCK_ABOVE: AtomicU64 = AtomicU64::new(0);
2441+static WS_BLOCK_LEFT: AtomicU64 = AtomicU64::new(0);
2442+/// Parse-thread time between two submits, i.e. everything parse still does
2443+/// itself (symbol decode plus the predictions not deferred).
2444+static WS_PARSE: AtomicU64 = AtomicU64::new(0);
2445+/// Parse-thread time spent waiting for the wavefront: at [`wave_barrier`]
2446+/// (the intrabc/interintra reads) and at the tile's end.
2447+static WS_BARRIER: AtomicU64 = AtomicU64::new(0);
2448+static WS_BARRIERS: AtomicU64 = AtomicU64::new(0);
2449+static WS_DRAIN: AtomicU64 = AtomicU64::new(0);
2450+static WS_TILES: AtomicU64 = AtomicU64::new(0);
2451+
2452+fn wave_stats() -> bool {
2453+ static ON: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
2454+ match ON.load(Relaxed) {
2455+ 0 => {
2456+ let on = crate::envflags::var("EC_AV1_WAVE_STATS")
2457+ .map(|v| v.trim() == "1")
2458+ .unwrap_or(false);
2459+ ON.store(1 + u8::from(on), Relaxed);
2460+ on
2461+ }
2462+ n => n == 2,
2463+ }
2464+}
2465+
2466+fn wave_stats_dump() {
2467+ let ms = |n: u64| n as f64 / 1e6;
2468+ let mut s = format!("wave_stats tiles={}", WS_TILES.load(Relaxed));
2469+ for i in 0..WS_SLOTS {
2470+ let jobs = WS_JOBS[i].load(Relaxed);
2471+ if jobs == 0 {
2472+ continue;
2473+ }
2474+ s += &format!(
2475+ " | w{i} jobs={jobs} ops/job={:.1} busy={:.0}ms wait={:.0}ms wait/job={:.0}us",
2476+ WS_OPS[i].load(Relaxed) as f64 / jobs as f64,
2477+ ms(WS_BUSY[i].load(Relaxed)),
2478+ ms(WS_WAIT[i].load(Relaxed)),
2479+ WS_WAIT[i].load(Relaxed) as f64 / jobs as f64 / 1e3,
2480+ );
2481+ }
2482+ s += &format!(
2483+ " | parse={:.0}ms barrier={:.0}ms/{} drain={:.0}ms block_above={} block_left={}",
2484+ ms(WS_PARSE.load(Relaxed)),
2485+ ms(WS_BARRIER.load(Relaxed)),
2486+ WS_BARRIERS.load(Relaxed),
2487+ ms(WS_DRAIN.load(Relaxed)),
2488+ WS_BLOCK_ABOVE.load(Relaxed),
2489+ WS_BLOCK_LEFT.load(Relaxed),
2490+ );
2491+ eprintln!("{s}");
2492+}
2493+
2382 #[allow(unsafe_code)]2494 #[allow(unsafe_code)]
2383-fn wave_worker(st: &WaveState) {2495+fn wave_worker(st: &WaveState, idx: usize) {
2384 let fctx = FrameCtx::new();2496 let fctx = FrameCtx::new();
2385 fctx.bit_depth.set(st.bit_depth);2497 fctx.bit_depth.set(st.bit_depth);
2386 fctx.enable_edge_filter.set(st.enable_edge_filter);2498 fctx.enable_edge_filter.set(st.enable_edge_filter);
2499+ let stats = wave_stats();
2500+ let slot = idx.min(WS_SLOTS - 1);
2387 loop {2501 loop {
2502+ let t0 = std::time::Instant::now();
2388 let mut q = st.q.lock().unwrap();2503 let mut q = st.q.lock().unwrap();
2389 let (r, c, ops) = loop {2504 let (r, c, ops) = loop {
2390- if let Some(job) = q.jobs.pop_front() {2505+ if let Some(job) = q.take_runnable(st.last_col, stats) {
2391 break job;2506 break job;
2392 }2507 }
2393- if q.closed {2508+ if q.closed && q.queued == 0 {
2394 return;2509 return;
2395 }2510 }
2396 q = st.cv.wait(q).unwrap();2511 q = st.cv.wait(q).unwrap();
2397 };2512 };
2398 q.active += 1;2513 q.active += 1;
2399- loop {
2400- let above = r == 0 || q.done[r - 1] >= (c + 1).min(st.last_col) as isize;
2401- let left = c == 0 || q.done[r] >= c as isize - 1;
2402- if above && left {
2403- break;
2404- }
2405- q = st.cv.wait(q).unwrap();
2406- }
2407 drop(q);2514 drop(q);
2515+ if stats {
2516+ WS_WAIT[slot].fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
2517+ WS_JOBS[slot].fetch_add(1, Relaxed);
2518+ WS_OPS[slot].fetch_add(ops.len() as u64, Relaxed);
2519+ }
2520+ let t1 = std::time::Instant::now();
2408 let ReconPlanes(y, u, v) = st.planes;2521 let ReconPlanes(y, u, v) = st.planes;
2409 // SAFETY: this job writes only superblock (r, c)'s own pixels, and2522 // SAFETY: this job writes only superblock (r, c)'s own pixels, and
2410 // every superblock that could have written or be reading them is2523 // every superblock that could have written or be reading them is
@@ -2415,6 +2528,9 @@ fn wave_worker(st: &WaveState) {
2415 exec_op(op, &mut *y, &mut *u, &mut *v, &mut cur, &fctx);2528 exec_op(op, &mut *y, &mut *u, &mut *v, &mut cur, &fctx);
2416 }2529 }
2417 }2530 }
2531+ if stats {
2532+ WS_BUSY[slot].fetch_add(t1.elapsed().as_nanos() as u64, Relaxed);
2533+ }
2418 let mut q = st.q.lock().unwrap();2534 let mut q = st.q.lock().unwrap();
2419 q.done[r] = c as isize;2535 q.done[r] = c as isize;
2420 q.active -= 1;2536 q.active -= 1;
@@ -2449,7 +2565,8 @@ impl<'a> WaveGuard<'a> {
2449 }2565 }
2450 let st = std::sync::Arc::new(WaveState {2566 let st = std::sync::Arc::new(WaveState {
2451 q: std::sync::Mutex::new(WaveQueue {2567 q: std::sync::Mutex::new(WaveQueue {
2452- jobs: std::collections::VecDeque::new(),2568+ rows: (0..rows).map(|_| std::collections::VecDeque::new()).collect(),
2569+ queued: 0,
2453 done: vec![-1; rows],2570 done: vec![-1; rows],
2454 active: 0,2571 active: 0,
2455 closed: false,2572 closed: false,
@@ -2467,11 +2584,12 @@ impl<'a> WaveGuard<'a> {
2467 last_col: cols - 1,2584 last_col: cols - 1,
2468 });2585 });
2469 let batch = crate::par::Batch::new("ec-av1-recon");2586 let batch = crate::par::Batch::new("ec-av1-recon");
2470- for _ in 0..threads {2587+ for idx in 0..threads {
2471 let st = std::sync::Arc::clone(&st);2588 let st = std::sync::Arc::clone(&st);
2472- batch.submit(move || wave_worker(&st));2589+ batch.submit(move || wave_worker(&st, idx));
2473 }2590 }
2474 fctx.wave.with(|w| *w.borrow_mut() = Some(st));2591 fctx.wave.with(|w| *w.borrow_mut() = Some(st));
2592+ fctx.wave_mark.with(|c| c.set(Some(std::time::Instant::now())));
2475 Some(Self(fctx, Some(batch)))2593 Some(Self(fctx, Some(batch)))
2476 }2594 }
2477 }2595 }
@@ -2483,8 +2601,14 @@ impl Drop for WaveGuard<'_> {
2483 st.q.lock().unwrap().closed = true;2601 st.q.lock().unwrap().closed = true;
2484 st.cv.notify_all();2602 st.cv.notify_all();
2485 }2603 }
2604+ let t0 = std::time::Instant::now();
2486 // Dropping the batch waits every worker out, as the joins did.2605 // Dropping the batch waits every worker out, as the joins did.
2487 drop(self.1.take());2606 drop(self.1.take());
2607+ if wave_stats() {
2608+ WS_DRAIN.fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
2609+ WS_TILES.fetch_add(1, Relaxed);
2610+ wave_stats_dump();
2611+ }
2488 }2612 }
2489 }2613 }
2490 2614
@@ -2496,9 +2620,18 @@ fn wave_submit(fctx: &crate::decode::FrameCtx, r: usize, c: usize) -> bool {
2496 let Some(st) = st else { return false };2620 let Some(st) = st else { return false };
2497 let ops = fctx.recon_ops.with(|c| std::mem::take(&mut *c.borrow_mut()));2621 let ops = fctx.recon_ops.with(|c| std::mem::take(&mut *c.borrow_mut()));
2498 if !ops.is_empty() {2622 if !ops.is_empty() {
2499- st.q.lock().unwrap().jobs.push_back((r, c, ops));2623+ let mut q = st.q.lock().unwrap();
2624+ q.rows[r].push_back((c, ops));
2625+ q.queued += 1;
2626+ drop(q);
2500 st.cv.notify_all();2627 st.cv.notify_all();
2501 }2628 }
2629+ if wave_stats() {
2630+ let now = std::time::Instant::now();
2631+ if let Some(t) = fctx.wave_mark.with(|c| c.replace(Some(now))) {
2632+ WS_PARSE.fetch_add((now - t).as_nanos() as u64, Relaxed);
2633+ }
2634+ }
2502 true2635 true
2503 }2636 }
2504 2637
@@ -2508,10 +2641,17 @@ fn wave_submit(fctx: &crate::decode::FrameCtx, r: usize, c: usize) -> bool {
2508 fn wave_barrier(fctx: &crate::decode::FrameCtx) {2641 fn wave_barrier(fctx: &crate::decode::FrameCtx) {
2509 let st = fctx.wave.with(|w| w.borrow().clone());2642 let st = fctx.wave.with(|w| w.borrow().clone());
2510 let Some(st) = st else { return };2643 let Some(st) = st else { return };
2644+ let stats = wave_stats();
2645+ let t0 = std::time::Instant::now();
2511 let mut q = st.q.lock().unwrap();2646 let mut q = st.q.lock().unwrap();
2512- while !q.jobs.is_empty() || q.active > 0 {2647+ while q.queued > 0 || q.active > 0 {
2513 q = st.cv.wait(q).unwrap();2648 q = st.cv.wait(q).unwrap();
2514 }2649 }
2650+ drop(q);
2651+ if stats {
2652+ WS_BARRIER.fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
2653+ WS_BARRIERS.fetch_add(1, Relaxed);
2654+ }
2515 }2655 }
2516 2656
2517 /// Performs an intra write at its push site when the tile registered its2657 /// Performs an intra write at its push site when the tile registered its