/ Модель

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

Контекст
2 048 токенов
Параметры
167 млн
Архитектура
bert · dense
Библиотека
transformers
Опубликована
22 фев 2024

ruRoPEBert-e5-base-2k

Заполнение пропусковТекст → текст9 профессий

Русскоязычный RoPEBert-энкодер для построения текстовых эмбеддингов и сравнения семантической близости текстов с контекстом до 2048 токенов.

3 928скачиваний за 30 дней11лайковвеса обновлены13 мар 2024

Бенчмарки

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

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

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

В подключённых источниках результатов для этой модели пока нет.

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

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

ruRoPEBert-e5-base-2k — русскоязычная модель-энкодер от Tochka AI на архитектуре RoPEBert с 166,5 млн параметров. Она дообучена на датасете CulturaX методом cloning на основе hivaze/ru-e5-base, который использует русские и английские эмбеддинги intfloat/multilingual-e5-base.

Модель предназначена для получения эмбеддингов предложений и текстов, сравнения их семантической близости и построения классификаторов. В архитектуру встроен mean-pooling с учётом маски внимания; также доступен вариант pooling с преобразованием первого токена. Контекст обучения составляет до 2048 токенов. В бенчмарке encodechka модель показала более высокий общий показатель S+W, чем приведённые в карточке ruRoPEBert-e5-base-512 и multilingual-e5-base.

Для загрузки требуется Transformers версии 4.37.2 или новее и разрешение загрузки кода из репозитория через trust_remote_code=True. Карточка не указывает лицензию. Модель может работать с более длинным контекстом при настройке RoPE scaling, однако качество за пределами обучающей длины отдельно не подтверждено.

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

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

Ограничения

Для корректной загрузки нужен Transformers 4.37.2 или новее и включённый trust_remote_code=True. Лицензия в предоставленной карточке не указана; работа на контексте длиннее 2048 токенов требует RoPE scaling, а качество на таких длинах не подтверждено.

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

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

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

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

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

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

Открыть на Hugging Face

ruRoPEBert Sentence Model for Russian language

This is an encoder model from Tochka AI based on the RoPEBert architecture, using the cloning method described in our article on Habr.

CulturaX dataset was used for model training. The hivaze/ru-e5-base (only english and russian embeddings of intfloat/multilingual-e5-base) model was used as the original; this model surpasses it and all other models in quality (at the time of creation), according to the S+W score of encodechka benchmark.

The model source code is available in the file modeling_rope_bert.py

The model is trained on contexts up to 2048 tokens in length, but can be used on larger contexts.

Usage

Important: 4.37.2 and higher is the recommended version of transformers. To load the model correctly, you must enable dowloading code from the model's repository: trust_remote_code=True, this will download the modeling_rope_bert.py script and load the weights into the correct architecture. Otherwise, you can download this script manually and use classes from it directly to load the model.

Basic usage (no efficient attention)

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')

With SDPA (efficient attention)

model = AutoModel.from_pretrained(model_name, trust_remote_code=True, attn_implementation='sdpa')

Getting embeddings

The correct pooler (mean) is already built into the model architecture, which averages embeddings based on the attention mask. You can also select the pooler type (first_token_transform), which performs a learnable linear transformation on the first token.

To change built-in pooler implementation use pooler_type parameter in AutoModel.from_pretrained function

test_batch = tokenizer.batch_encode_plus(["Привет, чем занят?", "Здравствуйте, чем вы занимаетесь?"], return_tensors='pt', padding=True)
with torch.inference_mode():
  pooled_output = model(**test_batch).pooler_output   

In addition, you can calculate cosine similarities between texts in batch using normalization and matrix multiplication:

import torch.nn.functional as F
F.normalize(pooled_output, dim=1) @ F.normalize(pooled_output, dim=1).T

Using as classifier

To load the model with trainable classification head on top (change num_labels parameter):

model = AutoModelForSequenceClassification.from_pretrained(model_name, trust_remote_code=True, attn_implementation='sdpa', num_labels=4)

With RoPE scaling

Allowed types for RoPE scaling are: linear and dynamic. To extend the model's context window you need to change tokenizer max length and add rope_scaling parameter.

If you want to scale your model context by 2x:

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}
                                  ) # 2.0 for x2 scaling, 4.0 for x4, etc..

P.S. Don't forget to specify the dtype and device you need to use resources efficiently.

Metrics

Evaluation of this model on encodechka benchmark:

Model nameSTSPINLISATIIAICICXNE1NE2Avg S (no NE)Avg S+W (with NE)
ruRoPEBert-e5-base-5120.7930.7040.4570.8030.9700.7880.8020.7490.3280.3960.7580.679
ruRoPEBert-e5-base-2k0.7870.7080.4600.8040.9700.7920.8030.7490.4020.4230.7590.689
intfloat/multilingual-e5-base0.8340.7040.4580.7950.9640.7820.8030.7400.2340.3730.760.668

Authors

  • Sergei Bratchikov (Tochka AI Team, HF, GitHub)
  • Maxim Afanasiev (Tochka AI Team, HF, GitHub)

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

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

GPU в ailist

Универсальный рантайм · transformers · fill-mask

Можно запустить

Подбираем GPU…

Класс архитектуры
RoPEBertForMaskedLM
Ревизия весов
2cb9947

0 моделей