use ndarray::{Array1, Array2, ArrayView2};
use std::collections::HashMap;
use std::fmt;
use super::npz::{NpzArchive, NpzError};
#[derive(Debug, Clone, PartialEq)]
pub struct LinearWeights {
pub weight: Array2<f32>,
pub bias: Array1<f32>,
}
impl LinearWeights {
pub fn apply(&self, x: ArrayView2<'_, f32>) -> Array2<f32> {
let mut y = x.dot(&self.weight.t());
y += &self.bias;
y
}
fn in_out_dim(&self) -> (usize, usize) {
(self.weight.shape()[1], self.weight.shape()[0])
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum SoftAggError {
Npz(NpzError),
ShapeMismatch {
field: &'static str,
message: String,
},
}
impl fmt::Display for SoftAggError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Npz(inner) => write!(f, "SoftAgg weight load failed: {inner}"),
Self::ShapeMismatch { field, message } => {
write!(f, "SoftAgg weight shape mismatch in {field}: {message}")
}
}
}
}
impl std::error::Error for SoftAggError {}
impl From<NpzError> for SoftAggError {
fn from(value: NpzError) -> Self {
Self::Npz(value)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct SoftAgg {
pub f: LinearWeights,
pub g: LinearWeights,
pub h: LinearWeights,
}
impl SoftAgg {
pub fn new(f: LinearWeights, g: LinearWeights, h: LinearWeights) -> Result<Self, SoftAggError> {
let dims = [f.in_out_dim(), g.in_out_dim(), h.in_out_dim()];
let (in0, out0) = dims[0];
if in0 != out0 || dims.iter().any(|&(i, o)| i != in0 || o != out0) {
return Err(SoftAggError::ShapeMismatch {
field: "f/g/h",
message: format!(
"expected all three Linear(dim, dim) layers to share one square dim, got {dims:?}"
),
});
}
Ok(Self { f, g, h })
}
pub fn load_from_npz(archive: &NpzArchive, prefix: &str) -> Result<Self, SoftAggError> {
let load_linear = |name: &str| -> Result<LinearWeights, SoftAggError> {
let (w_shape, w_data) = archive.read_f32(&format!("{prefix}{name}_weight"))?;
let (b_shape, b_data) = archive.read_f32(&format!("{prefix}{name}_bias"))?;
if w_shape.len() != 2 {
return Err(SoftAggError::ShapeMismatch {
field: "weight",
message: format!("expected a 2-D weight, got shape {w_shape:?}"),
});
}
if b_shape.len() != 1 || b_shape[0] != w_shape[0] {
return Err(SoftAggError::ShapeMismatch {
field: "bias",
message: format!(
"expected a 1-D bias matching weight's out_dim {}, got shape {b_shape:?}",
w_shape[0]
),
});
}
let weight = Array2::from_shape_vec((w_shape[0], w_shape[1]), w_data).map_err(|e| {
SoftAggError::ShapeMismatch {
field: "weight",
message: e.to_string(),
}
})?;
let bias = Array1::from_vec(b_data);
Ok(LinearWeights { weight, bias })
};
Self::new(load_linear("f")?, load_linear("g")?, load_linear("h")?)
}
pub fn forward(&self, x: ArrayView2<'_, f32>, group_key: &[i64]) -> Array2<f32> {
let num_edges = x.nrows();
let dim = x.ncols();
debug_assert_eq!(group_key.len(), num_edges);
if num_edges == 0 {
return Array2::zeros((0, dim));
}
let mut group_of: HashMap<i64, usize> = HashMap::new();
let group_ids: Vec<usize> = group_key
.iter()
.map(|&key| {
let next_id = group_of.len();
*group_of.entry(key).or_insert(next_id)
})
.collect();
let num_groups = group_of.len();
let g_x = self.g.apply(x);
let f_x = self.f.apply(x);
let mut group_max = Array2::<f32>::from_elem((num_groups, dim), f32::NEG_INFINITY);
for (edge, &gid) in group_ids.iter().enumerate() {
for c in 0..dim {
let v = g_x[(edge, c)];
if v > group_max[(gid, c)] {
group_max[(gid, c)] = v;
}
}
}
let mut exp_x = Array2::<f32>::zeros((num_edges, dim));
for (edge, &gid) in group_ids.iter().enumerate() {
for c in 0..dim {
exp_x[(edge, c)] = (g_x[(edge, c)] - group_max[(gid, c)]).exp();
}
}
let mut group_sum = Array2::<f32>::zeros((num_groups, dim));
for (edge, &gid) in group_ids.iter().enumerate() {
for c in 0..dim {
group_sum[(gid, c)] += exp_x[(edge, c)];
}
}
let mut y = Array2::<f32>::zeros((num_groups, dim));
for (edge, &gid) in group_ids.iter().enumerate() {
for c in 0..dim {
let weight = exp_x[(edge, c)] / group_sum[(gid, c)];
y[(gid, c)] += f_x[(edge, c)] * weight;
}
}
let y_h = self.h.apply(y.view());
let mut out = Array2::<f32>::zeros((num_edges, dim));
for (edge, &gid) in group_ids.iter().enumerate() {
out.row_mut(edge).assign(&y_h.row(gid));
}
out
}
}
pub fn neighbors_cpu(kk: &[i64], jj: &[i64]) -> (Vec<i64>, Vec<i64>) {
debug_assert_eq!(kk.len(), jj.len());
let n = kk.len();
let mut groups: HashMap<i64, Vec<usize>> = HashMap::new();
for (edge, &key) in kk.iter().enumerate() {
groups.entry(key).or_default().push(edge);
}
let mut ix = vec![-1i64; n];
let mut jx = vec![-1i64; n];
for members in groups.values_mut() {
members.sort_by_key(|&edge| jj[edge]);
for (position, &edge) in members.iter().enumerate() {
ix[edge] = if position > 0 {
members[position - 1] as i64
} else {
-1
};
jx[edge] = if position + 1 < members.len() {
members[position + 1] as i64
} else {
-1
};
}
}
(ix, jx)
}
#[cfg(test)]
mod tests {
use super::*;
use ndarray::array;
#[test]
fn neighbors_cpu_matches_hand_worked_example() {
let kk = vec![0, 0, 1, 1];
let jj = vec![2, 1, 2, 1];
let (ix, jx) = neighbors_cpu(&kk, &jj);
assert_eq!(ix, vec![1, -1, 3, -1]);
assert_eq!(jx, vec![-1, 0, -1, 2]);
}
#[test]
fn neighbors_cpu_singleton_groups_have_no_neighbours() {
let kk = vec![0, 1, 2];
let jj = vec![5, 5, 5];
let (ix, jx) = neighbors_cpu(&kk, &jj);
assert_eq!(ix, vec![-1, -1, -1]);
assert_eq!(jx, vec![-1, -1, -1]);
}
#[test]
fn neighbors_cpu_handles_empty_input() {
let (ix, jx) = neighbors_cpu(&[], &[]);
assert!(ix.is_empty() && jx.is_empty());
}
#[test]
fn neighbors_cpu_breaks_jj_ties_by_original_order() {
let kk = vec![0, 0, 0];
let jj = vec![5, 5, 5]; let (ix, jx) = neighbors_cpu(&kk, &jj);
assert_eq!(ix, vec![-1, 0, 1]);
assert_eq!(jx, vec![1, 2, -1]);
}
fn identity_linear(dim: usize) -> LinearWeights {
LinearWeights {
weight: Array2::eye(dim),
bias: Array1::zeros(dim),
}
}
#[test]
fn softagg_forward_reduces_to_hand_computable_softmax_average_with_identity_weights() {
let dim = 1;
let agg = SoftAgg::new(
identity_linear(dim),
identity_linear(dim),
identity_linear(dim),
)
.unwrap();
let x = array![[0.0_f32], [1.0], [5.0]];
let group_key = vec![0_i64, 0, 1];
let out = agg.forward(x.view(), &group_key);
let expected_group0 = 0.7310586_f32;
assert!(
(out[(0, 0)] - expected_group0).abs() < 1e-5,
"out[0]={}",
out[(0, 0)]
);
assert!(
(out[(1, 0)] - expected_group0).abs() < 1e-5,
"out[1]={}",
out[(1, 0)]
);
assert!((out[(2, 0)] - 5.0).abs() < 1e-5, "out[2]={}", out[(2, 0)]);
}
#[test]
fn softagg_forward_handles_empty_input() {
let dim = 4;
let agg = SoftAgg::new(
identity_linear(dim),
identity_linear(dim),
identity_linear(dim),
)
.unwrap();
let x = Array2::<f32>::zeros((0, dim));
let out = agg.forward(x.view(), &[]);
assert_eq!(out.shape(), &[0, dim]);
}
#[test]
fn softagg_new_rejects_mismatched_layer_dims() {
let dim4 = identity_linear(4);
let dim8 = identity_linear(8);
let result = SoftAgg::new(dim4.clone(), dim8, dim4);
assert!(matches!(result, Err(SoftAggError::ShapeMismatch { .. })));
}
}