/ Модель

Характеристики

Лицензия
CC BY-NC 4.0
Опубликована
23 мая 2024

NV-Embed-v1

ЭмбеддингиТекст → embedding10 профессий

Англоязычная модель NVIDIA на базе Mistral-7B-v0.1, создающая 4096-мерные текстовые эмбеддинги для семантического поиска и сравнения текстов.

122скачиваний за 30 дней429лайковвеса обновлены30 ноя 2024

Бенчмарки

Как модель справилась с задачами пользователей ailist и что о ней публикуют открытые лидерборды

Публичные оценки29

Из открытых лидербордов. Сравнивайте результаты одного теста при одинаковых условиях — отсутствие оценки не значит, что модель хуже.

  • TweetTopicSingleClassification

    main_score

    Результат

    0,6297

    MTEB

    Публичная таблицадругая ревизия

  • MassiveScenarioClassification

    main_score

    Результат

    0,7166

    Общий результат 0,7198Общий результат 0,7077Общий результат 0,704
    MTEB

    Публичная таблицадругая ревизия

  • LEMBPasskeyRetrieval

    main_score

    Результат

    1

    MTEB

    Публичная таблицадругая ревизия

  • GeoreviewClusteringP2P

    main_score

    Результат

    0,6868

    MTEB

    Публичная таблицадругая ревизия

  • News21InstructionRetrieval

    main_score

    Результат

    0,0315

    MTEB

    Публичная таблицадругая ревизия

  • MassiveIntentClassification

    main_score

    Результат

    0,5595

    Общий результат 0,6803Общий результат 0,6774Общий результат 0,6
    MTEB

    Публичная таблицадругая ревизия

  • TempReasonL3Context

    main_score

    Результат

    0,1715

    MTEB

    Публичная таблицадругая ревизия

  • SIB200ClusteringS2S

    main_score

    Результат

    0,1888

    Общий результат 0,3194Общий результат 0,1862Общий результат 0,0165
    MTEB

    Публичная таблицадругая ревизия

  • GerDaLIRSmall

    main_score

    Результат

    0,0852

    MTEB

    Публичная таблицадругая ревизия

  • RiaNewsRetrieval

    main_score

    Результат

    0,697

    MTEB

    Публичная таблицадругая ревизия

  • CUREv1

    main_score

    Результат

    0,5842

    Общий результат 0,5933
    MTEB

    Публичная таблицадругая ревизия

  • NusaXBitextMining

    main_score

    Результат

    0,3828

    MTEB

    Публичная таблицадругая ревизия

  • IndicGenBenchFloresBitextMining

    main_score

    Результат

    0,7831

    Общий результат 0,516
    MTEB

    Публичная таблицадругая ревизия

  • MLQARetrieval

    main_score

    Результат

    0,686

    Общий результат 0,7336
    MTEB

    Публичная таблицадругая ревизия

  • TRECCOVID-PL

    main_score

    Результат

    0,7811

    MTEB

    Публичная таблицадругая ревизия

  • StatcanDialogueDatasetRetrieval

    main_score

    Результат

    0,1065

    Общий результат 0,2541
    MTEB

    Публичная таблицадругая ревизия

  • Tatoeba

    main_score

    Результат

    0,5111

    Общий результат 0,6578Общий результат 0,0375
    MTEB

    Публичная таблицадругая ревизия

  • STSBenchmarkMultilingualSTS

    main_score

    Результат

    0,7398

    MTEB

    Публичная таблицадругая ревизия

  • WikipediaRetrievalMultilingual

    main_score

    Результат

    0,8392

    Общий результат 0,9202
    MTEB

    Публичная таблицадругая ревизия

  • IndicCrosslingualSTS

    main_score

    Результат

    0,2886

    MTEB

    Публичная таблицадругая ревизия

  • NollySentiBitextMining

    main_score

    Результат

    0,1182

    MTEB

    Публичная таблицадругая ревизия

  • CBD

    main_score

    Результат

    0,6861

    MTEB

    Публичная таблицадругая ревизия

  • XNLI

    main_score

    Результат

    0,6039

    MTEB

    Публичная таблицадругая ревизия

  • AfriSentiClassification

    main_score

    Результат

    0,3996

    MTEB

    Публичная таблицадругая ревизия

  • DalajClassification

    main_score

    Результат

    0,5011

    MTEB

    Публичная таблицадругая ревизия

  • NusaTranslationBitextMining

    main_score

    Результат

    0,5439

    Общий результат 0,5675
    MTEB

    Публичная таблицадругая ревизия

  • MIRACLRetrievalHardNegatives

    main_score

    Результат

    0,5117

    MTEB

    Публичная таблицадругая ревизия

  • MTOPDomainClassification

    main_score

    Результат

    0,9348

    MTEB

    Публичная таблицадругая ревизия

  • EmotionClassification

    main_score

    Результат

    0,9171

    MTEB

    Публичная таблицаревизия не подтверждена

