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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
//! BERT encoder forward pass.
//!
//! Supports the canonical HuggingFace BERT weight layout used by
//! `bert-base-uncased`, `distilbert-*`, `sentence-transformers/*` and
//! similar encoders. Decoder-only or seq2seq models are out of scope.
//!
//! Inference shape:
//!
//! ```text
//! input_ids: [seq_len]    (u32 token ids)
//! output:    [seq_len, hidden_size]   (per-token embeddings)
//! ```
//!
//! For sentence-level embeddings (sentence-transformers convention), use
//! [`BertModel::embed_sentence`], which calls `forward` followed by mean
//! pooling. Pass an `attention_mask` to ignore padding positions.

use crate::error::{Error, Result};
use crate::loader::{Dtype, ModelFile};
use crate::ops::activations::gelu_erf;
use crate::ops::attention::{mean_pool, multi_head_attention_from_qkv};
use crate::ops::elementwise::add;
use crate::ops::embedding::embedding;
use crate::ops::layernorm::layer_norm;
use crate::ops::linear::linear;
use crate::ops::quantized::{linear_i8, linear_u8};
use crate::quant::{QuantizedTensorI8, QuantizedTensorU8};
use crate::tensor::Tensor;
use crate::tokenizer::WordPieceTokenizer;

/// Architectural hyperparameters for a BERT encoder.
///
/// Mirrors the fields of HuggingFace's `BertConfig` that the forward pass
/// actually uses. Fields like `hidden_dropout_prob` are intentionally
/// omitted — there is no training and inference does not apply dropout.
#[derive(Debug, Clone, Copy)]
pub struct BertConfig {
    /// Hidden dimension (e.g. 384 for MiniLM-L6, 768 for BERT-base).
    pub hidden_size: usize,
    /// Number of stacked encoder layers.
    pub num_hidden_layers: usize,
    /// Number of attention heads. Must divide `hidden_size`.
    pub num_attention_heads: usize,
    /// Feed-forward inner dimension (typically 4 * hidden_size).
    pub intermediate_size: usize,
    /// Token vocabulary size.
    pub vocab_size: usize,
    /// Maximum supported positional index.
    pub max_position_embeddings: usize,
    /// Token-type (segment) vocabulary size (BERT uses 2; some models use 1).
    pub type_vocab_size: usize,
    /// LayerNorm epsilon. BERT uses `1e-12`.
    pub layer_norm_eps: f32,
}

impl BertConfig {
    /// Parses a HuggingFace `config.json` string and extracts the BERT fields.
    ///
    /// Required keys: `hidden_size`, `num_hidden_layers`, `num_attention_heads`,
    /// `intermediate_size`, `vocab_size`, `max_position_embeddings`.
    /// Optional: `type_vocab_size` (default 2), `layer_norm_eps` (default 1e-12).
    pub fn from_config_json(json: &str) -> Result<Self> {
        let extract_usize = |key: &str| -> Option<usize> {
            let pattern = format!("\"{key}\":");
            let start = json.find(&pattern)? + pattern.len();
            let rest = json[start..].trim_start();
            let end = rest.find(|c: char| !c.is_ascii_digit())?;
            if end == 0 {
                return None;
            }
            rest[..end].parse().ok()
        };
        let extract_f32 = |key: &str| -> Option<f32> {
            let pattern = format!("\"{key}\":");
            let start = json.find(&pattern)? + pattern.len();
            let rest = json[start..].trim_start();
            let end = rest
                .find(|c: char| !matches!(c, '-' | '+' | '.' | 'e' | 'E') && !c.is_ascii_digit())?;
            if end == 0 {
                return None;
            }
            rest[..end].parse().ok()
        };

        let config = Self {
            hidden_size: extract_usize("hidden_size")
                .ok_or(Error::InvalidInput("config.json: missing hidden_size"))?,
            num_hidden_layers: extract_usize("num_hidden_layers").ok_or(Error::InvalidInput(
                "config.json: missing num_hidden_layers",
            ))?,
            num_attention_heads: extract_usize("num_attention_heads").ok_or(
                Error::InvalidInput("config.json: missing num_attention_heads"),
            )?,
            intermediate_size: extract_usize("intermediate_size").ok_or(Error::InvalidInput(
                "config.json: missing intermediate_size",
            ))?,
            vocab_size: extract_usize("vocab_size")
                .ok_or(Error::InvalidInput("config.json: missing vocab_size"))?,
            max_position_embeddings: extract_usize("max_position_embeddings").ok_or(
                Error::InvalidInput("config.json: missing max_position_embeddings"),
            )?,
            type_vocab_size: extract_usize("type_vocab_size").unwrap_or(2),
            layer_norm_eps: extract_f32("layer_norm_eps").unwrap_or(1e-12),
        };
        validate_config(config)?;
        Ok(config)
    }

