use crate::{
common::{init_session_builder, Error, Result, TokenizerFiles},
init::{HasMaxLength, InitOptionsWithLength, ProviderNames},
pooling::Pooling,
EmbeddingModel, OutputKey, QuantizationMode,
};
use ort::{
environment::Environment,
ep::ExecutionProviderDispatch,
session::{
builder::{AutoDevicePolicy, SessionBuilder},
Session,
},
};
use tokenizers::Tokenizer;
use super::DEFAULT_MAX_LENGTH;
impl HasMaxLength for EmbeddingModel {
const MAX_LENGTH: usize = DEFAULT_MAX_LENGTH;
}
pub type TextInitOptions = InitOptionsWithLength<EmbeddingModel>;
#[derive(Clone)]
#[non_exhaustive]
pub struct InitOptionsUserDefined {
pub environment: Option<Environment>,
pub execution_providers: Vec<ExecutionProviderDispatch>,
pub max_length: usize,
pub intra_threads: Option<usize>,
pub disable_cpu_fallback: bool,
pub dimension_overrides: Vec<(String, i64)>,
pub session_config: Vec<(String, String)>,
pub auto_device: Option<AutoDevicePolicy>,
}
impl std::fmt::Debug for InitOptionsUserDefined {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("InitOptionsUserDefined")
.field("environment", &self.environment)
.field(
"execution_providers",
&ProviderNames(&self.execution_providers),
)
.field("max_length", &self.max_length)
.field("intra_threads", &self.intra_threads)
.field("disable_cpu_fallback", &self.disable_cpu_fallback)
.field("dimension_overrides", &self.dimension_overrides)
.field("session_config", &self.session_config)
.field("auto_device", &self.auto_device)
.finish()
}
}
impl InitOptionsUserDefined {
pub fn new() -> Self {
Self {
..Default::default()
}
}
pub fn with_environment(mut self, environment: Environment) -> Self {
self.environment = Some(environment);
self
}
pub fn with_execution_providers(
mut self,
execution_providers: Vec<ExecutionProviderDispatch>,
) -> Self {
self.execution_providers = execution_providers;
self
}
pub fn with_max_length(mut self, max_length: usize) -> Self {
self.max_length = max_length;
self
}
pub fn with_intra_threads(mut self, intra_threads: usize) -> Self {
self.intra_threads = Some(intra_threads);
self
}
pub fn with_disable_cpu_fallback(mut self, disable: bool) -> Self {
self.disable_cpu_fallback = disable;
self
}
pub fn with_dimension_override(mut self, name: impl Into<String>, size: i64) -> Self {
self.dimension_overrides.push((name.into(), size));
self
}
pub fn with_session_config(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.session_config.push((key.into(), value.into()));
self
}
pub fn with_auto_device(mut self, policy: AutoDevicePolicy) -> Self {
self.auto_device = Some(policy);
self
}
pub(crate) fn into_session_builder(self) -> Result<(SessionBuilder, usize)> {
let Self {
environment,
execution_providers,
max_length,
intra_threads,
disable_cpu_fallback,
dimension_overrides,
session_config,
auto_device,
} = self;
let builder_error = |err: ort::Error<SessionBuilder>| Error::OrtBuilder(err.to_string());
let mut builder = init_session_builder(
environment,
execution_providers,
intra_threads,
session_config,
auto_device,
)?;
if disable_cpu_fallback {
builder = builder.with_disable_cpu_fallback().map_err(builder_error)?;
}
for (name, size) in dimension_overrides {
builder = builder
.with_dimension_override(name, size)
.map_err(builder_error)?;
}
Ok((builder, max_length))
}
}
impl Default for InitOptionsUserDefined {
fn default() -> Self {
Self {
environment: None,
execution_providers: Default::default(),
max_length: DEFAULT_MAX_LENGTH,
intra_threads: None,
disable_cpu_fallback: false,
dimension_overrides: Vec::new(),
session_config: Vec::new(),
auto_device: None,
}
}
}
impl From<TextInitOptions> for InitOptionsUserDefined {
fn from(options: TextInitOptions) -> Self {
InitOptionsUserDefined {
environment: options.environment,
execution_providers: options.execution_providers,
max_length: options.max_length,
intra_threads: options.intra_threads,
disable_cpu_fallback: false,
dimension_overrides: Vec::new(),
session_config: options.session_config,
auto_device: options.auto_device,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UserDefinedEmbeddingModel {
pub onnx_file: Vec<u8>,
pub external_initializers: Vec<ExternalInitializerFile>,
pub tokenizer_files: TokenizerFiles,
pub pooling: Option<Pooling>,
pub quantization: QuantizationMode,
pub output_key: Option<OutputKey>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExternalInitializerFile {
pub file_name: String,
pub buffer: Vec<u8>,
}
impl UserDefinedEmbeddingModel {
pub fn new(onnx_file: Vec<u8>, tokenizer_files: TokenizerFiles) -> Self {
Self {
onnx_file,
external_initializers: Vec::new(),
tokenizer_files,
quantization: QuantizationMode::None,
pooling: None,
output_key: None,
}
}
pub fn with_quantization(mut self, quantization: QuantizationMode) -> Self {
self.quantization = quantization;
self
}
pub fn with_pooling(mut self, pooling: Pooling) -> Self {
self.pooling = Some(pooling);
self
}
pub fn with_external_initializer(mut self, file_name: String, buffer: Vec<u8>) -> Self {
self.external_initializers
.push(ExternalInitializerFile { file_name, buffer });
self
}
}
pub struct TextEmbedding {
pub tokenizer: Tokenizer,
pub(crate) pooling: Option<Pooling>,
pub(crate) session: Session,
pub(crate) need_token_type_ids: bool,
pub(crate) quantization: QuantizationMode,
pub(crate) output_key: Option<OutputKey>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn user_defined_session_controls_are_opt_in_and_composable() {
let defaults = InitOptionsUserDefined::default();
assert!(!defaults.disable_cpu_fallback);
assert!(defaults.dimension_overrides.is_empty());
let configured = InitOptionsUserDefined::new()
.with_disable_cpu_fallback(true)
.with_dimension_override("batch_size", 1)
.with_dimension_override("sequence_length", 512);
assert!(configured.disable_cpu_fallback);
assert_eq!(
configured.dimension_overrides,
[
("batch_size".to_string(), 1),
("sequence_length".to_string(), 512)
]
);
}
#[test]
fn session_config_is_collected_and_carried_by_from() {
let opts = TextInitOptions::new(EmbeddingModel::AllMiniLML6V2)
.with_session_config("a", "1")
.with_session_config("b", "2");
assert_eq!(
opts.session_config,
vec![("a".into(), "1".into()), ("b".into(), "2".into())]
);
let user_defined = InitOptionsUserDefined::from(opts);
assert_eq!(
user_defined.session_config,
vec![("a".into(), "1".into()), ("b".into(), "2".into())]
);
}
#[test]
fn auto_device_defaults_to_none_and_is_carried_by_from() {
assert_eq!(
TextInitOptions::new(EmbeddingModel::AllMiniLML6V2).auto_device,
None
);
let opts = TextInitOptions::new(EmbeddingModel::AllMiniLML6V2)
.with_auto_device(AutoDevicePolicy::PreferCPU);
assert_eq!(opts.auto_device, Some(AutoDevicePolicy::PreferCPU));
let user_defined = InitOptionsUserDefined::from(opts);
assert_eq!(user_defined.auto_device, Some(AutoDevicePolicy::PreferCPU));
}
}