GPT-2 style language model trained from scratch on Reuters articles

A small decoder-only Transformer (GPT-2 architecture, 30,713,856 parameters) trained from random initialisation with the self-supervised next-token objective on the concatenated title + body of ingeniumacademy/reuters_articles. No pretrained model weights were used. Only the tokenizer ingeniumacademy/gpt2-reuters-tokenizer (vocabulary 52,000) was reused. The work was done for CS4681 Assignment 02 (Self-Supervised Learning), University of Moratuwa.

Test loss / perplexity 4.0241 / 55.93
Validation loss / perplexity 4.2257 / 68.42
Next-token accuracy on test (top-1 / top-5) 37.3% / 54.7%
Architecture 6 layers, 6 heads, width 384, context 256
Training 5 epochs, 3515 steps, 9.57 min on CUDA (Tesla T4)

Intended use: study and teaching (how a small language model behaves when trained on a narrow corpus). The model is not a source of facts and must not be used to produce or spread news content. See Limitations.

Table of contents

  1. Data
  2. Model
  3. Training
  4. Evaluation
  5. Controlled experiments
  6. Limitations
  7. How to use
  8. Reproducibility and files

1. Data

Source: ingeniumacademy/reuters_articles with train / validation / test splits of 17,262 / 2,158 / 2,158 articles. The full text of an article is title + blank line + body.

1.1 Quality check of the raw data

statistic train validation test
rows 17262.0 2158.0 2158.0
null_title 0.0 0.0 0.0
null_body 0.0 0.0 0.0
empty_title 718.0 6.0 13.0
empty_body 1948.0 188.0 399.0
body<50chars 1956.0 188.0 399.0
title_ALLCAPS_% 94.7 98.4 95.0
body_ends_Reuter_% 87.5 91.2 81.4
control_char_% 88.7 91.3 81.5
html_entity_% 0.0 0.0 0.0
non_ascii_% 0.0 0.05 0.0
title_words_med 7.0 7.0 7.0
body_words_mean 121.4 131.7 95.5
body_words_med 83.0 89.0 67.0
body_words_p95 402.95 435.15 323.15
body_words_max 1669.0 1005.0 854.0

Typical artefacts found in the raw text: articles are hard-wrapped at about 60 characters, paragraphs start with four spaces, almost every body ends with Reuter followed by an invisible control character, many items have an empty body (title-only news flashes), and some articles are duplicated.

Length of article bodies and titles in words (training split)

Length of article bodies and titles in words (training split)

1.2 Cleaning

  • Control characters removed, line endings normalised.
  • Hard-wrapped lines re-joined (a newline followed by indentation is kept as a paragraph break).
  • Train split only: title-only articles (body shorter than 30 characters), exact duplicates and articles that also occur in validation or test were removed. Validation and test keep every non-empty article, so evaluation stays close to the official splits.
split before after removed
train 17262 15098 2164
validation 2158 2152 6
test 2158 2145 13

Train rows removed by reason: {'title-only / body too short': 1234, 'duplicate inside train': 200, 'empty text': 718, 'also in validation/test': 12}.

1.3 Tokenization and blocks

The tokenizer is a byte-level BPE tokenizer with 52,000 entries. An end-of-text token (<|endoftext|>, id 0) is appended to every article. All articles are joined into one token stream and cut into blocks of 256 tokens (no padding, no truncation). Validation and test use these fixed blocks. Training draws random 256-token windows from the training stream, so every epoch shows new contexts.

split articles tokens blocks of 256
train 15098 2879531 11248
validation 2152 397753 1553
test 2145 309956 1210

Article length in tokens (training split). The dashed line marks the block size.

Article length in tokens (training split). The dashed line marks the block size.

2. Model

GPT2LMHeadModel created from a GPT2Config (random weights, input and output embeddings tied).

Setting Value
Layers / heads / embedding size 6 / 6 / 384
Context length 256 tokens
Vocabulary 52,000
Dropout 0.1
Total parameters 30,713,856
Token embeddings 19,968,000 (65.0%)
Transformer blocks 10,646,784 (34.7%)
Position embeddings 98,304 (0.3%)

The parameter count follows VΒ·d + TΒ·d + LΒ·(12dΒ² + 13d) + 2d and was checked against the counted value in the notebook. The untrained model had a loss of 10.91, close to ln(52,000) = 10.86, which is the loss of a uniform guess.

