mod bert_pooler;
#[cfg(test)]
pub(crate) mod flash_fixture;
mod logit_score;
mod roberta_classification;
use candle_core::DType;
use serde::Deserialize;
use serde::Serialize;
use super::EncoderInput;
use super::jina_bert;
use super::xlm_roberta_flash;
use crate::error::Result;
use crate::rerank::RerankScore;
use crate::rerank::ScoreActivation;
pub trait RerankModel: Send + Sync {
fn forward(&self, input: &EncoderInput) -> Result<Vec<RerankScore>>;
fn max_position_embeddings(&self) -> usize;
fn weights_dtype(&self) -> DType;
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
#[non_exhaustive]
pub enum RerankHead {
BertPooler,
RobertaClassificationHead,
LogitScore {
true_token_id: u32,
false_token_id: u32,
unembedding: Unembedding,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Unembedding {
Tied,
Untied,
}
impl Unembedding {
pub fn name(self) -> &'static str {
match self {
Unembedding::Tied => "tied",
Unembedding::Untied => "untied",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RerankConventions {
pub head: RerankHead,
pub score_activation: ScoreActivation,
pub alibi_variant: Option<jina_bert::AlibiSlopeVariant>,
pub position_scheme: Option<xlm_roberta_flash::PositionScheme>,
}
pub fn load_rerank(
model_type: &str,
config_json: &str,
vb: candle_nn::VarBuilder,
conventions: RerankConventions,
) -> Result<Box<dyn RerankModel>> {
match conventions.head {
RerankHead::BertPooler => Ok(Box::new(bert_pooler::BertPoolerRerank::load(
model_type,
config_json,
vb,
conventions.score_activation,
conventions.alibi_variant,
)?)),
RerankHead::RobertaClassificationHead => Ok(Box::new(
roberta_classification::RobertaClassificationRerank::load(
model_type,
config_json,
vb,
conventions.score_activation,
conventions.position_scheme,
)?,
)),
RerankHead::LogitScore {
true_token_id,
false_token_id,
unembedding,
} => Ok(Box::new(logit_score::LogitScoreRerank::load(
model_type,
config_json,
vb,
[true_token_id, false_token_id],
unembedding,
conventions.score_activation,
)?)),
}
}
#[cfg(test)]
mod tests;