BM3D (CPU): transform each block once per plane, not once per group (#4951)

The CPU collaborative filter ran the 2-D DCT on every member of every
group, so a block was transformed each time it joined a group, and the
Wiener step transformed the pilot's blocks again for every group. Each
block's coefficients are now worked out the first time a group asks for
them and reused. The output is bit-for-bit the same.

Co-Authored-By: Claude <[email protected]>
This commit is contained in:
Khawar Zamman WaniandClaude committed 2026-12-02 11:08:57 +05:30
1 parent c1f2cf664a
commit 312b2dc8bb
1 file changed
+101 -16
+101 -16
View File
@@ -203,22 +203,77 @@ struct Scratch {
col_tmp: Vec<f32>,
}
/// A group (`m` blocks of `n × n`, one after the other in `buf`) to the transform domain, or back.
fn group_transform(tf: &Transform, buf: &mut [f32], m: usize, s: &mut Scratch, forward: bool) {
/// A group (`m` blocks of `n × n`, one after the other in `buf`) back from the transform domain.
fn group_inverse(tf: &Transform, buf: &mut [f32], m: usize, s: &mut Scratch) {
let nn = tf.n * tf.n;
s.tmp.resize(nn, 0.0);
if !forward {
haar_columns(buf, m, nn, s, false);
}
haar_columns(buf, m, nn, s, false);
for blk in buf.chunks_exact_mut(nn) {
if forward {
tf.forward(blk, &mut s.tmp);
} else {
tf.inverse(blk, &mut s.tmp);
tf.inverse(blk, &mut s.tmp);
}
}
/// The 2-D DCT of the blocks of one plane, each worked out the first time a group asks for it: a block joins many
/// groups, and its coefficients do not depend on the group.
#[derive(Default)]
struct BlockCoeffs {
/// The coefficients of block `i`, at `i * n * n`.
data: Vec<f32>,
/// Whether block `i` is in `data` yet.
done: Vec<bool>,
/// Blocks along a side of the plane.
nb: usize,
}
impl BlockCoeffs {
/// Forget the blocks, for a plane of `t × t` cells that holds blocks of `n × n`.
fn reset(&mut self, t: usize, n: usize) {
self.nb = (t + 1).saturating_sub(n);
let count = self.nb * self.nb;
self.done.clear();
self.done.resize(count, false);
if self.data.len() < count * n * n {
self.data = vec![0.0; count * n * n];
}
}
if forward {
haar_columns(buf, m, nn, s, true);
/// A group (`members` are the blocks' top-left cells) in the transform domain: the blocks' DCTs one after the other
/// in `out`, then the Haar transform across them.
fn group(&mut self, tf: &Transform, plane: &[f32], t: usize, members: &[u32], out: &mut Vec<f32>, s: &mut Scratch) {
let n = tf.n;
let nn = n * n;
s.tmp.resize(nn, 0.0);
out.clear();
for &pos in members {
let (x, y) = (pos as usize % t.max(1), pos as usize / t.max(1));
let idx = y * self.nb + x;
if x < self.nb && y < self.nb {
let hit = self.done.get(idx).copied().unwrap_or(false);
if let (Some(slot), false) = (self.data.get_mut(idx * nn..(idx + 1) * nn), hit) {
for (j, dst) in slot.chunks_exact_mut(n).enumerate() {
let at = pos as usize + j * t;
match plane.get(at..at + n) {
Some(row) => dst.copy_from_slice(row),
None => dst.fill(0.0),
}
}
tf.forward(slot, &mut s.tmp);
if let Some(d) = self.done.get_mut(idx) {
*d = true;
}
}
if let Some(slot) = self.data.get(idx * nn..(idx + 1) * nn) {
out.extend_from_slice(slot);
continue;
}
}
// a block outside the plane's grid: not cached
let mut one = Vec::new();
gather(plane, t, n, &[pos], &mut one);
tf.forward(&mut one, &mut s.tmp);
out.extend_from_slice(&one);
}
haar_columns(out, members.len(), nn, s, true);
}
}
@@ -376,16 +431,18 @@ fn collaborate(y: &[Vec<f32>], pilot: Option<&[Vec<f32>]>, groups: &[Vec<u32>],
let lambda = lambda * sigma;
let mut s = Scratch::default();
let (mut buf, mut pbuf) = (Vec::new(), Vec::new());
let (mut cache, mut pcache) = (BlockCoeffs::default(), BlockCoeffs::default());
let mut out = Vec::with_capacity(y.len());
for plane in y {
let mut num = vec![0f32; t * t];
let mut den = vec![0f32; t * t];
let c = out.len();
let pilot_plane = pilot.and_then(|pl| pl.get(c));
cache.reset(t, n);
pcache.reset(t, n);
for members in groups {
let m = members.len();
gather(plane, t, n, members, &mut buf);
group_transform(tf, &mut buf, m, &mut s, true);
cache.group(tf, plane, t, members, &mut buf, &mut s);
let weight = match pilot_plane {
None => {
let mut kept = 0usize;
@@ -399,8 +456,7 @@ fn collaborate(y: &[Vec<f32>], pilot: Option<&[Vec<f32>]>, groups: &[Vec<u32>],
1.0 / kept.max(1) as f32
}
Some(pl) => {
gather(pl, t, n, members, &mut pbuf);
group_transform(tf, &mut pbuf, m, &mut s, true);
pcache.group(tf, pl, t, members, &mut pbuf, &mut s);
let mut energy = 0f32;
for (v, &q) in buf.iter_mut().zip(&pbuf) {
let w = q * q / (q * q + sigma * sigma);
@@ -410,7 +466,7 @@ fn collaborate(y: &[Vec<f32>], pilot: Option<&[Vec<f32>]>, groups: &[Vec<u32>],
1.0 / energy.max(1e-3)
}
};
group_transform(tf, &mut buf, m, &mut s, false);
group_inverse(tf, &mut buf, m, &mut s);
for (&pos, blk) in members.iter().zip(buf.chunks_exact(n * n)) {
for (j, row) in blk.chunks_exact(n).enumerate() {
let at = pos as usize + j * t;
@@ -523,6 +579,35 @@ mod tests {
.collect()
}
/// The cached group transform gives bit for bit what gathering the blocks and transforming each one does, for
/// matched groups, repeated blocks and the last block of the grid, whatever order the blocks are asked for.
#[test]
fn the_cached_group_transform_matches_transforming_each_block() {
let (t, n) = (24, 8);
let nb = t + 1 - n;
let tf = Transform::new(n);
let planes = noisy(t, 3.0, 11);
let plane = &planes[0];
let mut groups = match_groups(plane, t, n, 3, 6, 8, 2.0 * 2.0);
groups.push(vec![5, 5, 7, 5]);
groups.push(vec![(nb * t + nb - 1) as u32, 0, (nb * t + nb - 1) as u32, (nb - 1) as u32]);
let (mut cache, mut s) = (BlockCoeffs::default(), Scratch::default());
cache.reset(t, n);
let (mut got, mut want) = (Vec::new(), Vec::new());
for members in groups.iter().chain(groups.iter().rev()) {
let m = members.len();
cache.group(&tf, plane, t, members, &mut got, &mut s);
gather(plane, t, n, members, &mut want);
let mut tmp = vec![0f32; n * n];
for blk in want.chunks_exact_mut(n * n) {
tf.forward(blk, &mut tmp);
}
haar_columns(&mut want, m, n * n, &mut s, true);
assert_eq!(got.len(), want.len());
assert!(got.iter().zip(&want).all(|(a, b)| a.to_bits() == b.to_bits()), "group {members:?}");
}
}
/// The deviation of the planes' values around `level`.
fn spread(planes: &[Vec<f32>], level: f32) -> f32 {
let all: Vec<f32> = planes.iter().flatten().copied().collect();