    /// Config for `sentence-transformers/all-MiniLM-L6-v2`.
    pub fn mini_lm_l6_v2() -> Self {
        Self {
            hidden_size: 384,
            num_hidden_layers: 6,
            num_attention_heads: 12,
            intermediate_size: 1536,
            vocab_size: 30522,
            max_position_embeddings: 512,
            type_vocab_size: 2,
            layer_norm_eps: 1e-12,
        }
    }

    /// Config for `bert-base-uncased`.
    pub fn bert_base() -> Self {
        Self {
            hidden_size: 768,
            num_hidden_layers: 12,
            num_attention_heads: 12,
            intermediate_size: 3072,
            vocab_size: 30522,
            max_position_embeddings: 512,
            type_vocab_size: 2,
            layer_norm_eps: 1e-12,
        }
    }
}

// Internal sub-modules. Kept private so the public surface stays small —
// users only see `BertConfig` and `BertModel`. Custom loading paths should
// go through `BertModel::from_safetensors`.

struct BertEmbeddings {
    word: Tensor,
    position: Tensor,
    token_type: Tensor,
    ln_gamma: Tensor,
    ln_beta: Tensor,
}

enum LinearWeight {
    F32(Tensor),
    I8(QuantizedTensorI8),
    U8(QuantizedTensorU8),
}

struct BertSelfAttention {
    wq: LinearWeight,
    bq: Tensor,
    wk: LinearWeight,
    bk: Tensor,
    wv: LinearWeight,
    bv: Tensor,
}

struct BertAttention {
    self_attn: BertSelfAttention,
    wo: LinearWeight,
    bo: Tensor,
    ln_gamma: Tensor,
    ln_beta: Tensor,
}

struct BertFeedForward {
    w_inter: LinearWeight,
    b_inter: Tensor,
    w_out: LinearWeight,
    b_out: Tensor,
    ln_gamma: Tensor,
    ln_beta: Tensor,
}

struct BertLayer {
    attention: BertAttention,
    ffn: BertFeedForward,
}

/// Full BERT encoder.
///
/// Construct via [`BertModel::from_safetensors`]. The model owns its weights
/// (no external references), so it can be cached, sent across threads (it is
/// `Send`), or dropped freely.
pub struct BertModel {
    /// Architectural configuration this model was built with.
    pub config: BertConfig,
    embeddings: BertEmbeddings,
    layers: Vec<BertLayer>,
}

impl BertModel {
    /// Loads a BERT model, auto-detecting the tensor name prefix.
    ///
    /// Tries common prefixes used by HuggingFace saves in order:
    /// `""` (sentence-transformers), `"bert"`, `"roberta"`, `"distilbert"`.
    /// Returns the first that succeeds, or an error if none match.
    pub fn from_safetensors_auto(file: &ModelFile, config: BertConfig) -> Result<Self> {
        for prefix in &["", "bert", "roberta", "distilbert", "electra"] {
            if let Ok(model) = Self::from_safetensors(file, config, prefix) {
                return Ok(model);
            }
        }
        Err(Error::InvalidInput(
            "could not load model with any known prefix (tried '', 'bert', 'roberta', 'distilbert', 'electra')",
        ))
    }

