wasmicro 0.3.1

Tiny transformer inference for the web. BERT, GPT-2 and T5 in a 199 KB WASM bundle.
Documentation
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//! Multi-head self-attention and pooling helpers.
//!
//! Implementation choice: heads are processed in a loop on the Rust side
//! rather than via batched matmul. This keeps the code small and obvious; the
//! per-head work is the standard `softmax(Q K^T / sqrt(d)) V` pipeline.
//! When SIMD / batched matmul lands, the optimized path will replace this
//! reference without changing the public signature.

use crate::ops::elementwise::scale;
use crate::ops::linear::linear;
use crate::ops::matmul::{matmul, matmul_t_b};
use crate::ops::softmax::softmax_last_dim;
use crate::tensor::Tensor;

/// Extracts a single head's columns from a `[seq_len, hidden]` tensor.
/// Returns a `[seq_len, head_dim]` tensor.
fn extract_head(x: &Tensor, head_idx: usize, num_heads: usize) -> Tensor {
    let shape = x.shape().as_slice();
    assert_eq!(shape.len(), 2, "extract_head: x must be 2D");
    let seq_len = shape[0];
    let hidden = shape[1];
    assert!(
        hidden.is_multiple_of(num_heads),
        "extract_head: hidden ({}) must be divisible by num_heads ({})",
        hidden,
        num_heads
    );
    let head_dim = hidden / num_heads;
    let src = x.data();
    let mut out = vec![0.0f32; seq_len * head_dim];
    for t in 0..seq_len {
        let src_off = t * hidden + head_idx * head_dim;
        let dst_off = t * head_dim;
        out[dst_off..dst_off + head_dim].copy_from_slice(&src[src_off..src_off + head_dim]);
    }
    Tensor::from_vec(out, &[seq_len, head_dim])
}

/// Writes a per-head result `[seq_len, head_dim]` back into the correct
/// columns of a `[seq_len, hidden]` flat buffer.
fn write_head_back(dst: &mut [f32], head_result: &Tensor, head_idx: usize, num_heads: usize) {
    let shape = head_result.shape().as_slice();
    assert_eq!(shape.len(), 2, "write_head_back: head must be 2D");
    let seq_len = shape[0];
    let head_dim = shape[1];
    let hidden = num_heads * head_dim;
    let src = head_result.data();
    for t in 0..seq_len {
        let src_off = t * head_dim;
        let dst_off = t * hidden + head_idx * head_dim;
        dst[dst_off..dst_off + head_dim].copy_from_slice(&src[src_off..src_off + head_dim]);
    }
}

/// Multi-head self-attention with output projection.
///
/// All linear projections follow the PyTorch convention: weights are stored
/// as `[hidden, hidden]` with rows-as-outputs. The `linear` helper handles
/// the implicit transpose.
///
/// - `x`: input `[seq_len, hidden]`
/// - `wq`, `wk`, `wv`, `wo`: query / key / value / output projections
/// - `bq`, `bk`, `bv`, `bo`: optional biases (BERT uses all four)
/// - `num_heads`: must divide `hidden` evenly
///
/// Returns a `[seq_len, hidden]` tensor.
///
/// The flat parameter list mirrors the natural shape of self-attention
/// weights (Q/K/V/O × weight/bias). Wrapping them in a struct would force
/// every caller to construct one purely for the call — see `BertModel` for
/// an example of how higher-level structs feed into this op.
#[allow(clippy::too_many_arguments)]
pub fn multi_head_attention(
    x: &Tensor,
    wq: &Tensor,
    bq: Option<&Tensor>,
    wk: &Tensor,
    bk: Option<&Tensor>,
    wv: &Tensor,
    bv: Option<&Tensor>,
    wo: &Tensor,
    bo: Option<&Tensor>,
    num_heads: usize,
) -> Tensor {
    let shape = x.shape().as_slice();
    assert_eq!(shape.len(), 2, "multi_head_attention: x must be 2D");
    let hidden = shape[1];
    assert!(
        hidden.is_multiple_of(num_heads),
        "multi_head_attention: hidden ({}) must be divisible by num_heads ({})",
        hidden,
        num_heads
    );

    let q = linear(x, wq, bq);
    let k = linear(x, wk, bk);
    let v = linear(x, wv, bv);

    let concat = multi_head_attention_from_qkv(&q, &k, &v, num_heads);
    linear(&concat, wo, bo)
}

