Views
No views yet

jina-embeddings-v3 is a multilingual multi-task text embedding model designed for a variety of NLP applications.
Based on the Jina-XLM-RoBERTa architecture,
this model supports Rotary Position Embeddings to handle long input sequences up to 8192 tokens.
Additionally, it features 5 LoRA adapters to generate task-specific embeddings efficiently.task argument with the following options:
retrieval.query: Used for query embeddings in asymmetric retrieval tasksretrieval.passage: Used for passage embeddings in asymmetric retrieval tasksseparation: Used for embeddings in clustering and re-ranking applicationsclassification: Used for embeddings in classification taskstext-matching: Used for embeddings in tasks that quantify similarity between two texts, such as STS or symmetric retrieval tasks32, 64, 128, 256, 512, 768, 1024), allowing for truncating embeddings to fit your application.⚠️ Important Notice:
We fixed a bug in theencodefunction #60 where Matryoshka embedding truncation occurred after normalization, leading to non-normalized truncated embeddings. This issue has been resolved in the latest code revision.If you have encoded data using the previous version and wish to maintain consistency, please use the specific code revision when loading the model:AutoModel.from_pretrained('jinaai/jina-embeddings-v3', code_revision='da863dd04a4e5dce6814c6625adfba87b83838aa', ...)
encode function that handles this for you automatically.encode function,
you'll need to apply mean pooling manually. Here's how you can do it:1import torch
2import torch.nn.functional as F
3from transformers import AutoTokenizer, AutoModel
4
5
6def mean_pooling(model_output, attention_mask):
7 token_embeddings = model_output[0]
8 input_mask_expanded = (
9 attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
10 )
11 return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(
12 input_mask_expanded.sum(1), min=1e-9
13 )
14
15
16sentences = ["How is the weather today?", "What is the current weather like today?"]
17
18tokenizer = AutoTokenizer.from_pretrained("jinaai/jina-embeddings-v3")
19model = AutoModel.from_pretrained("jinaai/jina-embeddings-v3", trust_remote_code=True)
20
21encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors="pt")
22task = 'retrieval.query'
23task_id = model._adaptation_map[task]
24adapter_mask = torch.full((len(sentences),), task_id, dtype=torch.int32)
25with torch.no_grad():
26 model_output = model(**encoded_input, adapter_mask=adapter_mask)
27
28embeddings = mean_pooling(model_output, encoded_input["attention_mask"])
29embeddings = F.normalize(embeddings, p=2, dim=1)
30jina-embeddings-v3 is with the Jina Embedding API.jina-embeddings-v3 directly via Transformers package:1!pip install transformers torch einops
2!pip install 'numpy<2'!pip install flash-attn --no-build-isolation1from transformers import AutoModel
2
3# Initialize the model
4model = AutoModel.from_pretrained("jinaai/jina-embeddings-v3", trust_remote_code=True)
5
6texts = [
7 "Follow the white rabbit.", # English
8 "Sigue al conejo blanco.", # Spanish
9 "Suis le lapin blanc.", # French
10 "跟着白兔走。", # Chinese
11 "اتبع الأرنب الأبيض.", # Arabic
12 "Folge dem weißen Kaninchen.", # German
13]
14
15# When calling the `encode` function, you can choose a `task` based on the use case:
16# 'retrieval.query', 'retrieval.passage', 'separation', 'classification', 'text-matching'
17# Alternatively, you can choose not to pass a `task`, and no specific LoRA adapter will be used.
18embeddings = model.encode(texts, task="text-matching")
19
20# Compute similarities
21print(embeddings[0] @ embeddings[1].T)max_length parameter to the encode function:1embeddings = model.encode(["Very long ... document"], max_length=2048)
2truncate_dim parameter to the encode function:embeddings = model.encode(['Sample text'], truncate_dim=256)jina-embeddings-v3:!pip install -U sentence-transformers1from sentence_transformers import SentenceTransformer
2
3model = SentenceTransformer("jinaai/jina-embeddings-v3", trust_remote_code=True)
4
5task = "retrieval.query"
6embeddings = model.encode(
7 ["What is the weather like in Berlin today?"],
8 task=task,
9 prompt_name=task,
10)jina-embeddings-v3 using SentenceTransformerTrainer.
To fine-tune for a specific task, you should set the task before passing the model to the ST Trainer, either during initialization:model = SentenceTransformer("jinaai/jina-embeddings-v3", trust_remote_code=True, model_kwargs={'default_task': 'classification'})1model = SentenceTransformer("jinaai/jina-embeddings-v3", trust_remote_code=True)
2model[0].default_task = 'classification'model = SentenceTransformer("jinaai/jina-embeddings-v3", trust_remote_code=True, model_kwargs={'lora_main_params_trainable': True})jina-embeddings-v3:1import onnxruntime
2import numpy as np
3from transformers import AutoTokenizer, PretrainedConfig
4
5# Mean pool function
6def mean_pooling(model_output: np.ndarray, attention_mask: np.ndarray):
7 token_embeddings = model_output
8 input_mask_expanded = np.expand_dims(attention_mask, axis=-1)
9 input_mask_expanded = np.broadcast_to(input_mask_expanded, token_embeddings.shape)
10 sum_embeddings = np.sum(token_embeddings * input_mask_expanded, axis=1)
11 sum_mask = np.clip(np.sum(input_mask_expanded, axis=1), a_min=1e-9, a_max=None)
12 return sum_embeddings / sum_mask
13
14# Load tokenizer and model config
15tokenizer = AutoTokenizer.from_pretrained('jinaai/jina-embeddings-v3')
16config = PretrainedConfig.from_pretrained('jinaai/jina-embeddings-v3')
17
18# Tokenize input
19input_text = tokenizer('sample text', return_tensors='np')
20
21# ONNX session
22model_path = 'jina-embeddings-v3/onnx/model.onnx'
23session = onnxruntime.InferenceSession(model_path)
24
25# Prepare inputs for ONNX model
26task_type = 'text-matching'
27task_id = np.array(config.lora_adaptations.index(task_type), dtype=np.int64)
28inputs = {
29 'input_ids': input_text['input_ids'],
30 'attention_mask': input_text['attention_mask'],
31 'task_id': task_id
32}
33
34# Run model
35outputs = session.run(None, inputs)[0]
36
37# Apply mean pooling and normalization to the model outputs
38embeddings = mean_pooling(outputs, input_text["attention_mask"])
39embeddings = embeddings / np.linalg.norm(embeddings, ord=2, axis=1, keepdims=True)jina-embeddings-v3 is listed on AWS & Azure. If you need to use it beyond those platforms or on-premises within your company, note that the models is licensed under CC BY-NC 4.0. For commercial usage inquiries, feel free to contact us.jina-embeddings-v3 useful in your research, please cite the following paper:1@misc{sturua2024jinaembeddingsv3multilingualembeddingstask,
2 title={jina-embeddings-v3: Multilingual Embeddings With Task LoRA},
3 author={Saba Sturua and Isabelle Mohr and Mohammad Kalim Akram and Michael Günther and Bo Wang and Markus Krimmel and Feng Wang and Georgios Mastrapas and Andreas Koukounas and Andreas Koukounas and Nan Wang and Han Xiao},
4 year={2024},
5 eprint={2409.10173},
6 archivePrefix={arXiv},
7 primaryClass={cs.CL},
8 url={https://arxiv.org/abs/2409.10173},
9}
10