由 Jina AI 训练的文本嵌入模型。
开始使用 jina-embeddings-v2-base-code 最简单的方法是使用 Jina AI 的 Embedding API。
jina-embeddings-v2-base-code 是一款多语言嵌入模型,支持英语及 30 种广泛使用的编程语言。
与其他 jina-embeddings-v2 系列模型一样,它支持8192的序列长度。
jina-embeddings-v2-base-code 基于 Bert 架构(JinaBert)构建,该架构支持 ALiBi 的对称双向变体,以实现更长的序列长度。
该模型在 Jina AI 收集的超过 1.5 亿个代码问答及文档字符串源代码对上进行了进一步训练。
这些数据对来源于多个领域,并经过严格的清洗流程精心筛选。
嵌入模型的训练采用 512 序列长度,但借助 ALiBi 技术可外推至 8k 序列长度(甚至更长)。 这使得我们的模型适用于多种使用场景,尤其在需要处理长文档时,包括技术问答和代码搜索。
该模型拥有 1.61 亿参数,可实现快速且内存高效的推理,同时提供出色的性能。 此外,我们还提供以下嵌入模型:
Jina Embeddings V2 技术报告
mean pooling 会获取模型输出的所有 token 嵌入,并在句子/段落层面取其平均值。
事实证明,这是生成高质量句子嵌入最有效的方法。
我们提供了一个 encode 函数来处理此过程。
不过,若您希望不使用默认的 encode 函数来实现:
import torch
import torch.nn.functional as F
from transformers import AutoTokenizer, AutoModel
def mean_pooling(model_output, attention_mask):
token_embeddings = model_output[0]
input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
sentences = [
'How do I access the index while iterating over a sequence with a for loop?',
'# Use the built-in enumerator\nfor idx, x in enumerate(xs):\n print(idx, x)',
]
tokenizer = AutoTokenizer.from_pretrained('jinaai/jina-embeddings-v2-base-code')
model = AutoModel.from_pretrained('jinaai/jina-embeddings-v2-base-code', trust_remote_code=True)
encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
with torch.no_grad():
model_output = model(**encoded_input)
embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
embeddings = F.normalize(embeddings, p=2, dim=1)您可以直接通过 transformers 包使用 Jina Embedding 模型:
!pip install -U sentence-transformers
# coding = utf-8
import os
import torch
import torch_npu
from sentence_transformers import SentenceTransformer
from sentence_transformers.util import cos_sim
import argparse
from openmind import pipeline, is_torch_npu_available
parser = argparse.ArgumentParser(description='manual to this script')
parser.add_argument("--model_name_or_path", type=str, default="./")
args = parser.parse_args()
model_path = args.model_name_or_path
device= None
if is_torch_npu_available():
device = "npu:0"
else:
device = "cpu"
model = SentenceTransformer(model_path)
model = model.to(device)
embeddings = model.encode(['How do I access the index while iterating over a sequence with a for loop?',
'# Use the built-in enumerator\nfor idx, x in enumerate(xs):\n print(idx, x)'])
cosine_scores = cos_sim(embeddings[0], embeddings[1])
print(f"cosine_scores: {cosine_scores}")加入我们的Discord社区,与其他社区成员交流想法。