1use crate::{Error, Matrix, Result, Runtime};
6
7use super::super::{Module, ModuleRegistry, Parameter, autograd, matrix, random};
8
9enum ProjectionBias {
12 Parameter(Parameter),
13 Zero(Matrix),
14}
15
16impl ProjectionBias {
17 fn snapshot(&self) -> (Matrix, Option<(Parameter, u64)>, bool) {
18 match self {
19 Self::Parameter(parameter) => {
20 let (value, version, requires_grad) = parameter.snapshot();
21 (
22 value,
23 requires_grad.then(|| (parameter.clone(), version)),
24 requires_grad,
25 )
26 }
27 Self::Zero(value) => (value.clone(), None, false),
28 }
29 }
30}
31
32pub struct Swiglu {
34 input_features: usize,
35 intermediate_size: usize,
36 weights: [Parameter; 3],
37 biases: [ProjectionBias; 3],
38 registry: ModuleRegistry,
39}
40
41impl Swiglu {
42 #[allow(clippy::too_many_arguments)]
43 pub fn new_with_seed(
44 input_features: usize,
45 intermediate_size: usize,
46 bias: bool,
47 seed: u64,
48 ) -> Result<Self> {
49 Self::new_with_seed_on(
50 &Runtime::current()?,
51 input_features,
52 intermediate_size,
53 bias,
54 seed,
55 )
56 }
57
58 pub fn new_with_seed_on(
65 runtime: &Runtime,
66 input_features: usize,
67 intermediate_size: usize,
68 bias: bool,
69 seed: u64,
70 ) -> Result<Self> {
71 if input_features == 0 || intermediate_size == 0 {
72 return Err(Error::invalid_argument(
73 "SwiGLU feature counts must be nonzero",
74 ));
75 }
76 let gate_weight = xavier_parameter(
77 runtime,
78 "gate_weight",
79 input_features,
80 intermediate_size,
81 seed,
82 )?;
83 let up_weight = xavier_parameter(
84 runtime,
85 "up_weight",
86 input_features,
87 intermediate_size,
88 seed.wrapping_add(1),
89 )?;
90 let down_weight = xavier_parameter(
91 runtime,
92 "down_weight",
93 intermediate_size,
94 input_features,
95 seed.wrapping_add(2),
96 )?;
97 let biases = [
98 projection_bias(runtime, "gate_bias", intermediate_size, bias)?,
99 projection_bias(runtime, "up_bias", intermediate_size, bias)?,
100 projection_bias(runtime, "down_bias", input_features, bias)?,
101 ];
102 let weights = [gate_weight, up_weight, down_weight];
103 let mut registry = ModuleRegistry::new();
104 for (name, weight) in ["gate_weight", "up_weight", "down_weight"]
105 .into_iter()
106 .zip(&weights)
107 {
108 registry.register_parameter(name, weight.clone())?;
109 }
110 for (name, projection_bias) in ["gate_bias", "up_bias", "down_bias"]
111 .into_iter()
112 .zip(&biases)
113 {
114 if let ProjectionBias::Parameter(parameter) = projection_bias {
115 registry.register_parameter(name, parameter.clone())?;
116 }
117 }
118 Ok(Self {
119 input_features,
120 intermediate_size,
121 weights,
122 biases,
123 registry,
124 })
125 }
126
127 pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
136 let Some(&width) = input.shape().last() else {
137 return Err(Error::invalid_argument(
138 "SwiGLU input must have at least one dimension",
139 ));
140 };
141 if width != self.input_features {
142 return Err(Error::invalid_argument(
143 "SwiGLU input final dimension does not match input_features",
144 ));
145 }
146 let rows = input.num_elements() / width;
147 let flat = if input.shape().len() == 2 {
148 input.clone()
149 } else {
150 input.reshape([rows, width])?
151 };
152 let gate = project(&flat, &self.weights[0], &self.biases[0])?;
153 let up = project(&flat, &self.weights[1], &self.biases[1])?;
154 let activated = matrix::swiglu(&gate, &up)?;
155 let output = project(&activated, &self.weights[2], &self.biases[2])?;
156 if input.shape().len() == 2 {
157 return Ok(output);
158 }
159 let mut output_shape = input.shape().to_vec();
160 *output_shape
161 .last_mut()
162 .expect("nonempty input shape was validated") = self.input_features;
163 output.reshape(output_shape)
164 }
165
166 pub const fn input_features(&self) -> usize {
168 self.input_features
169 }
170
171 pub const fn intermediate_size(&self) -> usize {
173 self.intermediate_size
174 }
175
176 pub fn has_bias(&self) -> bool {
178 matches!(&self.biases[0], ProjectionBias::Parameter(_))
179 }
180}
181
182impl Module for Swiglu {
183 fn forward(&self, input: &Matrix) -> Result<Matrix> {
184 Swiglu::forward(self, input)
185 }
186
187 fn registry(&self) -> &ModuleRegistry {
188 &self.registry
189 }
190}
191
192fn xavier_parameter(
193 runtime: &Runtime,
194 name: &'static str,
195 input_features: usize,
196 output_features: usize,
197 seed: u64,
198) -> Result<Parameter> {
199 let count = input_features
200 .checked_mul(output_features)
201 .ok_or_else(|| Error::invalid_argument("SwiGLU weight size overflows usize"))?;
202 let denominator = input_features
203 .checked_add(output_features)
204 .ok_or_else(|| Error::invalid_argument("SwiGLU Xavier extent overflows usize"))?;
205 let limit = (6.0_f32 / denominator as f32).sqrt();
206 Parameter::new(
207 name,
208 Matrix::new_from_f32_on(
209 runtime,
210 [output_features, input_features],
211 &random::symmetric_uniform(count, limit, seed),
212 )?,
213 )
214}
215
216fn projection_bias(
217 runtime: &Runtime,
218 name: &'static str,
219 size: usize,
220 trainable: bool,
221) -> Result<ProjectionBias> {
222 let value = Matrix::new_from_f32_on(runtime, [size], &vec![0.0; size])?;
223 if trainable {
224 Ok(ProjectionBias::Parameter(Parameter::new(name, value)?))
225 } else {
226 Ok(ProjectionBias::Zero(value))
227 }
228}
229
230fn project(input: &Matrix, weight: &Parameter, bias: &ProjectionBias) -> Result<Matrix> {
231 let (weight_value, weight_version, weight_requires_grad) = weight.snapshot();
232 let (bias_value, bias_parameter, bias_requires_grad) = bias.snapshot();
233 let output = matrix::linear(input, &weight_value, &bias_value)?;
234 if weight_requires_grad || bias_requires_grad {
235 autograd::record_linear(
236 input,
237 &output,
238 weight.clone(),
239 weight_value,
240 weight_version,
241 bias_parameter,
242 )?;
243 }
244 Ok(output)
245}