    /// Loads a BERT model from a parsed safetensors file.
    ///
    /// `prefix` is prepended to every tensor name. Use:
    /// - `""` for sentence-transformers and `transformers.AutoModel` saves;
    /// - `"bert"` for `transformers.BertModel` saves that include the wrapper.
    ///
    /// The prefix is joined to names with a `.` automatically, so pass
    /// `"bert"` not `"bert."`.
    pub fn from_safetensors(file: &ModelFile, config: BertConfig, prefix: &str) -> Result<Self> {
        validate_config(config)?;

        let p = if prefix.is_empty() {
            String::new()
        } else {
            format!("{prefix}.")
        };

        let load = |name: &str| -> Result<Tensor> { file.get(&format!("{p}{name}"))?.to_tensor() };
        let load_linear = |name: &str| -> Result<LinearWeight> {
            let full_name = format!("{p}{name}");
            let view = file.get(&full_name)?;
            match view.dtype {
                Dtype::F32 => Ok(LinearWeight::F32(view.to_tensor()?)),
                Dtype::I8 => {
                    let scale_name = format!("{full_name}.scale");
                    Ok(LinearWeight::I8(QuantizedTensorI8::from_safetensors(
                        file,
                        &full_name,
                        &scale_name,
                    )?))
                }
                Dtype::U8 => {
                    let scale_name = format!("{full_name}.scale");
                    let zero_point_name = format!("{full_name}.zero_point");
                    Ok(LinearWeight::U8(QuantizedTensorU8::from_safetensors(
                        file,
                        &full_name,
                        &scale_name,
                        &zero_point_name,
                    )?))
                }
                _ => Err(Error::DtypeMismatch),
            }
        };

        let embeddings = BertEmbeddings {
            word: load("embeddings.word_embeddings.weight")?,
            position: load("embeddings.position_embeddings.weight")?,
            token_type: load("embeddings.token_type_embeddings.weight")?,
            ln_gamma: load("embeddings.LayerNorm.weight")?,
            ln_beta: load("embeddings.LayerNorm.bias")?,
        };

        let mut layers = Vec::with_capacity(config.num_hidden_layers);
        for i in 0..config.num_hidden_layers {
            let load_l =
                |suffix: &str| -> Result<Tensor> { load(&format!("encoder.layer.{i}.{suffix}")) };
            let load_linear_l = |suffix: &str| -> Result<LinearWeight> {
                load_linear(&format!("encoder.layer.{i}.{suffix}"))
            };

            let layer = BertLayer {
                attention: BertAttention {
                    self_attn: BertSelfAttention {
                        wq: load_linear_l("attention.self.query.weight")?,
                        bq: load_l("attention.self.query.bias")?,
                        wk: load_linear_l("attention.self.key.weight")?,
                        bk: load_l("attention.self.key.bias")?,
                        wv: load_linear_l("attention.self.value.weight")?,
                        bv: load_l("attention.self.value.bias")?,
                    },
                    wo: load_linear_l("attention.output.dense.weight")?,
                    bo: load_l("attention.output.dense.bias")?,
                    ln_gamma: load_l("attention.output.LayerNorm.weight")?,
                    ln_beta: load_l("attention.output.LayerNorm.bias")?,
                },
                ffn: BertFeedForward {
                    w_inter: load_linear_l("intermediate.dense.weight")?,
                    b_inter: load_l("intermediate.dense.bias")?,
                    w_out: load_linear_l("output.dense.weight")?,
                    b_out: load_l("output.dense.bias")?,
                    ln_gamma: load_l("output.LayerNorm.weight")?,
                    ln_beta: load_l("output.LayerNorm.bias")?,
                },
            };
            layers.push(layer);
        }

        Ok(Self {
            config,
            embeddings,
            layers,
        })
    }

    /// Runs the encoder forward pass. Returns per-token hidden states.
    ///
    /// - `input_ids`: token ids, length = sequence length.
    /// - `token_type_ids`: optional segment ids; defaults to all-zeros.
    pub fn forward(&self, input_ids: &[u32], token_type_ids: Option<&[u32]>) -> Tensor {
        self.try_forward(input_ids, token_type_ids)
            .expect("forward: invalid model input")
    }

