File size: 9,515 Bytes
1269259 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 | // 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]
}
}
|