use crate::dtype::Element;
use crate::ops::DistanceMetric;
use crate::runtime::cpu::{CpuClient, kernels};
use num_traits::{Float, FromPrimitive};
const CDIST_UNIT_WORK: usize = 32 * 1024;
#[inline]
fn cdist_col_block(d: usize) -> usize {
(CDIST_UNIT_WORK / d.max(1)).max(1)
}
#[allow(clippy::too_many_arguments)]
pub(super) unsafe fn cdist_units<T: Element + Float + FromPrimitive>(
client: &CpuClient,
x: *const T,
y: *const T,
out: *mut T,
n: usize,
m: usize,
d: usize,
metric: DistanceMetric,
) {
let block = cdist_col_block(d);
let blocks_per_row = m.div_ceil(block);
let count = n * blocks_per_row;
let work = n.saturating_mul(m).saturating_mul(d);
let (x_addr, y_addr, out_addr) = (x as usize, y as usize, out as usize);
client.par_for_each(count, work, |u| {
let row = u / blocks_per_row;
let col_start = (u % blocks_per_row) * block;
let col_end = (col_start + block).min(m);
unsafe {
kernels::cdist_block_kernel::<T>(
x_addr as *const T,
y_addr as *const T,
out_addr as *mut T,
row,
col_start,
col_end,
m,
d,
metric,
);
}
});
}
pub(super) unsafe fn pdist_units<T: Element + Float + FromPrimitive>(
client: &CpuClient,
x: *const T,
out: *mut T,
n: usize,
d: usize,
metric: DistanceMetric,
) {
let pairs = n * n.saturating_sub(1) / 2;
let work = pairs.saturating_mul(d);
let (x_addr, out_addr) = (x as usize, out as usize);
client.par_for_each(n, work, |row| unsafe {
kernels::pdist_row_kernel::<T>(x_addr as *const T, out_addr as *mut T, n, d, row, metric);
});
}