    /// Fallible encoder forward pass. Returns per-token hidden states.
    ///
    /// This validates user-provided ids and lengths before running tensor ops,
    /// so embedding lookups do not panic on bad input.
    pub fn try_forward(&self, input_ids: &[u32], token_type_ids: Option<&[u32]>) -> Result<Tensor> {
        validate_forward_input(&self.config, input_ids, token_type_ids)?;
        let seq_len = input_ids.len();

        // 1. Sum word + position + token-type embeddings, then LayerNorm.
        let word_e = embedding(input_ids, &self.embeddings.word);
        let position_ids: Vec<u32> = (0..seq_len as u32).collect();
        let pos_e = embedding(&position_ids, &self.embeddings.position);
        let owned_type_ids: Vec<u32>;
        let type_ids: &[u32] = match token_type_ids {
            Some(t) => {
                assert_eq!(t.len(), seq_len, "token_type_ids length mismatch");
                t
            }
            None => {
                owned_type_ids = vec![0u32; seq_len];
                &owned_type_ids
            }
        };
        let type_e = embedding(type_ids, &self.embeddings.token_type);

        let summed = add(&add(&word_e, &pos_e), &type_e);
        let mut hidden = layer_norm(
            &summed,
            &self.embeddings.ln_gamma,
            &self.embeddings.ln_beta,
            self.config.layer_norm_eps,
        );

        // 2. Encoder layers.
        for layer in &self.layers {
            hidden = encoder_layer_forward(&hidden, layer, &self.config);
        }

        Ok(hidden)
    }

    /// Convenience: forward + mean pooling, returning a single `[hidden]` vector.
    ///
    /// `attention_mask` follows the HuggingFace convention: `1` for real
    /// tokens, `0` for padding. Passing `None` averages over all positions.
    pub fn embed_sentence(
        &self,
        input_ids: &[u32],
        token_type_ids: Option<&[u32]>,
        attention_mask: Option<&[u32]>,
    ) -> Tensor {
        self.try_embed_sentence(input_ids, token_type_ids, attention_mask)
            .expect("embed_sentence: invalid model input")
    }

    /// Fallible forward + mean pooling, returning a single `[hidden]` vector.
    pub fn try_embed_sentence(
        &self,
        input_ids: &[u32],
        token_type_ids: Option<&[u32]>,
        attention_mask: Option<&[u32]>,
    ) -> Result<Tensor> {
        if let Some(mask) = attention_mask {
            if mask.len() != input_ids.len() {
                return Err(Error::InvalidInput(
                    "attention_mask length must match input_ids length",
                ));
            }
        }
        let hidden = self.try_forward(input_ids, token_type_ids)?;
        Ok(mean_pool(&hidden, attention_mask))
    }

    /// Convenience: tokenize one text, run the encoder, and mean-pool.
    ///
    /// `max_len` includes `[CLS]` and `[SEP]`. The tokenizer output is not
    /// padded, so the encoder only runs over real tokens.
    pub fn embed_text(
        &self,
        tokenizer: &WordPieceTokenizer,
        text: &str,
        max_len: usize,
    ) -> Result<Tensor> {
        let encoded = tokenizer.encode(text, max_len)?;
        self.try_embed_sentence(
            &encoded.input_ids,
            Some(&encoded.token_type_ids),
            Some(&encoded.attention_mask),
        )
    }

    /// Tokenizes and embeds a batch of texts, returning one vector per text.
    ///
    /// Each text is encoded independently (no shared padding). The returned
    /// `Vec` has the same length as `texts`.
    pub fn embed_batch(
        &self,
        tokenizer: &WordPieceTokenizer,
        texts: &[&str],
        max_len: usize,
    ) -> Result<Vec<Tensor>> {
        texts
            .iter()
            .map(|t| self.embed_text(tokenizer, t, max_len))
            .collect()
    }
}

fn validate_config(config: BertConfig) -> Result<()> {
    if config.hidden_size == 0 {
        return Err(Error::InvalidInput("hidden_size must be greater than zero"));
    }
    if config.num_attention_heads == 0 {
        return Err(Error::InvalidInput(
            "num_attention_heads must be greater than zero",
        ));
    }
    if !config
        .hidden_size
        .is_multiple_of(config.num_attention_heads)
    {
        return Err(Error::InvalidInput(
            "hidden_size must be divisible by num_attention_heads",
        ));
    }
    if config.vocab_size == 0 {
        return Err(Error::InvalidInput("vocab_size must be greater than zero"));
    }
    if config.max_position_embeddings == 0 {
        return Err(Error::InvalidInput(
            "max_position_embeddings must be greater than zero",
        ));
    }
    if config.type_vocab_size == 0 {
        return Err(Error::InvalidInput(
            "type_vocab_size must be greater than zero",
        ));
    }
    Ok(())
}

