HuggingFace镜像/e5-large-en-ru
模型介绍文件和版本分析
下载使用量0

E5-large-en-ru

模型信息

仅使用俄语和英语标记。

规模

intfloat/multilingual-e5-larged0rj/e5-large-en-ru
模型大小 (MB)2135.821394.8
参数数量559,890,946365,638,14
词嵌入维度256,002,04861,749,248

性能

在SberQuAD开发集基准测试中性能相当。

SberQuAD指标(4122个问题)intfloat/multilingual-e5-larged0rj/e5-large-en-ru
recall@30.7872392042697720.7882096069868996
map@30.72307132459971010.723192624939351
mrr@30.72416302765647840.7243651948892132
recall@50.82775351770984960.8284813197476953
map@50.73016031861555870.7302573588872716
mrr@50.73346676370693850.7335718906679607
recall@100.87166424065987380.871421639980592
map@100.73147749177303160.7313000338687417
mrr@100.73922236855279110.7391814537556898

使用方法

  • 检索时使用点积距离。

  • 在非对称任务(如开放域问答中的段落检索、特定主题信息检索)中,分别使用“query: ”和“passage: ”前缀。

  • 在对称任务(如语义相似度、双语文本挖掘、复述检索)中,使用“query: ”前缀。

  • 如果希望将嵌入用作特征(如线性探针分类、聚类),使用“query: ”前缀。

transformers

直接使用

from openmind import AutoTokenizer, AutoModel, is_torch_npu_available
from transformers import XLMRobertaTokenizer, XLMRobertaModel
import torch.nn.functional as F
from torch import Tensor
import argparse

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--model_name_or_path",
        type=str,
        help="Path to model",
        default="ChongqingAscend/e5-large-en-ru",
    )
    args = parser.parse_args()
    return args

def average_pool(last_hidden_states: Tensor,
                 attention_mask: Tensor) -> Tensor:
    last_hidden = last_hidden_states.masked_fill(~attention_mask[..., None].bool(), 0.0)
    return last_hidden.sum(dim=1) / attention_mask.sum(dim=1)[..., None]

def main():
    args = parse_args()
    model_path = args.model_name_or_path

    if is_torch_npu_available():
        device = "npu:0"
    else:
        device = "cpu"
        
    # Each input text should start with "query: " or "passage: ".
    # For tasks other than retrieval, you can simply use the "query: " prefix.
    input_texts = [
	  'query: How does a corporate website differ from a business card website?',
	  'query: Где был создан первый троллейбус?',
	  'passage: The first trolleybus was created in Germany by engineer Werner von Siemens, probably influenced by the idea of his brother, Dr. Wilhelm Siemens, who lived in England, expressed on May 18, 1881 at the twenty-second meeting of the Royal Scientific Society. The electrical circuit was carried out by an eight-wheeled cart (Kontaktwagen) rolling along two parallel contact wires. The wires were located quite close to each other, and in strong winds they often overlapped, which led to short circuits. An experimental trolleybus line with a length of 540 m (591 yards), opened by Siemens & Halske in the Berlin suburb of Halensee, operated from April 29 to June 13, 1882.',
	  'passage: Корпоративный сайт — содержит полную информацию о компании-владельце, услугах/продукции, событиях в жизни компании. Отличается от сайта-визитки и представительского сайта полнотой представленной информации, зачастую содержит различные функциональные инструменты для работы с контентом (поиск и фильтры, календари событий, фотогалереи, корпоративные блоги, форумы). Может быть интегрирован с внутренними информационными системами компании-владельца (КИС, CRM, бухгалтерскими системами). Может содержать закрытые разделы для тех или иных групп пользователей — сотрудников, дилеров, контрагентов и пр.',
    ]


    tokenizer = AutoTokenizer.from_pretrained(model_path)
    model = AutoModel.from_pretrained(model_path).to(device)
    model = model.eval()

    batch_dict = tokenizer(input_texts, max_length=512, padding=True, truncation=True, return_tensors='pt').to(device)

    outputs = model(**batch_dict)
    embeddings = average_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())
    
if __name__ == "__main__":
    main()

流水线

from transformers import pipeline


pipe = pipeline('feature-extraction', model='d0rj/e5-large-en-ru')
embeddings = pipe(input_texts, return_tensors=True)
embeddings[0].size()
# torch.Size([1, 17, 1024])

句子转换器

from sentence_transformers import SentenceTransformer


sentences = [
    'query: Что такое круглые тензоры?',
    'passage: Abstract: we introduce a novel method for compressing round tensors based on their inherent radial symmetry. We start by generalising PCA and eigen decomposition on round tensors...',
]

model = SentenceTransformer('d0rj/e5-large-en-ru')
embeddings = model.encode(sentences, convert_to_tensor=True)
embeddings.size()
# torch.Size([2, 1024])