/// Computes scaled dot-product multi-head attention from precomputed Q/K/V.
///
/// - `q`, `k`, `v`: shape `[seq_len, hidden]`
/// - `num_heads`: must divide `hidden` evenly
/// - returned tensor shape: `[seq_len, hidden]`
pub fn multi_head_attention_from_qkv(
    q: &Tensor,
    k: &Tensor,
    v: &Tensor,
    num_heads: usize,
) -> Tensor {
    let q_shape = q.shape().as_slice();
    let k_shape = k.shape().as_slice();
    let v_shape = v.shape().as_slice();
    assert_eq!(
        q_shape.len(),
        2,
        "multi_head_attention_from_qkv: q must be 2D"
    );
    assert_eq!(
        k_shape, q_shape,
        "multi_head_attention_from_qkv: k shape mismatch"
    );
    assert_eq!(
        v_shape, q_shape,
        "multi_head_attention_from_qkv: v shape mismatch"
    );

    let seq_len = q_shape[0];
    let hidden = q_shape[1];
    assert!(
        hidden.is_multiple_of(num_heads),
        "multi_head_attention_from_qkv: hidden ({}) must be divisible by num_heads ({})",
        hidden,
        num_heads
    );
    let head_dim = hidden / num_heads;
    let scale_factor = 1.0 / (head_dim as f32).sqrt();
    let mut concat = vec![0.0f32; seq_len * hidden];

    for h in 0..num_heads {
        let q_h = extract_head(q, h, num_heads);
        let k_h = extract_head(k, h, num_heads);
        let v_h = extract_head(v, h, num_heads);

        // scores = Q_h @ K_h^T / sqrt(head_dim)
        let scores = matmul_t_b(&q_h, &k_h);
        let scores = scale(&scores, scale_factor);
        let attn = softmax_last_dim(&scores);
        let head_out = matmul(&attn, &v_h);
        write_head_back(&mut concat, &head_out, h, num_heads);
    }

    Tensor::from_vec(concat, &[seq_len, hidden])
}

/// Mean-pools a `[seq_len, hidden]` tensor along the sequence dimension.
///
/// If `attention_mask` is provided, masked positions (mask value `0`) are
/// excluded from both the sum and the divisor. This matches the
/// sentence-transformers mean-pooling convention.
///
/// Returns a `[hidden]` tensor.
pub fn mean_pool(x: &Tensor, attention_mask: Option<&[u32]>) -> Tensor {
    let shape = x.shape().as_slice();
    assert_eq!(shape.len(), 2, "mean_pool: x must be 2D");
    let seq_len = shape[0];
    let hidden = shape[1];
    if let Some(m) = attention_mask {
        assert_eq!(
            m.len(),
            seq_len,
            "mean_pool: mask length must equal sequence length"
        );
    }

    let data = x.data();
    let mut out = vec![0.0f32; hidden];
    let mut count = 0.0f32;
    for t in 0..seq_len {
        let valid = match attention_mask {
            Some(m) => m[t] != 0,
            None => true,
        };
        if valid {
            let row = &data[t * hidden..(t + 1) * hidden];
            for (o, &v) in out.iter_mut().zip(row) {
                *o += v;
            }
            count += 1.0;
        }
    }
    if count > 0.0 {
        let inv = 1.0 / count;
        for o in out.iter_mut() {
            *o *= inv;
        }
    }
    Tensor::from_vec(out, &[hidden])
}

