1use ndarray::{Array2, Array3};
2use serde::{Deserialize, Serialize};
3
4use crate::layers::LayerNorm;
5use crate::nn::{DeltaNet, GatedDeltaNet, GatedLinearAttention, LinearAttention, PositionwiseFFN};
6use crate::optim::{Param, ToIntermediates, ToParams};
7
8pub trait LinearAttentionLike: ToParams + ToIntermediates {
9 fn new(d_in: usize, d_head: usize) -> Self;
10 fn forward(&mut self, x: Array3<f32>, grad: bool) -> Array3<f32>;
11 fn backward(&mut self, d_loss: Array3<f32>) -> Array3<f32>;
12 fn step(&self, x: &Array2<f32>, state: &mut Array3<f32>) -> Array2<f32>;
13 fn new_state(&self, batch_size: usize) -> Array3<f32>;
14}
15
16impl LinearAttentionLike for LinearAttention {
17 fn new(d_in: usize, d_head: usize) -> Self {
18 LinearAttention::new(d_in, d_head)
19 }
20
21 fn forward(&mut self, x: Array3<f32>, grad: bool) -> Array3<f32> {
22 self.forward(x, grad)
23 }
24
25 fn backward(&mut self, d_loss: Array3<f32>) -> Array3<f32> {
26 self.backward(d_loss)
27 }
28
29 fn step(&self, x: &Array2<f32>, state: &mut Array3<f32>) -> Array2<f32> {
30 LinearAttention::step(self, x, state)
31 }
32
33 fn new_state(&self, batch_size: usize) -> Array3<f32> {
34 LinearAttention::new_state(self, batch_size)
35 }
36}
37
38impl LinearAttentionLike for GatedLinearAttention {
39 fn new(d_in: usize, d_head: usize) -> Self {
40 GatedLinearAttention::new(d_in, d_head)
41 }
42
43 fn forward(&mut self, x: Array3<f32>, grad: bool) -> Array3<f32> {
44 self.forward(x, grad)
45 }
46
47 fn backward(&mut self, d_loss: Array3<f32>) -> Array3<f32> {
48 self.backward(d_loss)
49 }
50
51 fn step(&self, x: &Array2<f32>, state: &mut Array3<f32>) -> Array2<f32> {
52 GatedLinearAttention::step(self, x, state)
53 }
54
55 fn new_state(&self, batch_size: usize) -> Array3<f32> {
56 Array3::zeros((batch_size, self.d_head, self.d_head))
57 }
58}
59
60impl LinearAttentionLike for DeltaNet {
61 fn new(d_in: usize, d_head: usize) -> Self {
62 DeltaNet::new(d_in, d_head)
63 }
64
65 fn forward(&mut self, x: Array3<f32>, grad: bool) -> Array3<f32> {
66 self.forward(x, grad)
67 }
68
69 fn backward(&mut self, d_loss: Array3<f32>) -> Array3<f32> {
70 self.backward(d_loss)
71 }
72
73 fn step(&self, x: &Array2<f32>, state: &mut Array3<f32>) -> Array2<f32> {
74 DeltaNet::step(self, x, state)
75 }
76
77 fn new_state(&self, batch_size: usize) -> Array3<f32> {
78 Array3::zeros((batch_size, self.d_head, self.d_head))
79 }
80}
81
82impl LinearAttentionLike for GatedDeltaNet {
83 fn new(d_in: usize, d_head: usize) -> Self {
84 GatedDeltaNet::new(d_in, d_head, d_in)
85 }
86
87 fn forward(&mut self, x: Array3<f32>, grad: bool) -> Array3<f32> {
88 self.forward(x, grad)
89 }
90
91 fn backward(&mut self, d_loss: Array3<f32>) -> Array3<f32> {
92 self.backward(d_loss)
93 }
94
95 fn step(&self, x: &Array2<f32>, state: &mut Array3<f32>) -> Array2<f32> {
96 GatedDeltaNet::step(self, x, state)
97 }
98
99 fn new_state(&self, batch_size: usize) -> Array3<f32> {
100 Array3::zeros((batch_size, self.d_head, self.d_head))
101 }
102}
103
104#[derive(Serialize, Deserialize, Debug, Clone)]
105pub struct LinearTransformerBase<A: LinearAttentionLike> {
106 pub d_in: usize,
107 pub attn: A,
108 pub norm_attn: LayerNorm,
109 pub feed_forward: PositionwiseFFN,
110 pub norm_feed_forward: LayerNorm,
111}
112
113impl<A: LinearAttentionLike> LinearTransformerBase<A> {
114 pub fn new(d_in: usize, d_head: usize) -> Self {
115 Self::from_attn(d_in, A::new(d_in, d_head))
116 }
117
118 pub fn from_attn(d_in: usize, attn: A) -> Self {
119 Self {
120 d_in,
121 attn,
122 norm_attn: LayerNorm::new(d_in),
123 feed_forward: PositionwiseFFN::new(d_in, 4 * d_in, d_in),
124 norm_feed_forward: LayerNorm::new(d_in),
125 }
126 }
127
128 pub fn forward(&mut self, x: Array3<f32>, grad: bool) -> Array3<f32> {
129 let (batch_size, seq_len, features) = x.dim();
130
131 let norm_x = self.norm_attn.forward(x.clone(), grad);
132
133 let attn_x = self.attn.forward(norm_x, grad);
134 let x = x + &attn_x;
135
136 let norm_x = self.norm_feed_forward.forward(x.clone(), grad);
137 let norm_x_2d = norm_x
138 .into_shape_clone((batch_size * seq_len, features))
139 .unwrap();
140 let ff_x_2d = self.feed_forward.forward(norm_x_2d, grad);
141 let ff_x = ff_x_2d
142 .into_shape_clone((batch_size, seq_len, features))
143 .unwrap();
144 let x = x + ff_x;
145
146 x
147 }
148
149 pub fn new_state(&self, batch_size: usize) -> Array3<f32> {
150 self.attn.new_state(batch_size)
151 }
152
153 pub fn step(&self, x: &Array2<f32>, state: &mut Array3<f32>) -> Array2<f32> {
154 let norm_x = self.norm_attn.infer(x);
155 let x = x + &self.attn.step(&norm_x, state);
156
157 let norm_x = self.norm_feed_forward.infer(&x);
158 &x + &self.feed_forward.infer(&norm_x)
159 }
160
161 pub fn backward(&mut self, d_loss: Array3<f32>) -> Array3<f32> {
162 let (batch_size, seq_len, features) = d_loss.dim();
163
164 let d_loss_2d = d_loss
165 .clone()
166 .into_shape_clone((batch_size * seq_len, features))
167 .unwrap();
168 let d_ffn_2d = self.feed_forward.backward(d_loss_2d);
169 let d_ffn = d_ffn_2d
170 .into_shape_clone((batch_size, seq_len, features))
171 .unwrap();
172 let d_norm_1 = d_loss + self.norm_feed_forward.backward(d_ffn);
173
174 let d_attn = self.attn.backward(d_norm_1.clone());
175 let d_norm = self.norm_attn.backward(d_attn);
176
177 d_norm + d_norm_1
178 }
179}
180
181impl<A: LinearAttentionLike> ToParams for LinearTransformerBase<A> {
182 fn params(&mut self) -> Vec<Param> {
183 let mut params = vec![];
184
185 params.append(&mut self.attn.params());
186 params.append(&mut self.norm_attn.params());
187 params.append(&mut self.feed_forward.params());
188 params.append(&mut self.norm_feed_forward.params());
189
190 params
191 }
192}
193
194impl<A: LinearAttentionLike> ToIntermediates for LinearTransformerBase<A> {
195 fn intermediates(&mut self) -> Vec<&mut dyn crate::optim::Intermediate> {
196 let mut intermediates = vec![];
197
198 intermediates.append(&mut self.attn.intermediates());
199 intermediates.append(&mut self.norm_attn.intermediates());
200 intermediates.append(&mut self.feed_forward.intermediates());
201 intermediates.append(&mut self.norm_feed_forward.intermediates());
202
203 intermediates
204 }
205}
206
207pub type LinearTransformer = LinearTransformerBase<LinearAttention>;
208pub type GlaTransformer = LinearTransformerBase<GatedLinearAttention>;
209pub type DeltaNetTransformer = LinearTransformerBase<DeltaNet>;
210pub type GdnTransformer = LinearTransformerBase<GatedDeltaNet>;