Skip to content
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
81 changes: 75 additions & 6 deletions src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ use tokenizers::Tokenizer;
pub struct StaticModel {
tokenizer: Tokenizer,
embeddings: Array2<f32>,
weights: Option<Vec<f32>>,
token_mapping: Option<Vec<usize>>,
normalize: bool,
median_token_length: usize,
unk_token_id: Option<usize>,
Expand Down Expand Up @@ -114,9 +116,48 @@ impl StaticModel {
};
let embeddings = Array2::from_shape_vec((rows, cols), floats).context("failed to build embeddings array")?;

// Load optional weights for vocabulary quantization
let weights = match safet.tensor("weights") {
Ok(t) => {
let raw = t.data();
let v: Vec<f32> = match t.dtype() {
Dtype::F64 => raw
.chunks_exact(8)
.map(|b| f64::from_le_bytes(b.try_into().unwrap()) as f32)
.collect(),
Dtype::F32 => raw
.chunks_exact(4)
.map(|b| f32::from_le_bytes(b.try_into().unwrap()))
.collect(),
Dtype::F16 => raw
.chunks_exact(2)
.map(|b| half::f16::from_le_bytes(b.try_into().unwrap()).to_f32())
.collect(),
other => return Err(anyhow!("unsupported weights dtype: {:?}", other)),
};
Some(v)
}
Err(_) => None,
};

// Load optional token mapping for vocabulary quantization
let token_mapping = match safet.tensor("mapping") {
Ok(t) => {
let raw = t.data();
let v: Vec<usize> = raw
.chunks_exact(4)
.map(|b| i32::from_le_bytes(b.try_into().unwrap()) as usize)
.collect();
Some(v)
}
Err(_) => None,
};

Ok(Self {
tokenizer,
embeddings,
weights,
token_mapping,
normalize,
median_token_length,
unk_token_id: Some(unk_token_id),
Expand Down Expand Up @@ -201,18 +242,46 @@ impl StaticModel {

/// Mean-pool a single token-ID list into a vector
fn pool_ids(&self, ids: Vec<u32>) -> Vec<f32> {
let mut sum = vec![0.0; self.embeddings.ncols()];
let dim = self.embeddings.ncols();
let mut sum = vec![0.0; dim];
let mut cnt = 0usize;

for &id in &ids {
let row = self.embeddings.row(id as usize);
let tok = id as usize;

// Remap: row = token_mapping[id] or id
let row_idx = if let Some(m) = &self.token_mapping {
*m.get(tok).unwrap_or(&tok)
} else {
tok
};

// Scale by per-token weight if present
let scale = if let Some(w) = &self.weights {
*w.get(tok).unwrap_or(&1.0)
} else {
1.0
};

let row = self.embeddings.row(row_idx);
for (i, &v) in row.iter().enumerate() {
sum[i] += v;
sum[i] += v * scale;
}
cnt += 1;
}
let cnt = ids.len().max(1) as f32;
sum.iter_mut().for_each(|x| *x /= cnt);

// Mean pool the embeddings
let denom = (cnt.max(1)) as f32;
for x in &mut sum {
*x /= denom;
}

// Normalize the embeddings if required
if self.normalize {
let norm = sum.iter().map(|&v| v * v).sum::<f32>().sqrt().max(1e-12);
sum.iter_mut().for_each(|x| *x /= norm);
for x in &mut sum {
*x /= norm;
}
}
sum
}
Expand Down
22 changes: 22 additions & 0 deletions tests/common.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#![allow(dead_code)]
use model2vec_rs::model::StaticModel;

/// Load the small float32 test model from fixtures
Expand All @@ -10,3 +11,24 @@ pub fn load_test_model() -> StaticModel {
)
.expect("Failed to load test model")
}

/// Load the vocab quantized test model from fixtures
pub fn load_test_model_vocab_quantized() -> StaticModel {
StaticModel::from_pretrained(
"tests/fixtures/test-model-vocab-quantized",
None, // token
None, // normalize
None, // subfolder
)
.expect("Failed to load test model")
}

pub fn encode_with_model(path: &str) -> Vec<f32> {
// Helper function to load the model and encode "hello world"
let model = StaticModel::from_pretrained(path, None, None, None)
.unwrap_or_else(|e| panic!("Failed to load model at {path}: {e}"));

let out = model.encode(&["hello world".to_string()]);
assert_eq!(out.len(), 1);
out.into_iter().next().unwrap()
}
1 change: 1 addition & 0 deletions tests/fixtures/embeddings_vocab_quantized.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[[-0.363402567303566, -0.17280622671667234, 0.39940570500107386, -0.16813011070789555, -0.15618451933846883, -0.14994650725286524, 0.006071081245258223, -0.16688048919255372, 0.22185219763399205, -0.02887293996697886, -0.17287425174176316, -0.01464316366136059, 0.16364637740934518, 0.15876414737891392, 0.06036445094799073, 0.15604592511625437, -0.0671308839546444, -0.016413190151500695, 0.016156947144592284, -0.04046410877612431, 0.08342219180115457, -0.06072982382315607, -0.15155935894530448, -0.27756653365043565, 0.04183386122272067, -0.02478048814648766, 0.048693007647196467, 0.15564136567656622, 0.03729875053535759, -0.06892603188806953, 0.08513432033392887, 0.0036654278831274112, -0.017677908666363845, 0.062035159999304555, -0.1394435606629564, 0.05264278960819571, -0.10000422994390393, 0.162456462739632, 0.0026303158188036926, -0.010224468015697916, -0.12629957405039433, -0.08506841545219175, -0.06720500777509077, -0.04443293593977252, 0.01816271214883152, 0.11269895366859049, 0.15572718186207016, -0.12838458617894438, 0.020126459971623472, -0.16689367919078762, 0.1038076137507656, 0.005876202291780198, 0.11467950137199819, -0.06360069640738063, 0.12898717602987858, 0.06665970239323335, 0.1263998072107107, 0.054322006298590964, 0.02275680905863399, -0.09242075684142392, 0.0003214892909238989, 0.06269664923701938, 0.007532826486481935, 0.006629162182434642]]
100 changes: 100 additions & 0 deletions tests/fixtures/test-model-vocab-quantized/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
---
base_model: BAAI/bge-base-en-v1.5
language:
- en
library_name: model2vec
license: mit
model_name: test-model-vocab-quantized
tags:
- embeddings
- static-embeddings
- sentence-transformers
---

# test-model-vocab-quantized Model Card

This [Model2Vec](https://github.com/MinishLab/model2vec) model is a distilled version of the BAAI/bge-base-en-v1.5(https://huggingface.co/BAAI/bge-base-en-v1.5) Sentence Transformer. It uses static embeddings, allowing text embeddings to be computed orders of magnitude faster on both GPU and CPU. It is designed for applications where computational resources are limited or where real-time performance is critical. Model2Vec models are the smallest, fastest, and most performant static embedders available. The distilled models are up to 50 times smaller and 500 times faster than traditional Sentence Transformers.


## Installation

Install model2vec using pip:
```
pip install model2vec
```

## Usage

### Using Model2Vec

The [Model2Vec library](https://github.com/MinishLab/model2vec) is the fastest and most lightweight way to run Model2Vec models.

Load this model using the `from_pretrained` method:
```python
from model2vec import StaticModel

# Load a pretrained Model2Vec model
model = StaticModel.from_pretrained("test-model-vocab-quantized")

# Compute text embeddings
embeddings = model.encode(["Example sentence"])
```

### Using Sentence Transformers

You can also use the [Sentence Transformers library](https://github.com/UKPLab/sentence-transformers) to load and use the model:

```python
from sentence_transformers import SentenceTransformer

# Load a pretrained Sentence Transformer model
model = SentenceTransformer("test-model-vocab-quantized")

# Compute text embeddings
embeddings = model.encode(["Example sentence"])
```

### Distilling a Model2Vec model

You can distill a Model2Vec model from a Sentence Transformer model using the `distill` method. First, install the `distill` extra with `pip install model2vec[distill]`. Then, run the following code:

```python
from model2vec.distill import distill

# Distill a Sentence Transformer model, in this case the BAAI/bge-base-en-v1.5 model
m2v_model = distill(model_name="BAAI/bge-base-en-v1.5", pca_dims=256)

# Save the model
m2v_model.save_pretrained("m2v_model")
```

## How it works

Model2vec creates a small, fast, and powerful model that outperforms other static embedding models by a large margin on all tasks we could find, while being much faster to create than traditional static embedding models such as GloVe. Best of all, you don't need any data to distill a model using Model2Vec.

It works by passing a vocabulary through a sentence transformer model, then reducing the dimensionality of the resulting embeddings using PCA, and finally weighting the embeddings using [SIF weighting](https://openreview.net/pdf?id=SyK00v5xx). During inference, we simply take the mean of all token embeddings occurring in a sentence.

## Additional Resources

- [Model2Vec Repo](https://github.com/MinishLab/model2vec)
- [Model2Vec Base Models](https://huggingface.co/collections/minishlab/model2vec-base-models-66fd9dd9b7c3b3c0f25ca90e)
- [Model2Vec Results](https://github.com/MinishLab/model2vec/tree/main/results)
- [Model2Vec Tutorials](https://github.com/MinishLab/model2vec/tree/main/tutorials)
- [Website](https://minishlab.github.io/)


## Library Authors

Model2Vec was developed by the [Minish Lab](https://github.com/MinishLab) team consisting of [Stephan Tulkens](https://github.com/stephantul) and [Thomas van Dongen](https://github.com/Pringled).

## Citation

Please cite the [Model2Vec repository](https://github.com/MinishLab/model2vec) if you use this model in your work.
```
@article{minishlab2024model2vec,
author = {Tulkens, Stephan and {van Dongen}, Thomas},
title = {Model2Vec: Fast State-of-the-Art Static Embeddings},
year = {2024},
url = {https://github.com/MinishLab/model2vec}
}
```
13 changes: 13 additions & 0 deletions tests/fixtures/test-model-vocab-quantized/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"model_type": "model2vec",
"architectures": [
"StaticModel"
],
"tokenizer_name": "BAAI/bge-base-en-v1.5",
"apply_pca": 64,
"apply_zipf": null,
"sif_coefficient": 0.0001,
"hidden_dim": 64,
"seq_length": 1000000,
"normalize": true
}
Binary file not shown.
14 changes: 14 additions & 0 deletions tests/fixtures/test-model-vocab-quantized/modules.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[
{
"idx": 0,
"name": "0",
"path": ".",
"type": "sentence_transformers.models.StaticEmbedding"
},
{
"idx": 1,
"name": "1",
"path": "1_Normalize",
"type": "sentence_transformers.models.Normalize"
}
]
1 change: 1 addition & 0 deletions tests/fixtures/test-model-vocab-quantized/tokenizer.json

Large diffs are not rendered by default.

45 changes: 0 additions & 45 deletions tests/test_model.rs
Original file line number Diff line number Diff line change
@@ -1,51 +1,6 @@
mod common;
use approx::assert_relative_eq;
use common::load_test_model;
use model2vec_rs::model::StaticModel;
use std::fs;

#[test]
fn test_encode_matches_python_model2vec() {
// Load the test model
let model = load_test_model();

// Define the short and long text inputs
let long_text = vec!["hello"; 1000].join(" ");
let short_text = "hello world".to_string();
let cases = vec![
("tests/fixtures/embeddings_short.json", vec![short_text]),
("tests/fixtures/embeddings_long.json", vec![long_text]),
];

for (fixture_path, inputs) in cases {
// Read and parse the Python‐generated embedding fixture
let fixture =
fs::read_to_string(fixture_path).unwrap_or_else(|_| panic!("Fixture not found: {}", fixture_path));
let expected: Vec<Vec<f32>> = serde_json::from_str(&fixture).expect("Failed to parse fixture");

// Encode with the Rust model
let output = model.encode(&inputs);

// Sanity checks
assert_eq!(
output.len(),
expected.len(),
"number of sentences mismatch for {}",
fixture_path
);
assert_eq!(
output[0].len(),
expected[0].len(),
"vector dimensionality mismatch for {}",
fixture_path
);

// Element‐wise comparison
for (o, e) in output[0].iter().zip(&expected[0]) {
assert_relative_eq!(o, e, max_relative = 1e-5);
}
}
}

/// Test that encoding an empty input slice yields an empty output
#[test]
Expand Down
13 changes: 2 additions & 11 deletions tests/test_load.rs → tests/test_quantization.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,6 @@
mod common;
use approx::assert_relative_eq;
use model2vec_rs::model::StaticModel;

fn encode_with_model(path: &str) -> Vec<f32> {
// Helper function to load the model and encode "hello world"
let model = StaticModel::from_pretrained(path, None, None, None)
.unwrap_or_else(|e| panic!("Failed to load model at {path}: {e}"));

let out = model.encode(&["hello world".to_string()]);
assert_eq!(out.len(), 1);
out.into_iter().next().unwrap()
}
use common::encode_with_model;

#[test]
fn quantized_models_match_float32() {
Expand Down
Loading