bge-reranker-v2-m3-movies-lora
English | Русский
English
A cross-encoder reranker specialised for matching Russian-language movie records: given a movie card (the query) and a candidate card (the document), it decides whether the candidate describes the same movie. It is fine-tuned from BAAI/bge-reranker-v2-m3 (XLM-RoBERTa-large, ~568M parameters) on about 265k labelled pairs of Russian-language movie cards.
What a card looks like. Both sides of the pair are structured text with the same template: Russian and alternative titles, genres, director, cast and a plot description (empty fields are left out). The hard part is that many cards look alike: remakes, sequels, series with the same cast, films with similar titles. A general-purpose reranker gives these near-duplicates high scores. In our evaluation the original model accepted almost everything (recall 0.998, precision only 0.64 at threshold 0.5). This model learned to separate "similar card, different movie" from a real match, and precision rose to 0.974 with recall almost unchanged.
How it was trained. The model was trained with LoRA (rank 16) for 2 epochs. The adapter was then merged into the base weights (merge_and_unload()), so the repository holds a plain HF checkpoint and no separate adapter or peft is needed. The architecture is XLMRobertaForSequenceClassification with num_labels=1, the same as the original reranker, so it loads anywhere the base model does (transformers, vLLM, text-embeddings-inference).
How to read the output. The model takes a (query, document) pair and returns a single logit. Apply a sigmoid to get a probability of "same movie"; a higher value means a better match. Use it to reorder or filter candidates from a first-stage search such as bm25 or embeddings.
Intended use
Reranking candidates already retrieved by a first-stage search (in the training data this is a bm25 shortlist). The task is to tell "a similar card for a different movie" from a true match. The model was not trained or evaluated for other domains.
Usage
transformers
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
repo = "spions/bge-reranker-v2-m3-movies-lora"
tok = AutoTokenizer.from_pretrained(repo)
model = AutoModelForSequenceClassification.from_pretrained(repo).eval()
query = "Название: Начало (Inception). Жанр: фантастика, боевик. Режиссер: Кристофер Нолан."
docs = ["Название: Начало (Inception). Жанр: фантастика. Режиссер: Кристофер Нолан. В ролях: Леонардо Ди Каприо."]
inputs = tok([query] * len(docs), docs, padding=True, truncation=True,
max_length=512, return_tensors="pt")
with torch.no_grad():
logits = model(**inputs).logits.view(-1)
scores = torch.sigmoid(logits) # relevance probability, threshold 0.5
vLLM
Drop-in replacement for the original model; the config and tokenizer are the same:
vllm serve spions/bge-reranker-v2-m3-movies-lora
Data
Pointwise binary labels {"query", "document", "label": 0|1}, 264,723 pairs. Labels were assigned by an LLM judge. Negatives are hard negatives from a bm25 shortlist.
The training data is Russian only. About 98.5% of the letters in the data are Cyrillic (checked on the first 200k rows); every row contains Russian text. The only Latin text is alternative (original) movie titles inside the cards. The base model is multilingual, but this fine-tune was not trained or evaluated on any other language.
query and document follow this template:
Название: {names_rus} ({names_alt}). Жанр: ... Режиссер: ... В ролях: ... Описание: ...
(Title, genre, director, cast, description; empty fields are omitted.)
Only 18.6% of unique queries have both a positive and a negative document. Converting the data to the listwise pos/neg format used by FlagEmbedding would drop about 80% of the rows, so training is plain binary classification over pairs.
The split is stratified by label, seed=42:
- train: 232,956 pairs (88%)
- held-out eval: 31,767 pairs (12%), fixed and identical across all runs
Training
| Parameter | Value |
|---|---|
| Method | LoRA (PEFT), then merged into base weights |
| Target modules | query, key, value, attention.output.dense, intermediate.dense, output.dense (all 24 layers) |
| Classification head | trained in full (modules_to_save=["classifier"]) |
| LoRA r / alpha | 16 / 32 |
| Loss | BCEWithLogitsLoss |
| Learning rate | 2e-5 |
| Epochs | 2 |
| Batch size | 16 × gradient accumulation 2 (effective 32) |
| max_length | 512 |
| Hardware | 1× NVIDIA L4 on Modal, run cost ≈ $6 |
Pipeline: AutoModelForSequenceClassification + peft + transformers.Trainer.
Results
Held-out set (31,767 pairs, threshold 0.5):
| Model | Accuracy | Precision | Recall | ROC AUC |
|---|---|---|---|---|
BAAI/bge-reranker-v2-m3 (zero-shot) | 0.6564 | 0.6411 | 0.9983 | 0.9382 |
| pilot (40k pairs, 2 epochs) | 0.9756 | 0.9713 | 0.9894 | 0.9923 |
| this model (232,956 pairs, 2 epochs) | 0.9788 | 0.9740 | 0.9919 | 0.9937 |
On this domain the base model overestimates scores for almost every pair (recall 0.998 at precision 0.64). After fine-tuning, precision is much higher and recall barely drops.
Limitations
- Labels come from an LLM judge and contain noise; the model may have learned some of its mistakes.
- Metrics are computed on a held-out part of the same distribution (Russian movie cards in one template). Other query formats, languages (only Russian was used for training and evaluation, so quality on English or other languages is unknown and may be worse than the base model's) or domains were not evaluated.
- The 0.5 threshold is calibrated to the training distribution; re-tune it for production.
- Input is truncated at
max_length=512, so long descriptions are cut off.
License
Apache-2.0, same as the base model. The license of the source data is not specified; check it before commercial use.
Русский
Cross-encoder reranker для сопоставления русскоязычных записей о фильмах: на входе карточка фильма (query) и карточка-кандидат (document), на выходе оценка того, описывают ли они один и тот же фильм. Модель дообучена из BAAI/bge-reranker-v2-m3 (XLM-RoBERTa-large, ~568M параметров) примерно на 265 тыс. размеченных пар русскоязычных карточек фильмов.
Как выглядит карточка. Обе стороны пары — структурированный текст по одному шаблону: русское и альтернативные названия, жанры, режиссёр, актёры и описание сюжета (пустые поля пропускаются). Сложность в том, что многие карточки очень похожи: ремейки, сиквелы, сериалы с тем же составом, фильмы с близкими названиями. Универсальный reranker ставит таким почти-дубликатам высокие оценки. В нашей проверке исходная модель принимала почти всё подряд (recall 0.998, но precision всего 0.64 на пороге 0.5). Эта модель научилась отделять «похожая карточка, но другой фильм» от настоящего совпадения: precision выросла до 0.974, recall почти не изменился.
Как обучалась. LoRA (rank 16), 2 эпохи. После обучения адаптер влит в базовые веса (merge_and_unload()), поэтому в репозитории обычный HF-чекпоинт, отдельный адаптер и peft не нужны. Архитектура — XLMRobertaForSequenceClassification с num_labels=1, как у исходного reranker, так что модель грузится везде, где работает базовая (transformers, vLLM, text-embeddings-inference).
Как читать результат. Модель принимает пару (query, document) и возвращает один логит. Если применить sigmoid, получится вероятность «тот же фильм»; чем выше, тем лучше совпадение. Модель подходит для пересортировки или фильтрации кандидатов после первичного поиска, например bm25 или по эмбеддингам.
Назначение
Реранкинг кандидатов, которые уже отобрал первичный поиск (в обучающих данных это bm25-шортлист). Задача — отличить «похожая карточка, но другой фильм» от настоящего совпадения. Для других доменов модель специально не обучалась и не проверялась.
Использование
Примеры кода для transformers и vLLM приведены в английском разделе выше. Конфиг и токенизатор те же, что у исходной модели, поэтому её можно подставить вместо BAAI/bge-reranker-v2-m3.
Данные
Поточечная (pointwise) бинарная разметка {"query", "document", "label": 0|1}, 264 723 пары. Метки поставил LLM-судья. Негативы — hard negatives из bm25-шортлиста.
Данные только на русском языке. Около 98.5% букв в данных — кириллица (проверено на первых 200 тыс. строк), в каждой строке есть русский текст. Латиница встречается только в альтернативных (оригинальных) названиях фильмов внутри карточек. Базовая модель мультиязычная, но это дообучение другие языки не видело и на них не проверялось.
Поля query и document собраны по шаблону:
Название: {names_rus} ({names_alt}). Жанр: ... Режиссер: ... В ролях: ... Описание: ...
Пустые поля в строку не попадают.
Только у 18.6% уникальных запросов есть и позитивный, и негативный документ. Поэтому данные нельзя честно привести к listwise-формату pos/neg для FlagEmbedding, не потеряв примерно 80% строк. Обучение сделано как обычная бинарная классификация пар.
Разбиение стратифицировано по label, seed=42:
- train: 232 956 пар (88%)
- held-out eval: 31 767 пар (12%), он фиксирован и одинаков для всех прогонов
Обучение
| Параметр | Значение |
|---|---|
| Метод | LoRA (PEFT), затем merge в базовые веса |
| Целевые модули | query, key, value, attention.output.dense, intermediate.dense, output.dense (все 24 слоя) |
| Классификационная голова | обучалась целиком (modules_to_save=["classifier"]) |
| LoRA r / alpha | 16 / 32 |
| Лосс | BCEWithLogitsLoss |
| Learning rate | 2e-5 |
| Эпохи | 2 |
| Batch size | 16 × grad accumulation 2 (эффективный 32) |
| max_length | 512 |
| Железо | 1× NVIDIA L4 на Modal, стоимость прогона ≈ $6 |
Код пайплайна: AutoModelForSequenceClassification + peft + transformers.Trainer.
Результаты
Метрики на held-out выборке (31 767 пар, порог 0.5) приведены в таблице английского раздела. Кратко:
| Модель | Accuracy | Precision | Recall | ROC AUC |
|---|---|---|---|---|
BAAI/bge-reranker-v2-m3 (zero-shot) | 0.6564 | 0.6411 | 0.9983 | 0.9382 |
| эта модель (232 956 пар, 2 эпохи) | 0.9788 | 0.9740 | 0.9919 | 0.9937 |
Базовая модель на этом домене завышает оценки почти всем парам: recall 0.998 при precision 0.64. После дообучения precision заметно выше, а recall почти не просел.
Ограничения
- Метки поставил LLM-судья, поэтому в них есть шум. Модель могла перенять его ошибки.
- Метрики посчитаны на held-out части того же распределения (русскоязычные карточки фильмов в одном шаблоне). На других форматах запросов, других языках (обучение и проверка только на русском, поэтому качество на английском и других языках неизвестно и может быть хуже, чем у базовой модели) или других доменах качество не проверялось.
- Порог 0.5 откалиброван под распределение обучающих данных. В проде его стоит подобрать заново.
- Обрезка по
max_length=512: длинные описания обрезаются.
Лицензия
Apache-2.0, как у базовой модели. Лицензия исходных данных не оговорена, проверьте её, если планируете коммерческое использование.