A from-scratch implementation of RoBERTa (Robustly Optimized BERT Pre-training Approach) with masked language modeling (MLM) task, trained on diverse text data.
Overview
This project implements a RoBERTa-style transformer encoder model trained using the masked language modeling objective. The model learns to predict masked tokens in text sequences, developing a rich understanding of language patterns and semantics.
Load and authenticate with Hugging Face (requires HF_TOKEN in .env)
Generate corpus from combined datasets
Train SentencePiece tokenizer
Create text chunks and save as tensors
Initialize RoBERTa model
Train with masked language modeling objective
Save checkpoints and evaluate
Evaluation
The notebook includes:
Mask accuracy: Percentage of correctly predicted masked tokens
Embedding analysis:
Word embeddings visualization (3D and 2D PCA)
Sentence embeddings visualization
Similarity matrices between sequences
Key Features
✅ Custom transformer architecture - Built from scratch using PyTorch
✅ Efficient tokenization - SentencePiece BPE with 16K vocabulary
✅ Masked language modeling - Industry-standard pre-training objective
✅ Multi-source training data - Wikipedia, Alpaca, TinyStories
✅ Visualization tools - 3D embeddings and similarity analysis
✅ Checkpoint management - Save and resume training
Implementation Details
Special Design Choices
Dynamic masking guarantee: If a sequence has no masked tokens, at least one token is randomly selected for masking to ensure effective learning
Attention masking: Padding tokens are properly masked to prevent attention to pad positions
Residual connections: Applied in both attention and FFN blocks for training stability
GELU activation: Used instead of ReLU for smoother gradients and better performance
Layer normalization placement: Applied after each sublayer (post-norm) for numerical stability
Performance Metrics
The model tracks:
Training loss: Cross-entropy loss on masked tokens
Masking accuracy: Correct predictions / total masked tokens
Per-layer hidden states: For analysis and visualization