ferrox_models/encoder.rs
1//! The seam for encoder-only (embedding) models, which is deliberately
2//! **not** [`crate::engine::Engine`].
3//!
4//! # Why a second trait and not a variant of the first
5//!
6//! [`crate::engine::Engine`] is `forward_token(token_id, pos, &mut
7//! State) -> Vec<f32>`: one token in, one logit vector out, carrying
8//! per-layer state forward. Every part of that signature is an
9//! autoregression assumption, and a BERT encoder violates all of them:
10//!
11//! * **There is no state to carry.** Attention is bidirectional, so
12//! token 0's output depends on token 7. Nothing can be computed until
13//! the whole sequence is present, and nothing computed for one
14//! sequence is reusable for the next. A KV cache is not merely
15//! unnecessary here, it is meaningless — there is no "next token" for
16//! a cached key to be attended to by.
17//! * **There are no logits.** The result is `n_tokens × n_embd` hidden
18//! states (llama.cpp's `res->t_embd`); this checkpoint has no output
19//! head at all, and `token_embd.weight` is not tied to one.
20//! * **`pos` is not a cursor, it is an index into a learned table.**
21//! BERT adds `position_embd.weight[i]` to the token embedding rather
22//! than rotating Q/K, which is why the sequence length is hard-capped
23//! by `n_ctx_train` instead of merely degrading past it.
24//!
25//! Forcing that through `Engine` would mean a `State` that is a
26//! pretend-cache, a `forward_token` that can only be called with the
27//! last position after a hidden batch call, and a `vocab_size` that has
28//! no meaning. The Kimi comment on `Engine` already records the cost of
29//! bending a trait around a model it does not fit; this is the same
30//! judgement, made before rather than after.
31//!
32//! So: [`TextEncoder`] is sequence-in, matrix-out, stateless. What the
33//! two seams *do* share is pooling ([`crate::pooling`]), which is why
34//! that lives in its own module and not in either of them.
35
36use crate::pooling::{pool, PoolingError, PoolingType};
37use thiserror::Error;
38
39#[derive(Debug, Error)]
40pub enum EncodeError {
41 #[error("an encoder needs at least one token; got an empty sequence")]
42 EmptySequence,
43 #[error(
44 "sequence of {got} tokens exceeds the {max} learned position embeddings this \
45 checkpoint carries ({arch}.context_length). A learned position table cannot be \
46 extrapolated the way RoPE can, so this is a hard limit, not a quality cliff — \
47 truncate the input or use a longer-context embedding model"
48 )]
49 TooLong {
50 got: usize,
51 max: usize,
52 arch: String,
53 },
54 #[error("token id {id} is outside this checkpoint's {vocab_size}-entry vocabulary")]
55 TokenOutOfRange { id: u32, vocab_size: usize },
56 #[error(
57 "segment id {id} at position {pos} is outside this checkpoint's {n_segments}-row \
58 token-type table"
59 )]
60 SegmentOutOfRange {
61 id: u32,
62 pos: usize,
63 n_segments: usize,
64 },
65 #[error(
66 "{tokens} token(s) were given {segments} segment id(s); every position needs exactly \
67 one, or the graph would add a segment embedding to the wrong row"
68 )]
69 RaggedSegments { tokens: usize, segments: usize },
70 #[error(transparent)]
71 Pooling(#[from] PoolingError),
72}
73
74/// One two-segment encoder input: the token ids and, for each of them,
75/// which half of the pair it belongs to.
76///
77/// The two vectors are built together and travel together on purpose.
78/// They are the repo's dominant bug shape waiting to happen — two
79/// structures that must agree, here about a length and about where the
80/// boundary is — and the single place that can get them right is
81/// [`TextEncoder::wrap_special_pair`], which inserts the `[SEP]` that
82/// the boundary is defined by. Handing a caller the ids alone (what
83/// this seam used to do) meant the segment ids did not exist at all
84/// and every position was scored as "Sentence A".
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub struct PairSequence {
87 /// `[CLS] a [SEP] b [SEP]` for BERT.
88 pub tokens: Vec<u32>,
89 /// `0` for the `[CLS] a [SEP]` half, `1` for the `b [SEP]` half —
90 /// HuggingFace's `token_type_ids`. Always the same length as
91 /// [`Self::tokens`].
92 pub segments: Vec<u32>,
93}
94
95/// A model that turns a whole token sequence into hidden states in one
96/// pass, with no carried state and no logits.
97pub trait TextEncoder {
98 /// Width of one hidden-state row, and of the pooled embedding.
99 fn n_embd(&self) -> usize;
100
101 /// Longest sequence this checkpoint can represent. For a learned
102 /// position table this is the table's height, and exceeding it is
103 /// an error rather than a degradation.
104 fn n_ctx_train(&self) -> usize;
105
106 /// What the checkpoint's own `{arch}.pooling_type` said.
107 fn pooling_type(&self) -> PoolingType;
108
109 /// Wraps a tokenizer's pieces in whatever the *model* requires
110 /// around them — for BERT, `[CLS] … [SEP]`.
111 ///
112 /// This is on the encoder rather than the tokenizer because ferrox's
113 /// tokenizers deliberately encode text only (they are checked
114 /// token-for-token against `llama_tokenize(..., add_special =
115 /// false, ...)`), while llama.cpp keeps `add_special` in the vocab
116 /// and applies it here. The default adds nothing, so an encoder that
117 /// genuinely needs no wrapper does not have to say so.
118 fn wrap_special(&self, pieces: &[u32]) -> Vec<u32> {
119 pieces.to_vec()
120 }
121
122 /// How many rows the checkpoint's token-type ("segment") table
123 /// carries, i.e. the number of distinct segment ids
124 /// [`Self::encode`] will accept.
125 ///
126 /// `1` — the default — means the encoder can only represent
127 /// "Sentence A", which is enough for an embedding pass and is not
128 /// enough for a cross-encoder pair. Read at load time by
129 /// [`crate::EmbeddingModel`], which refuses a reranker checkpoint
130 /// that cannot express segment 1 rather than silently scoring the
131 /// document half as segment 0.
132 fn n_segments(&self) -> usize {
133 1
134 }
135
136 /// The two-segment input a **cross-encoder** scores: one sequence
137 /// holding a query and a document with the model's own boundary
138 /// between them, and the segment id of every position. For BERT
139 /// that is `[CLS] a [SEP] b [SEP]` with segments `0…0 1…1`, which is
140 /// exactly what HuggingFace's `tokenizer(query, document)` emits.
141 ///
142 /// `None` — the default — means this encoder has no two-segment
143 /// form, and a caller that needs one must refuse. Deliberately NOT
144 /// defaulted to `wrap_special(a ++ b)`: a cross-encoder was trained
145 /// with a separator between the halves, and one that never sees it
146 /// still returns a plausible float. That is the "computes something
147 /// else" failure, and it is invisible — a rerank with no boundary
148 /// produces an ordering, just not the model's.
149 fn wrap_special_pair(&self, _a: &[u32], _b: &[u32]) -> Option<PairSequence> {
150 None
151 }
152
153 /// `n_tokens × n_embd` hidden states, in row order.
154 ///
155 /// `segments` is the per-position segment id, or `None` for "all
156 /// zeros" — the single-sequence case. There is deliberately ONE
157 /// graph with a parameter rather than a segment-aware copy of a
158 /// segment-blind one: this repo has lost a model feature to every
159 /// copied forward pass it has ever had, and the pair path is
160 /// exercised far less often than the embedding path, so a copy is
161 /// exactly where a fix would fail to land.
162 fn encode(&self, tokens: &[u32], segments: Option<&[u32]>) -> Result<Vec<f32>, EncodeError>;
163
164 /// [`Self::encode`] for a single sequence: every position is
165 /// segment 0.
166 fn encode_tokens(&self, tokens: &[u32]) -> Result<Vec<f32>, EncodeError> {
167 self.encode(tokens, None)
168 }
169
170 /// [`Self::encode_tokens`] followed by the checkpoint's own pooling.
171 /// Not L2-normalized — see [`crate::pooling::pool`].
172 fn embed_tokens(&self, tokens: &[u32]) -> Result<Vec<f32>, EncodeError> {
173 let hidden = self.encode_tokens(tokens)?;
174 Ok(pool(&hidden, self.n_embd(), self.pooling_type())?)
175 }
176}