3. Training

Setting Value
Epochs / optimiser steps 5 / 3515 (best checkpoint at step 3515)
Effective batch 16 sequences of 256 tokens
Optimiser AdamW (beta2 0.95, weight decay 0.1)
Learning rate 0.0005, linear warm-up for 175 steps, then cosine decay
Gradient clipping 1.0
Precision fp16
Evaluation every 351 steps on the validation blocks, best model kept
Seed 42
Software transformers 5.22.1, torch 2.14.1+cu130

Training and validation loss (left), learning-rate schedule (middle), gradient norm before clipping (right)

Training and validation loss (left), learning-rate schedule (middle), gradient norm before clipping (right)

Validation loss during training:

step epoch eval_loss val_ppl
351.0 0.4993 5.3807 217.1759
1053.0 1.4979 4.7026 110.2282
1755.0 2.4964 4.426 83.5949
2457.0 3.495 4.2926 73.1592
3159.0 4.4936 4.2298 68.7067
3515.0 5.0 4.2257 68.4241

4. Evaluation

Split Loss Perplexity Top-1 accuracy Top-5 accuracy
Train (evaluation mode, subset) 3.7405 42.12
Validation 4.2257 68.42 33.8% 52.5%
Test 4.0241 55.93 37.3% 54.7%

Loss is the mean cross-entropy per token (not per word), and perplexity is exp(loss).

Does the model improve and does validation track training? Validation loss fell from 5.381 to 4.226, and the gains became very small at the end (the last evaluation changed the loss by 0.0000). Training and validation loss moved together, but a gap remains.

run epochs learning_rate train loss val_loss test_loss gap: val - train test - val
ref 5 0.0005 3.7405 4.2257 4.0241 0.4852 -0.2016
epochs_2 2 0.0005 4.4069 4.7083 4.464 0.3014 -0.2443
batch_32 5 0.0005 3.8269 4.2824 4.0676 0.4556 -0.2149

The gap between validation and training loss is 0.49 in the reference run. It grows with training time, which indicates mild overfitting. The test loss is lower than the validation loss in every run. This is a property of the splits (the test split has shorter articles and more empty bodies), not a sign of leakage.

Training and validation loss of the reference run, with the gap shaded

Training and validation loss of the reference run, with the gap shaded

5. Controlled experiments

Two extra runs were trained from fresh random weights. Each changes one setting of the reference run (epochs_2: 5 β†’ 2 epochs, batch_32: effective batch 16 β†’ 32, which halves the number of updates). Data, seed, model size and learning rate are identical.

run epochs effective_batch n_layer n_embd random_windows total_steps train_minutes train loss val_loss val_ppl test_loss test_ppl val top-1 % val top-5 %
ref 5 16 6 384 True 3515 9.57 3.7405 4.2257 68.4241 4.0241 55.9316 33.8 52.5
epochs_2 2 16 6 384 True 1406 4.18 4.4069 4.7083 110.8616 4.464 86.8336 29.3 46.9
batch_32 5 32 6 384 True 1760 9.73 3.8269 4.2824 72.4168 4.0676 58.4146 32.8 51.2

Validation loss of all runs against optimiser step and epoch

Validation loss of all runs against optimiser step and epoch

Findings

  • Training length: 2 epochs gave a validation loss that is +0.483 compared with the reference. Outputs of the shorter run are shorter, end early with Reuter and contain more broken fragments.
  • Batch size / number of updates: the validation loss changed by +0.057 with half as many updates. This comes from a single seed, so it is weak evidence and may be partly random variation.
  • A lower loss gave more complete and slightly more sensible text, but none of the runs fixed coherence. With a cosine schedule, "2 epochs" is not the same as stopping the 5-epoch run early.

Limitations

