SPFsmartGATE / src /ffn.rs
JosephStoneCellAI's picture
Upload 45 files
1269259 verified
// SPF Smart Gateway - Position-wise Feed-Forward Network
// Copyright 2026 Joseph Stone - All Rights Reserved
//
// Two-layer feed-forward network used in every transformer block.
// Linear → GELU → Linear with configurable hidden dimension.
// Pure Rust — builds on tensor.rs only.
//
// Depends on: tensor.rs (Layer 0)
//
// Weight convention: [out_features, in_features] (PyTorch standard)
// Matmul: y = x @ W^T + b
// This matches attention.rs — transpose_2d() on every weight matmul.
use crate::tensor::Tensor;
// ============================================================================
// ACTIVATION CACHE (for backward pass — P2-C)
// ============================================================================
/// Cached activations from FFN forward pass (for backward)
pub struct FfnCache {
/// Input to FFN [batch*seq, d_model]
pub input: Tensor,
/// Hidden state before GELU activation [batch*seq, d_ff]
pub hidden_pre_gelu: Tensor,
}
// ============================================================================
// FFN CONFIGURATION
// ============================================================================
/// Configuration for feed-forward network
#[derive(Debug, Clone)]
pub struct FfnConfig {
/// Input/output dimension (matches d_model)
pub d_model: usize,
/// Hidden layer dimension (typically 4× d_model)
pub d_ff: usize,
}
impl FfnConfig {
/// Default: hidden dim = 4× model dim (standard transformer ratio)
pub fn default_for(d_model: usize) -> Self {
Self {
d_model,
d_ff: d_model * 4,
}
}
}
// ============================================================================
// FEED-FORWARD NETWORK
// ============================================================================
/// Position-wise feed-forward network.
///
/// Applied independently to each position in the sequence.
/// Architecture: Linear(d_model → d_ff) → GELU → Linear(d_ff → d_model)
///
/// This is the "thinking" layer — attention gathers context,
/// FFN transforms each position's representation.
pub struct FeedForward {
pub config: FfnConfig,
/// First linear: [d_ff, d_model] (out=d_ff, in=d_model)
pub w1: Tensor,
/// First bias: [d_ff]
pub b1: Tensor,
/// Second linear: [d_model, d_ff] (out=d_model, in=d_ff)
pub w2: Tensor,
/// Second bias: [d_model]
pub b2: Tensor,
}
impl FeedForward {
/// Initialize with Xavier/Glorot scaling
/// Weight convention: [out_features, in_features]
pub fn new(config: FfnConfig, seed: u64) -> Self {
let d = config.d_model;
let ff = config.d_ff;
// Xavier scale based on fan_in + fan_out
let scale1 = (6.0 / (d + ff) as f32).sqrt();
let scale2 = (6.0 / (ff + d) as f32).sqrt();
Self {
w1: Tensor::randn(&[ff, d], seed).scale(scale1), // [d_ff, d_model]
b1: Tensor::zeros(&[ff]),
w2: Tensor::randn(&[d, ff], seed + 1).scale(scale2), // [d_model, d_ff]
b2: Tensor::zeros(&[d]),
config,
}
}
/// Forward pass: input [batch, seq_len, d_model] → output [batch, seq_len, d_model]
///
/// Steps:
/// 1. Reshape to [batch*seq, d_model]
/// 2. Linear projection to d_ff with GELU activation
/// 3. Linear projection back to d_model
/// 4. Reshape to [batch, seq_len, d_model]
///
/// Matmul convention: y = x @ W^T + b (W stored as [out, in])
pub fn forward(&self, x: &Tensor) -> Result<Tensor, String> {
if x.ndim() != 3 {
return Err(format!("FFN expects 3D input [batch, seq, d_model], got {}D", x.ndim()));
}
let batch = x.shape[0];
let seq_len = x.shape[1];
let d_model = x.shape[2];
if d_model != self.config.d_model {
return Err(format!(
"Input d_model {} doesn't match config {}",
d_model, self.config.d_model
));
}
// Flatten to 2D for matmul
let x_2d = x.reshape(&[batch * seq_len, d_model])?;
// First linear: x[batch*seq, d_model] × w1^T[d_model, d_ff] = [batch*seq, d_ff]
let hidden = x_2d.matmul(&self.w1.transpose_2d()?)?
.add(&self.expand_bias(&self.b1, batch * seq_len))?;
// GELU activation
let activated = hidden.gelu();
// Second linear: h[batch*seq, d_ff] × w2^T[d_ff, d_model] = [batch*seq, d_model]
let output = activated.matmul(&self.w2.transpose_2d()?)?
.add(&self.expand_bias(&self.b2, batch * seq_len))?;
// Reshape back to 3D
output.reshape(&[batch, seq_len, d_model])
}
/// Forward pass that also returns cached activations for backward.
/// Output is IDENTICAL to forward(). Cache is additional data only.
pub fn forward_with_cache(&self, x: &Tensor) -> Result<(Tensor, FfnCache), String> {
if x.ndim() != 3 {
return Err(format!("FFN expects 3D input [batch, seq, d_model], got {}D", x.ndim()));
}
let batch = x.shape[0];
let seq_len = x.shape[1];
let d_model = x.shape[2];
if d_model != self.config.d_model {
return Err(format!("Input d_model {} doesn't match config {}", d_model, self.config.d_model));
}
let x_2d = x.reshape(&[batch * seq_len, d_model])?;
let input_cache = x_2d.clone();
// First linear: [batch*seq, d_model] × w1^T = [batch*seq, d_ff]
let hidden = x_2d.matmul(&self.w1.transpose_2d()?)?
.add(&self.expand_bias(&self.b1, batch * seq_len))?;
let hidden_pre_gelu = hidden.clone();
// GELU activation
let activated = hidden.gelu();
// Second linear: [batch*seq, d_ff] × w2^T = [batch*seq, d_model]
let output = activated.matmul(&self.w2.transpose_2d()?)?
.add(&self.expand_bias(&self.b2, batch * seq_len))?;
let output = output.reshape(&[batch, seq_len, d_model])?;
let cache = FfnCache {
input: input_cache,
hidden_pre_gelu,
};
Ok((output, cache))
}
/// Expand bias [dim] to [n_rows, dim] for addition after matmul
fn expand_bias(&self, bias: &Tensor, n_rows: usize) -> Tensor {
let d = bias.numel();
let mut data = Vec::with_capacity(n_rows * d);
for _ in 0..n_rows {
data.extend_from_slice(&bias.data);
}
Tensor { data, shape: vec![n_rows, d] }
}
/// Total number of parameters
pub fn num_params(&self) -> usize {
let d = self.config.d_model;
let ff = self.config.d_ff;
// w1[ff,d] + b1[ff] + w2[d,ff] + b2[d]
ff * d + ff + d * ff + d
}
/// Collect all weight tensors (for serialization / gradient updates)
pub fn weights(&self) -> Vec<&Tensor> {
vec![&self.w1, &self.b1, &self.w2, &self.b2]
}
/// Collect all weight tensors mutably (for optimizer updates)
pub fn weights_mut(&mut self) -> Vec<&mut Tensor> {
vec![&mut self.w1, &mut self.b1, &mut self.w2, &mut self.b2]
}
}
// ============================================================================
// TESTS
// ============================================================================
#[cfg(test)]
mod tests {
use super::*;
fn test_config() -> FfnConfig {
FfnConfig { d_model: 64, d_ff: 256 }
}
#[test]
fn test_ffn_output_shape() {
let ffn = FeedForward::new(test_config(), 42);
let x = Tensor::randn(&[2, 8, 64], 99); // batch=2, seq=8, d=64
let out = ffn.forward(&x).unwrap();
assert_eq!(out.shape, vec![2, 8, 64]);
}
#[test]
fn test_ffn_values_finite() {
let ffn = FeedForward::new(test_config(), 42);
let x = Tensor::randn(&[1, 4, 64], 99);
let out = ffn.forward(&x).unwrap();
assert!(out.data.iter().all(|v| v.is_finite()));
}
#[test]
fn test_ffn_num_params() {
let ffn = FeedForward::new(test_config(), 42);
// d=64, ff=256: 256×64 + 256 + 64×256 + 64 = 16384 + 256 + 16384 + 64 = 33088
assert_eq!(ffn.num_params(), 33088);
}
#[test]
fn test_ffn_default_config() {
let config = FfnConfig::default_for(256);
assert_eq!(config.d_model, 256);
assert_eq!(config.d_ff, 1024);
}
#[test]
fn test_ffn_dimension_mismatch() {
let ffn = FeedForward::new(test_config(), 42);
let x = Tensor::randn(&[1, 4, 32], 99); // wrong d_model
assert!(ffn.forward(&x).is_err());
}
#[test]
fn test_ffn_weights_count() {
let ffn = FeedForward::new(test_config(), 42);
assert_eq!(ffn.weights().len(), 4); // w1, b1, w2, b2
}
#[test]
fn test_ffn_single_position() {
// seq_len=1 should work fine
let ffn = FeedForward::new(test_config(), 42);
let x = Tensor::randn(&[1, 1, 64], 99);
let out = ffn.forward(&x).unwrap();
assert_eq!(out.shape, vec![1, 1, 64]);
}
#[test]
fn test_ffn_weight_shapes() {
let ffn = FeedForward::new(test_config(), 42);
// Verify weight convention: [out_features, in_features]
assert_eq!(ffn.w1.shape, vec![256, 64]); // [d_ff, d_model]
assert_eq!(ffn.w2.shape, vec![64, 256]); // [d_model, d_ff]
assert_eq!(ffn.b1.shape, vec![256]); // [d_ff]
assert_eq!(ffn.b2.shape, vec![64]); // [d_model]
}
}