1use std::rc::Rc;
6
7use crate::{Matrix, Result, Runtime, matrix as core_matrix};
8
9use super::super::{Module, ModuleRegistry, matrix::swiglu};
10
11use super::{Linear, RmsNorm};
12
13pub struct Ffn {
20 model_width: usize,
21 hidden_width: usize,
22 epsilon: f32,
23 norm: Rc<RmsNorm>,
24 gate: Rc<Linear>,
25 up: Rc<Linear>,
26 down: Rc<Linear>,
27 registry: ModuleRegistry,
28}
29
30impl Ffn {
31 #[allow(clippy::too_many_arguments)]
32 pub fn new_with_seed(
33 model_width: usize,
34 hidden_width: usize,
35 epsilon: f32,
36 seed: u64,
37 ) -> Result<Self> {
38 Self::new_with_seed_on(
39 &Runtime::current()?,
40 model_width,
41 hidden_width,
42 epsilon,
43 seed,
44 )
45 }
46
47 pub fn new_with_seed_on(
54 runtime: &Runtime,
55 model_width: usize,
56 hidden_width: usize,
57 epsilon: f32,
58 seed: u64,
59 ) -> Result<Self> {
60 let norm = Rc::new(RmsNorm::new_on(runtime, model_width, epsilon)?);
61 let gate = Rc::new(Linear::new_with_seed_on(
62 runtime,
63 model_width,
64 hidden_width,
65 seed,
66 )?);
67 let up = Rc::new(Linear::new_with_seed_on(
68 runtime,
69 model_width,
70 hidden_width,
71 seed.wrapping_add(1),
72 )?);
73 let down = Rc::new(Linear::new_with_seed_on(
74 runtime,
75 hidden_width,
76 model_width,
77 seed.wrapping_add(2),
78 )?);
79 let mut registry = ModuleRegistry::new();
80 registry.register_module("norm", norm.clone())?;
81 registry.register_module("gate", gate.clone())?;
82 registry.register_module("up", up.clone())?;
83 registry.register_module("down", down.clone())?;
84 Ok(Self {
85 model_width,
86 hidden_width,
87 epsilon,
88 norm,
89 gate,
90 up,
91 down,
92 registry,
93 })
94 }
95
96 pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
103 let normalized = self.norm.forward(input)?;
104 let gate = self.gate.forward(&normalized)?;
105 let up = self.up.forward(&normalized)?;
106 let activated = swiglu(&gate, &up)?;
107 let projected = self.down.forward(&activated)?;
108 core_matrix::add(input, &projected)
109 }
110
111 pub const fn model_width(&self) -> usize {
113 self.model_width
114 }
115
116 pub const fn hidden_width(&self) -> usize {
118 self.hidden_width
119 }
120
121 pub const fn epsilon(&self) -> f32 {
123 self.epsilon
124 }
125}
126
127impl Module for Ffn {
128 fn forward(&self, input: &Matrix) -> Result<Matrix> {
129 Ffn::forward(self, input)
130 }
131
132 fn registry(&self) -> &ModuleRegistry {
133 &self.registry
134 }
135}