Skip to main content

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.
97///
98/// `Sync` because [`TextEncoder::encode`] hands `&self` to a rayon
99/// worker for the duration of the pass; see its doc comment.
100pub trait TextEncoder: Sync {
101    /// Width of one hidden-state row, and of the pooled embedding.
102    fn n_embd(&self) -> usize;
103
104    /// Longest sequence this checkpoint can represent. For a learned
105    /// position table this is the table's height, and exceeding it is
106    /// an error rather than a degradation.
107    fn n_ctx_train(&self) -> usize;
108
109    /// What the checkpoint's own `{arch}.pooling_type` said.
110    fn pooling_type(&self) -> PoolingType;
111
112    /// Wraps a tokenizer's pieces in whatever the *model* requires
113    /// around them — for BERT, `[CLS] … [SEP]`.
114    ///
115    /// This is on the encoder rather than the tokenizer because ferrox's
116    /// tokenizers deliberately encode text only (they are checked
117    /// token-for-token against `llama_tokenize(..., add_special =
118    /// false, ...)`), while llama.cpp keeps `add_special` in the vocab
119    /// and applies it here. The default adds nothing, so an encoder that
120    /// genuinely needs no wrapper does not have to say so.
121    fn wrap_special(&self, pieces: &[u32]) -> Vec<u32> {
122        pieces.to_vec()
123    }
124
125    /// How many rows the checkpoint's token-type ("segment") table
126    /// carries, i.e. the number of distinct segment ids
127    /// [`Self::encode`] will accept.
128    ///
129    /// `1` — the default — means the encoder can only represent
130    /// "Sentence A", which is enough for an embedding pass and is not
131    /// enough for a cross-encoder pair. Read at load time by
132    /// [`crate::EmbeddingModel`], which refuses a reranker checkpoint
133    /// that cannot express segment 1 rather than silently scoring the
134    /// document half as segment 0.
135    fn n_segments(&self) -> usize {
136        1
137    }
138
139    /// The two-segment input a **cross-encoder** scores: one sequence
140    /// holding a query and a document with the model's own boundary
141    /// between them, and the segment id of every position. For BERT
142    /// that is `[CLS] a [SEP] b [SEP]` with segments `0…0 1…1`, which is
143    /// exactly what HuggingFace's `tokenizer(query, document)` emits.
144    ///
145    /// `None` — the default — means this encoder has no two-segment
146    /// form, and a caller that needs one must refuse. Deliberately NOT
147    /// defaulted to `wrap_special(a ++ b)`: a cross-encoder was trained
148    /// with a separator between the halves, and one that never sees it
149    /// still returns a plausible float. That is the "computes something
150    /// else" failure, and it is invisible — a rerank with no boundary
151    /// produces an ordering, just not the model's.
152    fn wrap_special_pair(&self, _a: &[u32], _b: &[u32]) -> Option<PairSequence> {
153        None
154    }
155
156    /// `n_tokens × n_embd` hidden states, in row order.
157    ///
158    /// `segments` is the per-position segment id, or `None` for "all
159    /// zeros" — the single-sequence case. There is deliberately ONE
160    /// graph with a parameter rather than a segment-aware copy of a
161    /// segment-blind one: this repo has lost a model feature to every
162    /// copied forward pass it has ever had, and the pair path is
163    /// exercised far less often than the embedding path, so a copy is
164    /// exactly where a fix would fail to land.
165    ///
166    /// This is the body an encoder writes; callers want
167    /// [`Self::encode`], which is the same computation with the CPU
168    /// worker pool entered once for the whole pass.
169    fn encode_on_worker(
170        &self,
171        tokens: &[u32],
172        segments: Option<&[u32]>,
173    ) -> Result<Vec<f32>, EncodeError>;
174
175    /// [`Self::encode_on_worker`], with the CPU worker pool entered once
176    /// for the whole pass.
177    ///
178    /// Same rule, and the same reason, as
179    /// [`crate::engine::Engine::forward_token`]: a forward pass through
180    /// a stack of quantized projections opens a parallel region per
181    /// matmul, and every one of them costs a pthread park and wake when
182    /// the driving thread is not a rayon worker. An encoder pass is one
183    /// pass over the whole sequence rather than one per token, so the
184    /// saving is smaller than a decode loop's -- but it is the same
185    /// saving, and an encoder that had to remember to ask for it would
186    /// be one more place for the rule to be forgotten.
187    ///
188    /// Do not override. See
189    /// [`ferrox_core::par::on_workers`] for the three cases it declines
190    /// to promote.
191    fn encode(&self, tokens: &[u32], segments: Option<&[u32]>) -> Result<Vec<f32>, EncodeError> {
192        ferrox_core::par::on_workers(move || self.encode_on_worker(tokens, segments))
193    }
194
195    /// [`Self::encode`] for a single sequence: every position is
196    /// segment 0.
197    fn encode_tokens(&self, tokens: &[u32]) -> Result<Vec<f32>, EncodeError> {
198        self.encode(tokens, None)
199    }
200
201    /// [`Self::encode_tokens`] followed by the checkpoint's own pooling.
202    /// Not L2-normalized — see [`crate::pooling::pool`].
203    fn embed_tokens(&self, tokens: &[u32]) -> Result<Vec<f32>, EncodeError> {
204        let hidden = self.encode_tokens(tokens)?;
205        Ok(pool(&hidden, self.n_embd(), self.pooling_type())?)
206    }
207}