microsoft-harrier-oss-v1-0.6b
harrier-oss-v1
harrier-oss-v1 is a family of multilingual text embedding models developed by Microsoft.The models use decoder-only architectures with last-token pooling and L2 normalization to produce dense text embeddings.
They can be applied to a wide range of tasks, including but not limited to retrieval, clustering, semantic similarity, classification, bitext mining, and reranking.
The models achieve state-of-the-art results on the Multilingual MTEB v2 benchmark as of the release date.
| Model | Parameters | Embedding Dimension | Max Tokens | MTEB v2 Score |
|---|---|---|---|---|
| harrier-oss-v1-270m | 270M | 640 | 32,768 | 66.5 |
| harrier-oss-v1-0.6b | 0.6B | 1,024 | 32,768 | 69.0 |
| harrier-oss-v1-27b | 27B | 5,376 | 32,768 | 74.3 |
Training
All models are trained with contrastive learning objectives on a large-scale mixture of multilingual datasets covering diverse tasks.The 270m and 0.6b variants are additionally trained with knowledge distillation from larger embedding models.
Usage
Below is an example to encode queries and passages from the MS-MARCO passage ranking dataset.Sentence Transformers
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("microsoft/harrier-oss-v1-0.6b", model_kwargs={"dtype": "auto"})
queries = [
"how much protein should a female eat",
"summit define",
]
documents = [
"As a general guideline, the CDC's average requirement of protein for women ages 19 to 70 is 46 grams per day. But, as you can see from this chart, you'll need to increase that if you're expecting or training for a marathon. Check out the chart below to see how much protein you should be eating each day.",
"Definition of summit for English Language Learners. : 1 the highest point of a mountain : the top of a mountain. : 2 the highest level. : 3 a meeting or series of meetings between the leaders of two or more governments."
]
query_embeddings = model.encode(queries, prompt_name="web_search_query")
document_embeddings = model.encode(documents)
scores = (query_embeddings @ document_embeddings.T) * 100
print(scores.tolist())
web_search_query, sts_query, and bitext_query. You can also use a custom instruction directly via e.g. model.encode(queries, prompt="Instruct: Retrieve semantically similar text\nQuery: ").
Transformers
import torch
import torch.nn.functional as F
from torch import Tensor
from transformers import AutoTokenizer, AutoModel
def last_token_pool(last_hidden_states: Tensor, attention_mask: Tensor) -> Tensor:
left_padding = (attention_mask[:, -1].sum() == attention_mask.shape[0])
if left_padding:
return last_hidden_states[:, -1]
else:
sequence_lengths = attention_mask.sum(dim=1) - 1
batch_size = last_hidden_states.shape[0]
return last_hidden_states[torch.arange(batch_size, device=last_hidden_states.device), sequence_lengths]
def get_detailed_instruct(task_description: str, query: str) -> str:
return f'Instruct: {task_description}\nQuery: {query}'
# Each query must come with a one-sentence instruction that describes the task
task = 'Given a web search query, retrieve relevant passages that answer the query'
queries = [
get_detailed_instruct(task, 'how much protein should a female eat'),
get_detailed_instruct(task, 'summit define')
]
# No need to add instruction for retrieval documents
documents = [
"As a general guideline, the CDC's average requirement of protein for women ages 19 to 70 is 46 grams per day. But, as you can see from this chart, you'll need to increase that if you're expecting or training for a marathon. Check out the chart below to see how much protein you should be eating each day.",
"Definition of summit for English Language Learners. : 1 the highest point of a mountain : the top of a mountain. : 2 the highest level. : 3 a meeting or series of meetings between the leaders of two or more governments."
]
input_texts = queries + documents
tokenizer = AutoTokenizer.from_pretrained('microsoft/harrier-oss-v1-0.6b')
model = AutoModel.from_pretrained('microsoft/harrier-oss-v1-0.6b', dtype='auto')
model.eval()
model.cuda()
max_length = 32768
# Tokenize the input texts
batch_dict = tokenizer(input_texts, max_length=max_length, padding=True, truncation=True, return_tensors='pt')
batch_dict = {k: v.cuda() for k, v in batch_dict.items()}
outputs = model(**batch_dict)
embeddings = last_token_pool(outputs.last_hidden_state, batch_dict['attention_mask'])
# normalize embeddings
embeddings = F.normalize(embeddings, p=2, dim=1)
scores = (embeddings[:2] @ embeddings[2:].T) * 100
print(scores.tolist())
Supported Languages
The models are trained on multilingual data and support a wide range of languages,including but not limited to: Arabic, Bulgarian, Catalan, Czech, Danish, German, Greek, English, Spanish,
Estonian, Persian, Finnish, French, Hebrew, Hindi, Croatian, Hungarian, Indonesian, Italian, Japanese,
Korean, Lithuanian, Latvian, Macedonian, Malay, Dutch, Norwegian, Polish, Portuguese, Romanian, Russian,
Slovak, Slovenian, Albanian, Serbian, Swedish, Thai, Turkish, Ukrainian, Urdu, Vietnamese, and Chinese.
Evaluation
Please follow the mteb repository on how to reproduce our scores.The evaluation prompts used for each task are also available at mteb_v2_eval_prompts.json .
FAQ
1. Do I need to add instructions to the query? Yes, this is how the model is trained, otherwise you will see a performance degradation.The task definition should be a one-sentence instruction that describes the task.
This is a way to customize text embeddings for different scenarios through natural language instructions. On the other hand, there is no need to add instructions to the document side. 2. Why are my reproduced results slightly different from reported in the model card? Different versions of
transformers and pytorch could cause negligible but non-zero performance differences.
3. What pooling strategy does this model use?
The model uses last-token pooling — the embedding of the last non-padding token is used as the sentence representation.The embedding is then L2-normalized. This is handled automatically when using Sentence Transformers.
microsoft/harrier-oss-v1-0.6b powered by Text Embeddings Inference
- Original Model Card
- Text Embeddings Inference Documentation
feature-extractionTask on Hugging Facesentence-similarityTask on Hugging Face
OpenAI Embeddings API
Send Request
You can use cURL or any REST Client to send a request to the Azure ML endpoint with your Azure ML token.curl <AZUREML_ENDPOINT_URL> \
-X POST \
-H "Authorization: Bearer <AZUREML_TOKEN>" \
-H "Content-Type: application/json" \
-d '{"model":"microsoft/harrier-oss-v1-0.6b","input":"The food was delicious and the waiter..."}'
Supported Parameters
- input (string): Text to create the embeddings for.
- model (string): ID of the model to use.
- dimensions (string, optional): The number of dimensions the resulting output embeddings should have.
- encoding_format (string, optional): The format to return the embeddings in. Can be either float or base64.
Text Embeddings Inference API
Generate Embeddings
Additionally, Text Embeddings Inference (TEI) provides an endpoint to generate embeddings but using its own API Specification under the endpoint/embed.
Send Request
curl <AZUREML_ENDPOINT_URL>/embed \
-X POST \
-H "Authorization: Bearer <AZUREML_TOKEN>" \
-H "Content-Type: application/json" \
-d '{"inputs":"What is Deep Learning?}'
Supported Parameters
- inputs (string): The input sentence to create the embeddings for.
- dimensions (int, optional): Number of dimensions that the output embeddings should have. If not set, the original shape of the representation will be returned instead. Defaults to null.
- normalize (bool, optional): Wether to normalize returned vectors to be between -1 and 1. Defaults to true.
- prompt_name (string, optional): The name of the prompt that should be used by for encoding. If not set, no prompt will be applied. Must be a key in the
sentence-transformersconfigurationpromptsdictionary, which is either set in the constructor or loaded from the model configuration. For example if prompt_name is "query" and the prompts is {"query": "query: ", ...}, then the sentence "What is the capital of France?" will be encoded as "query: What is the capital of France?" because the sentence is appended to the prompt. Defaults to null. - truncate (bool, optional): Whether to truncate the inputs that are longer than the maximum sequence length supported by the model or not. Defaults to False.
- truncation_direction ('Left' or 'Right', optional): Can either be "Left" or "Right". Truncating to the "Right" means that tokens are removed from the end of the sequence until the maximum supported size is matched, whilst truncating to the "Left" means from the beginning of the sequence. Defaults to "Right".
/embed endpoint .
Sentence Similarity
Additionally, Text Embeddings Inference (TEI) provides an endpoint to compute the embeddings and their similarities under the endpoint/embed.
Send Request
curl <AZUREML_ENDPOINT_URL>/similarity \
-X POST \
-H "Authorization: Bearer <AZUREML_TOKEN>" \
-H "Content-Type: application/json" \
-d '{"inputs":{"sentences":["What is deep learning?","How many cats do you have?"],"source_sentence":"Do you like Deep Learning?"]}}'
Supported Parameters
- inputs (obejct):
- sentences (array): List of strings which will be compared against the source_sentence.
- source_sentence (string): String to compare sentences with. It can be a phrase, sentence, or longer passage, depending on the model being used.
- parameters (object):
- truncate (bool, optional): Wether to truncate the inputs that are longer than the maximum sequence length supported by the model or not. Defaults to False.
- truncation_direction ('Left' or 'Right', optional): Can either be "Left" or "Right". Truncating to the "Right" means that tokens are removed from the end of the sequence until the maximum supported size is matched, whilst truncating to the "Left" means from the beginning of the sequence. Defaults to "Right".
- prompt_name (string, optional): The name of the prompt that should be used by for encoding. If not set, no prompt will be applied. Must be a key in the
sentence-transformersconfigurationpromptsdictionary, which is either set in the constructor or loaded from the model configuration. For example if prompt_name is "query" and the prompts is {"query": "query: ", ...}, then the sentence "What is the capital of France?" will be encoded as "query: What is the capital of France?" because the sentence is appended to the prompt. Defaults to null.
/similarity endpoint .