库名称: transformers
语言:
- 俄语
任务标签: 特征提取
数据集:
- uonlp/CulturaX
俄语ruRoPEBert句子模型
这是由Tochka AI基于RoPEBert架构开发的编码器模型,采用了我们在Habr上的文章中描述的克隆方法。
模型训练使用了CulturaX数据集。原始模型为hivaze/ru-e5-base(仅使用intfloat/multilingual-e5-base的英语和俄语嵌入);根据encodechka基准的S+W
评分,本模型在质量上(截至创建时)超越了该模型及所有其他模型。
模型源代码见文件modeling_rope_bert.py
模型训练支持最长2048个标记的上下文,但也可用于更长的上下文。
使用方法
重要提示:推荐使用transformers
的4.37.2或更高版本。为确保正确加载模型,需启用从模型仓库下载代码的功能:trust_remote_code=True
,这将下载modeling_rope_bert.py脚本并将权重加载到正确的架构中。
也可手动下载该脚本,并直接使用其中的类来加载模型。
基础用法(不使用高效注意力)
model_name = 'Tochka-AI/ruRoPEBert-e5-base-2k'
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModel.from_pretrained(model_name, trust_remote_code=True, attn_implementation='eager')
使用SDPA(高效注意力)
model = AutoModel.from_pretrained(model_name, trust_remote_code=True, attn_implementation='sdpa')
获取嵌入向量
模型架构已内置正确的池化器(mean
),可根据注意力掩码对嵌入向量进行平均。也可选择池化器类型(first_token_transform
),对第一个标记进行可学习的线性变换。
要更改内置池化器实现,可在AutoModel.from_pretrained
函数中使用pooler_type
参数。
test_batch = tokenizer.batch_encode_plus(["Привет, чем занят?", "Здравствуйте, чем вы занимаетесь?"], return_tensors='pt', padding=True)
with torch.inference_mode():
pooled_output = model(**test_batch).pooler_output
此外,可通过归一化和矩阵乘法计算批次中文本间的余弦相似度:
import torch.nn.functional as F
F.normalize(pooled_output, dim=1) @ F.normalize(pooled_output, dim=1).T
用作分类器
加载带有可训练分类头的模型(需修改num_labels
参数):
model = AutoModelForSequenceClassification.from_pretrained(model_name, trust_remote_code=True, attn_implementation='sdpa', num_labels=4)
使用RoPE缩放
RoPE缩放允许的类型包括:linear
和dynamic
。要扩展模型的上下文窗口,需更改分词器的最大长度并添加rope_scaling
参数。
如需将模型上下文扩展2倍:
tokenizer.model_max_length = 4096
model = AutoModel.from_pretrained(model_name,
trust_remote_code=True,
attn_implementation='sdpa',
rope_scaling={'type': 'dynamic','factor': 2.0}
)
附注:别忘了指定所需的dtype和device以高效利用资源。
评估指标
该模型在encodechka基准上的评估结果:
模型名称 |
STS |
PI |
NLI |
SA |
TI |
IA |
IC |
ICX |
NE1 |
NE2 |
平均S(不含NE) |
平均S+W(含NE) |
ruRoPEBert-e5-base-512 |
0.793 |
0.704 |
0.457 |
0.803 |
0.970 |
0.788 |
0.802 |
0.749 |
0.328 |
0.396 |
0.758 |
0.679 |
ruRoPEBert-e5-base-2k |
0.787 |
0.708 |
0.460 |
0.804 |
0.970 |
0.792 |
0.803 |
0.749 |
0.402 |
0.423 |
0.759 |
0.689 |
intfloat/multilingual-e5-base |
0.834 |
0.704 |
0.458 |
0.795 |
0.964 |
0.782 |
0.803 |
0.740 |
0.234 |
0.373 |
0.760 |
0.668 |
作者