use ndarray::{Array4, ArrayView3, ArrayView4};
use rayon::prelude::*;
pub fn corr_cpu(
patch_feats: ArrayView4<'_, f32>,
target_fmap: ArrayView3<'_, f32>,
coords_center: ArrayView4<'_, f32>,
radius: usize,
) -> Array4<f32> {
let fmap_hwc = ChannelLastImage::from_chw(target_fmap);
corr_cpu_prebuilt_target(patch_feats, &fmap_hwc, coords_center, radius)
}
pub fn corr_cpu_prebuilt_target(
patch_feats: ArrayView4<'_, f32>,
fmap_hwc: &ChannelLastImage,
coords_center: ArrayView4<'_, f32>,
radius: usize,
) -> Array4<f32> {
let (num_edges, channels, patch, patch_check) = patch_feats.dim();
debug_assert_eq!(
patch, patch_check,
"patch_feats must be square in its last two dims"
);
debug_assert_eq!(
channels, fmap_hwc.channels,
"patch_feats/target_fmap channel count mismatch"
);
let taps = 2 * radius + 1;
let feats_hwc = ChannelLastPatches::from_ecpp(patch_feats);
let mut out = Array4::<f32>::zeros((num_edges, patch, patch, taps * taps));
let chunk_len = patch * patch * taps * taps;
let out_slice = out
.as_slice_mut()
.expect("corr_cpu's freshly-allocated output array is always contiguous C-order");
let per_edge = |edge: usize, out_chunk: &mut [f32]| {
for py in 0..patch {
for px in 0..patch {
let center_x = coords_center[(edge, py, px, 0)];
let center_y = coords_center[(edge, py, px, 1)];
let weights = BilinearWeights::new(center_x, center_y);
let anchor = feats_hwc.row(edge, py, px);
let out_row = &mut out_chunk
[(py * patch + px) * taps * taps..(py * patch + px + 1) * taps * taps];
for tx in 0..taps {
let dx = tx as isize - radius as isize;
let ix0 = weights.ix0 + dx;
for ty in 0..taps {
let dy = ty as isize - radius as isize;
let iy0 = weights.iy0 + dy;
out_row[tx * taps + ty] = weights.sample_dot(fmap_hwc, ix0, iy0, anchor);
}
}
}
}
};
out_slice
.par_chunks_mut(chunk_len)
.enumerate()
.for_each(|(edge, out_chunk)| per_edge(edge, out_chunk));
out
}
struct BilinearWeights {
ix0: isize,
iy0: isize,
w00: f32,
w01: f32,
w10: f32,
w11: f32,
}
impl BilinearWeights {
fn new(center_x: f32, center_y: f32) -> Self {
let floor_x = center_x.floor();
let floor_y = center_y.floor();
let frac_x = center_x - floor_x;
let frac_y = center_y - floor_y;
BilinearWeights {
ix0: floor_x as isize,
iy0: floor_y as isize,
w00: (1.0 - frac_x) * (1.0 - frac_y),
w01: frac_x * (1.0 - frac_y),
w10: (1.0 - frac_x) * frac_y,
w11: frac_x * frac_y,
}
}
#[inline]
fn sample_dot(&self, fmap: &ChannelLastImage, ix0: isize, iy0: isize, anchor: &[f32]) -> f32 {
let mut dot = 0.0_f32;
if self.w00 != 0.0 {
if let Some(c) = fmap.row(ix0, iy0) {
dot += self.w00 * dot_slice(anchor, c);
}
}
if self.w01 != 0.0 {
if let Some(c) = fmap.row(ix0 + 1, iy0) {
dot += self.w01 * dot_slice(anchor, c);
}
}
if self.w10 != 0.0 {
if let Some(c) = fmap.row(ix0, iy0 + 1) {
dot += self.w10 * dot_slice(anchor, c);
}
}
if self.w11 != 0.0 {
if let Some(c) = fmap.row(ix0 + 1, iy0 + 1) {
dot += self.w11 * dot_slice(anchor, c);
}
}
dot
}
}
#[inline]
fn dot_slice(a: &[f32], b: &[f32]) -> f32 {
debug_assert_eq!(a.len(), b.len());
a.iter().zip(b.iter()).map(|(x, y)| x * y).sum()
}
#[derive(Clone, Debug)]
pub struct ChannelLastImage {
data: Vec<f32>,
height: usize,
width: usize,
channels: usize,
}
impl ChannelLastImage {
pub fn from_chw(fmap: ArrayView3<'_, f32>) -> Self {
let (channels, height, width) = fmap.dim();
let mut data = vec![0.0_f32; height * width * channels];
for y in 0..height {
for x in 0..width {
let base = (y * width + x) * channels;
for c in 0..channels {
data[base + c] = fmap[(c, y, x)];
}
}
}
ChannelLastImage {
data,
height,
width,
channels,
}
}
#[inline]
fn row(&self, x: isize, y: isize) -> Option<&[f32]> {
if x < 0 || y < 0 || x as usize >= self.width || y as usize >= self.height {
return None;
}
let base = (y as usize * self.width + x as usize) * self.channels;
Some(&self.data[base..base + self.channels])
}
}
struct ChannelLastPatches {
data: Vec<f32>,
patch: usize,
channels: usize,
}
impl ChannelLastPatches {
fn from_ecpp(patch_feats: ArrayView4<'_, f32>) -> Self {
let (num_edges, channels, patch, _patch_check) = patch_feats.dim();
let mut data = vec![0.0_f32; num_edges * patch * patch * channels];
for edge in 0..num_edges {
for py in 0..patch {
for px in 0..patch {
let base = ((edge * patch + py) * patch + px) * channels;
for c in 0..channels {
data[base + c] = patch_feats[(edge, c, py, px)];
}
}
}
}
ChannelLastPatches {
data,
patch,
channels,
}
}
#[inline]
fn row(&self, edge: usize, py: usize, px: usize) -> &[f32] {
let base = ((edge * self.patch + py) * self.patch + px) * self.channels;
&self.data[base..base + self.channels]
}
}
#[cfg(test)]
fn bilinear_sample_zero_pad(
fmap: ArrayView3<'_, f32>,
x: f32,
y: f32,
mut out: ndarray::ArrayViewMut1<'_, f32>,
) {
let (channels, height, width) = fmap.dim();
out.fill(0.0);
let x0 = x.floor();
let y0 = y.floor();
let frac_x = x - x0;
let frac_y = y - y0;
let corners = [
(x0, y0, (1.0 - frac_x) * (1.0 - frac_y)),
(x0 + 1.0, y0, frac_x * (1.0 - frac_y)),
(x0, y0 + 1.0, (1.0 - frac_x) * frac_y),
(x0 + 1.0, y0 + 1.0, frac_x * frac_y),
];
for (cx, cy, weight) in corners {
if weight == 0.0 {
continue;
}
if cx < 0.0 || cy < 0.0 {
continue;
}
let (ix, iy) = (cx as usize, cy as usize);
if ix >= width || iy >= height {
continue;
}
for c in 0..channels {
out[c] += weight * fmap[(c, iy, ix)];
}
}
}
#[cfg(test)]
fn corr_cpu_reference(
patch_feats: ArrayView4<'_, f32>,
target_fmap: ArrayView3<'_, f32>,
coords_center: ArrayView4<'_, f32>,
radius: usize,
) -> Array4<f32> {
use ndarray::Array1;
let (num_edges, channels, patch, patch_check) = patch_feats.dim();
debug_assert_eq!(
patch, patch_check,
"patch_feats must be square in its last two dims"
);
let taps = 2 * radius + 1;
let mut out = Array4::<f32>::zeros((num_edges, patch, patch, taps * taps));
let mut sampled = Array1::<f32>::zeros(channels);
for edge in 0..num_edges {
for py in 0..patch {
for px in 0..patch {
let center_x = coords_center[(edge, py, px, 0)];
let center_y = coords_center[(edge, py, px, 1)];
for ty in 0..taps {
let dy = ty as f32 - radius as f32;
for tx in 0..taps {
let dx = tx as f32 - radius as f32;
bilinear_sample_zero_pad(
target_fmap,
center_x + dx,
center_y + dy,
sampled.view_mut(),
);
let mut dot = 0.0_f32;
for c in 0..channels {
dot += patch_feats[(edge, c, py, px)] * sampled[c];
}
out[(edge, py, px, tx * taps + ty)] = dot;
}
}
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use ndarray::{array, Array3};
#[test]
fn single_tap_exact_integer_sample_matches_raw_value() {
let mut fmap = Array3::<f32>::zeros((1, 4, 4));
for row in 0..4 {
for col in 0..4 {
fmap[(0, row, col)] = col as f32;
}
}
let patch_feats = Array4::<f32>::from_elem((1, 1, 1, 1), 1.0_f32);
let coords_center = array![[[[2.0_f32, 1.0_f32]]]]; let out = corr_cpu(patch_feats.view(), fmap.view(), coords_center.view(), 0);
assert_eq!(out.shape(), &[1, 1, 1, 1]);
assert!(
(out[(0, 0, 0, 0)] - 2.0).abs() < 1e-6,
"got {}",
out[(0, 0, 0, 0)]
);
}
#[test]
fn sampling_at_last_valid_pixel_is_not_spuriously_zeroed() {
let mut fmap = Array3::<f32>::zeros((1, 1, 3));
fmap[(0, 0, 0)] = 10.0;
fmap[(0, 0, 1)] = 20.0;
fmap[(0, 0, 2)] = 30.0;
let patch_feats = Array4::<f32>::from_elem((1, 1, 1, 1), 1.0_f32);
let coords_center = array![[[[2.0_f32, 0.0_f32]]]]; let out = corr_cpu(patch_feats.view(), fmap.view(), coords_center.view(), 0);
assert!(
(out[(0, 0, 0, 0)] - 30.0).abs() < 1e-6,
"got {}",
out[(0, 0, 0, 0)]
);
}
#[test]
fn sampling_past_border_zero_pads_the_out_of_range_corner() {
let mut fmap = Array3::<f32>::zeros((1, 1, 2));
fmap[(0, 0, 0)] = 5.0;
fmap[(0, 0, 1)] = 7.0;
let patch_feats = Array4::<f32>::from_elem((1, 1, 1, 1), 1.0_f32);
let coords_center = array![[[[1.5_f32, 0.0_f32]]]];
let out = corr_cpu(patch_feats.view(), fmap.view(), coords_center.view(), 0);
assert!(
(out[(0, 0, 0, 0)] - 3.5).abs() < 1e-6,
"got {}",
out[(0, 0, 0, 0)]
);
}
#[test]
fn preserves_raw_channel_dot_product() {
let mut fmap = Array3::<f32>::zeros((2, 2, 2));
fmap[(0, 0, 0)] = 1.0;
fmap[(1, 0, 0)] = 1.0;
let patch_feats = Array4::<f32>::from_elem((1, 2, 1, 1), 1.0_f32);
let coords_center = array![[[[0.0_f32, 0.0_f32]]]];
let out = corr_cpu(patch_feats.view(), fmap.view(), coords_center.view(), 0);
let expected = 2.0_f32;
assert!(
(out[(0, 0, 0, 0)] - expected).abs() < 1e-6,
"got {}",
out[(0, 0, 0, 0)]
);
}
#[test]
fn flattened_taps_match_upstream_x_major_order() {
let fmap = Array3::<f32>::from_shape_fn((1, 4, 4), |(_, y, x)| (10 * y + x) as f32);
let patch_feats = Array4::<f32>::from_elem((1, 1, 1, 1), 1.0);
let coords_center = array![[[[2.0_f32, 2.0_f32]]]];
let out = corr_cpu(patch_feats.view(), fmap.view(), coords_center.view(), 1);
let expected = [11.0, 21.0, 31.0, 12.0, 22.0, 32.0, 13.0, 23.0, 33.0];
assert_eq!(out.iter().copied().collect::<Vec<_>>(), expected);
}
#[test]
fn fast_matches_naive_reference_at_realistic_shape() {
let mut rng = DeterministicRng::new(0x5EED_u64);
let num_edges = 256;
let channels = 128;
let patch = 3;
let radius = 3;
let (height, width) = (120, 188);
let patch_feats =
Array4::<f32>::from_shape_fn((num_edges, channels, patch, patch), |_| rng.next_f32());
let target_fmap =
Array3::<f32>::from_shape_fn((channels, height, width), |_| rng.next_f32());
let coords_center =
Array4::<f32>::from_shape_fn((num_edges, patch, patch, 2), |(_, _, _, axis)| {
if axis == 0 {
rng.next_f32() * (width as f32 + 8.0) - 4.0
} else {
rng.next_f32() * (height as f32 + 8.0) - 4.0
}
});
let fast = corr_cpu(
patch_feats.view(),
target_fmap.view(),
coords_center.view(),
radius,
);
let reference = corr_cpu_reference(
patch_feats.view(),
target_fmap.view(),
coords_center.view(),
radius,
);
assert_eq!(fast.shape(), reference.shape());
let max_abs_diff = fast
.iter()
.zip(reference.iter())
.map(|(a, b)| (a - b).abs())
.fold(0.0_f32, f32::max);
assert!(
max_abs_diff <= 5e-5,
"fast/reference corr_cpu mismatch: max abs diff {max_abs_diff:.3e}"
);
}
struct DeterministicRng(u64);
impl DeterministicRng {
fn new(seed: u64) -> Self {
DeterministicRng(seed | 1)
}
fn next_u64(&mut self) -> u64 {
let mut x = self.0;
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
self.0 = x;
x
}
fn next_f32(&mut self) -> f32 {
(self.next_u64() >> 40) as f32 / (1u64 << 24) as f32
}
}
#[test]
#[ignore = "timing report, not a correctness check; run --release, see doc comment"]
fn corr_cpu_perf_at_realistic_working_set() {
let mut rng = DeterministicRng::new(0xC0FFEE_u64);
let num_edges = 3000;
let channels = 128;
let patch = 3;
let radius = 3;
let (height, width) = (120, 188);
let patch_feats =
Array4::<f32>::from_shape_fn((num_edges, channels, patch, patch), |_| rng.next_f32());
let target_fmap =
Array3::<f32>::from_shape_fn((channels, height, width), |_| rng.next_f32());
let coords_center =
Array4::<f32>::from_shape_fn((num_edges, patch, patch, 2), |(_, _, _, axis)| {
if axis == 0 {
rng.next_f32() * width as f32
} else {
rng.next_f32() * height as f32
}
});
let repeats = 10;
let start = std::time::Instant::now();
for _ in 0..repeats {
std::hint::black_box(corr_cpu(
patch_feats.view(),
target_fmap.view(),
coords_center.view(),
radius,
));
}
let fast_ms = start.elapsed().as_secs_f64() * 1000.0 / repeats as f64;
println!(" [perf] corr_cpu (fast, {num_edges} edges): {fast_ms:.3} ms/call");
let start = std::time::Instant::now();
std::hint::black_box(corr_cpu_reference(
patch_feats.view(),
target_fmap.view(),
coords_center.view(),
radius,
));
let naive_ms = start.elapsed().as_secs_f64() * 1000.0;
println!(" [perf] corr_cpu_reference (naive, {num_edges} edges): {naive_ms:.3} ms/call");
println!(" [perf] speedup: {:.2}x", naive_ms / fast_ms);
}
}