Что умеет модель

Описание составлено по карточке модели и метаданным Hugging Face

NV-Embed-v1 — англоязычная модель эмбеддингов от NVIDIA на базе decoder-only LLM Mistral-7B-v0.1. Она преобразует запросы и тексты в векторы размерностью 4096 для поиска и других задач сравнения и анализа текста.

Модель использует pooling с latent attention и двухэтапную настройку инструкциями. В README сообщается о результатах на бенчмарке MTEB по 56 задачам, включая поиск, ранжирование, классификацию, кластеризацию и семантическое сходство; также указаны результаты AIR-Bench QA для английского языка и Long-Doc. Для доступа к репозиторию требуется аутентификация Hugging Face.

Модель распространяется по лицензии CC BY-NC 4.0, которая ограничивает коммерческое использование. Она предназначена для получения эмбеддингов и поддерживает задачи извлечения признаков и сравнения предложений; в каталоге файлов указан формат safetensors.

Сценарии применения

  • семантический поиск по документам
  • поиск релевантных фрагментов для RAG
  • сравнение сходства запросов и документов
  • кластеризация текстов по смыслу
  • классификация текстов на основе эмбеддингов

Ограничения

Для доступа к модели на Hugging Face требуется аутентификация. Лицензия CC BY-NC 4.0 ограничивает коммерческое использование.

Для каких профессий подходит10

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Также подходит для

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

Introduction

We introduce NV-Embed, a generalist embedding model that ranks No. 1 on the Massive Text Embedding Benchmark (MTEB benchmark)(as of May 24, 2024), with 56 tasks, encompassing retrieval, reranking, classification, clustering, and semantic textual similarity tasks. Notably, our model also achieves the highest score of 59.36 on 15 retrieval tasks within this benchmark.

NV-Embed presents several new designs, including having the LLM attend to latent vectors for better pooled embedding output, and demonstrating a two-stage instruction tuning method to enhance the accuracy of both retrieval and non-retrieval tasks.

For more technical details, refer to our paper: NV-Embed: Improved Techniques for Training LLMs as Generalist Embedding Models.

For more benchmark results (other than MTEB), please find the AIR-Bench for QA (English only) and Long-Doc.

Model Details

  • Base Decoder-only LLM: Mistral-7B-v0.1
  • Pooling Type: Latent-Attention
  • Embedding Dimension: 4096

How to use

Here is an example of how to encode queries and passages using Huggingface-transformer and Sentence-transformer. Please find the required package version here.

Usage (HuggingFace Transformers)

import torch
import torch.nn.functional as F
from transformers import AutoTokenizer, AutoModel

# Each query needs to be accompanied by an corresponding instruction describing the task.
task_name_to_instruct = {"example": "Given a question, retrieve passages that answer the question",}

query_prefix = "Instruct: "+task_name_to_instruct["example"]+"\nQuery: "
queries = [
    'are judo throws allowed in wrestling?', 
    'how to become a radiology technician in michigan?'
    ]

# No instruction needed for retrieval passages
passage_prefix = ""
passages = [
    "Since you're reading this, you are probably someone from a judo background or someone who is just wondering how judo techniques can be applied under wrestling rules. So without further ado, let's get to the question. Are Judo throws allowed in wrestling? Yes, judo throws are allowed in freestyle and folkstyle wrestling. You only need to be careful to follow the slam rules when executing judo throws. In wrestling, a slam is lifting and returning an opponent to the mat with unnecessary force.",
    "Below are the basic steps to becoming a radiologic technologist in Michigan:Earn a high school diploma. As with most careers in health care, a high school education is the first step to finding entry-level employment. Taking classes in math and science, such as anatomy, biology, chemistry, physiology, and physics, can help prepare students for their college studies and future careers.Earn an associate degree. Entry-level radiologic positions typically require at least an Associate of Applied Science. Before enrolling in one of these degree programs, students should make sure it has been properly accredited by the Joint Review Committee on Education in Radiologic Technology (JRCERT).Get licensed or certified in the state of Michigan."
]

# load model with tokenizer
model = AutoModel.from_pretrained('nvidia/NV-Embed-v1', trust_remote_code=True)

# get the embeddings
max_length = 4096
query_embeddings = model.encode(queries, instruction=query_prefix, max_length=max_length)
passage_embeddings = model.encode(passages, instruction=passage_prefix, max_length=max_length)

# normalize embeddings
query_embeddings = F.normalize(query_embeddings, p=2, dim=1)
passage_embeddings = F.normalize(passage_embeddings, p=2, dim=1)

# get the embeddings with DataLoader (spliting the datasets into multiple mini-batches)
# batch_size=2
# query_embeddings = model._do_encode(queries, batch_size=batch_size, instruction=query_prefix, max_length=max_length, num_workers=32, return_numpy=True)
# passage_embeddings = model._do_encode(passages, batch_size=batch_size, instruction=passage_prefix, max_length=max_length, num_workers=32, return_numpy=True)