/// Causal (lower-triangular) multi-head self-attention.
///
/// Each position can attend only to itself and earlier positions. Used by
/// GPT-2 and other decoder-only models for autoregressive generation.
///
/// - `q`, `k`, `v`: shape `[seq_len, hidden]`
/// - returned tensor shape: `[seq_len, hidden]`
pub fn causal_multi_head_attention_from_qkv(
    q: &Tensor,
    k: &Tensor,
    v: &Tensor,
    num_heads: usize,
) -> Tensor {
    let q_shape = q.shape().as_slice();
    let seq_len = q_shape[0];
    let hidden = q_shape[1];
    assert!(
        hidden.is_multiple_of(num_heads),
        "causal_attention: hidden must be divisible by num_heads"
    );
    let head_dim = hidden / num_heads;
    let scale_factor = 1.0 / (head_dim as f32).sqrt();
    let mut concat = vec![0.0f32; seq_len * hidden];

    for h in 0..num_heads {
        let q_h = extract_head(q, h, num_heads);
        let k_h = extract_head(k, h, num_heads);
        let v_h = extract_head(v, h, num_heads);

        let raw = matmul_t_b(&q_h, &k_h);
        let raw = scale(&raw, scale_factor);
        let masked = apply_causal_mask(&raw);
        let attn = softmax_last_dim(&masked);
        let head_out = matmul(&attn, &v_h);
        write_head_back(&mut concat, &head_out, h, num_heads);
    }

    Tensor::from_vec(concat, &[seq_len, hidden])
}

/// Cross-attention: Q from decoder, K/V from encoder.
///
/// Q may have a different sequence length from K and V. No causal mask is
/// applied. Used for T5-style encoder-decoder attention.
///
/// - `q`: shape `[q_len, hidden]`
/// - `k`, `v`: shape `[kv_len, hidden]`
/// - returned tensor shape: `[q_len, hidden]`
pub fn cross_attention_from_qkv(q: &Tensor, k: &Tensor, v: &Tensor, num_heads: usize) -> Tensor {
    let q_shape = q.shape().as_slice();
    let q_len = q_shape[0];
    let hidden = q_shape[1];
    assert!(
        hidden.is_multiple_of(num_heads),
        "cross_attention: hidden must be divisible by num_heads"
    );
    let head_dim = hidden / num_heads;
    let scale_factor = 1.0 / (head_dim as f32).sqrt();
    let mut concat = vec![0.0f32; q_len * hidden];

    for h in 0..num_heads {
        let q_h = extract_head(q, h, num_heads);
        let k_h = extract_head(k, h, num_heads);
        let v_h = extract_head(v, h, num_heads);

        let raw = matmul_t_b(&q_h, &k_h);
        let raw = scale(&raw, scale_factor);
        let attn = softmax_last_dim(&raw);
        let head_out = matmul(&attn, &v_h);
        write_head_back(&mut concat, &head_out, h, num_heads);
    }

    Tensor::from_vec(concat, &[q_len, hidden])
}

/// Multi-head attention with an additive relative position bias (T5-style).
///
/// - `q`, `k`, `v`: shape `[q_len, hidden]` (K/V may have different q_len)
/// - `bias`: shape `[num_heads, q_len, kv_len]` — added to raw scores
/// - `causal`: if true, applies a lower-triangular mask after the bias
///
/// Returns `[q_len, hidden]`.
pub fn multi_head_attention_with_bias(
    q: &Tensor,
    k: &Tensor,
    v: &Tensor,
    num_heads: usize,
    bias: Option<&Tensor>,
    causal: bool,
) -> Tensor {
    let q_shape = q.shape().as_slice();
    let k_shape = k.shape().as_slice();
    let q_len = q_shape[0];
    let hidden = q_shape[1];
    let kv_len = k_shape[0];
    assert!(
        hidden.is_multiple_of(num_heads),
        "attention_with_bias: hidden must be divisible by num_heads"
    );
    let head_dim = hidden / num_heads;
    let scale_factor = 1.0 / (head_dim as f32).sqrt();
    let mut concat = vec![0.0f32; q_len * hidden];
    let bias_data = bias.map(|b| b.data());

    for h in 0..num_heads {
        let q_h = extract_head(q, h, num_heads);
        let k_h = extract_head(k, h, num_heads);
        let v_h = extract_head(v, h, num_heads);

        let raw = matmul_t_b(&q_h, &k_h);
        let mut scores = raw.data().to_vec();

        if let Some(bd) = bias_data {
            let bias_off = h * q_len * kv_len;
            for i in 0..q_len {
                for j in 0..kv_len {
                    scores[i * kv_len + j] =
                        scores[i * kv_len + j] * scale_factor + bd[bias_off + i * kv_len + j];
                }
            }
        } else {
            for s in &mut scores {
                *s *= scale_factor;
            }
        }

        if causal {
            for i in 0..q_len {
                for j in (i + 1)..kv_len {
                    scores[i * kv_len + j] = f32::NEG_INFINITY;
                }
            }
        }

        let scores_t = Tensor::from_vec(scores, &[q_len, kv_len]);
        let attn = softmax_last_dim(&scores_t);
        let head_out = matmul(&attn, &v_h);
        write_head_back(&mut concat, &head_out, h, num_heads);
    }

    Tensor::from_vec(concat, &[q_len, hidden])
}

