/ Модель

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

Контекст
128 токенов
Архитектура
gpt2 · dense
Библиотека
transformers
Опубликована
26 ноя 2026

reuters-gpt2

Генерация текстаТекст → текст
416скачиваний за 30 дней0лайковвеса обновлены28 ноя 2026

Описание модели

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

Небольшая GPT-2, обученная с нуля на новостях Reuters для учебных экспериментов и короткого продолжения англоязычных новостных текстов.

Reuters GPT-2 — небольшая авторегрессионная языковая модель на архитектуре GPT-2, обученная с нуля на англоязычных новостных статьях Reuters. Разработчик в карточке не назван. Модель предсказывает следующий токен и предназначена для учебных экспериментов с self-supervised learning, анализом гиперпараметров и вероятностей токенов, а также для короткого продолжения новостей и финансовых отчётов.

Опубликован вариант Experiment B: он обучался пять эпох и был выбран среди трёх запусков по наименьшей финальной валидационной потере. Контекст составляет 128 токенов. В тестировании этого запуска perplexity составила 51,62. Модель не обучалась следовать инструкциям и не предназначена для роли универсального чат-бота. Она использует токенизатор Reuters, указанный в README; веса сохранены в формате safetensors. Лицензия в предоставленных данных не указана.

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

  • короткое продолжение англоязычных новостных статей
  • генерация текста в стиле новостей Reuters
  • продолжение финансовых отчётов
  • изучение предсказания следующего токена
  • сравнение потерь и perplexity языковых моделей
  • анализ вероятностей следующих токенов для разных промптов

Ограничения

Контекст ограничен 128 токенами; модель не настроена на выполнение инструкций и не подходит как универсальный чат-бот. README отмечает, что разрыв между обучающей и валидационной потерями увеличивался в поздних эпохах.

Публичные бенчмарки

Результаты из открытых лидербордов в сравнении с лидерами каталога

Публичных оценок пока нет

В подключённых источниках результатов этой модели не нашлось. Отсутствие оценки не значит, что модель хуже: её могли просто не проверять.

Источники: Hugging Face Leaderboards, Hugging Face Eval Results, Open LLM v2, MTEB, timm, Open ASR, EvalPlus

Бенчмарки пользователейпока нет

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

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

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

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

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

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

    Модели ответят на каждую задачу, судья оценит ответы по шкале 0–100.

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

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

Открыть на Hugging Face

Reuters GPT-2 — Trained from Scratch

Reuters GPT-2 is a small autoregressive language model trained on English Reuters news articles using causal language modeling.

The model learns to predict the next token from raw article text. All model weights were randomly initialized; no pretrained GPT-2 weights were used. The existing Reuters tokenizer was reused as specified in the assignment.

This repository contains Experiment B, the five-epoch model selected based on the lowest final validation loss among three training runs.

Model details

PropertyValue
ArchitectureGPT-2 (GPT2LMHeadModel)
TaskCausal language modeling / text generation
LanguageEnglish
Parameter count16,504,320 (16.50M)
Vocabulary size52,000
Context length128 tokens
Embedding dimension256
Transformer layers4
Attention heads4
Attention head dimension64
Feed-forward hidden dimension1,024
Activation functiongelu_new
Attention, embedding and residual dropout0.1 each
BOS / EOS / padding token ID0
FrameworkPyTorch and Hugging Face Transformers
Weight initializationRandom

Intended uses

The model is intended for educational experiments involving:

  • Self-supervised learning and next-token prediction.
  • Short news-style and financial-report-style text completion.
  • Comparing language modeling hyperparameters and perplexity.
  • Exploring how changes in a prompt affect next-token probabilities.

It is not an instruction-tuned model or a general-purpose chatbot.

Training data and preprocessing

The dataset contains news article titles and bodies. The original splits were retained throughout training and evaluation.

SplitArticles128-token blocks
Training17,26223,773
Validation2,1583,219
Test2,1582,475
Total21,57829,467

For preprocessing, the title and body of each article were stripped of surrounding whitespace and joined using a newline. An end-of-sequence token (<|endoftext|>) was appended to each article before tokenization.

Within each split, token sequences were concatenated in batches and divided into non-overlapping blocks of 128 tokens. Incomplete trailing blocks were discarded within each preprocessing batch. No padding was needed for these blocks. The input token IDs were copied as labels, with GPT-2 internally shifting the labels to calculate next-token cross-entropy loss.

Training procedure

The model was trained in Google Colab on a Tesla T4 GPU using the Hugging Face Trainer API. Training used only the training split for weight updates; validation loss was recorded after each epoch, and test loss was measured after training.

Hyperparameters of the published model

HyperparameterValue
Epochs5
Learning rate0.0003 (3e-4)
OptimizerAdamW
Learning rate schedulerConstant
Training batch size8
Evaluation batch size8
Gradient accumulation steps2
Effective training batch size16
Weight decay0.01
Mixed precisionFP16
Random seed42
Evaluation and logging frequencyEvery epoch
Training time9.164045 minutes

Software versions specified in the training notebook: transformers==4.51.3, datasets==3.6.0, and accelerate==1.6.0.

Training history (Experiment B)

EpochTraining lossValidation loss
15.4168004.904490
24.4534004.504122
34.0791004.302712
43.8252004.196773
53.6284004.128728

Both training and validation losses decreased across five epochs. The gap between them widened in later epochs, although validation loss continued to improve.

Evaluation results

Three independent training runs were conducted using the same architecture, dataset, tokenizer, seed and other training settings. Each run started from randomly initialized weights. Only the number of epochs or learning rate was changed relative to the baseline.

ExperimentEpochsLearning rateTraining time (min)Validation lossTest lossTest perplexity
A — Baseline20.00033.56774.5041224.28572372.655038
B — Increased epochs (published)50.00039.16404.1287283.94400251.624774
C — Reduced learning rate20.00013.83365.0043034.766883117.552248

How to use

Install the required libraries:

pip install torch transformers

Generate a short continuation

import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed

model_id = "InduwaraR/reuters-gpt2"

tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id)

device = "cuda" if torch.cuda.is_available() else "cpu"
model = model.to(device)
model.eval()

set_seed(42)

prompt = "AEL INDUSTRIES INC <AELNA.O> FIRST QTR NET\n"
inputs = tokenizer(prompt, return_tensors="pt").to(device)
input_length = inputs["input_ids"].shape[1]

# Keep the prompt and continuation within the 128-token context.
max_new_tokens = min(60, model.config.n_positions - input_length)
if max_new_tokens <= 0:
    raise ValueError("Please use a shorter prompt.")

with torch.no_grad():
    output = model.generate(
        **inputs,
        max_new_tokens=max_new_tokens,
        do_sample=True,
        temperature=0.8,
        top_k=50,
        top_p=0.95,
        pad_token_id=tokenizer.pad_token_id
    )

print(tokenizer.decode(output[0, input_length:], skip_special_tokens=True))

Sampling results may vary with software versions, hardware and random seeds.

Inspect next-token probabilities

After loading the model and tokenizer using the code above:

prompt = "ROMEO:"
inputs = tokenizer(prompt, return_tensors="pt").to(device)

with torch.no_grad():
    logits = model(**inputs).logits[0, -1, :]
    probabilities = torch.softmax(logits, dim=-1)
    top_probs, top_ids = torch.topk(probabilities, k=5)

for token_id, probability in zip(top_ids, top_probs):
    token = tokenizer.decode([token_id.item()])
    print(f"{token!r}: {probability.item():.6f}")

References

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

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

GPU в ailist

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

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

Подбираем GPU…

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

0 моделей