scores = (query_embeddings @ passage_embeddings.T) * 100
print(scores.tolist())
#[[77.9402084350586, 0.4248958230018616], [3.757718086242676, 79.60113525390625]]

Usage (Sentence-Transformers)

import torch
from sentence_transformers import SentenceTransformer

# Each query needs to be accompanied by an corresponding instruction describing the task.
task_name_to_instruct = {"example": "Given a question, retrieve passages that answer the question",}

query_prefix = "Instruct: "+task_name_to_instruct["example"]+"\nQuery: "
queries = [
    'are judo throws allowed in wrestling?', 
    'how to become a radiology technician in michigan?'
    ]

# No instruction needed for retrieval passages
passages = [
    "Since you're reading this, you are probably someone from a judo background or someone who is just wondering how judo techniques can be applied under wrestling rules. So without further ado, let's get to the question. Are Judo throws allowed in wrestling? Yes, judo throws are allowed in freestyle and folkstyle wrestling. You only need to be careful to follow the slam rules when executing judo throws. In wrestling, a slam is lifting and returning an opponent to the mat with unnecessary force.",
    "Below are the basic steps to becoming a radiologic technologist in Michigan:Earn a high school diploma. As with most careers in health care, a high school education is the first step to finding entry-level employment. Taking classes in math and science, such as anatomy, biology, chemistry, physiology, and physics, can help prepare students for their college studies and future careers.Earn an associate degree. Entry-level radiologic positions typically require at least an Associate of Applied Science. Before enrolling in one of these degree programs, students should make sure it has been properly accredited by the Joint Review Committee on Education in Radiologic Technology (JRCERT).Get licensed or certified in the state of Michigan."
]

# load model with tokenizer
model = SentenceTransformer('nvidia/NV-Embed-v1', trust_remote_code=True)
model.max_seq_length = 4096
model.tokenizer.padding_side="right"

def add_eos(input_examples):
  input_examples = [input_example + model.tokenizer.eos_token for input_example in input_examples]
  return input_examples

# get the embeddings
batch_size = 2
query_embeddings = model.encode(add_eos(queries), batch_size=batch_size, prompt=query_prefix, normalize_embeddings=True)
passage_embeddings = model.encode(add_eos(passages), batch_size=batch_size, normalize_embeddings=True)

scores = (query_embeddings @ passage_embeddings.T) * 100
print(scores.tolist())

Correspondence to

Chankyu Lee (chankyul@nvidia.com), Rajarshi Roy (rajarshir@nvidia.com), Wei Ping (wping@nvidia.com)

Citation

If you find this code useful in your research, please consider citing:

@misc{lee2024nvembed,
      title={NV-Embed: Improved Techniques for Training LLMs as Generalist Embedding Models}, 
      author={Chankyu Lee and Rajarshi Roy and Mengyao Xu and Jonathan Raiman and Mohammad Shoeybi and Bryan Catanzaro and Wei Ping},
      year={2024},
      eprint={2405.17428},
      archivePrefix={arXiv},
      primaryClass={cs.CL}
}

License

This model should not be used for any commercial purpose. Refer the license for the detailed terms.

For commercial purpose, we recommend you to use the models of NeMo Retriever Microservices (NIMs).

Troubleshooting

1. How to enable Multi-GPU (Note, this is the case for HuggingFace Transformers)

from transformers import AutoModel
from torch.nn import DataParallel

embedding_model = AutoModel.from_pretrained("nvidia/NV-Embed-v1")
for module_key, module in embedding_model._modules.items():
    embedding_model._modules[module_key] = DataParallel(module)

2. Required Packages

If you have trouble, try installing the python packages as below

pip uninstall -y transformer-engine
pip install torch==2.2.0
pip install transformers==4.42.4
pip install flash-attn==2.2.0
pip install sentence-transformers==2.7.0

3. Fixing "nvidia/NV-Embed-v1 is not the path to a directory containing a file named config.json"

Switch to your local model path,and open config.json and change the value of "_name_or_path" and replace it with your local model path.

4. Access to model nvidia/NV-Embed-v1 is restricted. You must be authenticated to access it

Use your huggingface access token to execute "huggingface-cli login".

5. How to resolve slight mismatch in Sentence transformer results.

A slight mismatch in the Sentence Transformer implementation is caused by a discrepancy in the calculation of the instruction prefix length within the Sentence Transformer package.

To fix this issue, you need to build the Sentence Transformer package from source, making the necessary modification in this line as below.

git clone https://github.com/UKPLab/sentence-transformers.git
cd sentence-transformers
git checkout v2.7-release
# Modify L353 in SentenceTransformer.py to **'extra_features["prompt_length"] = tokenized_prompt["input_ids"].shape[-1]'**.
pip install -e .

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм

Нельзя запустить

Доступ к модели ограничен автором; у платформы нет доступа к весам.

Ревизия весов
2e8b322

0 моделей