/ Модель

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

Контекст
1 024 токена
Лицензия
MIT
Архитектура
gpt2 · dense
Опубликована
11 янв 2023

czech-gpt2-oscar

Генерация текстаТекст → текст3 профессии

Небольшая чешскоязычная модель GPT-2 для продолжения и генерации текста по подсказке.

408скачиваний за 30 дней4лайкавеса обновлены22 мар 2023

Бенчмарки

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

Тесты пользователейпока нет

Никто ещё не опубликовал тест этой модели. Соберите бенчмарк из своих задач — результат появится здесь.

  1. Добавьте модель в бенчмарк

    Вместе с другими моделями категории «Текст» — сравнение идёт внутри одной категории.

  2. Опишите свои задачи

    Напишите запросы, при необходимости приложите файлы и эталонные ответы.

  3. Запустите и опубликуйте

    Модели ответят на каждую задачу, судья оценит ответы. Опубликованный результат появится на этой странице.

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

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

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

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

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

Czech-GPT2-OSCAR — небольшая языковая модель GPT-2, обученная Лუკашем Халоупским как часть магистерской работы и подтверждение возможности адаптировать английскую GPT-2 для чешского языка. Это плотная авторегрессионная модель GPT2LMHeadModel, дообученная методом transfer learning на чешской части корпуса OSCAR объёмом около 21 ГБ; для обучения использовались Transformers, Tokenizers и fastai v2. Репозиторий поддерживает PyTorch, TensorFlow и safetensors.

Модель предназначена прежде всего для продолжения и генерации чешского текста по текстовой подсказке. Автор описывает её как основу для последующей Czech-GPT2-Medical. Контекст модели составляет 1024 токена по метаданным; в README также упоминается обучение с целевой длиной последовательности 512 токенов. Лицензия — MIT.

Модель унаследовала ограничения GPT-2: она может генерировать недостоверные сведения и отражать предвзятости неотфильтрованного интернет-корпуса OSCAR. Её не следует применять для задач, где необходима фактическая точность или где предвзятость может причинить вред, без соответствующей проверки.

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

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

Ограничения

Модель может генерировать недостоверные утверждения и отражать предвзятости и неотфильтрованное содержание обучающего корпуса OSCAR. В README приведены разные значения длины последовательности: 512 токенов для обучения и 1024 токена для контекста.

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

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

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

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

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

Открыть на Hugging Face

Czech GPT-2 small model trained on the OSCAR dataset

This model was trained as a part of the master thesis on the Czech part of the OSCAR dataset.

Introduction

Czech-GPT2-OSCAR (Czech GPT-2 small) is a state-of-the-art language model for Czech based on the GPT-2 small model. Unlike the original GPT-2 small model, this model is trained to predict only 512 tokens instead of 1024 as it serves as a basis for the Czech-GPT2-Medical.

The model was trained the Czech part of the OSCAR dataset using Transfer Learning and Fine-tuning techniques in about a week on one NVIDIA A100 SXM4 40GB and with a total of 21 GB of training data.

This model was trained as a part of the master thesis as a proof-of-concept that it is possible to get a state-of-the-art language model in Czech language with smaller ressources than the original one, and in a significantly shorter time and mainly as a basis for the Czech-GPT2-Medical model. There was no Czech GPT-2 model available at the time the master thesis began.

It was fine-tuned from the English pre-trained GPT-2 small using the Hugging Face libraries (Transformers and Tokenizers) wrapped into the fastai v2 Deep Learning framework. All the fine-tuning fastai v2 techniques were used. The solution is based on the Faster than training from scratch — Fine-tuning the English GPT-2 in any language with Hugging Face and fastai v2 (practical case with Portuguese) article.

Trained model is now available on Hugging Face under czech-gpt2-oscar. For more information please let me know in the discussion.

Training/Evaluation

For more information on training the model or its evaluation, please have a look at the thesis itself.

GPT-2 Model description

Note: information copied/pasted from Model: gpt2 >> Model description

GPT-2 is a transformers model pretrained on a very large corpus of English data in a self-supervised fashion. This means it was pretrained on the raw texts only, with no humans labelling them in any way (which is why it can use lots of publicly available data) with an automatic process to generate inputs and labels from those texts. More precisely, it was trained to guess the next word in sentences.

More precisely, inputs are sequences of continuous text of a certain length and the targets are the same sequence, shifted one token (word or piece of word) to the right. The model uses internally a mask-mechanism to make sure the predictions for the token i only uses the inputs from 1 to i but not the future tokens.