fn validate_forward_input(
    config: &BertConfig,
    input_ids: &[u32],
    token_type_ids: Option<&[u32]>,
) -> Result<()> {
    if input_ids.is_empty() {
        return Err(Error::InvalidInput("input_ids must not be empty"));
    }
    if input_ids.len() > config.max_position_embeddings {
        return Err(Error::InvalidInput(
            "input_ids length exceeds max_position_embeddings",
        ));
    }
    if input_ids.iter().any(|&id| id as usize >= config.vocab_size) {
        return Err(Error::InvalidInput("input id is out of vocabulary range"));
    }
    if let Some(type_ids) = token_type_ids {
        if type_ids.len() != input_ids.len() {
            return Err(Error::InvalidInput(
                "token_type_ids length must match input_ids length",
            ));
        }
        if type_ids
            .iter()
            .any(|&id| id as usize >= config.type_vocab_size)
        {
            return Err(Error::InvalidInput(
                "token type id is out of token type vocabulary range",
            ));
        }
    }
    Ok(())
}

fn encoder_layer_forward(x: &Tensor, layer: &BertLayer, config: &BertConfig) -> Tensor {
    // Attention block.
    let q = linear_weight(
        x,
        &layer.attention.self_attn.wq,
        Some(&layer.attention.self_attn.bq),
    );
    let k = linear_weight(
        x,
        &layer.attention.self_attn.wk,
        Some(&layer.attention.self_attn.bk),
    );
    let v = linear_weight(
        x,
        &layer.attention.self_attn.wv,
        Some(&layer.attention.self_attn.bv),
    );
    let attn = multi_head_attention_from_qkv(&q, &k, &v, config.num_attention_heads);
    let attn = linear_weight(&attn, &layer.attention.wo, Some(&layer.attention.bo));
    let residual = add(x, &attn);
    let post_attn = layer_norm(
        &residual,
        &layer.attention.ln_gamma,
        &layer.attention.ln_beta,
        config.layer_norm_eps,
    );

    // Feed-forward block.
    let inter = linear_weight(&post_attn, &layer.ffn.w_inter, Some(&layer.ffn.b_inter));
    let inter = gelu_erf(&inter);
    let proj = linear_weight(&inter, &layer.ffn.w_out, Some(&layer.ffn.b_out));
    let residual = add(&post_attn, &proj);
    layer_norm(
        &residual,
        &layer.ffn.ln_gamma,
        &layer.ffn.ln_beta,
        config.layer_norm_eps,
    )
}

