pipeline_tag: 句子相似度
language:
- 西班牙语
tags:
- 句子转换器
- 特征提取
- 句子相似度
- 变换器
- LSG
- STS
- 长文本处理
license: apache-2.0
hiiamsid/sentence_similarity_spanish_es的LSG变体
概述
此模型是hiiamsid/sentence_similarity_spanish_es的增强版本,现采用局部稀疏全局(LSG)注意力机制进行改造。LSG的适配使模型能高效处理更长的序列,从而在更广泛的自然语言处理任务中展现出更强的通用性和鲁棒性。
该LSG适配使模型能够高效处理长达4096个标记的序列。
关于LSG架构
LSG(局部稀疏全局)注意力是一种前沿方法,旨在克服传统Transformer模型中自注意力机制在处理长序列时的局限性。通过结合局部、稀疏和全局注意力,LSG注意力在显著降低计算复杂度的同时,保持甚至提升了模型性能。
模型适配
此LSG变体从原始模型适配而来,主要目标是扩展其能力,使其能高效处理更长的文本输入。这一增强使模型即使在处理基础模型先前难以应对的较长序列时,也能保持高准确性和效率。
应用场景
LSG增强模型特别擅长处理涉及较长文档嵌入的任务。
import torch.nn.functional as F
from transformers import AutoTokenizer, AutoModel
import torch
tokenizer = AutoTokenizer.from_pretrained('prudant/lsg_4096_sentence_similarity_spanish')
model = AutoModel.from_pretrained('prudant/lsg_4096_sentence_similarity_spanish', trust_remote_code=True)
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 = [
'这是一个快乐的人',
"这是一只快乐的狗",
"这是一个非常快乐的人",
"今天是个晴天",
"这是一个高兴的人",
]
encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
with torch.no_grad():
model_output = model(**encoded_input)
sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
print("句子嵌入:")
print(sentence_embeddings)
normalized_embeddings = F.normalize(sentence_embeddings, p=2, dim=1)
cosine_similarities = F.cosine_similarity(normalized_embeddings[0].unsqueeze(0), normalized_embeddings[1:], dim=1)
print(cosine_similarities)
句子嵌入:
tensor([[-0.1691, -0.2517, -1.3000, ..., 0.1557, 0.3824, 0.2048],
[ 0.1872, -0.7604, -0.4863, ..., -0.4922, -0.1511, -0.8539],
[-0.2467, -0.2373, -1.1708, ..., 0.4637, 0.0616, 0.2841],
[-0.2384, 0.1681, -0.3498, ..., -0.2744, -0.1722, -1.2513],
[ 0.2273, -0.2393, -1.6124, ..., 0.6065, 0.2784, -0.3354]])
tensor([0.5132, 0.9346, 0.3471, 0.8543])
致谢
此模型由Darío Muñoz Prudant适配,感谢Hugging Face社区及LSG注意力机制的贡献者提供的资源和支持。