This way, the model learns an inner representation of the English language that can then be used to extract features useful for downstream tasks. The model is best at what it was pretrained for however, which is generating texts from a prompt.

How to use Czech-GPT2-OSCAR with HuggingFace (PyTorch)

The following code use PyTorch. To use TensorFlow, check the below corresponding paragraph.

Load Czech-GPT2-OSCAR and its sub-word tokenizer (Byte-level BPE)

from transformers import GPT2Tokenizer, GPT2LMHeadModel
import torch

tokenizer = GPT2Tokenizer.from_pretrained("lchaloupsky/czech-gpt2-oscar")
model = GPT2LMHeadModel.from_pretrained("lchaloupsky/czech-gpt2-oscar")

# Get sequence length max of 1024
tokenizer.model_max_length=1024
# For older versions of the 'transformers' library use this
# tokenizer.max_len=1024

model.eval()  # disable dropout (or leave in train mode to finetune)

Generate one word

# input sequence
text = "Univerzita je základem"
inputs = tokenizer(text, return_tensors="pt")

# model output
outputs = model(**inputs, labels=inputs["input_ids"])
loss, logits = outputs[:2]
predicted_index = torch.argmax(logits[0, -1, :]).item()
predicted_text = tokenizer.decode([predicted_index])

# results
print('input text:', text)
print('predicted text:', predicted_text)

Generate one full sequence

# input sequence
text = "Univerzita je základem"
inputs = tokenizer(text, return_tensors="pt") # tokenizer.encode(text, return_tensors="pt") directly for input_ids

# model output using Top-k sampling text generation method
sample_outputs = model.generate(inputs.input_ids,
                                pad_token_id=50256,
                                do_sample=True, 
                                max_length=50, # put the token number you want
                                top_k=40,
                                num_return_sequences=1)

# generated sequence
for i, sample_output in enumerate(sample_outputs):
    print("{}\n\n{}".format(i+1, tokenizer.decode(sample_output.tolist()))) # tokenizer.decode(sample_output, skip_special_tokens=True)

How to use Czech-GPT2-OSCAR with HuggingFace (TensorFlow)

The following code use TensorFlow. To use PyTorch, check the above corresponding paragraph.

Load Czech-GPT2-OSCAR and its sub-word tokenizer (Byte-level BPE)

from transformers import GPT2Tokenizer, TFGPT2LMHeadModel
import tensorflow as tf

tokenizer = GPT2Tokenizer.from_pretrained("lchaloupsky/czech-gpt2-oscar")
model = TFGPT2LMHeadModel.from_pretrained("lchaloupsky/czech-gpt2-oscar")

# Get sequence length max of 1024
tokenizer.model_max_length=1024
# For older versions of the 'transformers' library use this
# tokenizer.max_len=1024

model.eval()  # disable dropout (or leave in train mode to finetune)

Generate one full sequence

# input sequence
text = "Univerzita je základem"
input_ids = tokenizer.encode(text, return_tensors="tf")

# model output using Top-k sampling text generation method
outputs = model.generate(input_ids, eos_token_id=50256, pad_token_id=50256, 
                         do_sample=True,
                         max_length=40,
                         top_k=40)
print(tokenizer.decode(outputs[0])) # tokenizer.decode(outputs[0], skip_special_tokens=True)

Limitations and bias

The training data used for this model come from the Czech part of the OSCAR dataset. We know it contains a lot of unfiltered content from the internet, which is far from neutral. As the openAI team themselves point out in their model card:

Because large-scale language models like GPT-2 do not distinguish fact from fiction, we don’t support use-cases that require the generated text to be true. Additionally, language models like GPT-2 reflect the biases inherent to the systems they were trained on, so we do not recommend that they be deployed into systems that interact with humans > unless the deployers first carry out a study of biases relevant to the intended use-case. We found no statistically significant difference in gender, race, and religious bias probes between 774M and 1.5B, implying all versions of GPT-2 should be approached with similar levels of caution around use cases that are sensitive to biases around human attributes.

Author

Czech-GPT2-OSCAR was trained and evaluated by Lukáš Chaloupský thanks to the computing power of the GPU (NVIDIA A100 SXM4 40GB) cluster of IT4I (VSB - Technical University of Ostrava).

Citation

@article{chaloupsky2022automatic,
  title={Automatic generation of medical reports from chest X-rays in Czech},
  author={Chaloupsk{\`y}, Luk{\'a}{\v{s}}},
  year={2022},
  publisher={Charles University, Faculty of Mathematics and Physics}
}

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

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

GPU в ailist

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

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

Подбираем GPU…

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

0 моделей