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, PairSequence, 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 #[error(
107 "the reranker checkpoint {name:?} ({arch}) carries a classification head but only \
108 {rows} token-type row(s): there is no \"Sentence B\" embedding to put the document \
109 half of a pair on. Scoring both halves as Sentence A is what this cross-encoder was \
110 NOT trained on, and it reorders the results rather than merely shifting them, so \
111 this refuses at load instead of serving a plausible wrong ranking"
112 )]
113 NoSegmentB {
114 name: String,
115 arch: String,
116 rows: usize,
117 },
118}
119
120/// The one condition under which a checkpoint that HAS a classification
121/// head still cannot serve `/v1/rerank`: its token-type table has no
122/// "Sentence B" row, so a pair would put both halves on segment 0.
123///
124/// A function rather than an `if` inside the loader so the arm is
125/// testable without a GGUF carrying that shape. A refusal whose
126/// condition cannot be shown to fire reads as coverage and is not: this
127/// repo has shipped one keyed on a GGUF spelling nothing writes.
128///
129/// It is checked at LOAD, and only here, because this is the only place
130/// the head and the encoder are both in hand — the BERT loader does not
131/// know whether a head was found, and asking once per request would put
132/// the answer in two places. A checkpoint in this state cannot answer
133/// the one route it exists for, so it does not load.
134fn refuse_unpairable_reranker(
135 has_rank_head: bool,
136 n_segments: usize,
137 name: &str,
138 arch: &str,
139) -> Option<EmbedError> {
140 if has_rank_head && n_segments < 2 {
141 return Some(EmbedError::NoSegmentB {
142 name: name.to_string(),
143 arch: arch.to_string(),
144 rows: n_segments,
145 });
146 }
147 None
148}
149
150/// A loaded embedding model: tokenizer + encoder + the checkpoint's own
151/// pooling rule.
152pub struct EmbeddingModel {
153 encoder: Box<dyn TextEncoder + Send + Sync>,
154 tokenizer: GgufWordPieceTokenizer,
155 /// The reranker classification head, when the checkpoint carries
156 /// one. `None` for a plain embedding model, and that is what makes
157 /// `/v1/rerank` refuse rather than substitute a cosine similarity.
158 rank_head: Option<RankHead>,
159 arch: String,
160 name: String,
161}
162
163impl EmbeddingModel {
164 /// Opens `path` and builds whichever embedding stack its
165 /// `general.architecture` names, or refuses naming what is missing.
166 pub fn from_gguf_path(path: impl AsRef<std::path::Path>) -> Result<Self, EmbedError> {
167 let file = ferrox_gguf::ShardedGguf::open(path.as_ref()).map_err(LoadError::from)?;
168 let arch = ferrox_gguf::TensorSource::metadata_str(&file, "general.architecture")
169 .ok_or_else(|| LoadError::MissingHparam("general.architecture".into()))?
170 .to_string();
171 if arch != BERT_ARCH {
172 return Err(match NOT_YET.iter().find(|(a, _)| *a == arch) {
173 Some((_, needs)) => EmbedError::NotYetImplemented { arch, needs },
174 None => EmbedError::NotAnEmbeddingModel(arch),
175 });
176 }
177 let tok_model = ferrox_gguf::TensorSource::metadata_str(&file, "tokenizer.ggml.model")
178 .unwrap_or_default()
179 .to_string();
180 if tok_model != "bert" {
181 return Err(EmbedError::UnsupportedTokenizer {
182 arch,
183 model: tok_model,
184 });
185 }
186 let name = ferrox_gguf::TensorSource::metadata_str(&file, "general.name")
187 .map(str::to_string)
188 .unwrap_or_else(|| arch.clone());
189 let tokenizer = GgufWordPieceTokenizer::from_gguf(&file)?;
190
191 // ORDER IS LOAD-BEARING. `load_rank_head` MUST run before
192 // `load_bert_encoder`, which ends in
193 // `assert_every_tensor_consumed`: `cls.weight`, `cls.output.*`
194 // and `cls.norm.weight` are read by nothing else in this crate,
195 // so with the two lines swapped every reranker checkpoint dies
196 // with an `UnconsumedTensors` refusal listing tensors ferrox
197 // does in fact read. `read_bert_hparams` touches metadata only,
198 // so asking for the geometry twice costs nothing.
199 let hp = read_bert_hparams(&file)?;
200 let rank_head = load_rank_head(&file, &hp.arch, hp.n_embd, hp.layer_norm_eps)?;
201 let encoder = load_bert_encoder(&file)?;
202
203 if let Some(refusal) =
204 refuse_unpairable_reranker(rank_head.is_some(), encoder.n_segments(), &name, &arch)
205 {
206 return Err(refusal);
207 }
208
209 Ok(Self {
210 encoder: Box::new(encoder),
211 tokenizer,
212 rank_head,
213 arch,
214 name,
215 })
216 }
217
218 pub fn architecture(&self) -> &str {
219 &self.arch
220 }
221
222 /// The checkpoint's `general.name`, or its architecture when the
223 /// file carries none. What `/v1/embeddings` reports as `model`.
224 pub fn name(&self) -> &str {
225 &self.name
226 }
227
228 pub fn n_embd(&self) -> usize {
229 self.encoder.n_embd()
230 }
231
232 pub fn n_ctx_train(&self) -> usize {
233 self.encoder.n_ctx_train()
234 }
235
236 pub fn pooling_type(&self) -> PoolingType {
237 self.encoder.pooling_type()
238 }
239
240 /// The exact ids the encoder will see for `text`: the tokenizer's
241 /// pieces wrapped in the model's own special tokens. Public because
242 /// `/v1/embeddings` has to report `usage.prompt_tokens`, and that
243 /// number is this length — llama.cpp counts the specials too.
244 pub fn token_ids(&self, text: &str) -> Vec<u32> {
245 self.encoder.wrap_special(&self.tokenizer.encode(text))
246 }
247
248 /// Text for `ids`, through this checkpoint's own vocabulary.
249 ///
250 /// The counterpart to [`Self::token_ids`], so `/v1/detokenize`
251 /// answers for an encoder rather than refusing. An embedding
252 /// model's whole contract is the vector it returns for a string,
253 /// and when that vector is surprising the first question is what
254 /// tokens it actually saw. Without this the only way to ask was to
255 /// load the checkpoint in a second tool.
256 ///
257 /// Not `wrap_special`'s inverse: it decodes exactly the ids given,
258 /// including specials if the caller passes them, because a caller
259 /// checking a tokenization wants to see what it sent.
260 pub fn decode_tokens(&self, ids: &[u32]) -> String {
261 self.tokenizer.decode(ids)
262 }
263
264 /// Pooled embedding for `text`. `normalize` applies L2 normalization,
265 /// which is what an OpenAI-compatible `/v1/embeddings` response is
266 /// expected to carry and what llama.cpp's server does by default;
267 /// the raw pooled vector is what the graph produced.
268 pub fn embed(&self, text: &str, normalize: bool) -> Result<Vec<f32>, EmbedError> {
269 let ids = self.token_ids(text);
270 let mut v = self.encoder.embed_tokens(&ids)?;
271 if normalize {
272 l2_normalize(&mut v);
273 }
274 Ok(v)
275 }
276
277 /// Un-pooled `n_tokens × n_embd` hidden states, for a caller that
278 /// wants to pool differently (or not at all).
279 pub fn hidden_states(&self, text: &str) -> Result<Vec<f32>, EmbedError> {
280 Ok(self.encoder.encode_tokens(&self.token_ids(text))?)
281 }
282
283 /// The checkpoint's reranker classification head, or `None` for a
284 /// plain embedding model. What `/v1/rerank` checks before it
285 /// promises a caller a relevance score.
286 pub fn rank_head(&self) -> Option<&RankHead> {
287 self.rank_head.as_ref()
288 }
289
290 /// The exact input [`Self::rerank_score`] will see for one
291 /// `(query, document)` pair: `[CLS] query [SEP] document [SEP]`,
292 /// **with** the segment id of every position.
293 ///
294 /// Separate from the scoring call for the same reason
295 /// [`Self::token_ids`] is separate from [`Self::embed`] — a route
296 /// has to report `usage.prompt_tokens`, and that number is
297 /// `tokens.len()`.
298 pub fn rerank_input(&self, query: &str, document: &str) -> Result<PairSequence, EmbedError> {
299 self.encoder
300 .wrap_special_pair(
301 &self.tokenizer.encode(query),
302 &self.tokenizer.encode(document),
303 )
304 .ok_or_else(|| EmbedError::NoPairInput {
305 arch: self.arch.clone(),
306 })
307 }
308
309 /// The head's relevance score for a pair sequence built by
310 /// [`Self::rerank_input`].
311 ///
312 /// This is upstream's RANK path in full: encode, take the **CLS**
313 /// row, run the classification head, report output 0
314 /// (`send_rerank`'s `embd[0]`). The CLS row is taken here regardless
315 /// of what `{arch}.pooling_type` says, because the head was trained
316 /// on that position — `pooling_type = RANK` is the checkpoint
317 /// *declaring* this path, not naming a pooling rule, which is why
318 /// [`crate::pooling::pool`] still refuses RANK and must keep
319 /// refusing it.
320 ///
321 /// No L2 normalization and no sigmoid: upstream reports the raw
322 /// logit, so a score is comparable only against other scores from
323 /// the same head, and this must not quietly squash it into `0..1`.
324 pub fn rerank_score(&self, pair: &PairSequence) -> Result<f32, EmbedError> {
325 let head = self
326 .rank_head
327 .as_ref()
328 .ok_or_else(|| EmbedError::NoRankHead {
329 name: self.name.clone(),
330 arch: self.arch.clone(),
331 })?;
332 let hidden = self.pair_hidden_states(pair)?;
333 let cls = pool(&hidden, self.encoder.n_embd(), PoolingType::Cls)
334 .map_err(|e| EmbedError::Encode(EncodeError::Pooling(e)))?;
335 Ok(head.score(&cls))
336 }
337
338 /// Un-pooled `n_tokens × n_embd` hidden states for a pair built by
339 /// [`Self::rerank_input`] — [`Self::hidden_states`]'s counterpart
340 /// for the cross-encoder input, and the one graph call
341 /// [`Self::rerank_score`] itself makes.
342 ///
343 /// Public for the same reason [`Self::hidden_states`] is: when a
344 /// relevance score is surprising, the first questions are what
345 /// tokens the model saw and what came out before the head, and
346 /// without this the only way to ask was to load the checkpoint a
347 /// second time — which for a reranker does not even work, because
348 /// [`crate::load_bert_encoder_from_path`] alone leaves `cls.*`
349 /// unconsumed and refuses.
350 ///
351 /// The pair's own `segments` are honoured, so passing a
352 /// [`PairSequence`] whose segments are all zero reproduces the
353 /// segment-blind graph exactly, without a second copy of it to
354 /// drift.
355 pub fn pair_hidden_states(&self, pair: &PairSequence) -> Result<Vec<f32>, EmbedError> {
356 Ok(self.encoder.encode(&pair.tokens, Some(&pair.segments))?)
357 }
358}
359
360#[cfg(test)]
361mod tests {
362 use super::*;
363
364 /// Every deferred embedding architecture must produce a refusal
365 /// that names it and names what it needs — not a generic error.
366 #[test]
367 fn every_deferred_embedding_arch_is_named_in_its_own_refusal() {
368 for (arch, needs) in NOT_YET {
369 let err = EmbedError::NotYetImplemented {
370 arch: (*arch).to_string(),
371 needs,
372 };
373 let msg = err.to_string();
374 assert!(msg.contains(arch), "{msg} does not name {arch}");
375 assert!(msg.contains(needs), "{msg} does not say what is missing");
376 }
377 }
378
379 /// The catalog rows this module claims to cover must actually be
380 /// the encoder/embedding rows the capability registry defers, so a
381 /// new row added there cannot silently fall through to the generic
382 /// "not an embedding model" arm.
383 #[test]
384 fn the_deferred_list_is_a_subset_of_the_capability_registry() {
385 for (arch, _) in NOT_YET {
386 assert!(
387 crate::capability::resolve_profile(arch).is_some(),
388 "{arch} is not in the capability registry"
389 );
390 }
391 }
392
393 /// [`is_embedding_arch`] is what a server routes on, so it has to
394 /// name *exactly* the architectures this module can answer for:
395 /// `bert`, which loads, plus every row in [`NOT_YET`], which
396 /// refuses by name. A registry row scoped
397 /// `DeferredEncoderEmbedding` that is in neither would be routed
398 /// here and hit the generic `NotAnEmbeddingModel` arm, which says
399 /// the opposite of the truth about it.
400 #[test]
401 fn is_embedding_arch_covers_the_registry_rows_and_nothing_else() {
402 let mut registry: Vec<&str> = crate::capability::architecture_catalog()
403 .iter()
404 .filter(|p| {
405 matches!(
406 p.scope,
407 crate::capability::ArchScope::DeferredEncoderEmbedding
408 )
409 })
410 .map(|p| p.gguf_name)
411 .collect();
412 registry.sort_unstable();
413 let mut known: Vec<&str> = NOT_YET
414 .iter()
415 .map(|(a, _)| *a)
416 .chain(std::iter::once(BERT_ARCH))
417 .collect();
418 known.sort_unstable();
419 assert_eq!(
420 registry, known,
421 "the registry's encoder/embedding rows and this module's own list disagree"
422 );
423 for arch in ®istry {
424 assert!(is_embedding_arch(arch), "{arch} is not routed to this path");
425 }
426 // A decoder must NOT be routed here, or `FERROX_MODEL_PATH`
427 // pointing at a llama GGUF would be told it is an embedding
428 // model.
429 for arch in ["llama", "qwen3", "gemma3", "deepseek2"] {
430 assert!(!is_embedding_arch(arch), "{arch} was routed to this path");
431 }
432 }
433
434 /// A reranker that cannot express "Sentence B" is refused at load,
435 /// and a plain embedding model in the same state is NOT — an
436 /// embedding pass is all segment 0 and has nothing to say about a
437 /// second row.
438 ///
439 /// The point of the test is that the refusing arm is REACHABLE.
440 /// Written as a condition inside the loader it could only be
441 /// exercised by a checkpoint nobody publishes, which is how a gate
442 /// comes to read as coverage while never firing.
443 #[test]
444 fn only_a_reranker_needs_a_second_token_type_row_and_it_is_refused_without_one() {
445 assert!(refuse_unpairable_reranker(true, 2, "r", "bert").is_none());
446 assert!(refuse_unpairable_reranker(false, 1, "e", "bert").is_none());
447 assert!(refuse_unpairable_reranker(false, 0, "e", "bert").is_none());
448
449 let err = refuse_unpairable_reranker(true, 1, "some-reranker", "bert")
450 .expect("a head with one segment row must refuse");
451 let msg = err.to_string();
452 for fact in ["some-reranker", "bert", "1 token-type row"] {
453 assert!(msg.contains(fact), "{msg} does not carry {fact}");
454 }
455 assert!(matches!(err, EmbedError::NoSegmentB { rows: 1, .. }));
456 }
457}