Edit model card

jester6136/multilingual-e5-large-m2v Model Card

This Model2Vec model is a distilled version of the intfloat/multilingual-e5-large 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.

Installation

Install using pip:

pip install model2vec reach tqdm numpy

Usage

import numpy as np
from model2vec import StaticModel
from reach import Reach
from tqdm import tqdm
import time

class TextDeduplicator:
    def __init__(self, model_path: str):
        # Load the pre-trained model
        self.model = StaticModel.from_pretrained(model_path)

    def encode_texts(self, texts: list[str]) -> np.ndarray:
        # Prepare the texts and encode them into embeddings
        texts = [f"query: {text}" for text in texts]
        embedding_matrix = self.model.encode(texts, show_progressbar=True)
        return embedding_matrix

    def deduplicate(self, embedding_matrix: np.ndarray, threshold: float, batch_size: int = 1024
    ) -> tuple[np.ndarray, dict[int, list[int]]]:
        # Deduplicate the texts based on their embeddings
        reach = Reach(vectors=embedding_matrix, items=[str(i) for i in range(len(embedding_matrix))])
        results = reach.nearest_neighbor_threshold(
            embedding_matrix, threshold=threshold, batch_size=batch_size, show_progressbar=True
        )

        deduplicated_indices = set(range(len(embedding_matrix)))
        duplicate_groups = {}

        for i, similar_items in enumerate(tqdm(results)):
            if i not in deduplicated_indices:
                continue

            similar_indices = [int(item[0]) for item in similar_items if int(item[0]) != i]
            for sim_idx in similar_indices:
                if sim_idx in deduplicated_indices:
                    deduplicated_indices.remove(sim_idx)
                    if i not in duplicate_groups:
                        duplicate_groups[i] = []
                    duplicate_groups[i].append(sim_idx)

        return np.array(list(deduplicated_indices)), duplicate_groups

    def deduplicate_texts(self, texts: list[str], threshold: float) -> tuple[np.ndarray, dict[int, list[int]]]:
        # End-to-end deduplication process
        embedding_matrix = self.encode_texts(texts)
        return self.deduplicate(embedding_matrix, threshold)


if __name__ == "__main__":
    # Example usage
    texts = [
        "Anh yêu em.",
        "Mọi thứ ở công ty mới đều lạ lẫm, nhưng tôi cảm thấy rất sẵn sàng để bắt đầu hành trình mới.",
        "Trận đấu bóng đá tối qua rất căng thẳng, hai đội liên tục tấn công và phòng thủ.",
        "Một quan chức Fed muốn giảm bớt tốc độ hạ lãi suất",
        "Ngày đầu tiên tại công ty mới đầy ấn tượng, tôi hy vọng sẽ nhanh chóng hòa nhập với môi trường làm việc.",
        "Mùa hè này, cả gia đình sẽ có một chuyến đi đến Đà Nẵng, nơi mà chúng tôi đã mong chờ từ rất lâu.",
        "Gia đình tôi đã lên kế hoạch cho kỳ nghỉ tại Đà Nẵng vào mùa hè này, một chuyến đi mà mọi người đều háo hức.",
        "Fed có bước tiến mới để hạ lãi suất",
        "Chúng tôi đã dự định từ lâu sẽ đi Đà Nẵng vào mùa hè này, và cả nhà đều rất trông đợi chuyến du lịch.",
        "Ngày đầu đi làm thật là thú vị, tuy có chút hồi hộp nhưng tôi mong chờ những điều mới mẻ.",
        "Mùa hè năm nay, gia đình tôi sẽ du lịch Đà Nẵng, chuyến đi mà ai cũng mong đợi từ trước."
    ]

    deduplicator = TextDeduplicator("jester6136/multilingual-e5-large-m2v")

    start_time = time.time()
    deduplicated_indices, duplicate_groups = deduplicator.deduplicate_texts(texts, threshold=0.85)
    end_time = time.time()

    print(f"Deduplication completed in {end_time - start_time:.2f} seconds")
    print(f"Deduped output: {deduplicated_indices}")
    print(f"Group dup: {duplicate_groups}")

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 zipf weighting. During inference, we simply take the mean of all token embeddings occurring in a sentence.

Additional Resources

Library Authors

Model2Vec was developed by the Minish Lab team consisting of Stephan Tulkens and Thomas van Dongen.

Citation

Please cite the Model2Vec repository if you use this model in your work.

@software{minishlab2024model2vec,
  authors = {Stephan Tulkens, Thomas van Dongen},
  title = {Model2Vec: Turn any Sentence Transformer into a Small Fast Model},
  year = {2024},
  url = {https://github.com/MinishLab/model2vec},
}
Downloads last month
2
Safetensors
Model size
64M params
Tensor type
F32
·
Inference API
Unable to determine this model’s pipeline type. Check the docs .

Model tree for jester6136/multilingual-e5-large-m2v

Finetuned
(47)
this model