Skip to content

About

Simple Neuronal Network to translate from French to English

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

13 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

French β†’ English Neural Machine Translation System

High-Performance Encoder-Decoder Transformer Built From Scratch

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.


πŸ“‘ Table of Contents


πŸ›οΈ Overview & Architecture

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.")

⚑ Key Architectural Improvements

  1. GELU Activations: Replaced standard ReLU with Gaussian Error Linear Units (nn.GELU()) in feed-forward networks, providing smoother gradients and richer representation capacity.
  2. 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.
  3. Fused Attention Kernels: Utilizes PyTorch's native F.scaled_dot_product_attention for 2-4x higher execution throughput and reduced memory consumption on both CPU and GPU.
  4. 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.
  5. Decoupled Weight Decay (AdamW): Weight decay ($10^{-2}$) is applied strictly to multi-dimensional weight matrices while disabling decay on LayerNorm parameters and biases.
  6. Optimized Beam Search Exclusively: Greedy decoding has been replaced across the pipeline by Beam Search featuring length normalization and 3-gram repetition blocking.
  7. Automatic Mixed Precision (AMP): Uses torch.amp.autocast and GradScaler to accelerate training on GPUs, reducing memory usage and speeding up iterations.
  8. PyTorch 2.0 Compilation: Optional torch.compile() support to fuse operations and optimize the computational graph.
  9. Optimized Dataloading: Asynchronous data loading with num_workers=4 and pin_memory=True to eliminate host-to-device transfer bottlenecks.

πŸ“ Mathematical Foundations & Tensor Dimensions

(Note: B = Batch Size, L = Sequence Length, d_model = 256, h = 8 heads, d_k = d_v = 32, d_ff = 1024, V_size = 8000)

1. Sinusoidal Positional Encoding

Deterministic sinusoidal encodings provide positional order. The resulting tensor $PE \in \mathbb{R}^{L \times d_{model}}$ is added to the token embeddings:

$$PE_{(pos, 2i)} = \sin\left(\frac{pos}{10000^{2i / d_{model}}}\right)$$

$$PE_{(pos, 2i+1)} = \cos\left(\frac{pos}{10000^{2i / d_{model}}}\right)$$

2. Scaled Dot-Product Attention

Given Query ($Q$), Key ($K$), and Value ($V$) matrices, all $\in \mathbb{R}^{B \times h \times L \times d_k}$:

$$\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}} + M\right)V$$

  • $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}$

3. Multi-Head Attention (8 Heads)

Multi-Head Attention projects inputs into $h = 8$ representation subspaces. Input sequence $X \in \mathbb{R}^{B \times L \times d_{model}}$. Projection weights $W_i^Q, W_i^K, W_i^V \in \mathbb{R}^{d_{model} \times d_k}$ and $W^O \in \mathbb{R}^{d_{model} \times d_{model}}$.

$$\text{head}_i = \text{Attention}(XW_i^Q, XW_i^K, XW_i^V) \quad \in \mathbb{R}^{B \times L \times d_k}$$

$$\text{MultiHead}(X) = \text{Concat}(\text{head}_1, \dots, \text{head}_8)W^O \quad \in \mathbb{R}^{B \times L \times d_{model}}$$

4. Attention Masks

  • 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$.

5. Pre-LN Stacks with Residual Scaling

For input tensor $x^{(l)} \in \mathbb{R}^{B \times L \times d_{model}}$:

$$x^{(l+1)} = x^{(l)} + \lambda \cdot \text{SubLayer}(\text{LayerNorm}(x^{(l)}))$$

Where $\lambda = \frac{1}{\sqrt{2 N_{layers}}}$ for encoder layers and $\lambda = \frac{1}{\sqrt{3 N_{layers}}}$ for decoder layers.

6. Weight Tying

Target embedding weights are shared with the final projection head to output vocabulary logits $\in \mathbb{R}^{B \times L \times V_{size}}$:

$$W_{generator} = W_{tgt_embedding} \quad \in \mathbb{R}^{V_{size} \times d_{model}}$$


πŸ”€ Byte-Pair Encoding (BPE) Tokenizer

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).

🌐 Dataset Pipeline & Kaggle / Web Integration

  • Automatic HuggingFace Download: Downloads the high-quality OPUS Books French-English literary corpus (opus_books) via the HuggingFace datasets library. 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.

πŸ‹οΈ Training Strategy

AdamW with Decoupled Weight Decay

Weights with dimension $\ge 2$ receive $10^{-2}$ weight decay, while 1D biases and LayerNorm parameters receive $0.0$ decay.

Teacher Forcing & Label Smoothing

Cross-entropy loss with label_smoothing=0.1 and ignore_index=PAD_IDX.

Noam Learning Rate Scheduler

$$lr = d_{model}^{-0.5} \cdot \min(step^{-0.5}, step \cdot \text{warmup-steps}^{-1.5})$$


πŸ” Inference: Optimized Beam Search

The system uses Beam Search as its definitive decoding strategy:

Length Normalization (Wu et al.)

$$\text{score}(Y) = \frac{\log P(Y)}{\text{LP}(Y)}, \quad \text{LP}(Y) = \frac{(5 + |Y|)^\alpha}{(5 + 1)^\alpha} \quad (\alpha = 0.7)$$

Repetition Blocking

An active n-gram filter (no_repeat_ngram_size=3) discards any candidate token that would create a repeated trigram, eliminating repetitive loops.


πŸ“ Project Structure

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

πŸš€ Installation & Quick Start

1. Installation

# Create and activate virtual environment
python3 -m venv .venv
source .venv/bin/activate

# Install PyTorch, NumPy, and HuggingFace datasets
pip install torch numpy datasets

2. Running the Full Pipeline

# 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 2000

3. Interactive Translation Chatbot

Launch the interactive chat interface directly:

.venv/bin/python main.py --chat

Or 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.json

Chatbot 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.

βš™οΈ CLI Arguments Reference

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.

About

Simple Neuronal Network to translate from French to English

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Contributors

Languages