/// Applies a lower-triangular causal mask to a `[q_len, k_len]` score tensor.
/// Positions where `j > i` are set to `-inf` so softmax zeroes them out.
fn apply_causal_mask(scores: &Tensor) -> Tensor {
    let shape = scores.shape().as_slice();
    let q_len = shape[0];
    let k_len = shape[1];
    let mut out = scores.data().to_vec();
    for i in 0..q_len {
        for j in (i + 1)..k_len {
            out[i * k_len + j] = f32::NEG_INFINITY;
        }
    }
    Tensor::from_vec(out, shape)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn extract_then_write_back_is_identity() {
        // hidden = 4, num_heads = 2 -> head_dim = 2
        // Build a [3, 4] tensor with distinct values per cell.
        let x = Tensor::from_vec((0..12).map(|v| v as f32).collect(), &[3, 4]);
        let mut reconstructed = vec![0.0f32; 12];
        for h in 0..2 {
            let head = extract_head(&x, h, 2);
            write_head_back(&mut reconstructed, &head, h, 2);
        }
        assert_eq!(reconstructed, x.data());
    }

    #[test]
    fn attention_output_shape_matches_input() {
        // hidden = 8, num_heads = 2, seq_len = 3
        let seq_len = 3;
        let hidden = 8;
        let x = Tensor::from_vec(vec![0.1f32; seq_len * hidden], &[seq_len, hidden]);
        // Identity-ish projections.
        let identity = identity_matrix(hidden);
        let zero_bias = Tensor::from_vec(vec![0.0; hidden], &[hidden]);
        let y = multi_head_attention(
            &x,
            &identity,
            Some(&zero_bias),
            &identity,
            Some(&zero_bias),
            &identity,
            Some(&zero_bias),
            &identity,
            Some(&zero_bias),
            2,
        );
        assert_eq!(y.shape().as_slice(), &[seq_len, hidden]);
    }

    #[test]
    fn mean_pool_basic() {
        let x = Tensor::from_vec(vec![1., 2., 3., 4., 5., 6.], &[3, 2]);
        let y = mean_pool(&x, None);
        // Mean per column: (1+3+5)/3 = 3, (2+4+6)/3 = 4
        assert_eq!(y.shape().as_slice(), &[2]);
        assert_eq!(y.data(), &[3.0, 4.0]);
    }

    #[test]
    fn mean_pool_respects_mask() {
        let x = Tensor::from_vec(vec![1., 2., 99., 99., 5., 6.], &[3, 2]);
        let mask = [1u32, 0, 1];
        let y = mean_pool(&x, Some(&mask));
        // Only rows 0 and 2 contribute: (1+5)/2 = 3, (2+6)/2 = 4
        assert_eq!(y.data(), &[3.0, 4.0]);
    }

    fn identity_matrix(n: usize) -> Tensor {
        let mut data = vec![0.0f32; n * n];
        for i in 0..n {
            data[i * n + i] = 1.0;
        }
        Tensor::from_vec(data, &[n, n])
    }
}