use crate::dtype::DType;
use crate::runtime::communicator::ReduceOp;
trait Lane: Copy {
const BYTES: usize;
fn load(chunk: &[u8]) -> Self;
fn store(self, out: &mut Vec<u8>);
fn combine(self, next: Self, op: ReduceOp) -> Self;
}
macro_rules! int_lane {
($($t:ty),*) => {$(
impl Lane for $t {
const BYTES: usize = std::mem::size_of::<$t>();
fn load(chunk: &[u8]) -> Self {
<$t>::from_ne_bytes(chunk.try_into().unwrap_or_default())
}
fn store(self, out: &mut Vec<u8>) {
out.extend_from_slice(&self.to_ne_bytes());
}
fn combine(self, next: Self, op: ReduceOp) -> Self {
match op {
ReduceOp::Sum => self.wrapping_add(next),
ReduceOp::Prod => self.wrapping_mul(next),
ReduceOp::Max => Ord::max(self, next),
ReduceOp::Min => Ord::min(self, next),
}
}
}
)*};
}
macro_rules! float_lane {
($($t:ty),*) => {$(
impl Lane for $t {
const BYTES: usize = std::mem::size_of::<$t>();
fn load(chunk: &[u8]) -> Self {
<$t>::from_ne_bytes(chunk.try_into().unwrap_or_default())
}
fn store(self, out: &mut Vec<u8>) {
out.extend_from_slice(&self.to_ne_bytes());
}
fn combine(self, next: Self, op: ReduceOp) -> Self {
match op {
ReduceOp::Sum => self + next,
ReduceOp::Prod => self * next,
ReduceOp::Max => self.max(next),
ReduceOp::Min => self.min(next),
}
}
}
)*};
}
int_lane!(i8, i16, i32, i64, u8, u16, u32, u64);
float_lane!(f32, f64);
#[cfg(feature = "f16")]
macro_rules! half_lane {
($name:ident, $t:ty) => {
#[derive(Clone, Copy)]
struct $name(f32);
impl Lane for $name {
const BYTES: usize = 2;
fn load(chunk: &[u8]) -> Self {
Self(<$t>::from_ne_bytes(chunk.try_into().unwrap_or_default()).to_f32())
}
fn store(self, out: &mut Vec<u8>) {
out.extend_from_slice(&<$t>::from_f32(self.0).to_ne_bytes());
}
fn combine(self, next: Self, op: ReduceOp) -> Self {
Self(self.0.combine(next.0, op))
}
}
};
}
#[cfg(feature = "f16")]
half_lane!(Half, half::f16);
#[cfg(feature = "f16")]
half_lane!(Brain, half::bf16);
fn fold<L: Lane>(inputs: &[Vec<u8>], op: ReduceOp) -> Vec<u8> {
let Some((first, rest)) = inputs.split_first() else {
return Vec::new();
};
let mut acc: Vec<L> = first.chunks_exact(L::BYTES).map(L::load).collect();
for buf in rest {
for (value, chunk) in acc.iter_mut().zip(buf.chunks_exact(L::BYTES)) {
*value = value.combine(L::load(chunk), op);
}
}
let mut out = Vec::with_capacity(first.len());
for value in acc {
value.store(&mut out);
}
out
}
pub(super) fn reduce(inputs: &[Vec<u8>], dtype: DType, op: ReduceOp) -> Option<Vec<u8>> {
let out = match dtype {
DType::F64 => fold::<f64>(inputs, op),
DType::F32 => fold::<f32>(inputs, op),
#[cfg(feature = "f16")]
DType::F16 => fold::<Half>(inputs, op),
#[cfg(feature = "f16")]
DType::BF16 => fold::<Brain>(inputs, op),
DType::I64 => fold::<i64>(inputs, op),
DType::I32 => fold::<i32>(inputs, op),
DType::I16 => fold::<i16>(inputs, op),
DType::I8 => fold::<i8>(inputs, op),
DType::U64 => fold::<u64>(inputs, op),
DType::U32 => fold::<u32>(inputs, op),
DType::U16 => fold::<u16>(inputs, op),
DType::U8 => fold::<u8>(inputs, op),
_ => return None,
};
Some(out)
}
pub(super) fn supports(dtype: DType) -> bool {
reduce(&[], dtype, ReduceOp::Sum).is_some()
}
#[cfg(test)]
mod tests {
use super::*;
fn bytes<T: bytemuck::Pod>(values: &[T]) -> Vec<u8> {
bytemuck::cast_slice(values).to_vec()
}
#[test]
fn f32_sum_follows_rank_order() {
let inputs = [bytes(&[1e8f32]), bytes(&[1.0f32]), bytes(&[-1e8f32])];
let out = reduce(&inputs, DType::F32, ReduceOp::Sum).unwrap();
assert_eq!(out, bytes(&[0.0f32]));
}
#[test]
fn integers_wrap_instead_of_overflowing() {
let inputs = [bytes(&[i32::MAX]), bytes(&[1i32])];
let out = reduce(&inputs, DType::I32, ReduceOp::Sum).unwrap();
assert_eq!(out, bytes(&[i32::MIN]));
let inputs = [bytes(&[200u8]), bytes(&[2u8])];
assert_eq!(
reduce(&inputs, DType::U8, ReduceOp::Prod).unwrap(),
vec![144u8]
);
}
#[test]
fn unsupported_dtypes_are_rejected() {
assert!(!supports(DType::Bool));
assert!(!supports(DType::Complex64));
assert!(supports(DType::U64));
assert_eq!(supports(DType::F16), cfg!(feature = "f16"));
}
#[cfg(feature = "f16")]
#[test]
fn half_widens_and_rounds_once() {
use half::{bf16, f16};
let h = |v: f32| f16::from_f32(v).to_ne_bytes().to_vec();
let inputs = [h(2048.0), h(1.0), h(1.0)];
assert_eq!(
reduce(&inputs, DType::F16, ReduceOp::Sum).unwrap(),
h(2050.0)
);
let b = |v: f32| bf16::from_f32(v).to_ne_bytes().to_vec();
let inputs = [b(256.0), b(1.0), b(1.0)];
assert_eq!(
reduce(&inputs, DType::BF16, ReduceOp::Sum).unwrap(),
b(258.0)
);
}
}