The evidence comes from the tables above and from notebook Sections 7.3 and 7.4.

  1. Small training corpus. 2,879,488 tokens per epoch and 14,397,440 tokens seen in 5 epochs. This is 0.47 tokens per parameter, while compute-optimal scaling studies suggest about 20 (about 614,277,120 tokens). The model is strongly data-limited, and more epochs on the same data give little gain.
  2. Capacity is spent on the vocabulary. The embedding table holds 65.0% of the parameters. 7,912 of 52,000 vocabulary entries never occur in training and 19,105 occur fewer than 5 times.
  3. Short context (256 tokens). Long articles are seen in pieces, and the loss rises with article length. The model cannot keep a topic over several paragraphs.
  4. Narrow domain and time. Only financial newswire from 1987. The model has no knowledge of other domains (see the ROMEO: / JULIET: results) and uses vocabulary and abbreviations of that period (dlrs, mln, pct).
  5. No factual knowledge. Names, companies and figures in the generated text are invented and can look plausible. Generated text must never be read as news.
  6. Weak coherence and repetition. Generated text drifts from the title and falls into repetition under loose decoding. Decoding rules reduce this but do not remove it.
  7. Generalisation gap. Train loss in evaluation mode is 3.74 against 4.23 for validation (gap 0.49), and the gap widens with training time.
  8. Evaluation caveats. The test loss is lower than the validation loss in every run because of the properties of the splits, so the two numbers should not be compared as if they were measured on identical data. The reported validation loss belongs to the checkpoint that was chosen because it had the lowest validation loss, so it is slightly optimistic. The test loss is the unbiased estimate.
  9. Perplexity of generated text is biased low and is not a quality measure. Fluency and coherence were judged by reading samples (three prompts), not by a large human or automatic evaluation.
  10. One seed per run. Small differences between runs (for example the batch-size comparison) cannot be separated from random variation.
  11. Token-level metric. Loss and perplexity are per BPE token. They are not comparable with word-level perplexity or with models that use another tokenizer.

Risks and ethical considerations

The model can produce fluent but false news-like text. It reflects the topics, style and possible biases of 1987 financial reporting. It should be used only for learning and analysis, not for generating or publishing news, and any generated text must be marked as synthetic.

Possible improvements

More text (for example several years of news), a longer context, a vocabulary that fits the corpus size, several seeds for the comparisons, and a larger human evaluation of fluency and coherence.

How to use

import torch
from transformers import AutoTokenizer, GPT2LMHeadModel

repo = "fernandonpa22/gpt2-reuters-scratch"
tok = AutoTokenizer.from_pretrained(repo)
model = GPT2LMHeadModel.from_pretrained(repo).eval()

def encode_title(title):
    # Training format: <EOS> + title + blank line. Tokenizing "title\n\n" alone would merge the two
    # newlines into one token that never occurs inside training articles, so a sentinel word is added and removed again.
    ids = tok(title + "\n\nThe", add_special_tokens=False)["input_ids"]
    ids = ids[:-len(tok("The", add_special_tokens=False)["input_ids"])]
    return torch.tensor([[tok.eos_token_id] + ids])

x = encode_title("U.S. MAY END ADDITIONAL SANCTIONS AGAINST JAPAN")
out = model.generate(x, attention_mask=torch.ones_like(x), do_sample=True, temperature=0.6, top_k=40, top_p=0.9,
                     no_repeat_ngram_size=3, max_new_tokens=100, pad_token_id=tok.eos_token_id, eos_token_id=tok.eos_token_id)
print(tok.decode(out[0][x.shape[1]:], skip_special_tokens=True))

The model needs the prompt format used in training (<EOS> + title + blank line). Prompts that are not newswire headlines produce news-like text anyway (see Section 8.1).

Reproducibility and files

  • Seed 42, one training run per configuration, all settings are in the CFG dictionary of the notebook. Trained on Tesla T4.
  • Cleaned data, token blocks and token streams were saved by the notebook in the project folder (data/). The numbers in this card were generated from the notebook variables.
File Content
model.safetensors, config.json, generation_config.json trained weights and configuration
tokenizer files ingeniumacademy/gpt2-reuters-tokenizer (unchanged)
ref_log_history.csv, ref_summary.json training log and run summary
q4_comparison.csv, q2_final_table.csv result tables
generations_ref.csv, generations_decoders.csv, generations_all_runs.csv generated samples with perplexity
q5_loss_by_token_class.csv, q6_*.csv, q7_top10.csv, q8_pairs_summary.csv analysis tables
figures/ all figures used in this card

Acknowledgements. Dataset: ingeniumacademy/reuters_articles. Tokenizer: ingeniumacademy/gpt2-reuters-tokenizer. Libraries: Hugging Face Transformers, PyTorch.

Downloads last month
98
Safetensors
Model size
30.7M params
Tensor type
F32
Β·
Inference Providers NEW
This model isn't deployed by any Inference Provider. πŸ™‹ Ask for provider support

Dataset used to train fernandonpa22/gpt2-reuters-scratch