forge
Explore
Log in

Don't you dare go Hollow

Band the encoder's frame-level filter stage across the tile workers

Browse files at this commit

996b58754774f663abcb138396901963ac3aba9fAhmet Kaan GümüşParent: 8a4a771
  • perf
    • band the encoder's frame-level filter stage across the tile workers
Show full message
perf(av1): band the encoder's frame-level filter stage across the tile workers

The per-tile search leaves every core idle for the rest of the frame. The
filter stage now bands itself across the same workers:
`par::override_filter_threads` (thread-local, so nothing outside this span
changes) puts the deblock and CDEF replays, the capture decode's own filter
chain and the loop-restoration passes on the decoder's existing band split,
the per-64 SSE gets a unit-row band of its own (`unit_sse_rows`, partial
u64 sums), and a candidate's ~6 MB plane copies come off a recycled buffer
pool -- a fresh Vec per copy was 12.6% of a 1080p frame's wall in page
faults alone -- banded when the buffer is already the right length.

Gated by `filter_stage_bytes_do_not_depend_on_the_thread_count` (one tile,
a cropping size, 1 vs 2/4/8 threads) and by `unit_sse_matches_the_naive_sum`
at 2/4/8 bands.
crates/ec-av1/src/decode.rsmodified+61 -13
@@ -19729,6 +19729,12 @@ pub(crate) struct FilterReplay {
19729 /// stash the cropped return path leaves behind.19729 /// stash the cropped return path leaves behind.
19730 true_width: usize,19730 true_width: usize,
19731 true_height: usize,19731 true_height: usize,
19732+ /// lane-av1fpar: plane buffers this replay is done with. Every candidate
19733+ /// works on its own copy of three ~6 MB planes, and a fresh `Vec` per
19734+ /// copy is a fresh mmap the kernel faults in page by page -- 12.6% of a
19735+ /// 1080p frame's wall in allocation, not in filtering. Recycled here
19736+ /// instead; the pool holds at most the six planes one candidate has live.
19737+ scratch: Vec<Vec<u16>>,
19732 /// The last deblocked planes and the levels that produced them.19738 /// The last deblocked planes and the levels that produced them.
19733 /// Deblocking depends on nothing else the search moves, and the search19739 /// Deblocking depends on nothing else the search moves, and the search
19734 /// fixes the levels before it walks the CDEF strengths, so every19740 /// fixes the levels before it walks the CDEF strengths, so every
@@ -19796,11 +19802,36 @@ fn capture_filter_replay(
19796 height,19802 height,
19797 true_width,19803 true_width,
19798 true_height,19804 true_height,
19805+ scratch: Vec::new(),
19799 deblocked: None,19806 deblocked: None,
19800 });19807 });
19801 });19808 });
19802 }19809 }
19803 19810
19811+/// One candidate's working copy of a captured plane, off [`FilterReplay`]'s
19812+/// own buffer pool: a cleared `Vec` that already has the capacity keeps the
19813+/// allocator and the page fault handler out of the filter search.
19814+fn pooled(p: &PlaneBuf<'_>, scratch: &mut Vec<Vec<u16>>) -> PlaneBuf<'static> {
19815+ let mut buf = scratch.pop().unwrap_or_default();
19816+ let src: &[u16] = &p.data;
19817+ let threads = crate::par::filter_threads();
19818+ if buf.len() != src.len() || threads <= 1 {
19819+ buf.clear();
19820+ buf.extend_from_slice(src);
19821+ } else {
19822+ // A recycled buffer is already the right length, so the copy is a
19823+ // plain `copy_from_slice` -- and one worth banding: ~6 MB per
19824+ // candidate is memory bandwidth, not arithmetic, and the halves are
19825+ // disjoint `&mut` slices (no `par::Shared` needed).
19826+ let per = src.len().div_ceil(threads);
19827+ let batch = crate::par::Batch::new("ec-av1-filter");
19828+ for (dst, src) in buf.chunks_mut(per).zip(src.chunks(per)) {
19829+ batch.submit(move || dst.copy_from_slice(src));
19830+ }
19831+ }
19832+ PlaneBuf { data: std::borrow::Cow::Owned(buf), ..*p }
19833+}
19834+
19804 /// The filter half of a captured decode, under new parameters: exactly the19835 /// The filter half of a captured decode, under new parameters: exactly the
19805 /// [`apply_deblock`] / [`apply_cdef`] pair the decoder's own tail runs, on a19836 /// [`apply_deblock`] / [`apply_cdef`] pair the decoder's own tail runs, on a
19806 /// copy of the captured planes. `None` when nothing is captured (the caller19837 /// copy of the captured planes. `None` when nothing is captured (the caller
@@ -19816,16 +19847,23 @@ pub(crate) fn replay_filters(
19816 }19847 }
19817 REPLAY.with_borrow_mut(|slot| {19848 REPLAY.with_borrow_mut(|slot| {
19818 let r = slot.as_mut()?;19849 let r = slot.as_mut()?;
19819- let copy = |p: &PlaneBuf<'_>| PlaneBuf {
19820- data: std::borrow::Cow::Owned(p.data.to_vec()),
19821- ..*p
19822- };
19823 let hit = matches!(&r.deblocked, Some((lf, ..)) if lf == loop_filter);19850 let hit = matches!(&r.deblocked, Some((lf, ..)) if lf == loop_filter);
19851+ let cpt = crate::par::timer(crate::par::S_COPY);
19824 let (mut y, mut u, mut v) = if hit {19852 let (mut y, mut u, mut v) = if hit {
19825- let (_, dy, du, dv) = r.deblocked.as_ref().expect("just matched");19853+ let (deblocked, scratch) = (&r.deblocked, &mut r.scratch);
19826- (copy(dy), copy(du), copy(dv))19854+ let (_, dy, du, dv) = deblocked.as_ref().expect("just matched");
19855+ (pooled(dy, scratch), pooled(du, scratch), pooled(dv, scratch))
19827 } else {19856 } else {
19828- let (mut y, mut u, mut v) = (copy(&r.y), copy(&r.u), copy(&r.v));19857+ // The levels moved, so the cached deblocked planes are dead:
19858+ // their buffers are this candidate's working copies.
19859+ if let Some((_, dy, du, dv)) = r.deblocked.take() {
19860+ r.scratch.push(dy.data.into_owned());
19861+ r.scratch.push(du.data.into_owned());
19862+ r.scratch.push(dv.data.into_owned());
19863+ }
19864+ let (cap_y, cap_u, cap_v, scratch) = (&r.y, &r.u, &r.v, &mut r.scratch);
19865+ let (mut y, mut u, mut v) =
19866+ (pooled(cap_y, scratch), pooled(cap_u, scratch), pooled(cap_v, scratch));
19829 let _t = crate::par::timer(crate::par::S_DEBLOCK);19867 let _t = crate::par::timer(crate::par::S_DEBLOCK);
19830 apply_deblock(19868 apply_deblock(
19831 &mut y,19869 &mut y,
@@ -19837,9 +19875,12 @@ pub(crate) fn replay_filters(
19837 r.frame_height,19875 r.frame_height,
19838 fctx,19876 fctx,
19839 );19877 );
19840- r.deblocked = Some((*loop_filter, copy(&y), copy(&u), copy(&v)));19878+ let scratch = &mut r.scratch;
19879+ r.deblocked =
19880+ Some((*loop_filter, pooled(&y, scratch), pooled(&u, scratch), pooled(&v, scratch)));
19841 (y, u, v)19881 (y, u, v)
19842 };19882 };
19883+ drop(cpt);
19843 let ct = crate::par::timer(crate::par::S_CDEF);19884 let ct = crate::par::timer(crate::par::S_CDEF);
19844 apply_cdef(&mut y, &mut u, &mut v, cdef, &r.neighbours, (r.frame_width, r.frame_height), fctx);19885 apply_cdef(&mut y, &mut u, &mut v, cdef, &r.neighbours, (r.frame_width, r.frame_height), fctx);
19845 drop(ct);19886 drop(ct);
@@ -19881,13 +19922,20 @@ pub(crate) fn replay_filters(
19881 v: crop(&v, tw.div_ceil(2), th.div_ceil(2)),19922 v: crop(&v, tw.div_ceil(2), th.div_ceil(2)),
19882 });19923 });
19883 });19924 });
19884- Some(Picture {19925+ let out = Picture {
19885 width: fw,19926 width: fw,
19886 height: fh,19927 height: fh,
19887- y: crop_owned(y, fw, fh),19928+ y: crop(&y, fw, fh),
19888- u: crop_owned(u, fw.div_ceil(2), fh.div_ceil(2)),19929+ u: crop(&u, fw.div_ceil(2), fh.div_ceil(2)),
19889- v: crop_owned(v, fw.div_ceil(2), fh.div_ceil(2)),19930+ v: crop(&v, fw.div_ceil(2), fh.div_ceil(2)),
19890- })19931+ };
19932+ // The working planes outlive the crop, so they go back to the pool.
19933+ for plane in [y, u, v] {
19934+ if r.scratch.len() < 6 {
19935+ r.scratch.push(plane.data.into_owned());
19936+ }
19937+ }
19938+ Some(out)
19891 })19939 })
19892 }19940 }
19893 19941
crates/ec-av1/src/encode.rsmodified+6 -0
@@ -4146,6 +4146,11 @@ fn pick_and_apply_filters(
4146 // preset search reads comes off the REPLAYED picture, which is the same4146 // preset search reads comes off the REPLAYED picture, which is the same
4147 // picture a decode produces -- that is what the replay is pinned on.4147 // picture a decode produces -- that is what the replay is pinned on.
4148 crate::decode::clear_filter_replay();4148 crate::decode::clear_filter_replay();
4149+ // lane-av1fpar: the per-tile search is over, so every core is idle from
4150+ // here to the end of the frame -- band each candidate's deblock/CDEF
4151+ // replay, the capture decode's own filter chain and the loop-restoration
4152+ // passes across the same workers the search used.
4153+ let _bands = crate::par::override_filter_threads(crate::par::tile_threads());
4149 let ft = crate::par::timer(crate::par::S_FILTER);4154 let ft = crate::par::timer(crate::par::S_FILTER);
4150 let search_result = crate::filter_search::pick_filters(4155 let search_result = crate::filter_search::pick_filters(
4151 |lf, cdef| {4156 |lf, cdef| {
@@ -4153,6 +4158,7 @@ fn pick_and_apply_filters(
4153 return Ok(picture);4158 return Ok(picture);
4154 }4159 }
4155 crate::decode::arm_filter_replay();4160 crate::decode::arm_filter_replay();
4161+ let _t = crate::par::timer(crate::par::S_FIRST);
4156 decode(lf, cdef, &hdr, tiles, &none_lr)4162 decode(lf, cdef, &hdr, tiles, &none_lr)
4157 },4163 },
4158 source,4164 source,
crates/ec-av1/src/encoder.rsmodified+37 -0
@@ -1862,6 +1862,43 @@ mod tests {
1862 tile_search_wall(3840, 1608, 6, &[(2, 1), (3, 2)], &[1, 8, 12]);1862 tile_search_wall(3840, 1608, 6, &[(2, 1), (3, 2)], &[1, 8, 12]);
1863 }1863 }
1864 1864
1865+ /// lane-av1fpar: the frame-level FILTER stage is banded across the same
1866+ /// workers the tile search uses (`par::override_filter_threads`), so the
1867+ /// deblock/CDEF replays, the per-64 SSE and the plane copies all run in
1868+ /// pieces. Every piece is a disjoint band of the same integers, so the
1869+ /// stream must not move -- at a size that crops and is several superblock
1870+ /// rows tall, which is what makes the bands non-trivial.
1871+ #[test]
1872+ fn filter_stage_bytes_do_not_depend_on_the_thread_count() {
1873+ let _gate_lock = crate::stream::tests::lock_gate_counters();
1874+ let (width, height) = (384usize, 288usize);
1875+ let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
1876+ let coded = |threads: usize| {
1877+ crate::par::set_tile_threads(threads);
1878+ let config = EncoderConfig {
1879+ width,
1880+ height,
1881+ base_q_idx: 120,
1882+ gop: 2,
1883+ colour: Colour::Bt709Limited,
1884+ tile_cols_log2: 0,
1885+ tile_rows_log2: 0,
1886+ };
1887+ let mut enc = Av1Encoder::new(config).unwrap();
1888+ let mut stream = Vec::new();
1889+ for picture in &sources {
1890+ stream.extend_from_slice(&enc.encode(picture).unwrap().data);
1891+ }
1892+ stream
1893+ };
1894+ // One tile, so only the filter stage can differ between these.
1895+ let one = coded(1);
1896+ for threads in [2usize, 4, 8] {
1897+ assert_eq!(one, coded(threads), "the filter stage moved at {threads} threads");
1898+ }
1899+ crate::par::set_tile_threads(1);
1900+ }
1901+
1865 /// lane-av1fpar: the filter search scores its ~30 candidates by replaying1902 /// lane-av1fpar: the filter search scores its ~30 candidates by replaying
1866 /// the loop filters on one captured reconstruction instead of decoding1903 /// the loop filters on one captured reconstruction instead of decoding
1867 /// the coded tile again per candidate. The replay must be that decode,1904 /// the coded tile again per candidate. The replay must be that decode,
crates/ec-av1/src/filter_search.rsmodified+56 -2
@@ -81,10 +81,52 @@ fn unit_sse(
81 unit: usize,81 unit: usize,
82 sb_cols: usize,82 sb_cols: usize,
83 out: &mut [u64],83 out: &mut [u64],
84+) -> u64 {
85+ // lane-av1fpar: the whole-frame pass, split across the filter workers by
86+ // UNIT ROW -- each band owns its own rows of `out` (`chunks_mut`, so the
87+ // disjointness is the borrow checker's) and its partial totals are `u64`
88+ // integers, which add up to the same value in any order.
89+ let threads = crate::par::filter_threads().min(h.div_ceil(unit));
90+ if threads <= 1 {
91+ return unit_sse_rows(dec, dec_w, src, src_w, w, 0, h, unit, sb_cols, out);
92+ }
93+ let per = h.div_ceil(unit).div_ceil(threads);
94+ let total = std::sync::atomic::AtomicU64::new(0);
95+ {
96+ let batch = crate::par::Batch::new("ec-av1-filter");
97+ for (band, rows) in out.chunks_mut(per * sb_cols).enumerate() {
98+ let (r0, r1) = ((band * per * unit).min(h), ((band + 1) * per * unit).min(h));
99+ if r0 == r1 {
100+ continue;
101+ }
102+ let total = &total;
103+ batch.submit(move || {
104+ let sse = unit_sse_rows(dec, dec_w, src, src_w, w, r0, r1, unit, sb_cols, rows);
105+ total.fetch_add(sse, std::sync::atomic::Ordering::Relaxed);
106+ });
107+ }
108+ }
109+ total.into_inner()
110+}
111+
112+/// [`unit_sse`] over rows `r0..r1` alone, accumulating into `out` as if it
113+/// started at unit row `r0 / unit`.
114+#[allow(clippy::too_many_arguments)]
115+fn unit_sse_rows(
116+ dec: &[u16],
117+ dec_w: usize,
118+ src: &[u8],
119+ src_w: usize,
120+ w: usize,
121+ r0: usize,
122+ r1: usize,
123+ unit: usize,
124+ sb_cols: usize,
125+ out: &mut [u64],
84 ) -> u64 {126 ) -> u64 {
85 let mut total = 0u64;127 let mut total = 0u64;
86- for row in 0..h {128+ for row in r0..r1 {
87- let base = (row / unit) * sb_cols;129+ let base = ((row - r0) / unit) * sb_cols;
88 let (d, s) = (&dec[row * dec_w..][..w], &src[row * src_w..][..w]);130 let (d, s) = (&dec[row * dec_w..][..w], &src[row * src_w..][..w]);
89 for (i, (dc, sc)) in d.chunks(unit).zip(s.chunks(unit)).enumerate() {131 for (i, (dc, sc)) in d.chunks(unit).zip(s.chunks(unit)).enumerate() {
90 let mut acc = 0u32;132 let mut acc = 0u32;
@@ -556,5 +598,17 @@ mod tests {
556 let mut got = vec![7u64; sb_cols * 4];598 let mut got = vec![7u64; sb_cols * 4];
557 assert_eq!(unit_sse(&dec, dec_w, &src, src_w, w, h, unit, sb_cols, &mut got), total);599 assert_eq!(unit_sse(&dec, dec_w, &src, src_w, w, h, unit, sb_cols, &mut got), total);
558 assert_eq!(got, want);600 assert_eq!(got, want);
601+ // lane-av1fpar: and banded across workers -- same per-unit slots,
602+ // same frame total (the partial sums are integers).
603+ for threads in [2usize, 4, 8] {
604+ let _bands = crate::par::override_filter_threads(threads);
605+ let mut banded = vec![7u64; sb_cols * 4];
606+ assert_eq!(
607+ unit_sse(&dec, dec_w, &src, src_w, w, h, unit, sb_cols, &mut banded),
608+ total,
609+ "{threads} bands: the frame total moved"
610+ );
611+ assert_eq!(banded, want, "{threads} bands: a unit's error moved");
612+ }
559 }613 }
560 }614 }
crates/ec-av1/src/par.rsmodified+38 -1
@@ -32,7 +32,40 @@
32 /// touching the process environment.32 /// touching the process environment.
33 static FILTER_THREADS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);33 static FILTER_THREADS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
34 34
35+thread_local! {
36+ /// This thread's override of [`filter_threads`], 0 = none. The ENCODER's
37+ /// frame-level filter search sets it for the span of that search
38+ /// (lane-av1fpar): the tile search is over by then, so every core is
39+ /// free, and each candidate's deblock/CDEF replay is exactly the banded
40+ /// stage the decoder already splits -- same bands, same byte-exact
41+ /// output, gated by
42+ /// `a_real_stream_filters_identically_with_one_and_four_filter_threads`
43+ /// on the decode side and by
44+ /// `encoder::tests::tile_bytes_do_not_depend_on_the_thread_count` here.
45+ static FILTER_BANDS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
46+}
47+
48+/// Restores the previous [`FILTER_BANDS`] override when it drops.
49+pub(crate) struct FilterBands(usize);
50+
51+impl Drop for FilterBands {
52+ fn drop(&mut self) {
53+ FILTER_BANDS.set(self.0);
54+ }
55+}
56+
57+/// Bands every filter stage on THIS thread across `n` workers until the
58+/// returned guard drops; `n <= 1` leaves the process default in place.
59+pub(crate) fn override_filter_threads(n: usize) -> FilterBands {
60+ let previous = FILTER_BANDS.replace(if n > 1 { n.clamp(1, 64) } else { 0 });
61+ FilterBands(previous)
62+}
63+
35 pub(crate) fn filter_threads() -> usize {64 pub(crate) fn filter_threads() -> usize {
65+ let over = FILTER_BANDS.get();
66+ if over > 0 {
67+ return over;
68+ }
36 match FILTER_THREADS.load(std::sync::atomic::Ordering::Relaxed) {69 match FILTER_THREADS.load(std::sync::atomic::Ordering::Relaxed) {
37 0 => {70 0 => {
38 let n = crate::envflags::var("EC_AV1_FILTER_THREADS")71 let n = crate::envflags::var("EC_AV1_FILTER_THREADS")
@@ -469,7 +502,7 @@ impl Drop for Batch<'_> {
469 // Off (the default) each `stage` call is one relaxed atomic load.502 // Off (the default) each `stage` call is one relaxed atomic load.
470 503
471 /// The stages [`stage`] accumulates, in the order a frame runs them.504 /// The stages [`stage`] accumulates, in the order a frame runs them.
472-pub(crate) const STAGES: [&str; 8] = [505+pub(crate) const STAGES: [&str; 10] = [
473 "tile search",506 "tile search",
474 "tile write",507 "tile write",
475 "filter: deblock replay",508 "filter: deblock replay",
@@ -478,6 +511,8 @@ pub(crate) const STAGES: [&str; 8] = [
478 "filter search (total)",511 "filter search (total)",
479 "capture decode",512 "capture decode",
480 "lr search",513 "lr search",
514+ "filter: plane copies",
515+ "filter: first decode",
481 ];516 ];
482 pub(crate) const S_TILE_SEARCH: usize = 0;517 pub(crate) const S_TILE_SEARCH: usize = 0;
483 pub(crate) const S_TILE_WRITE: usize = 1;518 pub(crate) const S_TILE_WRITE: usize = 1;
@@ -487,6 +522,8 @@ pub(crate) const S_SSE: usize = 4;
487 pub(crate) const S_FILTER: usize = 5;522 pub(crate) const S_FILTER: usize = 5;
488 pub(crate) const S_CAPTURE: usize = 6;523 pub(crate) const S_CAPTURE: usize = 6;
489 pub(crate) const S_LR: usize = 7;524 pub(crate) const S_LR: usize = 7;
525+pub(crate) const S_COPY: usize = 8;
526+pub(crate) const S_FIRST: usize = 9;
490 527
491 static STAGE_NS: [std::sync::atomic::AtomicU64; STAGES.len()] =528 static STAGE_NS: [std::sync::atomic::AtomicU64; STAGES.len()] =
492 [const { std::sync::atomic::AtomicU64::new(0) }; STAGES.len()];529 [const { std::sync::atomic::AtomicU64::new(0) }; STAGES.len()];