/ Модель

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

Контекст
514 токенов
Параметры
110 млн
Лицензия
MIT
Архитектура
xlm-roberta · dense
Опубликована
11 фев 2023

multilingual-MiniLMv2-L6-mnli-xnli

Классификация текстаТекст → label8 профессий

Многоязычная модель для NLI и классификации текстов по заданным пользователем категориям без отдельного обучения.

22 223скачиваний за 30 дней52лайкавеса обновлены22 апр 2024

Бенчмарки

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

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

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

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

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

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

Moritz Laurer дообучил multilingual-MiniLM-L6 от Microsoft для распознавания логических отношений между текстами (NLI) и классификации без заранее заданного набора классов. Модель основана на XLM-RoBERTa и использует архитектуру XLMRobertaForSequenceClassification; в ней 6 слоёв и 110,2 млн параметров. Контекст — до 514 токенов. Доступны веса в форматах PyTorch, Safetensors и ONNX.

Модель принимает пару текстов для оценки отношений между ними либо текст и список возможных меток для zero-shot-классификации. Она обучена на MNLI и переводах XNLI; карточка сообщает о поддержке NLI более чем на 100 языках и приводит результаты оценки на 15 языках. Компактность модели обеспечивает более быстрый вывод и меньшие требования к памяти по сравнению с XLM-RoBERTa-large, но качество ниже, чем у более крупной модели-учителя. Для языков вне набора оценки качество может быть ниже. Лицензия — MIT.

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

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

Ограничения

Компактная модель уступает более крупной XLM-RoBERTa-large по качеству; для языков вне оценки XNLI результаты могут быть ниже. Возможны смещения, связанные с данными NLI.

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

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

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

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

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

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

Открыть на Hugging Face

Multilingual MiniLMv2-L6-mnli-xnli

Model description

This multilingual model can perform natural language inference (NLI) on 100+ languages and is therefore also suitable for multilingual zero-shot classification. The underlying multilingual-MiniLM-L6 model was created by Microsoft and was distilled from XLM-RoBERTa-large (see details in the original paper and newer information in this repo). The model was then fine-tuned on the XNLI dataset, which contains hypothesis-premise pairs from 15 languages, as well as the English MNLI dataset.

The main advantage of distilled models is that they are smaller (faster inference, lower memory requirements) than their teachers (XLM-RoBERTa-large). The disadvantage is that they lose some of the performance of their larger teachers.

For highest inference speed, I recommend using this 6-layer model. For higher performance I recommend mDeBERTa-v3-base-mnli-xnli (as of 14.02.2023).

How to use the model

Simple zero-shot classification pipeline

from transformers import pipeline
classifier = pipeline("zero-shot-classification", model="MoritzLaurer/multilingual-MiniLMv2-L6-mnli-xnli")

sequence_to_classify = "Angela Merkel ist eine Politikerin in Deutschland und Vorsitzende der CDU"
candidate_labels = ["politics", "economy", "entertainment", "environment"]
output = classifier(sequence_to_classify, candidate_labels, multi_label=False)
print(output)

NLI use-case

from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")

model_name = "MoritzLaurer/multilingual-MiniLMv2-L6-mnli-xnli"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name)

premise = "Angela Merkel ist eine Politikerin in Deutschland und Vorsitzende der CDU"
hypothesis = "Emmanuel Macron is the President of France"

input = tokenizer(premise, hypothesis, truncation=True, return_tensors="pt")
output = model(input["input_ids"].to(device))  # device = "cuda:0" or "cpu"
prediction = torch.softmax(output["logits"][0], -1).tolist()
label_names = ["entailment", "neutral", "contradiction"]
prediction = {name: round(float(pred) * 100, 1) for pred, name in zip(prediction, label_names)}
print(prediction)

Training data

This model was trained on the XNLI development dataset and the MNLI train dataset. The XNLI development set consists of 2490 professionally translated texts from English to 14 other languages (37350 texts in total) (see this paper). Note that the XNLI contains a training set of 15 machine translated versions of the MNLI dataset for 15 languages, but due to quality issues with these machine translations, this model was only trained on the professional translations from the XNLI development set and the original English MNLI training set (392 702 texts). Not using machine translated texts can avoid overfitting the model to the 15 languages; avoids catastrophic forgetting of the other languages it was pre-trained on; and significantly reduces training costs.

Training procedure

The model was trained using the Hugging Face trainer with the following hyperparameters. The exact underlying model is mMiniLMv2-L6-H384-distilled-from-XLMR-Large.

training_args = TrainingArguments(
    num_train_epochs=3,              # total number of training epochs
    learning_rate=4e-05,
    per_device_train_batch_size=64,   # batch size per device during training
    per_device_eval_batch_size=120,    # batch size for evaluation
    warmup_ratio=0.06,                # number of warmup steps for learning rate scheduler
    weight_decay=0.01,               # strength of weight decay
)

Eval results

The model was evaluated on the XNLI test set on 15 languages (5010 texts per language, 75150 in total). Note that multilingual NLI models are capable of classifying NLI texts without receiving NLI training data in the specific language (cross-lingual transfer). This means that the model is also able of doing NLI on the other languages it was training on, but performance is most likely lower than for those languages available in XNLI.

The average XNLI performance of multilingual-MiniLM-L6 reported in the paper is 0.68 (see table 11). This reimplementation has an average performance of 0.713. This increase in performance is probably thanks to the addition of MNLI in the training data and this model was distilled from XLM-RoBERTa-large instead of -base (multilingual-MiniLM-L6-v2).

Datasetsavg_xnliarbgdeelenesfrhiruswthtrurvizh
Accuracy0.7130.6870.7420.7190.7230.7890.7480.7410.6910.7140.6420.6990.6960.6640.7230.721
Speed text/sec (A100 GPU, eval_batch=120)6093.06210.06003.06053.05409.06531.06205.05615.05734.05970.06219.06289.06533.05851.05970.06798.0
Datasetsmnli_mmnli_mm
Accuracy0.7820.8
Speed text/sec (A100 GPU, eval_batch=120)4430.04395.0

Limitations and bias

Please consult the original paper and literature on different NLI datasets for potential biases.

Citation

If you use this model, please cite: Laurer, Moritz, Wouter van Atteveldt, Andreu Salleras Casas, and Kasper Welbers. 2022. ‘Less Annotating, More Classifying – Addressing the Data Scarcity Issue of Supervised Machine Learning with Deep Transfer Learning and BERT - NLI’. Preprint, June. Open Science Framework. https://osf.io/74b8k.

Ideas for cooperation or questions?

If you have questions or ideas for cooperation, contact me at m{dot}laurer{at}vu{dot}nl or LinkedIn

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

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

GPU в ailist

Универсальный рантайм · text-classification

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

Подбираем GPU…

Класс архитектуры
XLMRobertaForSequenceClassification
Ревизия весов
0a71e92

0 моделей