/ Модель

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

Контекст
514 токенов
Параметры
305 млн
Лицензия
CC BY 4.0
Архитектура
xlm-roberta · dense
Базовая модель
xlm-roberta-base
Опубликована
11 мар 2023

xlm-roberta-base-lora-language-detection

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

dominguesm/xlm-roberta-base-lora-language-detection — мультиязычная модель для автоматического определения языка текста.

3 419скачиваний за 30 дней2лайкавеса обновлены2 мая 2024

Бенчмарки

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

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

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

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

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

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

Она разработана на базе xlm-roberta-base и дообучена методом PEFT-LoRA с классификационной головой для задач классификации последовательностей.

Модель поддерживает 20 языков: арабский, болгарский, немецкий, современный греческий, английский, испанский, французский, хинди, итальянский, японский, нидерландский, польский, португальский, русский, суахили, тайский, турецкий, урду, вьетнамский и китайский. Дообучение проводилось на датасете papluca/language-identification: 70 тысяч обучающих, 10 тысяч валидационных и 10 тысяч тестовых примеров. На тестовой выборке заявлены accuracy и F1 на уровне 99,43–99,4%.

Сильной стороной является высокая точность при поддержке нескольких языков и сниженные вычислительные и требования к хранению затраты благодаря LoRA, которая изменяет лишь небольшое число дополнительных параметров. Ограничение модели — классификация только указанных 20 языков; качество на текстах, отличающихся от распределения исходного датасета, в README отдельно не оценено. Лицензия — CC BY 4.0.

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

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

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

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

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

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

Открыть на Hugging Face

xlm-roberta-base-lora-language-detection

This model is a fine-tuned version of xlm-roberta-base on the Language Identification dataset. Using the PEFT-LoRA method to only fine-tune a small number of (extra) model parameters, thereby greatly decreasing the computational and storage costs.

Model description

This model is an XLM-RoBERTa transformer model with a classification head on top (i.e. a linear layer on top of the pooled output). For additional information please refer to the xlm-roberta-base model card or to the paper Unsupervised Cross-lingual Representation Learning at Scale by Conneau et al.

Intended uses & limitations

You can directly use this model as a language detector, i.e. for sequence classification tasks. Currently, it supports the following 20 languages:

arabic (ar), bulgarian (bg), german (de), modern greek (el), english (en), spanish (es), french (fr), hindi (hi), italian (it), japanese (ja), dutch (nl), polish (pl), portuguese (pt), russian (ru), swahili (sw), thai (th), turkish (tr), urdu (ur), vietnamese (vi), and chinese (zh)

Training and evaluation data

The model was fine-tuned on the Language Identification dataset, which consists of text sequences in 20 languages. The training set contains 70k samples, while the validation and test sets 10k each. The average accuracy on the test set is 99.4% (this matches the average macro/weighted F1-score being the test set perfectly balanced). A more detailed evaluation is provided by the following table.

LanguagePrecisionRecallF1-scoresupport
ar1.0000.9980.999500
bg0.9921.0000.996500
de1.0001.0001.000500
el1.0001.0001.000500
en0.9920.9920.992500
es0.9940.9920.993500
fr0.9980.9980.998500
hi0.9451.0000.972500
it1.0000.9840.992500
ja1.0001.0001.000500
nl0.9960.9920.994500
pl0.9920.9880.990500
pt0.9880.9860.987500
ru0.9980.9960.997500
sw0.9920.9940.993500
th1.0001.0001.000500
tr1.0001.0001.000500
ur1.0000.9640.982500
vi1.0001.0001.000500
zh1.0001.0001.000500

Benchmarks

As a baseline to compare xlm-roberta-base-lora-language-detection against, we have used the Python langid library. Since it comes pre-trained on 97 languages, we have used its .set_languages() method to constrain the language set to our 20 languages. The average accuracy of langid on the test set is 98.5%. More details are provided by the table below.

LanguagePrecisionRecallF1-scoresupport
ar0.9900.9700.980500
bg0.9980.9640.981500
de0.9920.9440.967500
el1.0000.9980.999500
en1.0001.0001.000500
es1.0000.9680.984500
fr0.9961.0000.998500
hi0.9490.9760.963500
it0.9900.9800.985500
ja0.9270.9880.956500
nl0.9801.0000.990500
pl0.9860.9960.991500
pt0.9500.9960.973500
ru0.9960.9740.985500
sw1.0001.0001.000500
th1.0000.9960.998500
tr0.9900.9680.979500
ur0.9980.9960.997500
vi0.9710.9900.980500
zh1.0001.0001.000500

Using the model for inference

# pip install -q loralib transformers
# pip install -q git+https://github.com/huggingface/peft.git@main

import torch
from peft import PeftConfig, PeftModel
from transformers import (
    AutoConfig,
    AutoModelForSequenceClassification,
    AutoTokenizer,
    pipeline,
)

peft_model_id = "dominguesm/xlm-roberta-base-lora-language-detection"

# Load the Peft model config
peft_config = PeftConfig.from_pretrained(peft_model_id)

# Load the base model config
base_config = AutoConfig.from_pretrained(peft_config.base_model_name_or_path)

# Load the base model
base_model = AutoModelForSequenceClassification.from_pretrained(
    peft_config.base_model_name_or_path, config=base_config
)

# Load the tokenizer
tokenizer = AutoTokenizer.from_pretrained(peft_config.base_model_name_or_path)

# Load the inference model
inference_model = PeftModel.from_pretrained(base_model, peft_model_id)

# Load the pipeline
pipe = pipeline("text-classification", model=inference_model, tokenizer=tokenizer)


def detect_lang(text: str) -> str:
    # This code runs on CPU, so we use torch.cpu.amp.autocast to perform
    # automatic mixed precision.
    with torch.cpu.amp.autocast():
        # or `with torch.cuda.amp.autocast():`
        pred = pipe(text)
    return pred


detect_lang(
    "Cada qual sabe amar a seu modo; o modo, pouco importa; o essencial é que saiba amar."
)
# [{'label': 'pt', 'score': 0.9959434866905212}]

Training procedure

Fine-tuning was done via the Trainer API. Here is the Jupyter notebook with the training code.

Training hyperparameters

The following hyperparameters were used during training:

  • learning_rate: 2e-05
  • train_batch_size: 64
  • eval_batch_size: 128
  • optimizer: Adam with betas=(0.9,0.999) and epsilon=1e-08
  • num_epochs: 2

Training results

The validation results on the valid split of the Language Identification dataset are summarised here below.

Training LossEpochStepValidation LossAccuracyF1
1.44031.010940.05910.99520.9952
0.02562.021880.02720.99550.9955

In short, it achieves the following results on the validation set:

  • Loss: 0.0298
  • Accuracy: 0.9946
  • F1: 0.9946

Framework versions

  • torch 1.13.1+cu116
  • datasets 2.10.1
  • sklearn 1.2.1
  • transformers 4.27.0.dev0
  • langid 1.1.6
  • peft 0.3.0.dev0

Note

This study was fully based and inspired by the xlm-roberta-base-language-detection model, developed by Luca Papariello.

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

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

GPU в ailist

Универсальный рантайм

Нельзя запустить

Репозиторий содержит только адаптер (LoRA/PEFT) без базовой модели.

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

0 моделей