ferrox_models/embedding_model.rs
1//! One GGUF path in, one embedding vector out.
2//!
3//! Binds a tokenizer to a [`TextEncoder`] and owns the two steps
4//! between them that neither half should own alone: adding the model's
5//! own special tokens (`[CLS] … [SEP]`) around the tokenizer's pieces,
6//! and pooling the hidden states the way the checkpoint's
7//! `pooling_type` says.
8//!
9//! This is the type `/v1/embeddings` and the CLI both hold. It exists
10//! so neither of them has to know that `bert` is an encoder, that
11//! WordPiece does not add its own specials, or that CLS pooling means
12//! row zero.
13
14use thiserror::Error;
15
16use crate::bert_gguf_loader::{load_bert_encoder, read_bert_hparams, BERT_ARCH};
17use crate::encoder::{EncodeError, TextEncoder};
18use crate::loader::LoadError;
19use crate::pooling::{l2_normalize, pool, PoolingType};
20use crate::rank_head::{load_rank_head, RankHead};
21use crate::tokenizer::{GgufWordPieceTokenizer, TokenizerLoadError};
22
23/// Encoder architectures upstream builds from `bert.cpp` and the other
24/// embedding rows in the capability catalog, with what each one needs
25/// that this crate does not have. Used to refuse *by name* instead of
26/// with a generic "unsupported".
27const NOT_YET: &[(&str, &str)] = &[
28 ("nomic-bert", "RoPE on Q/K and a gated FFN"),
29 ("nomic-bert-moe", "RoPE, a gated FFN and MoE expert layers"),
30 ("jina-bert-v2", "GEGLU and a second attention norm"),
31 ("jina-bert-v3", "RoPE and per-projection QK norm"),
32 ("neo-bert", "per-projection QK norm"),
33 (
34 "modern-bert",
35 "its own graph (local/global alternating attention)",
36 ),
37 ("eurobert", "its own graph"),
38 ("t5encoder", "the T5 encoder stack"),
39 ("llama-embed", "a decoder embedding path, not an encoder"),
40 (
41 "gemma-embedding",
42 "a decoder embedding path, not an encoder",
43 ),
44 ("pangu-embedded", "a decoder embedding path, not an encoder"),
45];
46
47/// True when `general.architecture` names an encoder / embedding model
48/// rather than something with an output head.
49///
50/// This is the question a *server* asks before it decides which loader
51/// a checkpoint path goes to: an encoder can never reach the decoder
52/// path, so routing it there produces a refusal about a missing tensor
53/// instead of "this is an embedding model". The answer comes from the
54/// capability registry's own [`crate::capability::ArchScope`] and not
55/// from a second list beside [`NOT_YET`], because two lists of the same
56/// architectures is the copy this repo has already paid for seven times
57/// — a row added to the registry is covered here the moment it lands.
58///
59/// `true` does not mean ferrox can serve it. It means
60/// [`EmbeddingModel::from_gguf_path`] is the loader that will either
61/// build it or refuse it *by name*.
62pub fn is_embedding_arch(arch: &str) -> bool {
63 crate::capability::resolve_profile(arch).is_some_and(|p| {
64 matches!(
65 p.scope,
66 crate::capability::ArchScope::DeferredEncoderEmbedding
67 )
68 })
69}
70
71#[derive(Debug, Error)]
72pub enum EmbedError {
73 #[error(transparent)]
74 Load(#[from] LoadError),
75 #[error(transparent)]
76 Tokenizer(#[from] TokenizerLoadError),
77 #[error(transparent)]
78 Encode(#[from] EncodeError),
79 #[error(
80 "architecture {arch:?} is an embedding model ferrox cannot serve yet: it needs {needs}. \
81 Only {BERT_ARCH:?} is implemented"
82 )]
83 NotYetImplemented { arch: String, needs: &'static str },
84 #[error(
85 "architecture {0:?} is not an embedding model this build knows. \
86 Only {BERT_ARCH:?} is implemented"
87 )]
88 NotAnEmbeddingModel(String),
89 #[error(
90 "{arch:?} carries tokenizer.ggml.model = {model:?}, but this embedding path only has \
91 WordPiece (\"bert\")"
92 )]
93 UnsupportedTokenizer { arch: String, model: String },
94 #[error(
95 "the embedding model {name:?} ({arch}) carries no reranker classification head: the \
96 checkpoint has no cls / cls.output tensors, so it has no relevance score to \
97 report. It can only produce embeddings"
98 )]
99 NoRankHead { name: String, arch: String },
100 #[error(
101 "the encoder for {arch:?} has no two-segment (query, document) input form, which a \
102 cross-encoder rerank needs. Concatenating the two texts would score fluently and \
103 wrongly, so this refuses instead"
104 )]
105 NoPairInput { arch: String },
106}
107
108/// A loaded embedding model: tokenizer + encoder + the checkpoint's own
109/// pooling rule.
110pub struct EmbeddingModel {
111 encoder: Box<dyn TextEncoder + Send + Sync>,
112 tokenizer: GgufWordPieceTokenizer,
113 /// The reranker classification head, when the checkpoint carries
114 /// one. `None` for a plain embedding model, and that is what makes
115 /// `/v1/rerank` refuse rather than substitute a cosine similarity.
116 rank_head: Option<RankHead>,
117 arch: String,
118 name: String,
119}
120
121impl EmbeddingModel {
122 /// Opens `path` and builds whichever embedding stack its
123 /// `general.architecture` names, or refuses naming what is missing.
124 pub fn from_gguf_path(path: impl AsRef<std::path::Path>) -> Result<Self, EmbedError> {
125 let file = ferrox_gguf::ShardedGguf::open(path.as_ref()).map_err(LoadError::from)?;
126 let arch = ferrox_gguf::TensorSource::metadata_str(&file, "general.architecture")
127 .ok_or_else(|| LoadError::MissingHparam("general.architecture".into()))?
128 .to_string();
129 if arch != BERT_ARCH {
130 return Err(match NOT_YET.iter().find(|(a, _)| *a == arch) {
131 Some((_, needs)) => EmbedError::NotYetImplemented { arch, needs },
132 None => EmbedError::NotAnEmbeddingModel(arch),
133 });
134 }
135 let tok_model = ferrox_gguf::TensorSource::metadata_str(&file, "tokenizer.ggml.model")
136 .unwrap_or_default()
137 .to_string();
138 if tok_model != "bert" {
139 return Err(EmbedError::UnsupportedTokenizer {
140 arch,
141 model: tok_model,
142 });
143 }
144 let name = ferrox_gguf::TensorSource::metadata_str(&file, "general.name")
145 .map(str::to_string)
146 .unwrap_or_else(|| arch.clone());
147 let tokenizer = GgufWordPieceTokenizer::from_gguf(&file)?;
148
149 // ORDER IS LOAD-BEARING. `load_rank_head` MUST run before
150 // `load_bert_encoder`, which ends in
151 // `assert_every_tensor_consumed`: `cls.weight`, `cls.output.*`
152 // and `cls.norm.weight` are read by nothing else in this crate,
153 // so with the two lines swapped every reranker checkpoint dies
154 // with an `UnconsumedTensors` refusal listing tensors ferrox
155 // does in fact read. `read_bert_hparams` touches metadata only,
156 // so asking for the geometry twice costs nothing.
157 let hp = read_bert_hparams(&file)?;
158 let rank_head = load_rank_head(&file, &hp.arch, hp.n_embd, hp.layer_norm_eps)?;
159 let encoder = load_bert_encoder(&file)?;
160
161 Ok(Self {
162 encoder: Box::new(encoder),
163 tokenizer,
164 rank_head,
165 arch,
166 name,
167 })
168 }
169
170 pub fn architecture(&self) -> &str {
171 &self.arch
172 }
173
174 /// The checkpoint's `general.name`, or its architecture when the
175 /// file carries none. What `/v1/embeddings` reports as `model`.
176 pub fn name(&self) -> &str {
177 &self.name
178 }
179
180 pub fn n_embd(&self) -> usize {
181 self.encoder.n_embd()
182 }
183
184 pub fn n_ctx_train(&self) -> usize {
185 self.encoder.n_ctx_train()
186 }
187
188 pub fn pooling_type(&self) -> PoolingType {
189 self.encoder.pooling_type()
190 }
191
192 /// The exact ids the encoder will see for `text`: the tokenizer's
193 /// pieces wrapped in the model's own special tokens. Public because
194 /// `/v1/embeddings` has to report `usage.prompt_tokens`, and that
195 /// number is this length — llama.cpp counts the specials too.
196 pub fn token_ids(&self, text: &str) -> Vec<u32> {
197 self.encoder.wrap_special(&self.tokenizer.encode(text))
198 }
199
200 /// Pooled embedding for `text`. `normalize` applies L2 normalization,
201 /// which is what an OpenAI-compatible `/v1/embeddings` response is
202 /// expected to carry and what llama.cpp's server does by default;
203 /// the raw pooled vector is what the graph produced.
204 pub fn embed(&self, text: &str, normalize: bool) -> Result<Vec<f32>, EmbedError> {
205 let ids = self.token_ids(text);
206 let mut v = self.encoder.embed_tokens(&ids)?;
207 if normalize {
208 l2_normalize(&mut v);
209 }
210 Ok(v)
211 }
212
213 /// Un-pooled `n_tokens × n_embd` hidden states, for a caller that
214 /// wants to pool differently (or not at all).
215 pub fn hidden_states(&self, text: &str) -> Result<Vec<f32>, EmbedError> {
216 Ok(self.encoder.encode_tokens(&self.token_ids(text))?)
217 }
218
219 /// The checkpoint's reranker classification head, or `None` for a
220 /// plain embedding model. What `/v1/rerank` checks before it
221 /// promises a caller a relevance score.
222 pub fn rank_head(&self) -> Option<&RankHead> {
223 self.rank_head.as_ref()
224 }
225
226 /// The exact ids [`Self::rerank_score`] will see for one
227 /// `(query, document)` pair: `[CLS] query [SEP] document [SEP]`.
228 ///
229 /// Separate from the scoring call for the same reason
230 /// [`Self::token_ids`] is separate from [`Self::embed`] — a route
231 /// has to report `usage.prompt_tokens`, and that number is this
232 /// length.
233 pub fn rerank_token_ids(&self, query: &str, document: &str) -> Result<Vec<u32>, EmbedError> {
234 self.encoder
235 .wrap_special_pair(
236 &self.tokenizer.encode(query),
237 &self.tokenizer.encode(document),
238 )
239 .ok_or_else(|| EmbedError::NoPairInput {
240 arch: self.arch.clone(),
241 })
242 }
243
244 /// The head's relevance score for a pair sequence built by
245 /// [`Self::rerank_token_ids`].
246 ///
247 /// This is upstream's RANK path in full: encode, take the **CLS**
248 /// row, run the classification head, report output 0
249 /// (`send_rerank`'s `embd[0]`). The CLS row is taken here regardless
250 /// of what `{arch}.pooling_type` says, because the head was trained
251 /// on that position — `pooling_type = RANK` is the checkpoint
252 /// *declaring* this path, not naming a pooling rule, which is why
253 /// [`crate::pooling::pool`] still refuses RANK and must keep
254 /// refusing it.
255 ///
256 /// No L2 normalization and no sigmoid: upstream reports the raw
257 /// logit, so a score is comparable only against other scores from
258 /// the same head, and this must not quietly squash it into `0..1`.
259 pub fn rerank_score(&self, pair_ids: &[u32]) -> Result<f32, EmbedError> {
260 let head = self
261 .rank_head
262 .as_ref()
263 .ok_or_else(|| EmbedError::NoRankHead {
264 name: self.name.clone(),
265 arch: self.arch.clone(),
266 })?;
267 let hidden = self.encoder.encode_tokens(pair_ids)?;
268 let cls = pool(&hidden, self.encoder.n_embd(), PoolingType::Cls)
269 .map_err(|e| EmbedError::Encode(EncodeError::Pooling(e)))?;
270 Ok(head.score(&cls))
271 }
272}
273
274#[cfg(test)]
275mod tests {
276 use super::*;
277
278 /// Every deferred embedding architecture must produce a refusal
279 /// that names it and names what it needs — not a generic error.
280 #[test]
281 fn every_deferred_embedding_arch_is_named_in_its_own_refusal() {
282 for (arch, needs) in NOT_YET {
283 let err = EmbedError::NotYetImplemented {
284 arch: (*arch).to_string(),
285 needs,
286 };
287 let msg = err.to_string();
288 assert!(msg.contains(arch), "{msg} does not name {arch}");
289 assert!(msg.contains(needs), "{msg} does not say what is missing");
290 }
291 }
292
293 /// The catalog rows this module claims to cover must actually be
294 /// the encoder/embedding rows the capability registry defers, so a
295 /// new row added there cannot silently fall through to the generic
296 /// "not an embedding model" arm.
297 #[test]
298 fn the_deferred_list_is_a_subset_of_the_capability_registry() {
299 for (arch, _) in NOT_YET {
300 assert!(
301 crate::capability::resolve_profile(arch).is_some(),
302 "{arch} is not in the capability registry"
303 );
304 }
305 }
306
307 /// [`is_embedding_arch`] is what a server routes on, so it has to
308 /// name *exactly* the architectures this module can answer for:
309 /// `bert`, which loads, plus every row in [`NOT_YET`], which
310 /// refuses by name. A registry row scoped
311 /// `DeferredEncoderEmbedding` that is in neither would be routed
312 /// here and hit the generic `NotAnEmbeddingModel` arm, which says
313 /// the opposite of the truth about it.
314 #[test]
315 fn is_embedding_arch_covers_the_registry_rows_and_nothing_else() {
316 let mut registry: Vec<&str> = crate::capability::architecture_catalog()
317 .iter()
318 .filter(|p| {
319 matches!(
320 p.scope,
321 crate::capability::ArchScope::DeferredEncoderEmbedding
322 )
323 })
324 .map(|p| p.gguf_name)
325 .collect();
326 registry.sort_unstable();
327 let mut known: Vec<&str> = NOT_YET
328 .iter()
329 .map(|(a, _)| *a)
330 .chain(std::iter::once(BERT_ARCH))
331 .collect();
332 known.sort_unstable();
333 assert_eq!(
334 registry, known,
335 "the registry's encoder/embedding rows and this module's own list disagree"
336 );
337 for arch in ®istry {
338 assert!(is_embedding_arch(arch), "{arch} is not routed to this path");
339 }
340 // A decoder must NOT be routed here, or `FERROX_MODEL_PATH`
341 // pointing at a llama GGUF would be told it is an embedding
342 // model.
343 for arch in ["llama", "qwen3", "gemma3", "deepseek2"] {
344 assert!(!is_embedding_arch(arch), "{arch} was routed to this path");
345 }
346 }
347}