fn linear_weight(x: &Tensor, weight: &LinearWeight, bias: Option<&Tensor>) -> Tensor {
    match weight {
        LinearWeight::F32(w) => linear(x, w, bias),
        LinearWeight::I8(w) => linear_i8(x, w, bias),
        LinearWeight::U8(w) => linear_u8(x, w, bias),
    }
}

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

    /// Builds a deterministic, tiny BERT for smoke testing.
    fn tiny_bert() -> (BertConfig, BertModel) {
        let config = BertConfig {
            hidden_size: 8,
            num_hidden_layers: 2,
            num_attention_heads: 2,
            intermediate_size: 16,
            vocab_size: 16,
            max_position_embeddings: 32,
            type_vocab_size: 2,
            layer_norm_eps: 1e-12,
        };

        let hidden = config.hidden_size;
        let inter = config.intermediate_size;

        let ones = |shape: &[usize]| {
            let n: usize = shape.iter().product();
            Tensor::from_vec(vec![0.01f32; n], shape)
        };
        let linear_ones = |shape: &[usize]| LinearWeight::F32(ones(shape));
        let one_vec = |n: usize| Tensor::from_vec(vec![1.0f32; n], &[n]);
        let zero_vec = |n: usize| Tensor::from_vec(vec![0.0f32; n], &[n]);

        let embeddings = BertEmbeddings {
            word: ones(&[config.vocab_size, hidden]),
            position: ones(&[config.max_position_embeddings, hidden]),
            token_type: ones(&[config.type_vocab_size, hidden]),
            ln_gamma: one_vec(hidden),
            ln_beta: zero_vec(hidden),
        };

        let mut layers = Vec::new();
        for _ in 0..config.num_hidden_layers {
            layers.push(BertLayer {
                attention: BertAttention {
                    self_attn: BertSelfAttention {
                        wq: linear_ones(&[hidden, hidden]),
                        bq: zero_vec(hidden),
                        wk: linear_ones(&[hidden, hidden]),
                        bk: zero_vec(hidden),
                        wv: linear_ones(&[hidden, hidden]),
                        bv: zero_vec(hidden),
                    },
                    wo: linear_ones(&[hidden, hidden]),
                    bo: zero_vec(hidden),
                    ln_gamma: one_vec(hidden),
                    ln_beta: zero_vec(hidden),
                },
                ffn: BertFeedForward {
                    w_inter: linear_ones(&[inter, hidden]),
                    b_inter: zero_vec(inter),
                    w_out: linear_ones(&[hidden, inter]),
                    b_out: zero_vec(hidden),
                    ln_gamma: one_vec(hidden),
                    ln_beta: zero_vec(hidden),
                },
            });
        }

        (
            config,
            BertModel {
                config,
                embeddings,
                layers,
            },
        )
    }

    #[test]
    fn forward_produces_correct_shape() {
        let (config, model) = tiny_bert();
        let ids = vec![1u32, 2, 3, 4, 5];
        let out = model.forward(&ids, None);
        assert_eq!(out.shape().as_slice(), &[ids.len(), config.hidden_size]);
        // Output must contain finite numbers.
        for &v in out.data() {
            assert!(v.is_finite(), "non-finite output: {}", v);
        }
    }

    #[test]
    fn embed_sentence_produces_hidden_vector() {
        let (config, model) = tiny_bert();
        let ids = vec![1u32, 2, 3];
        let emb = model.embed_sentence(&ids, None, None);
        assert_eq!(emb.shape().as_slice(), &[config.hidden_size]);
    }

    #[test]
    fn embed_sentence_respects_attention_mask() {
        let (_config, model) = tiny_bert();
        let ids = vec![1u32, 2, 3, 4];
        let mask = [1u32, 1, 0, 0];
        let masked = model.embed_sentence(&ids, None, Some(&mask));
        let unmasked = model.embed_sentence(&ids[..2], None, None);
        // Masking the last two tokens should give the same result as passing
        // only the first two tokens (the actual hidden states still differ
        // because position embeddings are present, so we just check the
        // outputs are similarly shaped and finite).
        assert_eq!(masked.shape().as_slice(), unmasked.shape().as_slice());
        for &v in masked.data() {
            assert!(v.is_finite());
        }
    }

    #[test]
    fn embed_text_uses_tokenizer_output() {
        let (config, model) = tiny_bert();
        let vocab = b"[PAD]\n[UNK]\n[CLS]\n[SEP]\n[MASK]\nhello\n";
        let tokenizer = WordPieceTokenizer::from_vocab_bytes(vocab).unwrap();
        let embedding = model.embed_text(&tokenizer, "hello", 8).unwrap();
        assert_eq!(embedding.shape().as_slice(), &[config.hidden_size]);
        for &v in embedding.data() {
            assert!(v.is_finite(), "non-finite embedding: {}", v);
        }
    }

    #[test]
    fn try_forward_rejects_bad_user_input() {
        let (_config, model) = tiny_bert();

        assert_eq!(
            model.try_forward(&[], None).unwrap_err(),
            Error::InvalidInput("input_ids must not be empty")
        );
        assert_eq!(
            model.try_forward(&[99], None).unwrap_err(),
            Error::InvalidInput("input id is out of vocabulary range")
        );
        assert_eq!(
            model.try_forward(&[1, 2], Some(&[0])).unwrap_err(),
            Error::InvalidInput("token_type_ids length must match input_ids length")
        );
        assert_eq!(
            model
                .try_embed_sentence(&[1, 2], None, Some(&[1]))
                .unwrap_err(),
            Error::InvalidInput("attention_mask length must match input_ids length")
        );
    }

    #[test]
    fn validate_config_rejects_invalid_config() {
        let config = BertConfig {
            hidden_size: 7,
            num_hidden_layers: 1,
            num_attention_heads: 2,
            intermediate_size: 8,
            vocab_size: 8,
            max_position_embeddings: 16,
            type_vocab_size: 2,
            layer_norm_eps: 1e-12,
        };

        assert_eq!(
            validate_config(config).unwrap_err(),
            Error::InvalidInput("hidden_size must be divisible by num_attention_heads")
        );
    }
}