use crate::{
f,
layers::Linear,
optim::{Param, ToParams},
};
use ndarray::{Array2, Array3, ArrayViewMut1, Axis, Zip};
use ndarray_rand::{RandomExt, rand_distr::Normal};
use serde::{Deserialize, Serialize};
#[derive(Debug, Default, Clone)]
pub struct GATv2LayerCache {
pub s: Array2<f32>,
pub r: Array2<f32>,
pub alpha: Array2<f32>,
pub denom: Array2<f32>,
pub exp: Array2<f32>,
pub z: Array3<f32>,
}
#[derive(Debug, Default, Clone)]
pub struct GATv2LayerGrads {
pub d_a: Array2<f32>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct GATv2Layer {
pub d_in: usize,
pub d_head: usize,
pub n_head: usize,
pub d_out: usize,
pub s_proj: Linear,
pub r_proj: Linear,
pub o_proj: Linear,
pub a: Array2<f32>,
#[serde(skip)]
pub cache: GATv2LayerCache,
#[serde(skip)]
pub grads: GATv2LayerGrads,
}
impl GATv2Layer {
pub fn new(d_in: usize, d_head: usize, n_head: usize, d_out: usize) -> Self {
Self {
d_in,
d_head,
n_head,
d_out,
s_proj: Linear::new(d_in, n_head * d_head),
r_proj: Linear::new(d_in, n_head * d_head),
o_proj: Linear::new(n_head * d_head, d_out),
a: Array2::random((n_head, d_head), Normal::new(0., 1.).unwrap()),
cache: GATv2LayerCache::default(),
grads: GATv2LayerGrads::default(),
}
}
pub fn scatter_sum(x: &Array2<f32>, indices: &[usize], n: usize) -> Array2<f32> {
let e = x.dim().0;
let mut n_sum: Array2<f32> = Array2::zeros((n, x.ncols()));
for i in 0..e {
let mut n_dst: ArrayViewMut1<f32> = n_sum.row_mut(indices[i]);
n_dst += &(x.row(i));
}
n_sum
}
pub fn scatter_max(x: &Array2<f32>, indices: &[usize], n: usize) -> Array2<f32> {
let e = x.dim().0;
let mut n_max: Array2<f32> = Array2::from_elem((n, x.ncols()), f32::NEG_INFINITY);
for i in 0..e {
let dst = indices[i];
let mut n_dst: ArrayViewMut1<f32> = n_max.row_mut(dst);
Zip::from(&mut n_dst).and(&x.row(i)).for_each(|a, b| {
*a = (*a).max(*b);
});
}
n_max
}
pub fn forward(&mut self, x: Array2<f32>, index: &Array2<usize>, grad: bool) -> Array2<f32> {
let n = x.nrows();
let e = index.dim().0;
let x_s = self.s_proj.forward(x.clone(), grad); let x_r = self.r_proj.forward(x, grad);
let send = index.column(0).to_vec();
let recv = index.column(1).to_vec();
let s = x_s.select(Axis(0), &send); let r = x_r.select(Axis(0), &recv);
if grad {
self.cache.s = s.clone();
self.cache.r = r.clone();
}
let z = f::leaky_relu(&(&s + &r))
.into_shape_clone((e, self.n_head, self.d_head))
.unwrap();
let scores = (&z * &self.a.view().insert_axis(Axis(0))).sum_axis(Axis(2));
let m = GATv2Layer::scatter_max(&scores, &recv, n).select(Axis(0), &recv); let exp = (&scores - &m).exp(); let denom = GATv2Layer::scatter_sum(&exp, &recv, n).select(Axis(0), &recv); let alpha = &exp / &denom;
if grad {
self.cache.z = z.clone();
self.cache.alpha = alpha.clone();
}
let v = s
.view()
.into_shape_with_order((e, self.n_head, self.d_head))
.unwrap();
let msg = &v * &alpha.view().insert_axis(Axis(2));
let msg = msg
.into_shape_with_order((e, self.n_head * self.d_head))
.unwrap();
let agg = GATv2Layer::scatter_sum(&msg, &recv, n);
self.o_proj.forward(agg, grad) }
pub fn backward(&mut self, d_loss: Array2<f32>, index: &Array2<usize>) -> Array2<f32> {
if self.grads.d_a.dim() == (0, 0) {
self.grads.d_a = Array2::zeros(self.a.dim())
}
let send = index.column(0).to_vec();
let recv = index.column(1).to_vec();
let e = send.len();
let n = d_loss.nrows();
let d_agg = self.o_proj.backward(d_loss); let d_msg = d_agg.select(Axis(0), &recv);
let alpha = &self.cache.alpha;
let d_msg = d_msg
.into_shape_with_order((e, self.n_head, self.d_head))
.unwrap(); let v = self
.cache
.s
.view()
.into_shape_with_order((e, self.n_head, self.d_head))
.unwrap(); let d_v = &d_msg * &alpha.view().insert_axis(Axis(2));
let d_alpha = (&d_msg * &v).sum_axis(Axis(2));
let ag = alpha * &d_alpha; let row = GATv2Layer::scatter_sum(&ag, &recv, n).select(Axis(0), &recv); let d_scores = alpha * &(&d_alpha - &row);
let z = &self.cache.z;
let d_scores_3 = d_scores.view().insert_axis(Axis(2));
let d_a = (z * &d_scores_3).sum_axis(Axis(0));
let d_z = &self.a * &d_scores_3;
let d_z = d_z
.into_shape_with_order((e, self.n_head * self.d_head))
.unwrap();
let z = z
.view()
.into_shape_with_order((e, self.n_head * self.d_head))
.unwrap();
let d_u = d_z * f::d_leaky_relu(&z);
let d_v = d_v
.into_shape_with_order((e, self.n_head * self.d_head))
.unwrap();
let d_s = &d_u + &d_v;
let d_r = d_u
.into_shape_with_order((e, self.n_head * self.d_head))
.unwrap();
let d_x_s = GATv2Layer::scatter_sum(&d_s, &send, n); let d_x_r = GATv2Layer::scatter_sum(&d_r, &recv, n);
self.grads.d_a += &d_a;
let d_x1 = self.s_proj.backward(d_x_s);
let d_x2 = self.r_proj.backward(d_x_r);
d_x1 + d_x2
}
}
impl ToParams for GATv2Layer {
fn params(&mut self) -> Vec<crate::optim::Param> {
let mut params = vec![];
params.append(&mut self.s_proj.params());
params.append(&mut self.r_proj.params());
params.append(&mut self.o_proj.params());
params.push(Param::new(&mut self.a).with_grad(&mut self.grads.d_a));
params
}
}