Skip to content

Add mean pooling strategy for Modernbert classifier #616

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jun 2, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion backends/candle/src/models/flash_modernbert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,11 @@ impl FlashModernBertModel {

let (pool, classifier) = match model_type {
ModelType::Classifier => {
let pool = Pool::Cls;
let pool: Pool = config
.classifier_pooling
.as_deref()
.and_then(|s| Pool::from_str(s).ok())
.unwrap_or(Pool::Cls);

let classifier: Box<dyn ClassificationHead + Send> =
Box::new(ModernBertClassificationHead::load(vb.clone(), config)?);
Expand Down
7 changes: 6 additions & 1 deletion backends/candle/src/models/modernbert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use candle::{DType, Device, IndexOp, Module, Result, Tensor, D};
use candle_nn::{Embedding, VarBuilder};
use serde::Deserialize;
use text_embeddings_backend_core::{Batch, ModelType, Pool};
use std::str::FromStr;

// https://github.com/huggingface/transformers/blob/main/src/transformers/models/modernbert/configuration_modernbert.py
#[derive(Debug, Clone, PartialEq, Deserialize)]
Expand Down Expand Up @@ -484,7 +485,11 @@ impl ModernBertModel {
pub fn load(vb: VarBuilder, config: &ModernBertConfig, model_type: ModelType) -> Result<Self> {
let (pool, classifier) = match model_type {
ModelType::Classifier => {
let pool = Pool::Cls;
let pool: Pool = config
.classifier_pooling
.as_deref()
.and_then(|s| Pool::from_str(s).ok())
.unwrap_or(Pool::Cls);

let classifier: Box<dyn ClassificationHead + Send> =
Box::new(ModernBertClassificationHead::load(vb.clone(), config)?);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
source: backends/candle/tests/test_modernbert.rs
assertion_line: 229
expression: predictions_single
---
- - -0.30617672

32 changes: 32 additions & 0 deletions backends/candle/tests/test_modernbert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,3 +202,35 @@ fn test_modernbert_classification() -> Result<()> {

Ok(())
}

#[test]
Copy link
Contributor Author

@kwnath kwnath May 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Having a bit of trouble running this test (unable to download the HF model, hitting a 429, just lacking a HF token) and not super pleased with this test but it;s just to test that both cls/mean produce different outputs as expected.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about just testing with the reranker-ModernBERT-large-gooaq-bce model directly, which is a mean classifier-pooling, instead of gte-reranker model with mean pooling?

I think we can check whether classifier pooling correctly works by running the reranker-ModernBERT-gooqa-bce model, while cls classifier pooling has already been verified in the above test! (implicitly assume cls and mean will behave differently)

unable to download the HF model, hitting a 429,

when I faced that issue, in my case, I manually download the model via git or huggingface-cli on my local, and then set HUGGINGFACE_HUB_CACHE to point to that local path.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That sounds like a good idea, will try this!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It couldn't find from the cache but I managed to just export a hugginface token, all good!

successes:
    test_modernbert_classification_mean_pooling

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 3 filtered out; finished in 3.94s

#[serial_test::serial]
fn test_modernbert_classification_mean_pooling() -> Result<()> {
let model_root = download_artifacts("tomaarsen/reranker-ModernBERT-large-gooaq-bce", None)?;
let tokenizer = load_tokenizer(&model_root)?;
let backend = CandleBackend::new(&model_root, "float32".to_string(), ModelType::Classifier)?;

let input_single = batch(
vec![tokenizer
.encode(("What is Deep Learning?", "Deep Learning is not..."), true)
.unwrap()],
[0].to_vec(),
vec![],
);

let predictions: Vec<Vec<f32>> = backend
.predict(input_single)?
.into_iter()
.map(|(_, v)| v)
.collect();
let predictions_single = SnapshotScores::from(predictions);

let matcher = relative_matcher();
insta::assert_yaml_snapshot!(
"modernbert_classification_mean_pooling",
predictions_single,
&matcher
);

Ok(())
}
17 changes: 17 additions & 0 deletions backends/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,23 @@ impl fmt::Display for Pool {
}
}

impl std::str::FromStr for Pool {
type Err = String;

fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.trim().to_lowercase().as_str() {
"cls" => Ok(Pool::Cls),
"mean" => Ok(Pool::Mean),
"splade" => Ok(Pool::Splade),
"last_token" => Ok(Pool::LastToken),
_ => Err(format!(
"Invalid pooling method '{}'. Valid options: cls, mean, splade, last_token",
s
)),
}
}
}

#[derive(Debug, Error, Clone)]
pub enum BackendError {
#[error("No backend found")]
Expand Down