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
impl OwnedQuantizedModel {
/// Tiled causal attention
///
/// IMP-111c: Flash Attention with causal masking.
/// For position i, only attends to positions 0..=i.
#[allow(clippy::too_many_arguments)]
pub fn tiled_causal_attention(
&self,
q: &[f32],
k: &[f32],
v: &[f32],
seq_len: usize,
head_dim: usize,
scale: f32,
tile_size: usize,
) -> Result<Vec<f32>> {
let tile_size = tile_size.max(1);
let mut output = vec![0.0f32; seq_len * head_dim];
// Process each query position
for i in 0..seq_len {
let q_i = &q[i * head_dim..(i + 1) * head_dim];
// Running statistics for online softmax
let mut running_max = f32::NEG_INFINITY;
let mut running_sum = 0.0f32;
let mut running_output = vec![0.0f32; head_dim];
// Only process K/V up to position i (causal)
let causal_len = i + 1;
// Process K/V in tiles
for tile_start in (0..causal_len).step_by(tile_size) {
let tile_end = (tile_start + tile_size).min(causal_len);
// Compute scores for this tile: q_i @ K_tile^T
let mut tile_scores = Vec::with_capacity(tile_end - tile_start);
for j in tile_start..tile_end {
let mut dot = 0.0f32;
for d in 0..head_dim {
dot += q_i[d] * k[j * head_dim + d];
}
tile_scores.push(dot * scale);
}
// Find tile max
let tile_max = tile_scores
.iter()
.cloned()
.fold(f32::NEG_INFINITY, f32::max);
// Update running statistics
let new_max = running_max.max(tile_max);
// Rescale previous output and sum
if new_max > running_max && running_sum > 0.0 {
let rescale = (running_max - new_max).exp();
running_sum *= rescale;
for out_val in &mut running_output {
*out_val *= rescale;
}
}
running_max = new_max;
// Accumulate this tile's contribution
for (idx, &score) in tile_scores.iter().enumerate() {
let j = tile_start + idx;
let weight = (score - running_max).exp();
running_sum += weight;
for d in 0..head_dim {
running_output[d] += weight * v[j * head_dim + d];
}
}
}
// Normalize output
if running_sum > 0.0 {
for d in 0..head_dim {
output[i * head_dim + d] = running_output[d] / running_sum;
}
}
}
Ok(output)
}
/// PMAT-395 step 3: Bidirectional attention for encoder
///
/// Same as tiled_causal_attention but attends to ALL positions
/// (no causal mask). Used by T5/Whisper encoder where each
/// position can attend to every other position.
#[allow(clippy::too_many_arguments)]
pub fn tiled_bidirectional_attention(
&self,
q: &[f32],
k: &[f32],
v: &[f32],
seq_len: usize,
head_dim: usize,
scale: f32,
tile_size: usize,
) -> Result<Vec<f32>> {
let tile_size = tile_size.max(1);
let mut output = vec![0.0f32; seq_len * head_dim];
for i in 0..seq_len {
let q_i = &q[i * head_dim..(i + 1) * head_dim];
let mut running_max = f32::NEG_INFINITY;
let mut running_sum = 0.0f32;
let mut running_output = vec![0.0f32; head_dim];
// Bidirectional: attend to ALL positions (not just 0..=i)
for tile_start in (0..seq_len).step_by(tile_size) {
let tile_end = (tile_start + tile_size).min(seq_len);
let mut tile_scores = Vec::with_capacity(tile_end - tile_start);
for j in tile_start..tile_end {
let mut dot = 0.0f32;
for d in 0..head_dim {
dot += q_i[d] * k[j * head_dim + d];
}
tile_scores.push(dot * scale);
}
let tile_max = tile_scores
.iter()
.cloned()
.fold(f32::NEG_INFINITY, f32::max);
let new_max = running_max.max(tile_max);
if new_max > running_max && running_sum > 0.0 {
let rescale = (running_max - new_max).exp();
running_sum *= rescale;
for out_val in &mut running_output {
*out_val *= rescale;
}
}
running_max = new_max;
for (idx, &score) in tile_scores.iter().enumerate() {
let j = tile_start + idx;
let weight = (score - running_max).exp();
running_sum += weight;
for d in 0..head_dim {
running_output[d] += weight * v[j * head_dim + d];
}
}
}
if running_sum > 0.0 {
for d in 0..head_dim {
output[i * head_dim + d] = running_output[d] / running_sum;
}
}
}
Ok(output)
}
/// PMAT-395 step 4: Cross-attention for encoder-decoder
///
/// Q comes from decoder, K/V come from encoder output.
/// No causal mask — decoder attends to all encoder positions.
/// Used in T5 decoder layers between self-attention and FFN.
#[allow(clippy::too_many_arguments)]
pub fn tiled_cross_attention(
&self,
q: &[f32], // [decoder_len, head_dim]
enc_k: &[f32], // [encoder_len, head_dim]
enc_v: &[f32], // [encoder_len, head_dim]
decoder_len: usize,
encoder_len: usize,
head_dim: usize,
scale: f32,
tile_size: usize,
) -> Result<Vec<f32>> {
let tile_size = tile_size.max(1);
let mut output = vec![0.0f32; decoder_len * head_dim];
for i in 0..decoder_len {
let q_i = &q[i * head_dim..(i + 1) * head_dim];
let mut running_max = f32::NEG_INFINITY;
let mut running_sum = 0.0f32;
let mut running_output = vec![0.0f32; head_dim];
// Cross-attention: attend to ALL encoder positions
for tile_start in (0..encoder_len).step_by(tile_size) {
let tile_end = (tile_start + tile_size).min(encoder_len);
let mut tile_scores =
Vec::with_capacity(tile_end - tile_start);
for j in tile_start..tile_end {
let mut dot = 0.0f32;
for d in 0..head_dim {
dot += q_i[d] * enc_k[j * head_dim + d];
}
tile_scores.push(dot * scale);
}
let tile_max = tile_scores
.iter()
.cloned()
.fold(f32::NEG_INFINITY, f32::max);
let new_max = running_max.max(tile_max);
if new_max > running_max && running_sum > 0.0 {
let rescale = (running_max - new_max).exp();
running_sum *= rescale;
for out_val in &mut running_output {
*out_val *= rescale;
}
}
running_max = new_max;
for (idx, &score) in tile_scores.iter().enumerate() {
let j = tile_start + idx;
let weight = (score - running_max).exp();
running_sum += weight;
for d in 0..head_dim {
running_output[d] +=
weight * enc_v[j * head_dim + d];
}
}
}
if running_sum > 0.0 {
for d in 0..head_dim {
output[i * head_dim + d] =
running_output[d] / running_sum;
}
}
}
Ok(output)
}
}
include!("batched.rs");
include!("batch_size.rs");
include!("acceleration.rs");
include!("attention.rs");