From 9e2426f6c12a0d2348bcf74ea37842a88ddb4317 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 25 Oct 2026 14:52:26 +0100 Subject: [PATCH 1/4] Format the AHD bit-for-bit test with rustfmt Co-Authored-By: Claude Sonnet 5.5 --- crates/raw/src/demosaic.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/raw/src/demosaic.rs b/crates/raw/src/demosaic.rs index f691c9584bf..6e768c0b2d1 100644 --- a/crates/raw/src/demosaic.rs +++ b/crates/raw/src/demosaic.rs @@ -811,7 +811,11 @@ mod tests { let mut want = vec![0.0f32; w * h * 3]; ahd_ref(&p, phase, &m, &mut want, jobs); let got = demosaic(&p, phase, Demosaic::Ahd, &m, jobs); - assert_eq!(want.iter().map(|v| v.to_bits()).collect::>(), got.iter().map(|v| v.to_bits()).collect::>(), "{w}x{h} {phase:?} {jobs}"); + assert_eq!( + want.iter().map(|v| v.to_bits()).collect::>(), + got.iter().map(|v| v.to_bits()).collect::>(), + "{w}x{h} {phase:?} {jobs}" + ); } } } From 3370667b39333ff2da2a3ddc9c3dff234255bb75 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 17:31:19 +0100 Subject: [PATCH 2/4] Integration: AHD scratch sized to the rows the memory check approved (#9450) Each AHD worker allocated scratch for a full 38-row band while develop's memory check budgets h.min(32) + 6 rows, so short images allocated more than was approved: a 262144 x 1 strip was budgeted ~106 MB and allocated ~580 MB (5.4x). The scratch is now sized from the same row count as the budget, and the budget also counts the two u32 vertical-sum rows, so budget == allocation (~109 MB there). Pixels are unchanged. Tests: ahd_scratch_fits_its_budget (budget equals the real scratch for h = 1..5000), ahd_matches_reference_with_reused_scratch (1100 rows, jobs 1 and 2, all four phases: one scratch serves many bands). Co-authored-by: vangel76 <271991477+vangel76@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 (1M context) (cherry picked from commit 630e32c4238df452d9d5e70357bdb968045ab8c3) --- crates/raw/src/demosaic.rs | 71 ++++++++++++++++++++++++++++++++++---- 1 file changed, 65 insertions(+), 6 deletions(-) diff --git a/crates/raw/src/demosaic.rs b/crates/raw/src/demosaic.rs index 6e768c0b2d1..ce7cb293fe4 100644 --- a/crates/raw/src/demosaic.rs +++ b/crates/raw/src/demosaic.rs @@ -462,10 +462,19 @@ const AHD_BAND: usize = 32; /// Extra band rows above and below the output rows. const M: usize = 3; -/// Maximum scratch allocation of one AHD band: two green, RGB and Lab float -/// planes and two byte homogeneity planes, including their border rows. +/// Scratch rows one AHD worker allocates: the output rows of the tallest band +/// this image has, plus their border rows. +fn ahd_scratch_rows(h: usize) -> usize { + h.min(AHD_BAND) + 2 * M +} + +/// Scratch allocation of one AHD worker ([`AhdScratch::for_image`]): two green, +/// RGB and Lab float planes and two byte homogeneity planes over +/// [`ahd_scratch_rows`], plus the two `u32` rows of vertical sums. pub(crate) fn ahd_scratch(w: u64, h: u64) -> u64 { - w.saturating_add(2 * PAD as u64).saturating_mul(h.min(AHD_BAND as u64).saturating_add(2 * M as u64)).saturating_mul(58) + let s = w.saturating_add(2 * PAD as u64); + let rows = h.min(AHD_BAND as u64).saturating_add(2 * M as u64); + s.saturating_mul(rows.saturating_mul(58).saturating_add(8)) } pub(crate) fn ahd_bands(h: usize) -> usize { @@ -474,7 +483,7 @@ pub(crate) fn ahd_bands(h: usize) -> usize { pub(crate) const AHD_TABLE_BYTES: u64 = (LABF_STEPS as u64 + 1) * 8; -/// One AHD band's working planes, reused for every band a worker runs (sized for a full band). +/// One AHD band's working planes, reused for every band a worker runs (sized for the tallest band). struct AhdScratch { /// Green interpolated horizontally (0) and vertically (1). g: [Vec; 2], @@ -498,6 +507,11 @@ impl AhdScratch { vs: [vec![0u32; s], vec![0u32; s]], } } + + /// The scratch for an image `h` rows tall with stride `s`: the size [`ahd_scratch`] budgets. + fn for_image(h: usize, s: usize) -> Self { + AhdScratch::new(ahd_scratch_rows(h) * s, s) + } } /// AHD (see [`ahd_ref`] for the plain statement): the same arithmetic in the same order, per @@ -513,9 +527,8 @@ fn ahd(p: &Padded, phase: [u8; 4], to_xyz: &Mat3, out: &mut [f32], jobs: usize) // A few groups per worker for balance; each group allocates its scratch once. let groups = (par::workers().min(jobs.max(1)) * 4).clamp(1, bands.max(1)); let per_group = bands.div_ceil(groups).max(1); - let cap = (AHD_BAND + 2 * M) * s; par::chunks_mut_limited(out, per_group * AHD_BAND * w * 3, jobs, |group, gchunk| { - let mut sc = AhdScratch::new(cap, s); + let mut sc = AhdScratch::for_image(h, s); for (j, chunk) in gchunk.chunks_mut(AHD_BAND * w * 3).enumerate() { ahd_band(d, w, s, phase, &m, &labf, group * per_group + j, chunk, &mut sc); } @@ -821,6 +834,52 @@ mod tests { } } + /// Bytes the scratch planes actually hold. + fn scratch_bytes(sc: &AhdScratch) -> u64 { + let f = sc.g.iter().chain(sc.rgb.iter().flatten()).chain(sc.lab.iter().flatten()).map(|v| v.capacity() * 4).sum::(); + let b = sc.hom.iter().map(Vec::capacity).sum::(); + let u = sc.vs.iter().map(|v| v.capacity() * 4).sum::(); + (f + b + u) as u64 + } + + /// The memory check in `develop` admits a file on [`ahd_scratch`] per worker; the scratch + /// `ahd` allocates must not exceed it. A short wide strip used to allocate the 38 rows of a + /// full band against a budget of `h + 6` rows (5.4x at `h = 1`). + #[test] + fn ahd_scratch_fits_its_budget() { + for w in [1usize, 2, 33, 4000] { + for h in [1usize, 2, 7, 31, 32, 33, 100, 5000] { + let s = w + 2 * PAD; + let sc = AhdScratch::for_image(h, s); + let budget = ahd_scratch(w as u64, h as u64); + assert_eq!(scratch_bytes(&sc), budget, "{w}x{h}: allocated vs budgeted bytes"); + // The tallest band `ahd` hands out (at most 32 rows, plus 3 above and below) fits. + assert!(sc.g[0].len() >= (h.min(32) + 6) * s, "{w}x{h}"); + } + } + } + + /// One scratch serves many bands (1100 rows are 35 bands, the last one short, over 4 scratches + /// with jobs 1 and at most 8 with jobs 2), so a stage reading a cell left over from an earlier band would show. + #[test] + fn ahd_matches_reference_with_reused_scratch() { + let m = [[0.41, 0.36, 0.18], [0.21, 0.72, 0.07], [0.02, 0.12, 0.95]]; + let (w, h) = (37, 1100); + let cfa: Vec = (0..w * h).map(|i| ((i * 7919 + i / w * 104729) % 1013) as f32 / 1000.0 - 0.006).collect(); + let p = Padded::from_plane(&cfa, w, h); + for jobs in [1, 2] { + let groups = (par::workers().min(jobs) * 4).clamp(1, ahd_bands(h)); + assert!(ahd_bands(h).div_ceil(groups) >= 2, "jobs {jobs}: each scratch must serve several bands"); + for phase in [[0, 1, 1, 2], [2, 1, 1, 0], [1, 0, 2, 1], [1, 2, 0, 1]] { + let mut want = vec![0.0f32; w * h * 3]; + ahd_ref(&p, phase, &m, &mut want, jobs); + let got = demosaic(&p, phase, Demosaic::Ahd, &m, jobs); + assert_eq!(want.len(), got.len()); + assert!(want.iter().zip(&got).all(|(a, b)| a.to_bits() == b.to_bits()), "{w}x{h} {phase:?} jobs {jobs}"); + } + } + } + /// Mosaics an RGB image with the given phase. fn mosaic(rgb: &[[f32; 3]], w: usize, h: usize, phase: [u8; 4]) -> Vec { (0..w * h).map(|i| rgb[i][phase[((i / w) & 1) * 2 + ((i % w) & 1)] as usize]).collect() From 3bceaf4d66256ac1dbbb78fe3e11393ac39220c8 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 25 Oct 2026 23:14:30 +0100 Subject: [PATCH 3/4] raw: AHD allocates its scratch once per worker, not once per band The bands were split into four groups per worker, clamped to the number of bands. A 24 MP raw has 126 bands, so with 32 workers every group held one band and every band allocated and zeroed a fresh 16-plane scratch, which cost more than the reuse saved. The bands are now split into one group per worker, so the scratch is allocated once per worker whatever the thread count. Pixels are unchanged. Adds a test that runs 35 bands in groups of 9 on a 4-thread pool and compares the result with the reference bit for bit, so the band index of later groups and a scratch reused for several bands are checked. Co-Authored-By: Claude Sonnet 5.5 --- crates/raw/src/demosaic.rs | 40 +++++++++++++++++++++++++++++++++----- 1 file changed, 35 insertions(+), 5 deletions(-) diff --git a/crates/raw/src/demosaic.rs b/crates/raw/src/demosaic.rs index ce7cb293fe4..85af3c9ae4e 100644 --- a/crates/raw/src/demosaic.rs +++ b/crates/raw/src/demosaic.rs @@ -477,6 +477,14 @@ pub(crate) fn ahd_scratch(w: u64, h: u64) -> u64 { s.saturating_mul(rows.saturating_mul(58).saturating_add(8)) } +/// Bands one scratch serves: the bands are split into one group per worker (at most `jobs`), so +/// the scratch is allocated and zeroed once per worker however many workers there are. More +/// groups than workers would allocate a fresh scratch for every band on a many-core machine. +fn ahd_bands_per_group(bands: usize, jobs: usize) -> usize { + let groups = par::workers().min(jobs.max(1)).clamp(1, bands.max(1)); + bands.div_ceil(groups).max(1) +} + pub(crate) fn ahd_bands(h: usize) -> usize { h.div_ceil(AHD_BAND) } @@ -524,9 +532,7 @@ fn ahd(p: &Padded, phase: [u8; 4], to_xyz: &Mat3, out: &mut [f32], jobs: usize) let m: [[f32; 3]; 3] = std::array::from_fn(|i| std::array::from_fn(|j| to_xyz[i][j] as f32 / white[i])); let labf = LabF::new(); let bands = ahd_bands(h); - // A few groups per worker for balance; each group allocates its scratch once. - let groups = (par::workers().min(jobs.max(1)) * 4).clamp(1, bands.max(1)); - let per_group = bands.div_ceil(groups).max(1); + let per_group = ahd_bands_per_group(bands, jobs); par::chunks_mut_limited(out, per_group * AHD_BAND * w * 3, jobs, |group, gchunk| { let mut sc = AhdScratch::for_image(h, s); for (j, chunk) in gchunk.chunks_mut(AHD_BAND * w * 3).enumerate() { @@ -868,8 +874,7 @@ mod tests { let cfa: Vec = (0..w * h).map(|i| ((i * 7919 + i / w * 104729) % 1013) as f32 / 1000.0 - 0.006).collect(); let p = Padded::from_plane(&cfa, w, h); for jobs in [1, 2] { - let groups = (par::workers().min(jobs) * 4).clamp(1, ahd_bands(h)); - assert!(ahd_bands(h).div_ceil(groups) >= 2, "jobs {jobs}: each scratch must serve several bands"); + assert!(ahd_bands_per_group(ahd_bands(h), jobs) >= 2, "jobs {jobs}: each scratch must serve several bands"); for phase in [[0, 1, 1, 2], [2, 1, 1, 0], [1, 0, 2, 1], [1, 2, 0, 1]] { let mut want = vec![0.0f32; w * h * 3]; ahd_ref(&p, phase, &m, &mut want, jobs); @@ -880,6 +885,31 @@ mod tests { } } + /// A 4-worker pool splits 35 bands into groups of 9 (the last of 8), so groups after the first + /// start at band `group * 9` and every scratch is reused for several bands: a wrong band index + /// or a stale scratch cell would change pixels. The group size does not depend on the machine. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn ahd_groups_of_several_bands_match_reference() { + let m = [[0.41, 0.36, 0.18], [0.21, 0.72, 0.07], [0.02, 0.12, 0.95]]; + let (w, h) = (37, 1100); + let cfa: Vec = (0..w * h).map(|i| ((i * 7919 + i / w * 104729) % 1013) as f32 / 1000.0 - 0.006).collect(); + let p = Padded::from_plane(&cfa, w, h); + let pool = rayon::ThreadPoolBuilder::new().num_threads(4).build().unwrap(); + pool.install(|| { + assert_eq!(par::workers(), 4); + assert_eq!(ahd_bands_per_group(ahd_bands(h), 4), 9); + // One worker per group, never more groups than workers, however many bands there are. + assert_eq!(ahd_bands_per_group(126, 1000), 32); + for phase in [[0, 1, 1, 2], [1, 2, 0, 1]] { + let mut want = vec![0.0f32; w * h * 3]; + ahd_ref(&p, phase, &m, &mut want, 4); + let got = demosaic(&p, phase, Demosaic::Ahd, &m, 4); + assert!(want.iter().zip(&got).all(|(a, b)| a.to_bits() == b.to_bits()), "{phase:?}"); + } + }); + } + /// Mosaics an RGB image with the given phase. fn mosaic(rgb: &[[f32; 3]], w: usize, h: usize, phase: [u8; 4]) -> Vec { (0..w * h).map(|i| rgb[i][phase[((i / w) & 1) * 2 + ((i % w) & 1)] as usize]).collect() From 1e52abfb2803ac3e6cabfdc15d1d3514ef3ed663 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 26 Oct 2026 01:15:47 +0100 Subject: [PATCH 4/4] raw: restore the LabF pair table that the main revert dropped from the merge Main reverted the earlier #9455 merge, which also removed the AHD changes that came in with it; keep this PR's AHD code and add clampf plus the NaN-plane test from main. Co-Authored-By: Claude Sonnet 5.5 --- crates/raw/src/demosaic.rs | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/crates/raw/src/demosaic.rs b/crates/raw/src/demosaic.rs index 63b3ed44f03..862dbb2ad6d 100644 --- a/crates/raw/src/demosaic.rs +++ b/crates/raw/src/demosaic.rs @@ -426,9 +426,10 @@ const GRAD_EPS: f32 = 1.0 / 256.0; /// Regularizes the green-similarity weights of the colour differences. const DIFF_EPS: f32 = 1.0 / 64.0; -/// CIE f(t) for L*a*b*, tabulated on 0..2 with linear interpolation. +/// CIE f(t) for L*a*b*, tabulated on 0..2 with linear interpolation. Each entry holds the +/// sample and the step to the next one (one load per lookup; the same `a + (b - a) * f`). struct LabF { - table: Vec, + pairs: Vec<[f32; 2]>, } const LABF_STEPS: usize = 1 << 14; @@ -436,7 +437,8 @@ const LABF_RANGE: f32 = 2.0; impl LabF { fn new() -> Self { - LabF { table: (0..=LABF_STEPS + 1).map(|i| Self::exact(i as f32 * LABF_RANGE / LABF_STEPS as f32)).collect() } + let table: Vec = (0..=LABF_STEPS + 1).map(|i| Self::exact(i as f32 * LABF_RANGE / LABF_STEPS as f32)).collect(); + LabF { pairs: table.windows(2).map(|p| [p[0], p[1] - p[0]]).collect() } } fn exact(t: f32) -> f32 { @@ -450,8 +452,8 @@ impl LabF { } let x = t * (LABF_STEPS as f32 / LABF_RANGE); let i = (x as usize).min(LABF_STEPS); - let a = self.table[i]; - a + (self.table[i + 1] - a) * (x - i as f32) + let [a, step] = self.pairs[i]; + a + step * (x - i as f32) } } @@ -487,7 +489,7 @@ pub(crate) fn ahd_bands(h: usize) -> usize { h.div_ceil(AHD_BAND) } -pub(crate) const AHD_TABLE_BYTES: u64 = (LABF_STEPS as u64 + 2) * 4; +pub(crate) const AHD_TABLE_BYTES: u64 = (LABF_STEPS as u64 + 1) * 8; /// `v` limited to `lo..=hi` like `f32::clamp`, without its panic on NaN bounds (hostile black /// levels can put NaN in the plane): same result for every non-NaN bound. @@ -846,12 +848,6 @@ mod tests { } } - #[test] - fn ahd_survives_nan_planes() { - let p = Padded::from_plane(&[f32::NAN; 64], 8, 8); - assert_eq!(demosaic(&p, [0, 1, 1, 2], Demosaic::Ahd, &IDENTITY, 1).len(), 192); - } - /// Bytes the scratch planes actually hold. fn scratch_bytes(sc: &AhdScratch) -> u64 { let f = sc.g.iter().chain(sc.rgb.iter().flatten()).chain(sc.lab.iter().flatten()).map(|v| v.capacity() * 4).sum::(); @@ -922,6 +918,12 @@ mod tests { }); } + #[test] + fn ahd_survives_nan_planes() { + let p = Padded::from_plane(&[f32::NAN; 64], 8, 8); + assert_eq!(demosaic(&p, [0, 1, 1, 2], Demosaic::Ahd, &IDENTITY, 1).len(), 192); + } + /// Mosaics an RGB image with the given phase. fn mosaic(rgb: &[[f32; 3]], w: usize, h: usize, phase: [u8; 4]) -> Vec { (0..w * h).map(|i| rgb[i][phase[((i / w) & 1) * 2 + ((i % w) & 1)] as usize]).collect()