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

Property Value
Architecture GPT-2 (GPT2LMHeadModel)
Task Causal language modeling / text generation
Language English
Parameter count 16,504,320 (16.50M)
Vocabulary size 52,000
Context length 128 tokens
Embedding dimension 256
Transformer layers 4
Attention heads 4
Attention head dimension 64
Feed-forward hidden dimension 1,024
Activation function gelu_new
Attention, embedding and residual dropout 0.1 each
BOS / EOS / padding token ID 0
Framework PyTorch and Hugging Face Transformers
Weight initialization Random

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.

Split Articles 128-token blocks
Training 17,262 23,773
Validation 2,158 3,219
Test 2,158 2,475
Total 21,578 29,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

Hyperparameter Value
Epochs 5
Learning rate 0.0003 (3e-4)
Optimizer AdamW
Learning rate scheduler Constant
Training batch size 8
Evaluation batch size 8
Gradient accumulation steps 2
Effective training batch size 16
Weight decay 0.01
Mixed precision FP16
Random seed 42
Evaluation and logging frequency Every epoch
Training time 9.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)

Epoch Training loss Validation loss
1 5.416800 4.904490
2 4.453400 4.504122
3 4.079100 4.302712
4 3.825200 4.196773
5 3.628400 4.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.

Experiment Epochs Learning rate Training time (min) Validation loss Test loss Test perplexity
A β€” Baseline 2 0.0003 3.5677 4.504122 4.285723 72.655038
B β€” Increased epochs (published) 5 0.0003 9.1640 4.128728 3.944002 51.624774
C β€” Reduced learning rate 2 0.0001 3.8336 5.004303 4.766883 117.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

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

Dataset used to train InduwaraR/reuters-gpt2