Skip to main content

ferrox_models/
bert_encoder.rs

1//! BERT: the encoder graph, transcribed from llama.cpp
2//! `src/models/bert.cpp` (`llama_model_bert::graph::graph`).
3//!
4//! Loading lives next door in [`crate::bert_gguf_loader`]; pooling in
5//! [`crate::pooling`]; the reason this is not an
6//! [`crate::engine::Engine`] in [`crate::encoder`].
7//!
8//! # The graph, and the five places it is not a decoder
9//!
10//! ```text
11//! h[i] = tok_embd[t[i]] + type_embd[0] + pos_embd[i]      (1) (2)
12//! h    = LayerNorm(h, token_embd_norm)                        (3)
13//! for each layer:
14//!     q,k,v = Wq h + bq,  Wk h + bk,  Wv h + bv
15//!     a     = softmax(q·kᵀ / √head_dim) v                  (4)
16//!     x     = LayerNorm(Wo a + bo + h,  attn_output_norm)      (3)
17//!     f     = W_down · GELU(W_up x + b_up) + b_down        (5)
18//!     h     = LayerNorm(f + x, layer_output_norm)              (3)
19//! result = h                                              (6)
20//! ```
21//!
22//! 1. **Learned position embeddings, added.** Not RoPE. `pos_embd` is a
23//!    real `[n_ctx_train, n_embd]` table and position `i` is a row
24//!    lookup. A learned table cannot be extrapolated, which is why
25//!    [`crate::encoder::EncodeError::TooLong`] is an error and not a
26//!    warning.
27//! 2. **A token-type embedding.** Upstream hardcodes row 0 ("Sentence
28//!    A") — `ggml_view_1d(ctx0, model.type_embd, n_embd, 0)` — because
29//!    the single-sequence embedding use never has a sentence B. Ferrox
30//!    does the same, and the loader refuses a checkpoint whose
31//!    `token_types` table is missing when the metadata says it should
32//!    have one.
33//! 3. **LayerNorm, not RMSNorm, at three sites per layer plus one on
34//!    the input.** Mean-subtracting, and every one of them carries a
35//!    `bias` tensor as well as a `weight`. Substituting RMSNorm here
36//!    loads fine and produces a plausible-looking vector that is wrong.
37//! 4. **No causal mask.** Row 0 attends to the last token. This is the
38//!    single property that makes the whole model an encoder, and
39//!    `attention_is_bidirectional_not_causal` below is the test that
40//!    would go red if a mask ever appeared.
41//! 5. **A plain GELU MLP, not a gated one.** Two matrices, not three,
42//!    and both carry biases. `LLM_FFN_GELU, LLM_FFN_SEQ` upstream.
43//! 6. **No output head and no logits.** The hidden states *are* the
44//!    result (`res->t_embd`); this checkpoint has no `output.weight` at
45//!    all.
46//!
47//! # What this module does not do
48//!
49//! Only `arch == "bert"`, and only its dense, non-RoPE, separate-QKV
50//! shape. `nomic-bert` (RoPE + gated FFN), `jina-bert-v2` (GEGLU + a
51//! second attention norm), `nomic-bert-moe` (expert layers) and
52//! `modern-bert` all share `bert.cpp` upstream and are all refused by
53//! name in the loader instead of being run through this graph.
54
55use ferrox_core::matmul::{gelu, layer_norm};
56use ferrox_core::weight_matrix::WeightMatrix;
57
58use crate::encoder::{EncodeError, TextEncoder};
59use crate::pooling::PoolingType;
60
61/// `bert.*` metadata, after the loader has checked it.
62#[derive(Debug, Clone)]
63pub struct BertHparams {
64    pub arch: String,
65    pub n_layer: usize,
66    pub n_embd: usize,
67    pub n_ff: usize,
68    pub n_head: usize,
69    pub n_head_kv: usize,
70    /// Height of the learned position table.
71    pub n_ctx_train: usize,
72    pub n_token_types: usize,
73    pub layer_norm_eps: f32,
74    pub pooling: PoolingType,
75    /// `[CLS]` / `[SEP]`, from `tokenizer.ggml.bos_token_id` and
76    /// `tokenizer.ggml.seperator_token_id` (upstream's spelling of the
77    /// key, typo included). See [`BertEncoder::wrap_special`].
78    pub cls_id: u32,
79    pub sep_id: u32,
80}
81
82impl BertHparams {
83    pub fn head_dim(&self) -> usize {
84        self.n_embd / self.n_head
85    }
86}
87
88/// One transformer block's weights. Biases that llama.cpp marks
89/// `TENSOR_NOT_REQUIRED` are `Option`, so a checkpoint without them is
90/// run without them rather than with a silently fabricated zero vector.
91pub struct BertLayer {
92    pub wq: WeightMatrix,
93    pub bq: Option<Vec<f32>>,
94    pub wk: WeightMatrix,
95    pub bk: Option<Vec<f32>>,
96    pub wv: WeightMatrix,
97    pub bv: Option<Vec<f32>>,
98    pub wo: WeightMatrix,
99    pub bo: Option<Vec<f32>>,
100    /// `attn_output_norm`, applied after the attention residual.
101    pub attn_out_norm_w: Vec<f32>,
102    pub attn_out_norm_b: Vec<f32>,
103    pub ffn_up: WeightMatrix,
104    pub ffn_up_b: Option<Vec<f32>>,
105    pub ffn_down: WeightMatrix,
106    pub ffn_down_b: Option<Vec<f32>>,
107    /// `layer_output_norm`, applied after the FFN residual.
108    pub layer_out_norm_w: Vec<f32>,
109    pub layer_out_norm_b: Vec<f32>,
110}
111
112pub struct BertEncoder {
113    pub hp: BertHparams,
114    pub tok_embd: WeightMatrix,
115    /// Row 0 of `token_types.weight` — "Sentence A". See the module docs.
116    pub type_embd_row0: Option<Vec<f32>>,
117    pub pos_embd: WeightMatrix,
118    pub tok_norm_w: Vec<f32>,
119    pub tok_norm_b: Vec<f32>,
120    pub layers: Vec<BertLayer>,
121}
122
123/// Adds `bias` to every `width`-wide row of `rows`, when there is one.
124fn add_bias_rows(rows: &mut [f32], width: usize, bias: Option<&Vec<f32>>) {
125    let Some(b) = bias else { return };
126    debug_assert_eq!(b.len(), width);
127    for row in rows.chunks_exact_mut(width) {
128        for (x, bv) in row.iter_mut().zip(b.iter()) {
129            *x += bv;
130        }
131    }
132}
133
134/// LayerNorm applied independently to each `width`-wide row, in place.
135fn layer_norm_rows(rows: &mut [f32], width: usize, weight: &[f32], bias: &[f32], eps: f32) {
136    for row in rows.chunks_exact_mut(width) {
137        let normed = layer_norm(row, weight, bias, eps);
138        row.copy_from_slice(&normed);
139    }
140}
141
142/// In-place softmax over one score row, max-shifted.
143fn softmax_row(scores: &mut [f32]) {
144    let max = scores.iter().copied().fold(f32::NEG_INFINITY, f32::max);
145    let mut sum = 0.0f32;
146    for s in scores.iter_mut() {
147        *s = (*s - max).exp();
148        sum += *s;
149    }
150    let inv = 1.0 / sum;
151    for s in scores.iter_mut() {
152        *s *= inv;
153    }
154}
155
156/// Full bidirectional multi-head attention over `n` positions.
157///
158/// `q` is `[n][n_head * head_dim]`; `k` and `v` are
159/// `[n][n_head_kv * head_dim]`. **Every query row attends to every key
160/// row** — there is no mask argument here on purpose, so a causal mask
161/// cannot be added by accident.
162fn bidirectional_attention(
163    q: &[f32],
164    k: &[f32],
165    v: &[f32],
166    n: usize,
167    n_head: usize,
168    n_head_kv: usize,
169    head_dim: usize,
170) -> Vec<f32> {
171    let q_width = n_head * head_dim;
172    let kv_width = n_head_kv * head_dim;
173    let heads_per_kv = n_head / n_head_kv;
174    let scale = 1.0 / (head_dim as f32).sqrt();
175    let mut out = vec![0.0f32; n * q_width];
176    let mut scores = vec![0.0f32; n];
177    for h in 0..n_head {
178        let kv_h = h / heads_per_kv;
179        let q_off = h * head_dim;
180        let kv_off = kv_h * head_dim;
181        for i in 0..n {
182            let qi = &q[i * q_width + q_off..i * q_width + q_off + head_dim];
183            for (j, s) in scores.iter_mut().enumerate() {
184                let kj = &k[j * kv_width + kv_off..j * kv_width + kv_off + head_dim];
185                *s = qi.iter().zip(kj).map(|(a, b)| a * b).sum::<f32>() * scale;
186            }
187            softmax_row(&mut scores);
188            let dst = &mut out[i * q_width + q_off..i * q_width + q_off + head_dim];
189            for (j, &p) in scores.iter().enumerate() {
190                let vj = &v[j * kv_width + kv_off..j * kv_width + kv_off + head_dim];
191                for (o, &vv) in dst.iter_mut().zip(vj) {
192                    *o += p * vv;
193                }
194            }
195        }
196    }
197    out
198}
199
200impl BertEncoder {
201    pub fn vocab_size(&self) -> usize {
202        self.tok_embd.rows()
203    }
204}
205
206impl TextEncoder for BertEncoder {
207    fn n_embd(&self) -> usize {
208        self.hp.n_embd
209    }
210
211    fn n_ctx_train(&self) -> usize {
212        self.hp.n_ctx_train
213    }
214
215    fn pooling_type(&self) -> PoolingType {
216        self.hp.pooling
217    }
218
219    /// `[CLS] … [SEP]`, which is what llama.cpp's WPM branch adds when
220    /// `add_special` is set: it pushes `special_bos_id` before the
221    /// pieces and `special_sep_id` after, unconditionally — the
222    /// `add_bos`/`add_eos` flags are not consulted on that path
223    /// (`llama-vocab.cpp`, `case LLAMA_VOCAB_TYPE_WPM`).
224    fn wrap_special(&self, pieces: &[u32]) -> Vec<u32> {
225        let mut out = Vec::with_capacity(pieces.len() + 2);
226        out.push(self.hp.cls_id);
227        out.extend_from_slice(pieces);
228        out.push(self.hp.sep_id);
229        out
230    }
231
232    fn encode_tokens(&self, tokens: &[u32]) -> Result<Vec<f32>, EncodeError> {
233        let n = tokens.len();
234        if n == 0 {
235            return Err(EncodeError::EmptySequence);
236        }
237        if n > self.hp.n_ctx_train {
238            return Err(EncodeError::TooLong {
239                got: n,
240                max: self.hp.n_ctx_train,
241                arch: self.hp.arch.clone(),
242            });
243        }
244        let d = self.hp.n_embd;
245        let vocab_size = self.vocab_size();
246
247        // (1)(2) token + type + position, then the input LayerNorm.
248        let mut h = vec![0.0f32; n * d];
249        for (i, &t) in tokens.iter().enumerate() {
250            if t as usize >= vocab_size {
251                return Err(EncodeError::TokenOutOfRange { id: t, vocab_size });
252            }
253            let tok = self.tok_embd.dequant_row(t as usize);
254            let pos = self.pos_embd.dequant_row(i);
255            let row = &mut h[i * d..(i + 1) * d];
256            for (j, slot) in row.iter_mut().enumerate() {
257                *slot = tok[j] + pos[j];
258            }
259            if let Some(ty) = &self.type_embd_row0 {
260                for (slot, tv) in row.iter_mut().zip(ty.iter()) {
261                    *slot += tv;
262                }
263            }
264        }
265        layer_norm_rows(
266            &mut h,
267            d,
268            &self.tok_norm_w,
269            &self.tok_norm_b,
270            self.hp.layer_norm_eps,
271        );
272
273        let head_dim = self.hp.head_dim();
274        for layer in &self.layers {
275            let mut q = layer.wq.apply_batch(&h, n);
276            let mut k = layer.wk.apply_batch(&h, n);
277            let mut v = layer.wv.apply_batch(&h, n);
278            add_bias_rows(&mut q, self.hp.n_head * head_dim, layer.bq.as_ref());
279            add_bias_rows(&mut k, self.hp.n_head_kv * head_dim, layer.bk.as_ref());
280            add_bias_rows(&mut v, self.hp.n_head_kv * head_dim, layer.bv.as_ref());
281
282            let attn =
283                bidirectional_attention(&q, &k, &v, n, self.hp.n_head, self.hp.n_head_kv, head_dim);
284
285            let mut x = layer.wo.apply_batch(&attn, n);
286            add_bias_rows(&mut x, d, layer.bo.as_ref());
287            // Residual over the *layer input*, then attn_output_norm.
288            for (xv, hv) in x.iter_mut().zip(h.iter()) {
289                *xv += hv;
290            }
291            layer_norm_rows(
292                &mut x,
293                d,
294                &layer.attn_out_norm_w,
295                &layer.attn_out_norm_b,
296                self.hp.layer_norm_eps,
297            );
298
299            // (5) plain GELU MLP; the FFN residual is over `x`, i.e.
300            // over the post-norm value, not over the layer input.
301            let mut up = layer.ffn_up.apply_batch(&x, n);
302            add_bias_rows(&mut up, self.hp.n_ff, layer.ffn_up_b.as_ref());
303            for a in up.iter_mut() {
304                *a = gelu(*a);
305            }
306            let mut down = layer.ffn_down.apply_batch(&up, n);
307            add_bias_rows(&mut down, d, layer.ffn_down_b.as_ref());
308            for (dv, xv) in down.iter_mut().zip(x.iter()) {
309                *dv += xv;
310            }
311            layer_norm_rows(
312                &mut down,
313                d,
314                &layer.layer_out_norm_w,
315                &layer.layer_out_norm_b,
316                self.hp.layer_norm_eps,
317            );
318            h = down;
319        }
320        Ok(h)
321    }
322}
323
324#[cfg(test)]
325mod tests {
326    use super::*;
327    use ferrox_core::tensor::Tensor;
328
329    /// Deterministic pseudo-random weights: a small LCG, so the fixture
330    /// is reproducible without pulling in a dependency.
331    struct Lcg(u64);
332    impl Lcg {
333        fn next_f32(&mut self) -> f32 {
334            self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1);
335            ((self.0 >> 33) as f32 / (1u64 << 31) as f32) - 0.5
336        }
337        fn vec(&mut self, n: usize) -> Vec<f32> {
338            (0..n).map(|_| self.next_f32()).collect()
339        }
340        fn matrix(&mut self, rows: usize, cols: usize) -> WeightMatrix {
341            WeightMatrix::F32(Tensor::new(self.vec(rows * cols), vec![rows, cols]))
342        }
343    }
344
345    const D: usize = 8;
346    const FF: usize = 16;
347    const HEADS: usize = 2;
348    const VOCAB: usize = 20;
349    const CTX: usize = 12;
350    const EPS: f32 = 1e-12;
351
352    fn fixture(n_layer: usize) -> BertEncoder {
353        let mut r = Lcg(0x5EED);
354        let tok_embd = r.matrix(VOCAB, D);
355        let pos_embd = r.matrix(CTX, D);
356        let type_embd_row0 = Some(r.vec(D));
357        let tok_norm_w = r.vec(D);
358        let tok_norm_b = r.vec(D);
359        let layers = (0..n_layer)
360            .map(|_| BertLayer {
361                wq: r.matrix(D, D),
362                bq: Some(r.vec(D)),
363                wk: r.matrix(D, D),
364                bk: Some(r.vec(D)),
365                wv: r.matrix(D, D),
366                bv: Some(r.vec(D)),
367                wo: r.matrix(D, D),
368                bo: Some(r.vec(D)),
369                attn_out_norm_w: r.vec(D),
370                attn_out_norm_b: r.vec(D),
371                ffn_up: r.matrix(FF, D),
372                ffn_up_b: Some(r.vec(FF)),
373                ffn_down: r.matrix(D, FF),
374                ffn_down_b: Some(r.vec(D)),
375                layer_out_norm_w: r.vec(D),
376                layer_out_norm_b: r.vec(D),
377            })
378            .collect();
379        BertEncoder {
380            hp: BertHparams {
381                arch: "bert".into(),
382                n_layer,
383                n_embd: D,
384                n_ff: FF,
385                n_head: HEADS,
386                n_head_kv: HEADS,
387                n_ctx_train: CTX,
388                n_token_types: 2,
389                layer_norm_eps: EPS,
390                pooling: PoolingType::Cls,
391                cls_id: 1,
392                sep_id: 2,
393            },
394            tok_embd,
395            type_embd_row0,
396            pos_embd,
397            tok_norm_w,
398            tok_norm_b,
399            layers,
400        }
401    }
402
403    /// An f64 transcription of the graph in the module docs, written
404    /// the slowest possible way: no `apply_batch`, no shared buffers,
405    /// one scalar loop per matrix element. It exists to disagree with
406    /// [`BertEncoder::encode_tokens`] if the fast path transposes a
407    /// matrix, drops a bias, norms the wrong residual, or reuses a
408    /// buffer it should not.
409    fn reference_forward(m: &BertEncoder, tokens: &[u32]) -> Vec<f64> {
410        let d = m.hp.n_embd;
411        let n = tokens.len();
412        let hd = m.hp.head_dim();
413
414        let dense = |w: &WeightMatrix| -> Vec<Vec<f64>> {
415            (0..w.rows())
416                .map(|r| w.dequant_row(r).iter().map(|&v| v as f64).collect())
417                .collect()
418        };
419        let matvec = |w: &Vec<Vec<f64>>, x: &[f64]| -> Vec<f64> {
420            w.iter()
421                .map(|row| row.iter().zip(x).map(|(a, b)| a * b).sum())
422                .collect()
423        };
424        let ln = |x: &[f64], wt: &[f32], b: &[f32]| -> Vec<f64> {
425            let mean = x.iter().sum::<f64>() / x.len() as f64;
426            let var = x.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / x.len() as f64;
427            let inv = 1.0 / (var + m.hp.layer_norm_eps as f64).sqrt();
428            x.iter()
429                .zip(wt)
430                .zip(b)
431                .map(|((v, w), bb)| (v - mean) * inv * (*w as f64) + (*bb as f64))
432                .collect()
433        };
434
435        let mut h: Vec<Vec<f64>> = tokens
436            .iter()
437            .enumerate()
438            .map(|(i, &t)| {
439                let tok = m.tok_embd.dequant_row(t as usize);
440                let pos = m.pos_embd.dequant_row(i);
441                let ty = m.type_embd_row0.clone().unwrap_or(vec![0.0; d]);
442                let row: Vec<f64> = (0..d)
443                    .map(|j| tok[j] as f64 + pos[j] as f64 + ty[j] as f64)
444                    .collect();
445                ln(&row, &m.tok_norm_w, &m.tok_norm_b)
446            })
447            .collect();
448
449        for layer in &m.layers {
450            let (wq, wk, wv, wo) = (
451                dense(&layer.wq),
452                dense(&layer.wk),
453                dense(&layer.wv),
454                dense(&layer.wo),
455            );
456            let (wu, wd) = (dense(&layer.ffn_up), dense(&layer.ffn_down));
457            let bias = |v: &mut Vec<f64>, b: &Option<Vec<f32>>| {
458                if let Some(b) = b {
459                    for (x, bb) in v.iter_mut().zip(b) {
460                        *x += *bb as f64;
461                    }
462                }
463            };
464            let mut q = Vec::new();
465            let mut k = Vec::new();
466            let mut v = Vec::new();
467            for row in &h {
468                let mut a = matvec(&wq, row);
469                bias(&mut a, &layer.bq);
470                q.push(a);
471                let mut a = matvec(&wk, row);
472                bias(&mut a, &layer.bk);
473                k.push(a);
474                let mut a = matvec(&wv, row);
475                bias(&mut a, &layer.bv);
476                v.push(a);
477            }
478            let mut attn = vec![vec![0.0f64; d]; n];
479            for head in 0..m.hp.n_head {
480                let off = head * hd;
481                for i in 0..n {
482                    let raw: Vec<f64> = (0..n)
483                        .map(|j| {
484                            (0..hd).map(|c| q[i][off + c] * k[j][off + c]).sum::<f64>()
485                                / (hd as f64).sqrt()
486                        })
487                        .collect();
488                    let mx = raw.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
489                    let ex: Vec<f64> = raw.iter().map(|s| (s - mx).exp()).collect();
490                    let sum: f64 = ex.iter().sum();
491                    for j in 0..n {
492                        let p = ex[j] / sum;
493                        for c in 0..hd {
494                            attn[i][off + c] += p * v[j][off + c];
495                        }
496                    }
497                }
498            }
499            let mut next = Vec::new();
500            for i in 0..n {
501                let mut o = matvec(&wo, &attn[i]);
502                bias(&mut o, &layer.bo);
503                for (x, hv) in o.iter_mut().zip(&h[i]) {
504                    *x += hv;
505                }
506                let x = ln(&o, &layer.attn_out_norm_w, &layer.attn_out_norm_b);
507                let mut up = matvec(&wu, &x);
508                bias(&mut up, &layer.ffn_up_b);
509                let act: Vec<f64> = up
510                    .iter()
511                    .map(|&u| {
512                        const K: f64 = 0.797_884_560_802_865_4;
513                        const C: f64 = 0.044_715;
514                        0.5 * u * (1.0 + (K * (u + C * u * u * u)).tanh())
515                    })
516                    .collect();
517                let mut down = matvec(&wd, &act);
518                bias(&mut down, &layer.ffn_down_b);
519                for (dv, xv) in down.iter_mut().zip(&x) {
520                    *dv += xv;
521                }
522                next.push(ln(&down, &layer.layer_out_norm_w, &layer.layer_out_norm_b));
523            }
524            h = next;
525        }
526        h.into_iter().flatten().collect()
527    }
528
529    #[test]
530    fn matches_an_independent_f64_transcription_of_the_graph() {
531        let m = fixture(3);
532        let tokens = [1u32, 7, 13, 4, 9, 2];
533        let got = m.encode_tokens(&tokens).unwrap();
534        let want = reference_forward(&m, &tokens);
535        assert_eq!(got.len(), want.len());
536        for (i, (g, w)) in got.iter().zip(&want).enumerate() {
537            assert!(
538                (*g as f64 - w).abs() < 2e-4,
539                "element {i}: {g} vs reference {w}"
540            );
541        }
542    }
543
544    /// The property that makes this an encoder. Row 0's output must
545    /// change when the *last* token changes; under a causal mask it
546    /// could not, because position 0 would attend only to itself.
547    #[test]
548    fn attention_is_bidirectional_not_causal() {
549        let m = fixture(2);
550        let a = m.encode_tokens(&[5u32, 6, 7, 8]).unwrap();
551        let b = m.encode_tokens(&[5u32, 6, 7, 19]).unwrap();
552        let moved: f32 = a[..D].iter().zip(&b[..D]).map(|(x, y)| (x - y).abs()).sum();
553        assert!(
554            moved > 1e-3,
555            "row 0 barely moved ({moved}) when the last token changed — \
556             attention is behaving causally"
557        );
558    }
559
560    /// Position is a learned table lookup, so the same token at a
561    /// different index must land somewhere else.
562    #[test]
563    fn position_embeddings_make_the_same_token_differ_by_index() {
564        let m = fixture(1);
565        let out = m.encode_tokens(&[11u32, 11]).unwrap();
566        let delta: f32 = out[..D]
567            .iter()
568            .zip(&out[D..2 * D])
569            .map(|(x, y)| (x - y).abs())
570            .sum();
571        assert!(
572            delta > 1e-3,
573            "identical tokens gave identical rows: {delta}"
574        );
575    }
576
577    /// The graph ends on a LayerNorm: with unit weight and zero bias
578    /// each output row is mean-zero and unit-variance. An RMSNorm in
579    /// that slot would leave the mean wherever it was.
580    #[test]
581    fn the_last_op_is_a_mean_subtracting_layer_norm() {
582        let mut m = fixture(2);
583        let last = m.layers.last_mut().unwrap();
584        last.layer_out_norm_w = vec![1.0; D];
585        last.layer_out_norm_b = vec![0.0; D];
586        let out = m.encode_tokens(&[3u32, 4, 5]).unwrap();
587        for row in out.as_chunks::<D>().0 {
588            let mean: f32 = row.iter().sum::<f32>() / D as f32;
589            let var: f32 = row.iter().map(|v| (v - mean).powi(2)).sum::<f32>() / D as f32;
590            assert!(mean.abs() < 1e-4, "row mean {mean} is not zero");
591            assert!((var - 1.0).abs() < 1e-3, "row variance {var} is not one");
592        }
593    }
594
595    #[test]
596    fn refuses_an_empty_sequence_and_one_past_the_position_table() {
597        let m = fixture(1);
598        assert!(matches!(
599            m.encode_tokens(&[]),
600            Err(EncodeError::EmptySequence)
601        ));
602        let long: Vec<u32> = (0..CTX as u32 + 1).map(|i| i % VOCAB as u32).collect();
603        let err = m.encode_tokens(&long).unwrap_err();
604        assert!(
605            matches!(err, EncodeError::TooLong { got, max, .. } if got == CTX + 1 && max == CTX)
606        );
607        assert!(matches!(
608            m.encode_tokens(&[VOCAB as u32]),
609            Err(EncodeError::TokenOutOfRange { .. })
610        ));
611    }
612
613    #[test]
614    fn wrap_special_brackets_the_pieces_with_cls_and_sep() {
615        let m = fixture(1);
616        assert_eq!(m.wrap_special(&[7, 8]), vec![1, 7, 8, 2]);
617        assert_eq!(m.wrap_special(&[]), vec![1, 2]);
618    }
619
620    /// `embed_tokens` must return the CLS row of the hidden states this
621    /// checkpoint's `pooling_type` names, not the mean and not the last.
622    #[test]
623    fn embed_tokens_pools_the_way_the_hparams_say() {
624        let m = fixture(2);
625        let tokens = [1u32, 9, 4, 2];
626        let hidden = m.encode_tokens(&tokens).unwrap();
627        assert_eq!(m.embed_tokens(&tokens).unwrap(), hidden[..D].to_vec());
628    }
629}