Hand-built attention
Q, K and V projections, scaled attention scores, padding masks and a learned output projection.
Explore a hand-built Transformer encoder for binary sentiment classification: multi-head self-attention, positional encoding, residual blocks, and PyTorch training—from an offline smoke test to Yelp Polarity experiments.
Implementation walkthrough · Source code and dependencies are public · Real-data modes use an existing MiniLM tokenizer and frozen token embeddings.
Contextual token representations
Q · K · V → Encoder blocks → Masked pooling
INSIDE THE IMPLEMENTATION
Rather than calling a pretrained encoder for classification, the project constructs attention and Transformer blocks directly from PyTorch layers. The same code supports a manual attention path and an optimized SDPA path.
Q, K and V projections, scaled attention scores, padding masks and a learned output projection.
Switch between explicit attention math and PyTorch’s scaled dot-product attention using --sdpa.
Fixed sinusoidal positions give the encoder sequence-order information without learned position parameters.
Configurable encoder layers with residual paths and LayerNorm before both attention and feed-forward branches.
Each block applies two linear transformations with a GELU nonlinearity, followed by a residual connection.
Masked mean pooling excludes padding tokens before the linear classification head.
AdamW, cross-entropy, gradient clipping, a fixed seed and best-validation-accuracy checkpoint selection.
Held-out test evaluation after checkpoint reload; optional model-diagram export using torchview and Graphviz.
SYSTEM ARCHITECTURE
Follow the flow of a review through tokenization, frozen wordpiece embeddings, the custom encoder and a binary classification head. The drawing reflects the structure described in the Python source.
THREE EXECUTION MODES
All modes share the same custom encoder; dataset loading and training configurations differ. The real-data modes download Yelp Polarity data and MiniLM resources unless already cached.
Synthetic Yelp-style review samples, a tiny tokenizer and random frozen embeddings. Exercises the complete training, checkpoint reload and evaluation path without a model download.
Uses the Yelp Polarity dataset, a pretrained MiniLM tokenizer and frozen input embeddings. Enables the attention implementation and training configuration to be studied on real reviews.
A larger requested dataset and longer training preset. GPU acceleration is optional when PyTorch detects CUDA; memory and runtime depend on hardware and review filtering.
Real-data sample counts are requested values: length filtering can reduce the number of eligible examples. The smoke test is a correctness exercise, not a benchmark for Yelp accuracy.
RUN IT LOCALLY
Use the commands below from Windows PowerShell. The script also runs in compatible Linux and macOS environments. For a first test, choose the offline smoke mode.
git clone https://github.com/su394611-del/LLM-from-scratch.git
cd LLM-from-scratch
py -3.12 -m venv .venv
.\.venv\Scripts\Activate.ps1
python -m pip install --upgrade pip
python -m pip install -r requirements.txt
python -m pip checkpython transformer_from_scratch.py --smoke-testpython transformer_from_scratch.py --train --sdpapython transformer_from_scratch.py --full --sdpapython transformer_from_scratch.py --train --sdpa `
--train-size 2000 --val-size 300 --test-size 300 `
--batch-size 4 --max-len 128 --epochs 3 `
--n-layers 3 --n-heads 6 --lr 0.0002python -m pip install torchview graphviz
python transformer_from_scratch.py --smoke-test --visualizeEVALUATION & REPRODUCIBILITY
The implementation separates training, validation and test data. It selects the best checkpoint by validation accuracy, reloads that checkpoint and reports held-out test accuracy.
Cross-entropy classification loss is optimized with AdamW. Gradient norms are clipped and a seed is set for repeatability. Training and validation losses and accuracies are printed after each epoch.
The project README reports a completed offline smoke test and saved checkpoint. It does not provide a standardized external benchmark or independently reproducible performance record in this website.
READ THE SOURCE
Review the code, execution instructions, dependencies, and source documentation on GitHub. The wiki navigation is linked, but its separate content was not independently retrieved for this page.
Explore the project structure, revision history and complete implementation.
View repository ↗PyTorch implementationAttention projections, encoder layers, pooling, data loading and training loop.
Read Python source ↗README & setupFull installation instructions, CLI flags, experiment presets and troubleshooting.
Open README ↗Python dependenciesPackage requirements for the smoke test and real-data training modes.
View requirements ↗GitHub WikiProject wiki navigation and any published architecture or reference pages.
Open wiki ↗AI engineering portfolioExplore related work in retrieval, agent workflows, model training and inference.
Explore portfolio ↗