forge
Explore
Log in

Don't you dare go Hollow

Recorded reconstruction ops index per-superblock arenas instead of owning a Vec each

Browse files at this commit

ba6ddd494c2d058d9b674a2e4d406f4b50d4122cAhmet Kaan GümüşParent: 6d124e3
  • perf
    • recorded reconstruction ops index per-superblock arenas instead of owning a Vec each
Show full message
perf(av1): recorded reconstruction ops index per-superblock arenas instead of owning a Vec each

A recorded transform unit copied its coefficient grid (`grid.to_vec()`) and
a recorded motion-compensated write copied its prediction window into a
fresh `Vec`, both on the parse thread, both freed on a recon worker: ~7.1 M
malloc/free pairs across the 4K segment, with `_int_malloc` on the frame
thread and `_int_free_chunk` on the workers.

The tile now carries two arenas (`FrameCtx::coeff_arena`, `pred_arena`); a
record is an `(offset, len)` into them. They are handed over WITH the ops at
both drain points -- `wave_submit` moves them into the job (`ReconJob`), so
one buffer per superblock reaches the worker instead of one per unit, and
`flush_recon` swaps them through spares -- which keeps every offset relative
to the live arena and every write byte-identical.

instructions:u on the 4K segment at (16 frame, 4 filter, 2 recon) threads:
456.25 G -> 453.00 G (-0.72%); wall on this box is load-dominated and does
not resolve it.
crates/ec-av1/src/decode.rsmodified+143 -38
@@ -85,6 +85,20 @@ pub(crate) struct FrameCtx {
8585 /// The queue buffer [`flush_recon`] just drained, kept for its capacity
8686 /// so a superblock's records do not regrow the vector from nothing.
8787 pub(crate) recon_spare: std::cell::RefCell<Vec<ReconOp>>,
88+ /// lane-recoparse: the coefficient grids of the recorded ops above, one
89+ /// buffer instead of a `Vec` per transform unit -- a recorded unit is
90+ /// `(offset, len)` into it ([`Residual::Coeffs`]). Written by parse
91+ /// before the op is published, read only by whoever replays that op, and
92+ /// handed over WITH the ops at every drain point ([`wave_submit`],
93+ /// [`flush_recon`]), so offsets are always relative to the live arena.
94+ pub(crate) coeff_arena: std::cell::RefCell<Vec<i32>>,
95+ /// [`recon_spare`](Self::recon_spare) for the arena, on the inline drain
96+ /// path (a submitted job's arena travels to its worker instead).
97+ pub(crate) coeff_spare: std::cell::RefCell<Vec<i32>>,
98+ /// [`coeff_arena`](Self::coeff_arena) for the recorded PREDICTIONS
99+ /// ([`PredSrc::Owned`]): same lifetime, same drain points.
100+ pub(crate) pred_arena: std::cell::RefCell<Vec<u16>>,
101+ pub(crate) pred_spare: std::cell::RefCell<Vec<u16>>,
88102 /// lane-wave1 step (ii): the tile decoder's own planes, registered by
89103 /// [`ReconInline`] while reconstruction runs INLINE (one recon thread).
90104 /// `None` while the queue is in use (wavefront workers) and outside a
@@ -155,6 +169,10 @@ impl FrameCtx {
155169 grain_bit_depth: std::cell::Cell::new(8),
156170 recon_ops: std::cell::RefCell::new(Vec::new()),
157171 recon_spare: std::cell::RefCell::new(Vec::new()),
172+ coeff_arena: std::cell::RefCell::new(Vec::new()),
173+ coeff_spare: std::cell::RefCell::new(Vec::new()),
174+ pred_arena: std::cell::RefCell::new(Vec::new()),
175+ pred_spare: std::cell::RefCell::new(Vec::new()),
158176 recon_planes: std::cell::Cell::new(None),
159177 wave: std::cell::RefCell::new(None),
160178 wave_mark: std::cell::Cell::new(None),
@@ -2108,29 +2126,66 @@ impl TxParams {
21082126 /// A recorded write's residual: already transformed, or the coefficients and
21092127 /// [`TxParams`] the worker transforms itself.
21102128 pub(crate) enum Residual {
2111- Done(Vec<i32>),
2112- Coeffs(TxParams, Vec<i32>),
2129+ /// An already-transformed residual in the arena, `(offset, len)`; a zero
2130+ /// `len` is the all-zero marker [`dense_residual`] expands.
2131+ Done(u32, u32),
2132+ /// The coefficients live in the pushing tile's arena
2133+ /// ([`crate::decode::FrameCtx::coeff_arena`]); this is their `(offset,
2134+ /// len)` in it.
2135+ Coeffs(TxParams, u32, u32),
21132136 }
21142137
21152138 impl Residual {
21162139 /// The record for a transform unit whose coefficient grid is all zero:
21172140 /// the empty marker, so neither the grid nor the residual is cloned and
21182141 /// the worker never runs the transform (60% of the 4K segment's units).
2119- fn coeffs(tx: TxParams, grid: &[i32]) -> Self {
2142+ fn coeffs(tx: TxParams, grid: &[i32], fctx: &crate::decode::FrameCtx) -> Self {
21202143 if grid.iter().all(|&c| c == 0) {
2121- return Self::Done(Vec::new());
2144+ return Self::Done(0, 0);
21222145 }
2123- Self::Coeffs(tx, grid.to_vec())
2146+ Self::Coeffs(tx, push_coeffs(grid, fctx), grid.len() as u32)
21242147 }
21252148
2126- fn resolve(self) -> Vec<i32> {
2149+ /// A residual the parse thread already transformed, kept in the arena
2150+ /// instead of its own `Vec`.
2151+ fn done(residual: &[i32], fctx: &crate::decode::FrameCtx) -> Self {
2152+ Self::Done(push_coeffs(residual, fctx), residual.len() as u32)
2153+ }
2154+
2155+ /// The residual to reconstruct with; `scratch` is where a transform run
2156+ /// on this thread lands, so the caller owns that buffer.
2157+ fn resolve<'a>(self, arena: &'a [i32], scratch: &'a mut Vec<i32>) -> &'a [i32] {
21272158 match self {
2128- Self::Done(v) => v,
2129- Self::Coeffs(p, grid) => p.run(&grid),
2159+ Self::Done(off, len) => &arena[off as usize..][..len as usize],
2160+ Self::Coeffs(p, off, len) => {
2161+ *scratch = p.run(&arena[off as usize..][..len as usize]);
2162+ scratch
2163+ }
21302164 }
21312165 }
21322166 }
21332167
2168+/// Appends to the tile's coefficient arena, returning the offset the record
2169+/// carries; see [`crate::decode::FrameCtx::coeff_arena`].
2170+fn push_coeffs(v: &[i32], fctx: &crate::decode::FrameCtx) -> u32 {
2171+ fctx.coeff_arena.with(|a| {
2172+ let mut a = a.borrow_mut();
2173+ let off = a.len();
2174+ a.extend_from_slice(v);
2175+ off as u32
2176+ })
2177+}
2178+
2179+/// [`push_coeffs`] for a recorded prediction.
2180+fn push_pred_samples(v: &[u16], fctx: &crate::decode::FrameCtx) -> u32 {
2181+ fctx.pred_arena.with(|a| {
2182+ let mut a = a.borrow_mut();
2183+ let off = a.len();
2184+ a.extend_from_slice(v);
2185+ off as u32
2186+ })
2187+}
2188+
21342189 /// An all-zero residual, for the transform units that code no coefficient:
21352190 /// [`crate::transform::dequant_and_inverse_typed_wh`] returns those EMPTY,
21362191 /// and the reconstruction loops below read this instead of a per-unit
@@ -2192,7 +2247,8 @@ impl<'a> Pred<'a> {
21922247
21932248 /// [`Pred`], resolved into what a recorded op carries.
21942249 pub(crate) enum PredSrc {
2195- Owned(Vec<u16>),
2250+ /// A prediction window in the tile's prediction arena, `(offset, len)`.
2251+ Owned(u32, u32),
21962252 /// A window of the block prediction: its plane, its offset, and the
21972253 /// stride it is read at -- which is the block's, not necessarily the
21982254 /// op's (a transform unit's residual stays dense, so the worker takes
@@ -2255,6 +2311,14 @@ fn push_pred<'a>(
22552311 push_op(fctx, ReconOp::Pred(PredBuild(boxed)));
22562312 }
22572313
2314+/// One superblock's recorded writes plus the two arenas they index -- the
2315+/// unit a wavefront worker takes off the queue (lane-recoparse).
2316+pub(crate) struct ReconJob {
2317+ ops: Vec<ReconOp>,
2318+ coeffs: Vec<i32>,
2319+ preds: Vec<u16>,
2320+}
2321+
22582322 pub(crate) enum ReconOp {
22592323 /// lane-wave4: build this block's prediction into the worker's slot.
22602324 Pred(PredBuild),
@@ -2367,7 +2431,11 @@ fn push_op(fctx: &crate::decode::FrameCtx, op: ReconOp) {
23672431 if let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) {
23682432 // SAFETY: see [`ReconPlanes`] -- one thread, and the write is the one
23692433 // the parse site would have performed itself before lane-wave1.
2370- unsafe { exec_op(op, &mut *y, &mut *u, &mut *v, &mut Default::default(), fctx) };
2434+ // The inline path never records coefficients (the transform runs at
2435+ // the push site), so the arena is not read here.
2436+ unsafe {
2437+ exec_op(op, &mut *y, &mut *u, &mut *v, &mut Default::default(), &[], &[], fctx)
2438+ };
23712439 return;
23722440 }
23732441 fctx.recon_ops.with(|c| c.borrow_mut().push(op));
@@ -2408,7 +2476,7 @@ struct WaveQueue {
24082476 /// dependencies are met. Popping the raster-oldest job instead (what
24092477 /// this replaced) put every worker on the SAME row, where the wavefront
24102478 /// rule serialises them, which is why 4 workers ran the tile at 1.2x.
2411- rows: Vec<std::collections::VecDeque<(usize, Vec<ReconOp>)>>,
2479+ rows: Vec<std::collections::VecDeque<(usize, ReconJob)>>,
24122480 /// Jobs sitting in `rows`, so a worker knows the queue is empty without
24132481 /// walking it.
24142482 queued: usize,
@@ -2422,7 +2490,11 @@ struct WaveQueue {
24222490 impl WaveQueue {
24232491 /// The lowest-row queued job whose wavefront dependencies are satisfied,
24242492 /// or `None` (with the blocking condition counted when instrumented).
2425- fn take_runnable(&mut self, last_col: usize, stats: bool) -> Option<(usize, usize, Vec<ReconOp>)> {
2493+ fn take_runnable(
2494+ &mut self,
2495+ last_col: usize,
2496+ stats: bool,
2497+ ) -> Option<(usize, usize, ReconJob)> {
24262498 let mut blocked: Option<bool> = None;
24272499 for r in 0..self.rows.len() {
24282500 let Some(front) = self.rows[r].front() else {
@@ -2432,9 +2504,9 @@ impl WaveQueue {
24322504 let above = r == 0 || self.done[r - 1] >= (c + 1).min(last_col) as isize;
24332505 let left = c == 0 || self.done[r] >= c as isize - 1;
24342506 if above && left {
2435- let (c, ops) = self.rows[r].pop_front().expect("front checked above");
2507+ let (c, job) = self.rows[r].pop_front().expect("front checked above");
24362508 self.queued -= 1;
2437- return Some((r, c, ops));
2509+ return Some((r, c, job));
24382510 }
24392511 if blocked.is_none() {
24402512 blocked = Some(above);
@@ -2528,7 +2600,7 @@ fn wave_worker(st: &WaveState, idx: usize) {
25282600 loop {
25292601 let t0 = std::time::Instant::now();
25302602 let mut q = st.q.lock().unwrap();
2531- let (r, c, ops) = loop {
2603+ let (r, c, job) = loop {
25322604 if let Some(job) = q.take_runnable(st.last_col, stats) {
25332605 break job;
25342606 }
@@ -2542,7 +2614,7 @@ fn wave_worker(st: &WaveState, idx: usize) {
25422614 if stats {
25432615 WS_WAIT[slot].fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
25442616 WS_JOBS[slot].fetch_add(1, Relaxed);
2545- WS_OPS[slot].fetch_add(ops.len() as u64, Relaxed);
2617+ WS_OPS[slot].fetch_add(job.ops.len() as u64, Relaxed);
25462618 }
25472619 let t1 = std::time::Instant::now();
25482620 let ReconPlanes(y, u, v) = st.planes;
@@ -2551,8 +2623,8 @@ fn wave_worker(st: &WaveState, idx: usize) {
25512623 // complete by the wavefront rule above.
25522624 let mut cur: [Vec<u16>; 3] = Default::default();
25532625 unsafe {
2554- for op in ops {
2555- exec_op(op, &mut *y, &mut *u, &mut *v, &mut cur, &fctx);
2626+ for op in job.ops {
2627+ exec_op(op, &mut *y, &mut *u, &mut *v, &mut cur, &job.coeffs, &job.preds, &fctx);
25562628 }
25572629 }
25582630 if stats {
@@ -2646,9 +2718,22 @@ fn wave_submit(fctx: &crate::decode::FrameCtx, r: usize, c: usize) -> bool {
26462718 let st = fctx.wave.with(|w| w.borrow().clone());
26472719 let Some(st) = st else { return false };
26482720 let ops = fctx.recon_ops.with(|c| std::mem::take(&mut *c.borrow_mut()));
2721+ // The job owns its coefficients: the arena is replaced by an empty one
2722+ // sized for the next superblock, so parse never regrows from nothing and
2723+ // the worker frees this buffer once, instead of once per unit.
2724+ let coeffs = fctx.coeff_arena.with(|c| {
2725+ let mut c = c.borrow_mut();
2726+ let cap = c.len();
2727+ std::mem::replace(&mut *c, Vec::with_capacity(cap))
2728+ });
2729+ let preds = fctx.pred_arena.with(|c| {
2730+ let mut c = c.borrow_mut();
2731+ let cap = c.len();
2732+ std::mem::replace(&mut *c, Vec::with_capacity(cap))
2733+ });
26492734 if !ops.is_empty() {
26502735 let mut q = st.q.lock().unwrap();
2651- q.rows[r].push_back((c, ops));
2736+ q.rows[r].push_back((c, ReconJob { ops, coeffs, preds }));
26522737 q.queued += 1;
26532738 drop(q);
26542739 st.cv.notify_all();
@@ -2764,7 +2849,7 @@ fn push_intra(
27642849 let pred = take_palette_pred(fctx);
27652850 push_op(fctx, ReconOp::Intra {
27662851 plane, x, y, bw: side, bh: side, rect: false, mode, angle_delta, reach,
2767- residual: Residual::Done(residual.to_vec()), cfl, filter_intra, smooth_neighbor, pred,
2852+ residual: Residual::done(residual, fctx), cfl, filter_intra, smooth_neighbor, pred,
27682853 });
27692854 }
27702855
@@ -2793,7 +2878,7 @@ fn push_intra_rect(
27932878 let pred = take_palette_pred(fctx);
27942879 push_op(fctx, ReconOp::Intra {
27952880 plane, x, y, bw, bh, rect: true, mode, angle_delta, reach,
2796- residual: Residual::Done(residual.to_vec()), cfl, filter_intra, smooth_neighbor, pred,
2881+ residual: Residual::done(residual, fctx), cfl, filter_intra, smooth_neighbor, pred,
27972882 });
27982883 }
27992884
@@ -2828,7 +2913,7 @@ fn push_mc_rect(
28282913 push_op(fctx, ReconOp::Mc {
28292914 plane, x, y, stride: ss, w, h,
28302915 prediction: PredSrc::Cur { plane: sp, off, src: ss },
2831- residual: Residual::Done(residual.to_vec()),
2916+ residual: Residual::done(residual, fctx),
28322917 });
28332918 return;
28342919 }
@@ -2838,7 +2923,10 @@ fn push_mc_rect(
28382923 }
28392924 push_op(fctx, ReconOp::Mc {
28402925 plane, x, y, stride, w, h,
2841- prediction: PredSrc::Owned(src.to_vec()), residual: Residual::Done(residual.to_vec()),
2926+ // The whole window `reconstruct_mc_rect` reads at `stride`, not
2927+ // `w * h`: the record keeps exactly what `src.to_vec()` carried.
2928+ prediction: PredSrc::Owned(push_pred_samples(src, fctx), src.len() as u32),
2929+ residual: Residual::done(residual, fctx),
28422930 });
28432931 }
28442932
@@ -2873,7 +2961,7 @@ fn push_intra_tx(
28732961 let pred = take_palette_pred(fctx);
28742962 push_op(fctx, ReconOp::Intra {
28752963 plane, x, y, bw, bh, rect, mode, angle_delta, reach,
2876- residual: Residual::coeffs(tx, grid), cfl, filter_intra, smooth_neighbor, pred,
2964+ residual: Residual::coeffs(tx, grid, fctx), cfl, filter_intra, smooth_neighbor, pred,
28772965 });
28782966 }
28792967
@@ -2904,7 +2992,7 @@ fn push_mc_rect_tx(
29042992 push_op(fctx, ReconOp::Mc {
29052993 plane, x, y, stride: w, w, h,
29062994 prediction: PredSrc::Cur { plane: sp, off, src: ss },
2907- residual: Residual::coeffs(tx, grid),
2995+ residual: Residual::coeffs(tx, grid, fctx),
29082996 });
29092997 return;
29102998 }
@@ -2937,15 +3025,19 @@ fn push_mc_rect_tx(
29373025 // copied 64*64 samples on the PARSING thread before. The residual is then
29383026 // produced dense too (`TxParams::stride = 0`), which is the same numbers
29393027 // in the same places at stride `w`.
2940- let mut window = Vec::with_capacity(w * h);
2941- for row in 0..h {
2942- window.extend_from_slice(&prediction[row * stride..][..w]);
2943- }
3028+ let off = fctx.pred_arena.with(|a| {
3029+ let mut a = a.borrow_mut();
3030+ let off = a.len();
3031+ for row in 0..h {
3032+ a.extend_from_slice(&prediction[row * stride..][..w]);
3033+ }
3034+ off as u32
3035+ });
29443036 let mut tx = tx;
29453037 tx.stride = 0;
29463038 push_op(fctx, ReconOp::Mc {
2947- plane, x, y, stride: w, w, h, prediction: PredSrc::Owned(window),
2948- residual: Residual::coeffs(tx, grid),
3039+ plane, x, y, stride: w, w, h, prediction: PredSrc::Owned(off, (w * h) as u32),
3040+ residual: Residual::coeffs(tx, grid, fctx),
29493041 });
29503042 }
29513043
@@ -2968,11 +3060,19 @@ fn flush_recon(
29683060 wave_barrier(fctx);
29693061 let mut ops = fctx.recon_spare.with(|c| std::mem::take(&mut *c.borrow_mut()));
29703062 fctx.recon_ops.with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut ops));
3063+ let mut coeffs = fctx.coeff_spare.with(|c| std::mem::take(&mut *c.borrow_mut()));
3064+ fctx.coeff_arena.with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut coeffs));
3065+ let mut preds = fctx.pred_spare.with(|c| std::mem::take(&mut *c.borrow_mut()));
3066+ fctx.pred_arena.with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut preds));
29713067 let mut cur: [Vec<u16>; 3] = Default::default();
29723068 for op in ops.drain(..) {
2973- exec_op(op, y, u, v, &mut cur, fctx);
3069+ exec_op(op, y, u, v, &mut cur, &coeffs, &preds, fctx);
29743070 }
3071+ coeffs.clear();
3072+ preds.clear();
29753073 fctx.recon_spare.with(|c| *c.borrow_mut() = ops);
3074+ fctx.coeff_spare.with(|c| *c.borrow_mut() = coeffs);
3075+ fctx.pred_spare.with(|c| *c.borrow_mut() = preds);
29763076 }
29773077
29783078 /// Performs one recorded write: the body [`flush_recon`] replays, and the
@@ -2983,27 +3083,32 @@ fn exec_op(
29833083 u: &mut PlaneBuf<'static>,
29843084 v: &mut PlaneBuf<'static>,
29853085 cur: &mut [Vec<u16>; 3],
3086+ coeffs: &[i32],
3087+ preds: &[u16],
29863088 fctx: &crate::decode::FrameCtx,
29873089 ) {
3090+ let mut scratch = Vec::new();
29883091 match op {
29893092 ReconOp::Pred(b) => *cur = (b.0)(y, u, v, fctx),
29903093 ReconOp::Intra {
29913094 plane, x, y: oy, bw, bh, rect, mode, angle_delta, reach, residual, cfl,
29923095 filter_intra, smooth_neighbor, pred,
29933096 } => exec_intra(
2994- y, u, v, plane, x, oy, bw, bh, rect, mode, angle_delta, reach, &residual.resolve(),
3097+ y, u, v, plane, x, oy, bw, bh, rect, mode, angle_delta, reach,
3098+ residual.resolve(coeffs, &mut scratch),
29953099 cfl, filter_intra, smooth_neighbor, pred, fctx,
29963100 ),
29973101 ReconOp::Mc { plane, x, y: oy, stride, w, h, prediction, residual } => {
2998- let residual = residual.resolve();
3102+ let residual = residual.resolve(coeffs, &mut scratch);
29993103 match prediction {
3000- PredSrc::Owned(p) => {
3001- exec_mc(y, u, v, plane, x, oy, stride, w, h, &p, &residual, fctx);
3104+ PredSrc::Owned(off, len) => {
3105+ let p = &preds[off as usize..][..len as usize];
3106+ exec_mc(y, u, v, plane, x, oy, stride, w, h, p, residual, fctx);
30023107 }
30033108 PredSrc::Cur { plane: sp, off, src } => {
30043109 let block = std::mem::take(&mut cur[sp]);
30053110 if src == stride {
3006- exec_mc(y, u, v, plane, x, oy, stride, w, h, &block[off..], &residual, fctx);
3111+ exec_mc(y, u, v, plane, x, oy, stride, w, h, &block[off..], residual, fctx);
30073112 } else {
30083113 // A transform unit's residual is dense, so its window
30093114 // of the block prediction is taken out dense too --
@@ -3012,7 +3117,7 @@ fn exec_op(
30123117 for row in 0..h {
30133118 window.extend_from_slice(&block[off + row * src..][..w]);
30143119 }
3015- exec_mc(y, u, v, plane, x, oy, stride, w, h, &window, &residual, fctx);
3120+ exec_mc(y, u, v, plane, x, oy, stride, w, h, &window, residual, fctx);
30163121 }
30173122 cur[sp] = block;
30183123 }