An end-to-end Neural Machine Translation (NMT) system that translates French sentences into English. The entire model, tokenizer, and decoding pipeline are built strictly from scratch in Python using PyTorch solely for tensor math, automatic differentiation, and hardware acceleration. No pre-trained models (such as Hugging Face transformers or MarianMT) or pre-existing weights are used.
- Overview & Architecture
- Key Architectural Improvements
- Mathematical Foundations
- Byte-Pair Encoding (BPE) Tokenizer
- Dataset Pipeline & Kaggle / Web Integration
- Training Strategy
- Inference: Optimized Beam Search
- Evaluation & Quality Metrics
- Project Structure
- Installation & Quick Start
- CLI Arguments Reference
The system implements an enhanced Seq2Seq Transformer architecture with an auto-regressive decoder:
French Source Sentence ("Je voudrais un cafΓ©.")
β
βΌ
[ BPE Tokenizer (French Vocab: 8000) ]
β
βΌ Token IDs: [2, 45, 128, 12, 89, 3] -> Shape: [Batch, Length]
β
ββββββ΄βββββββββββββββββββββββββββββββββββββββββββββββ
β ENCODER β
β Token Embeddings -> Shape: [B, L, 256] β
β + Positional Encodings -> Shape: [B, L, 256] β
β βββββββββββββββββββββββββββββββββββββββββββββββ β
β β Self-Attention (8 h) -> Shape: [B, L, 256] β β x 4
β β FFNN (d_ff=1024) -> Shape: [B, L, 256] β β Layers
β βββββββββββββββββββββββββββββββββββββββββββββββ β
ββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ
β Encoder Memory Representation
βΌ (Shape: [Batch, Length, 256])
βββββββββββββββββββββββββββββββββββββββββββββββββββββ
β DECODER β
β Target Tokens -> Shape: [B, L, 256] β
β + Positional Encodings -> Shape: [B, L, 256] β
β βββββββββββββββββββββββββββββββββββββββββββββββ β
β β Masked Attention -> Shape: [B, L, 256] β β x 4
β β Cross-Attention -> Shape: [B, L, 256] β β Layers
β β FFNN (d_ff=1024) -> Shape: [B, L, 256] β β
β βββββββββββββββββββββββββββββββββββββββββββββββ β
β Output Linear Head -> Shape: [B, L, 8000] β
ββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ
β
βΌ Logits (Shape: [Batch, Length, 8000])
Optimized Beam Search (k=5)
β
βΌ
English Translation ("I would like a coffee.")
-
GELU Activations: Replaced standard ReLU with Gaussian Error Linear Units (
nn.GELU()) in feed-forward networks, providing smoother gradients and richer representation capacity. -
Weight Tying: The target token embedding matrix is tied directly with the output linear projection matrix (
generator.weight = tgt_tok_embed.embedding.weight). This cuts parameter count in half for vocabulary projections and accelerates vocabulary learning. -
Fused Attention Kernels: Utilizes PyTorch's native
F.scaled_dot_product_attentionfor 2-4x higher execution throughput and reduced memory consumption on both CPU and GPU. -
Pre-LN with Deep Residual Scaling: Normalization is computed prior to attention and feed-forward sub-layers (Pre-LN), combined with depth-dependent residual scaling factors (
$1/\sqrt{2N_{enc}}$ and$1/\sqrt{3N_{dec}}$ ), guaranteeing stable gradient flow. -
Decoupled Weight Decay (AdamW): Weight decay (
$10^{-2}$ ) is applied strictly to multi-dimensional weight matrices while disabling decay on LayerNorm parameters and biases. - Optimized Beam Search Exclusively: Greedy decoding has been replaced across the pipeline by Beam Search featuring length normalization and 3-gram repetition blocking.
-
Automatic Mixed Precision (AMP): Uses
torch.amp.autocastandGradScalerto accelerate training on GPUs, reducing memory usage and speeding up iterations. -
PyTorch 2.0 Compilation: Optional
torch.compile()support to fuse operations and optimize the computational graph. -
Optimized Dataloading: Asynchronous data loading with
num_workers=4andpin_memory=Trueto eliminate host-to-device transfer bottlenecks.
(Note: B = Batch Size, L = Sequence Length, d_model = 256, h = 8 heads, d_k = d_v = 32, d_ff = 1024, V_size = 8000)
Deterministic sinusoidal encodings provide positional order. The resulting tensor
Given Query (
-
$QK^T \in \mathbb{R}^{B \times h \times L \times L}$ (Attention scores) -
$M \in \mathbb{R}^{B \times 1 \times L \times L}$ or$\mathbb{R}^{1 \times 1 \times L \times L}$ (Mask tensor) - Output
$\in \mathbb{R}^{B \times h \times L \times d_k}$
Multi-Head Attention projects inputs into
-
Padding Mask: Boolean tensor of shape
$(B, 1, 1, L)$ . Prevents attention to<PAD>tokens. -
Causal (Look-Ahead) Mask: Upper-triangular boolean tensor of shape
$(1, 1, L, L)$ ensuring position$t$ only attends to positions$\le t$ .
For input tensor
Where
Target embedding weights are shared with the final projection head to output vocabulary logits
Built from scratch (app/tokenizer/):
- Subword segmentation via iterative pair merges.
- End-of-word markers
</w>preserve morphology and avoid word boundary ambiguity. - Special tokens:
<PAD>(0),<UNK>(1),<BOS>(2),<EOS>(3).
- Automatic HuggingFace Download: Downloads the high-quality OPUS Books French-English literary corpus (
opus_books) via the HuggingFacedatasetslibrary. This provides rich, naturally long, and grammatically complex sentences compared to standard flashcard datasets. - Local Kaggle Support: Load any local Kaggle CSV/TSV via
--source local --kaggle-file path/to/dataset.csv. - Cleaning & Splits: Normalizes unicode (
NFKC), ensures sequences retain natural length variation without artificial truncations (to properly train on long sequences), and splits data into 80/10/10 Train/Validation/Test splits.
Weights with dimension
Cross-entropy loss with label_smoothing=0.1 and ignore_index=PAD_IDX.
The system uses Beam Search as its definitive decoding strategy:
An active n-gram filter (no_repeat_ngram_size=3) discards any candidate token that would create a repeated trigram, eliminating repetitive loops.
Translation/
βββ app/
β βββ tokenizer/ # Custom BPE Tokenizer
β β βββ vocabulary.py # Vocabulary mapping & special tokens
β β βββ tokenizer.py # Subword segmentation, encode & decode
β β βββ train_bpe.py # BPE merge training algorithm
β βββ data/ # Dataset processing & acquisition
β β βββ download.py # Internet / Kaggle dataset downloader
β β βββ clean.py # Unicode normalization & filtering
β β βββ split.py # Train / Validation / Test splitter
β β βββ dataset.py # PyTorch Dataset & dynamic batch collator
β βββ model/ # High-Performance Transformer Seq2Seq
β β βββ embeddings.py # TokenEmbedding & PositionalEncoding
β β βββ attention.py # Fused MultiHeadAttention (8 heads)
β β βββ masks.py # Padding & Causal look-ahead masks
β β βββ encoder.py # Pre-LN EncoderLayer (GELU) & TransformerEncoder
β β βββ decoder.py # Pre-LN DecoderLayer (GELU) & TransformerDecoder
β β βββ transformer.py # Seq2Seq Transformer with Weight Tying
β βββ training/ # Training pipeline
β β βββ scheduler.py # Noam learning rate scheduler
β β βββ validate.py # Validation evaluation loop
β β βββ checkpoint.py # Checkpoint serialization
β β βββ train.py # AdamW training loop with Teacher Forcing
β βββ inference/ # Autoregressive generation
β β βββ beam_search.py # Optimized Beam Search with repetition blocking
β βββ evaluation/ # Evaluation metrics & error reports
β β βββ chrf.py # chrF character F-score implementation
β β βββ error_analysis.py # Repetition, omission & hallucination analysis
β βββ interface/ # User interface & High-level API
β βββ api.py # Translator wrapper class (Beam Search)
β βββ app.py # Interactive CLI chatbot
βββ main.py # Automated end-to-end pipeline runner
βββ README.md # Project documentation
# Create and activate virtual environment
python3 -m venv .venv
source .venv/bin/activate
# Install PyTorch, NumPy, and HuggingFace datasets
pip install torch numpy datasets# Standard training run on the OPUS Books literary dataset (~50k sentences, 15 epochs)
.venv/bin/python main.py --source internet --skip-memorize --epochs 15
# Fast testing run on a small subset
.venv/bin/python main.py --source internet --max-samples 10000 --epochs 5 --vocab-size 2000Launch the interactive chat interface directly:
.venv/bin/python main.py --chatOr launch directly from a saved checkpoint:
.venv/bin/python app/interface/app.py checkpoints/best_model.pt data/tokenizers/tokenizer_fr.json data/tokenizers/tokenizer_en.jsonChatbot Commands:
- Type any French sentence to translate it into English.
/beam <size>: Adjust beam search width (e.g./beam 5)./aide: Display command help./quitter: Exit the chatbot.
| Argument | Type | Default | Description |
|---|---|---|---|
--source |
str |
"internet" |
Data source ("internet" for Tatoeba/Kaggle download, or "local"). |
--max-samples |
int |
None |
Number of sentence pairs to extract (None for all). |
--kaggle-file |
str |
None |
Path to a local CSV/TSV Kaggle dataset when --source local. |
--epochs |
int |
10 |
Number of training epochs. |
--vocab-size |
int |
8000 |
Target BPE vocabulary size. |
--batch-size |
int |
32 |
Training batch size. |
--beam-size |
int |
5 |
Beam search width for inference. |
--skip-memorize |
flag |
False |
Skip the step 4 memorization sanity check. |
--chat |
flag |
False |
Automatically launch the interactive chatbot. |
--force-train |
flag |
False |
Force retraining even if a checkpoint exists when using --chat. |