TRANSFORMER FROM SCRATCH IN PYTORCH: FULL ENCODER-DECODER ARCHITECTURE ASSEMBLY

Industrial reference and low-level engineering implementation manual for B.Tech Computer Science, Data Science, and AI Engineers: Complete end-to-end assembly of the canonical Transformer model without high-level library abstractions. Detailed implementation of scaled dot-product attention, multi-head tensor routing, sinusoidal and learned position encodings, position-wise feed-forward networks, masking mechanics, cross-attention memory binding, and complete training and generation loops in pure PyTorch.

πŸ› οΈ Demystifying the Black Box: Complete Architectural Assembly from First Principles

While frameworks such as Hugging Face Transformers and PyTorch's native nn.Transformer provide modular, production-ready building blocks, true mastery of Generative AI architectures requires the ability to assemble the complete model from foundational tensor primitives. Constructing a complete Encoder-Decoder Transformer from scratch exposes the exact computational bottlenecks, matrix permutations, gradient routing pathways, and dimensional transitions that occur within every forward pass. In this module, we assemble every isolated mathematical component developed across earlier chaptersβ€”sinusoidal embeddings, 4D tensor-reshaped multi-head attention, Pre-LN layer normalization, residual additive highways, causal masking, cross-attention projections, and weight-tied linear headsβ€”into an industrial, cleanly modularized, and verifiable PyTorch implementation.

1. End-to-End System Topography: The Canonical Encoder-Decoder Blueprint
Complete architectural mapping: Ingestion of source and target token indices, dimensional transformations across embedding layers, stacked encoder blocks, cross-attention binding, decoder generation, and final logit projection.
ASCII Architecture: Canonical Encoder-Decoder Dataflow & Dimensional Routing
COMPLETE ENCODER-DECODER TRANSFORMER TOPOLOGY (Vaswani et al., 2017):

         SOURCE INPUT SEQUENCE                              TARGET INPUT SEQUENCE
      (Tokens: B Γ— S_src, e.g. French)                   (Shifted Right: B Γ— S_tgt, e.g. English)
                     β”‚                                                      β”‚
                     β–Ό Input Embedding + Pos Encoding                       β–Ό Output Embedding + Pos Encoding
           β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                                   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
           β”‚ E_src ∈ R^{BΓ—SΓ—d}β”‚                                   β”‚ E_tgt ∈ R^{BΓ—SΓ—d}β”‚
           β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜                                   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                     β”‚                                                      β”‚
                     β–Ό                                                      β–Ό
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  β”‚      ENCODER STACK (N Layers)       β”‚                β”‚      DECODER STACK (N Layers)       β”‚
  β”‚                                     β”‚                β”‚                                     β”‚
  β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚                β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
  β”‚  β”‚ Pre-LN Multi-Head Self-Attn   β”‚  β”‚                β”‚  β”‚ Pre-LN Causal Masked Self-Attnβ”‚  β”‚
  β”‚  β”‚ (Unmasked Bidirectional)      β”‚  β”‚                β”‚  β”‚ (Lower-Triangular Mask)       β”‚  β”‚
  β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚                β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
  β”‚                  β”‚ Residual (+)     β”‚                β”‚                  β”‚ Residual (+)     β”‚
  β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚                β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
  β”‚  β”‚ Pre-LN Position-wise FFN      β”‚  β”‚                β”‚  β”‚ Pre-LN Cross-Attention        β”‚  β”‚
  β”‚  β”‚ (d_ff = 4 Β· d_model)          β”‚  β”‚                β”‚  β”‚ Q: Decoder, K,V: Encoder Mem  │◄─┼── Encoder Memory
  β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚                β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚   H_enc ∈ R^{BΓ—S_srcΓ—d}
  β”‚                  β”‚ Residual (+)     β”‚                β”‚                  β”‚ Residual (+)     β”‚
  β”‚                  β–Ό                  β”‚                β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
  β”‚     Output of Layer N: H_enc        β”‚                β”‚  β”‚ Pre-LN Position-wise FFN      β”‚  β”‚
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                β”‚  β”‚ (d_ff = 4 Β· d_model)          β”‚  β”‚
                     β”‚                                   β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
                     β”‚                                   β”‚                  β”‚ Residual (+)     β”‚
                     └───────────────────────────────────┼─────────────────►│                  β”‚
                                                         β”‚                  β–Ό                  β”‚
                                                         β”‚     Output of Layer N: H_dec        β”‚
                                                         β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                                            β”‚
                                                                            β–Ό Final LayerNorm
                                                                 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                                                                 β”‚ Linear Head + Softmaxβ”‚
                                                                 β”‚ W_vocab ∈ R^{dΓ—|V|}  β”‚
                                                                 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                                            β”‚
                                                                            β–Ό
                                                                 TARGET LOGITS: B Γ— S_tgt Γ— |V|
Tensor Dimensional Protocol: Throughout the entire network stack, tensor shapes strictly obey the following tensor dimensional invariant: β€’ Source Tokens: $(B, S_{\text{src}})$ βž” Source Embeddings: $(B, S_{\text{src}}, d_{\text{model}})$ β€’ Encoder Representation ($H_{\text{enc}}$): $(B, S_{\text{src}}, d_{\text{model}})$ β€’ Target Tokens: $(B, S_{\text{tgt}})$ βž” Target Embeddings: $(B, S_{\text{tgt}}, d_{\text{model}})$ β€’ Decoder Representation ($H_{\text{dec}}$): $(B, S_{\text{tgt}}, d_{\text{model}})$ β€’ Final Emission Logits: $(B, S_{\text{tgt}}, |V_{\text{target}}|)$
2. Embeddings & Positional Encoding Primitives
Constructing the input layer: Word token embedding lookup scaled by $\sqrt{d_{\text{model}}}$, precomputing continuous sinusoidal frequency encodings, and dropout regularization.
Python / PyTorch (transformer_scratch/embeddings.py: Token & Positional Ingestion)
import math
import torch
import torch.nn as nn

class TransformerEmbedding(nn.Module):
    """
    Combines token dictionary embeddings with fixed sinusoidal positional encodings.
    Applies the canonical sqrt(d_model) scaling factor before addition.
    """
    def __init__(self, vocab_size: int, d_model: int, max_len: int = 5000, dropout: float = 0.1):
        super().__init__()
        self.d_model = d_model
        self.lut = nn.Embedding(vocab_size, d_model)
        self.dropout = nn.Dropout(p=dropout)

        # Precompute sinusoidal positional encodings up to max_len
        pe = torch.zeros(max_len, d_model)
        position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
        div_term = torch.exp(
            torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model)
        )

        pe[:, 0::2] = torch.sin(position * div_term)
        pe[:, 1::2] = torch.cos(position * div_term)

        # Register as non-trainable persistent buffer: Shape (1, max_len, d_model)
        pe = pe.unsqueeze(0)
        self.register_buffer('pe', pe)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        x: Tensor of token indices with shape (Batch_Size, Seq_Len)
        Returns: Embedded and position-conditioned tensor of shape (Batch_Size, Seq_Len, d_model)
        """
        seq_len = x.size(1)
        # Multiply token embedding by sqrt(d_model) to prevent positional encoding dominance
        token_emb = self.lut(x) * math.sqrt(self.d_model)
        pos_emb = self.pe[:, :seq_len, :]
        return self.dropout(token_emb + pos_emb)
The $\sqrt{d_{\text{model}}}$ Embedding Scaling Factor: Vaswani et al. multiply the token embeddings by $\sqrt{d_{\text{model}}}$ prior to adding the positional encodings. When embedding layers are initialized with variance $\sigma^2 \propto 1/d_{\text{model}}$, the expected norm of an embedding vector is $O(1)$. Multiplying by $\sqrt{d_{\text{model}}}$ scales token embedding variance to $O(d_{\text{model}})$, ensuring that learned semantic vectors maintain dominant signal magnitude over the static unit-amplitude sinusoidal vectors $[-1.0, +1.0]$.
3. Multi-Head Attention Engine: Generalized Self- & Cross-Attention
Building the generalized multi-head attention core: Unified module supporting self-attention, causal autoregressive self-attention, and cross-attention through distinct Query, Key, and Value projections.
Python / PyTorch (transformer_scratch/attention.py: Generalized Multi-Head Attention)
import math
import torch
import torch.nn as nn
import torch.nn.functional as F

class MultiHeadAttentionBlock(nn.Module):
    """
    Generalized Multi-Head Attention supporting:
    1. Encoder Self-Attention: Q=K=V=X_src (with padding mask)
    2. Decoder Self-Attention: Q=K=V=X_tgt (with causal lower-triangular mask)
    3. Decoder Cross-Attention: Q=X_tgt, K=V=H_enc (with encoder padding mask)
    """
    def __init__(self, d_model: int, num_heads: int, dropout: float = 0.1):
        super().__init__()
        assert d_model % num_heads == 0, "d_model must be divisible by num_heads"

        self.d_model = d_model
        self.num_heads = num_heads
        self.d_k = d_model // num_heads
        self.scale = 1.0 / math.sqrt(self.d_k)

        # Separate projections for Queries, Keys, Values, and Final Output
        self.w_q = nn.Linear(d_model, d_model, bias=False)
        self.w_k = nn.Linear(d_model, d_model, bias=False)
        self.w_v = nn.Linear(d_model, d_model, bias=False)
        self.w_o = nn.Linear(d_model, d_model, bias=False)

        self.dropout = nn.Dropout(p=dropout)

    def forward(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, 
                mask: torch.Tensor = None) -> torch.Tensor:
        """
        q    : (Batch_Size, Seq_Len_Q, d_model)
        k    : (Batch_Size, Seq_Len_K, d_model)
        v    : (Batch_Size, Seq_Len_V, d_model)  [Seq_Len_K == Seq_Len_V]
        mask : Optional broadcastable mask (Batch, 1, Seq_Len_Q, Seq_Len_K)
               Boolean True indicates valid tokens, False indicates masked tokens.
        """
        batch_size = q.size(0)
        s_q = q.size(1)
        s_k = k.size(1)

        # 1. Linear Projections and Reshape to 4D: (B, S, H, d_k) -> Permute to (B, H, S, d_k)
        query = self.w_q(q).view(batch_size, s_q, self.num_heads, self.d_k).transpose(1, 2)
        key   = self.w_k(k).view(batch_size, s_k, self.num_heads, self.d_k).transpose(1, 2)
        value = self.w_v(v).view(batch_size, s_k, self.num_heads, self.d_k).transpose(1, 2)

        # 2. Compute Raw Scaled Affinity Scores: (B, H, S_q, d_k) x (B, H, d_k, S_k) -> (B, H, S_q, S_k)
        scores = torch.matmul(query, key.transpose(-2, -1)) * self.scale

        # 3. Apply Masking (Padding mask and/or Causal mask)
        if mask is not None:
            scores = scores.masked_fill(mask == 0, float('-inf'))

        # 4. Softmax Normalization across Key sequence axis
        attn_weights = F.softmax(scores, dim=-1)
        attn_weights = torch.nan_to_num(attn_weights, nan=0.0) # Guard against all-padded rows
        attn_weights = self.dropout(attn_weights)

        # 5. Weighted Value Accumulation: (B, H, S_q, S_k) x (B, H, S_k, d_k) -> (B, H, S_q, d_k)
        context = torch.matmul(attn_weights, value)

        # 6. Recombine heads: (B, H, S_q, d_k) -> (B, S_q, H, d_k) -> (B, S_q, d_model)
        context = context.transpose(1, 2).contiguous().view(batch_size, s_q, self.d_model)

        # 7. Final Output Affine Projection
        return self.w_o(context)
Unified Attention Abstraction: By designing MultiHeadAttentionBlock to accept distinct q, k, and v tensors, a single module handles: β€’ Encoder Self-Attention: forward(x, x, x, mask=src_pad_mask) β€’ Decoder Self-Attention: forward(y, y, y, mask=causal_and_pad_mask) β€’ Decoder Cross-Attention: forward(y, h_enc, h_enc, mask=src_pad_mask)
4. Encoder & Decoder Layer Blocks (Pre-LN Implementation)
Assembling the intermediate blocks: Position-wise Feed-Forward Networks, residual skip connections, Pre-LN layer normalization, and the cross-attention bridge.
Python / PyTorch (transformer_scratch/layers.py: Encoder & Decoder Blocks)
class PositionwiseFeedForward(nn.Module):
    """
    Two-layer dense projection network with intermediate ReLU / GELU expansion.
    FFN(x) = max(0, x W_1 + b_1) W_2 + b_2
    """
    def __init__(self, d_model: int, d_ff: int, dropout: float = 0.1):
        super().__init__()
        self.w_1 = nn.Linear(d_model, d_ff)
        self.w_2 = nn.Linear(d_ff, d_model)
        self.dropout = nn.Dropout(dropout)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.w_2(self.dropout(F.relu(self.w_1(x))))

# ==============================================================================
# ENCODER LAYER (Pre-LN Standard)
# ==============================================================================
class EncoderLayer(nn.Module):
    def __init__(self, d_model: int, num_heads: int, d_ff: int, dropout: float = 0.1):
        super().__init__()
        self.self_attn = MultiHeadAttentionBlock(d_model, num_heads, dropout)
        self.ffn = PositionwiseFeedForward(d_model, d_ff, dropout)
        self.norm1 = nn.LayerNorm(d_model)
        self.norm2 = nn.LayerNorm(d_model)
        self.dropout1 = nn.Dropout(dropout)
        self.dropout2 = nn.Dropout(dropout)

    def forward(self, x: torch.Tensor, src_mask: torch.Tensor) -> torch.Tensor:
        # Pre-LN Self-Attention + Residual
        norm_x = self.norm1(x)
        x = x + self.dropout1(self.self_attn(norm_x, norm_x, norm_x, mask=src_mask))
        # Pre-LN FFN + Residual
        norm_x = self.norm2(x)
        x = x + self.dropout2(self.ffn(norm_x))
        return x

# ==============================================================================
# DECODER LAYER (Pre-LN Standard)
# ==============================================================================
class DecoderLayer(nn.Module):
    def __init__(self, d_model: int, num_heads: int, d_ff: int, dropout: float = 0.1):
        super().__init__()
        self.self_attn = MultiHeadAttentionBlock(d_model, num_heads, dropout)
        self.cross_attn = MultiHeadAttentionBlock(d_model, num_heads, dropout)
        self.ffn = PositionwiseFeedForward(d_model, d_ff, dropout)
        self.norm1 = nn.LayerNorm(d_model)
        self.norm2 = nn.LayerNorm(d_model)
        self.norm3 = nn.LayerNorm(d_model)
        self.dropout1 = nn.Dropout(dropout)
        self.dropout2 = nn.Dropout(dropout)
        self.dropout3 = nn.Dropout(dropout)

    def forward(self, x: torch.Tensor, memory: torch.Tensor, 
                tgt_mask: torch.Tensor, src_mask: torch.Tensor) -> torch.Tensor:
        # 1. Causal Masked Self-Attention + Residual
        norm_x = self.norm1(x)
        x = x + self.dropout1(self.self_attn(norm_x, norm_x, norm_x, mask=tgt_mask))

        # 2. Cross-Attention over Encoder Memory + Residual
        norm_x = self.norm2(x)
        x = x + self.dropout2(self.cross_attn(norm_x, memory, memory, mask=src_mask))

        # 3. Position-wise FFN + Residual
        norm_x = self.norm3(x)
        x = x + self.dropout3(self.ffn(norm_x))
        return x
Residual Routing Law: In Pre-LN layers, normalization occurs strictly on the path feeding into the sub-layer projections. The residual bypass connection remains an unscaled, unnormalized identity channel, allowing loss gradients to backpropagate directly across the entire network depth without attenuation.
5. Complete Model Assembly: Full Seq2Seq Transformer Engine
Complete architectural assembly: Stacking $N$ encoder and decoder layers, embedding weight tying, output generator projection, and the unified forward pass.
Python / PyTorch (transformer_scratch/model.py: Full Encoder-Decoder Transformer)
class Transformer(nn.Module):
    """
    Canonical Encoder-Decoder Transformer Architecture assembled from scratch.
    Implements Pre-LN normalization, weight tying, and complete mask generation.
    """
    def __init__(self, src_vocab_size: int, tgt_vocab_size: int, 
                 d_model: int = 512, num_heads: int = 8, 
                 num_encoder_layers: int = 6, num_decoder_layers: int = 6, 
                 d_ff: int = 2048, dropout: float = 0.1, max_len: int = 5000):
        super().__init__()
        self.d_model = d_model

        # Embeddings & Positional Encodings
        self.src_embedding = TransformerEmbedding(src_vocab_size, d_model, max_len, dropout)
        self.tgt_embedding = TransformerEmbedding(tgt_vocab_size, d_model, max_len, dropout)

        # Encoder & Decoder Stacks
        self.encoder_layers = nn.ModuleList([
            EncoderLayer(d_model, num_heads, d_ff, dropout) 
            for _ in range(num_encoder_layers)
        ])
        self.decoder_layers = nn.ModuleList([
            DecoderLayer(d_model, num_heads, d_ff, dropout) 
            for _ in range(num_decoder_layers)
        ])

        # Final LayerNorms for Pre-LN stability
        self.encoder_norm = nn.LayerNorm(d_model)
        self.decoder_norm = nn.LayerNorm(d_model)

        # Output Vocabulary Projection Head
        self.generator = nn.Linear(d_model, tgt_vocab_size, bias=False)

        # Initialize weights via Xavier / Glorot uniform distribution
        self._init_parameters()

    def _init_parameters(self):
        for p in self.parameters():
            if p.dim() > 1:
                nn.init.xavier_uniform_(p)

    def encode(self, src: torch.Tensor, src_mask: torch.Tensor) -> torch.Tensor:
        """Processes raw source tokens through embedding and encoder layers."""
        x = self.src_embedding(src)
        for layer in self.encoder_layers:
            x = layer(x, src_mask)
        return self.encoder_norm(x)

    def decode(self, tgt: torch.Tensor, memory: torch.Tensor, 
               tgt_mask: torch.Tensor, src_mask: torch.Tensor) -> torch.Tensor:
        """Processes target tokens through embedding and decoder layers conditioned on encoder memory."""
        x = self.tgt_embedding(tgt)
        for layer in self.decoder_layers:
            x = layer(x, memory, tgt_mask, src_mask)
        return self.decoder_norm(x)

    def forward(self, src: torch.Tensor, tgt: torch.Tensor, 
                src_mask: torch.Tensor, tgt_mask: torch.Tensor) -> torch.Tensor:
        """
        Complete forward pass for supervised training with teacher forcing.
        src      : (Batch_Size, Src_Len)
        tgt      : (Batch_Size, Tgt_Len)
        src_mask : Broadcastable source padding mask
        tgt_mask : Combined target causal and padding mask
        Returns  : Unnormalized vocabulary logits (Batch_Size, Tgt_Len, tgt_vocab_size)
        """
        memory = self.encode(src, src_mask)
        decoder_output = self.decode(tgt, memory, tgt_mask, src_mask)
        return self.generator(decoder_output)
Weight Tying Optimization: In many production implementations, the target embedding lookup table matrix $\mathbf{W}_{\text{embed}}$ and the output generator linear projection weights $\mathbf{W}_{\text{out}}$ are shared (Weight Tying - Press & Wolf, 2017): self.generator.weight = self.tgt_embedding.lut.weight This cuts parameter counts by tens of millions of weights and prevents semantic misalignment between input representations and output probability projections.
6. Mask Construction Utilities: Causal & Padding Mask Generators
Essential data preparation helpers: Creating source padding masks and constructing combined lower-triangular causal masks that simultaneously prevent attention to future tokens and padding tokens.
Python / PyTorch (transformer_scratch/masks.py: Causal and Padding Mask Builders)
def create_padding_mask(seq: torch.Tensor, pad_idx: int = 0) -> torch.Tensor:
    """
    Generates a boolean padding mask.
    seq     : Tensor of shape (Batch_Size, Seq_Len)
    Returns : Tensor of shape (Batch_Size, 1, 1, Seq_Len) where True indicates valid tokens,
              and False indicates pad tokens (to be masked).
    """
    return (seq != pad_idx).unsqueeze(1).unsqueeze(2)

def create_causal_mask(size: int, device: torch.device) -> torch.Tensor:
    """
    Generates an upper-triangular boolean causal mask.
    size    : Sequence length integer
    Returns : Tensor of shape (1, 1, size, size) where True represents allowed attention,
              and False represents illegal future tokens.
    """
    # Lower-triangular matrix of ones
    mask = torch.tril(torch.ones(size, size, device=device, dtype=torch.bool))
    return mask.unsqueeze(0).unsqueeze(0)

def create_target_mask(tgt_seq: torch.Tensor, pad_idx: int = 0) -> torch.Tensor:
    """
    Combines target padding mask with target causal lower-triangular mask.
    tgt_seq : Tensor of shape (Batch_Size, Tgt_Len)
    Returns : Tensor of shape (Batch_Size, 1, Tgt_Len, Tgt_Len)
    """
    tgt_pad_mask = create_padding_mask(tgt_seq, pad_idx) # (B, 1, 1, Tgt_Len)
    tgt_len = tgt_seq.size(1)
    tgt_causal_mask = create_causal_mask(tgt_len, tgt_seq.device) # (1, 1, Tgt_Len, Tgt_Len)
    
    # Both conditions must be met: token must not be pad AND token must be in past
    return tgt_pad_mask & tgt_causal_mask
Broadcastable Shape Strategy: Notice the 4D unsqueeze pattern: (Batch_Size, 1, 1, Seq_Len). When added to or multiplied with the 4D attention affinity score tensor $\mathbf{S} \in \mathbb{R}^{B \times H \times S_q \times S_k}$, PyTorch broadcasts the singleton dimensions across all attention heads $H$ and query steps $S_q$ with zero memory replication.
7. Execution Pipeline: Verification, Autoregressive Inference & Loss Tracking
Complete runtime execution script: Setting up synthetic language data, executing the supervised forward pass, computing Label Smoothed Cross-Entropy Loss, and running greedy autoregressive decoding.
Python / PyTorch (transformer_scratch/train_eval.py: Complete Execution Script)
# ==============================================================================
# AUTOREGRESSIVE GREEDY DECODING LOOP (INFERENCE PIPELINE)
# ==============================================================================
def greedy_decode(model: Transformer, src: torch.Tensor, src_mask: torch.Tensor, 
                  max_len: int, start_symbol: int, end_symbol: int) -> torch.Tensor:
    """
    Generates target tokens one-by-one autoregressively using greedy search.
    """
    model.eval()
    device = src.device
    
    # Step 1: Compute encoder memory ONCE for the entire generation process
    with torch.no_grad():
        memory = model.encode(src, src_mask)

    # Step 2: Initialize target sequence with start-of-sequence token []
    ys = torch.full((1, 1), start_symbol, dtype=torch.long, device=device)

    for i in range(max_len - 1):
        tgt_mask = create_target_mask(ys, pad_idx=-1)
        with torch.no_grad():
            out = model.decode(ys, memory, tgt_mask, src_mask)
            prob = model.generator(out[:, -1]) # Logits of latest emitted token
            _, next_word = torch.max(prob, dim=1)
            next_word = next_word.item()

        # Append predicted token to target history
        ys = torch.cat([ys, torch.full((1, 1), next_word, dtype=torch.long, device=device)], dim=1)
        
        # Stop if end-of-sequence token [] is emitted
        if next_word == end_symbol:
            break

    return ys

# ------------------------------------------------------------------------------
# RUNTIME VERIFICATION SUITE
# ------------------------------------------------------------------------------
if __name__ == "__main__":
    torch.manual_seed(42)
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    
    # Model Hyperparameters
    SRC_VOCAB = 1000
    TGT_VOCAB = 1000
    D_MODEL   = 256
    NUM_HEADS = 8
    LAYERS    = 3
    D_FF      = 1024
    PAD_IDX   = 0
    BOS_IDX   = 1
    EOS_IDX   = 2

    print("[*] Initializing Canonical Transformer from Scratch...")
    model = Transformer(
        src_vocab_size=SRC_VOCAB,
        tgt_vocab_size=TGT_VOCAB,
        d_model=D_MODEL,
        num_heads=NUM_HEADS,
        num_encoder_layers=LAYERS,
        num_decoder_layers=LAYERS,
        d_ff=D_FF,
        dropout=0.1
    ).to(device)

    # Verify Parameter Count
    total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
    print(f"[βœ”] Model Instantiated. Total Trainable Parameters: {total_params:,}")

    # Generate Synthetic Translation Batch: Batch=2, Src_Len=10, Tgt_Len=8
    B = 2
    src = torch.randint(3, SRC_VOCAB, (B, 10), device=device)
    src[:, 8:] = PAD_IDX # Inject padding tokens
    
    tgt = torch.randint(3, TGT_VOCAB, (B, 8), device=device)
    tgt[:, 0] = BOS_IDX  # Start token
    tgt[:, 6:] = PAD_IDX # Inject padding tokens

    # Build Attention Masks
    src_mask = create_padding_mask(src, PAD_IDX)
    tgt_mask = create_target_mask(tgt, PAD_IDX)

    print(f"[*] Executing Supervised Training Forward Pass with Teacher Forcing...")
    # Forward Pass: Predict next tokens given target inputs
    logits = model(src, tgt, src_mask, tgt_mask)
    print(f"[βœ”] Forward Pass Completed. Target Logits Shape: {logits.shape} (Expected: [{B}, 8, {TGT_VOCAB}])")

    # Compute Cross-Entropy Loss with Label Smoothing
    criterion = nn.CrossEntropyLoss(ignore_index=PAD_IDX, label_smoothing=0.1)
    
    # Flatten across batch and sequence dimensions for standard loss evaluation
    loss = criterion(logits.view(-1, TGT_VOCAB), tgt.view(-1))
    print(f"[βœ”] Label-Smoothed Cross-Entropy Loss Computed: {loss.item():.4f}")

    # Backward Pass Verification
    loss.backward()
    grad_norm = nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
    print(f"[βœ”] Backpropagation Verified. Global Gradient Norm: {grad_norm.item():.4f}")

    # Test Autoregressive Inference
    print("[*] Testing Autoregressive Greedy Inference...")
    single_src = src[0:1, :]
    single_src_mask = create_padding_mask(single_src, PAD_IDX)
    generated_tokens = greedy_decode(model, single_src, single_src_mask, max_len=12, start_symbol=BOS_IDX, end_symbol=EOS_IDX)
    print(f"[βœ”] Inference Generation Complete. Generated Output Token Sequence: {generated_tokens.tolist()[0]}")
Execution Console Output: [*] Initializing Canonical Transformer from Scratch... [βœ”] Model Instantiated. Total Trainable Parameters: 5,528,832 [*] Executing Supervised Training Forward Pass with Teacher Forcing... [βœ”] Forward Pass Completed. Target Logits Shape: torch.Size([2, 8, 1000]) (Expected: [2, 8, 1000]) [βœ”] Label-Smoothed Cross-Entropy Loss Computed: 7.0214 [βœ”] Backpropagation Verified. Global Gradient Norm: 1.4820 [*] Testing Autoregressive Greedy Inference... [βœ”] Inference Generation Complete. Generated Output Token Sequence: [1, 412, 891, 12, 604, 78, 2]
8. Common Antipatterns & Computational Traps in Transformer Assembly
Diagnostic playbook covering critical assembly defects: Shared module instance re-use traps, incorrect Xavier scale parameters, target mask broadcasting bugs, and gradient accumulation leakage.
Troubleshooting Playbook: Transformer Engineering Defects & Remediations
TRANSFORMER ARCHITECTURE ASSEMBLY DEFECTS & REMEDIATIONS:

1. THE "MODULELIST VS. LIST" SUBMODULE REGISTRATION BUG:
   β€’ Symptom: Model trains, but encoder layers 2 to 6 receive ZERO gradient updates and parameters
     never move from their initial values!
   β€’ Root Cause: Using a standard Python list:
     self.layers = [EncoderLayer(...) for _ in range(N)]  # FATAL: PyTorch cannot register submodules!
   β€’ Remediation: Always wrap sequential custom layers inside 'nn.ModuleList':
     self.layers = nn.ModuleList([EncoderLayer(...) for _ in range(N)])

2. THE "SINGLETON INSTANCE RE-USE" TRAP:
   β€’ Symptom: Forward pass crashes with dimension errors or gradients accumulate across 6 layers into 1!
   β€’ Root Cause: Instantiating one layer object and referencing it 6 times:
     layer = EncoderLayer(...)
     self.layers = nn.ModuleList([layer for _ in range(6)]) # Re-uses the EXACT same weight memory!
   β€’ Remediation: Instantiate a fresh layer object on every loop iteration using list comprehension.

3. CAUSAL MASK TARGET-LENGTH DESYNCHRONIZATION IN INFERENCE:
   β€’ Symptom: Generation crashes with RuntimeError: "The size of tensor a (8) must match the size of tensor b (1)".
   β€’ Root Cause: Creating a static causal mask of size Max_Len instead of dynamic size equal to current ys.size(1).
   β€’ Remediation: Generate the causal mask dynamically based on the active target tensor shape:
     create_causal_mask(size=ys.size(1), device=ys.device)

4. OMITTING GRADIENT CLIPPING IN TRAINING:
   β€’ Symptom: Training diverges at step 500; loss spikes to NaN abruptly.
   β€’ Cause: Unstable gradient norms during early training traversing non-convex loss ravines.
   β€’ Remediation: Always clip gradients before optimizer steps:
     nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
Diagnostic Tool: To verify that all $N$ encoder and decoder layers are actively contributing to the final loss rather than remaining inactive due to registration bugs, check the gradient norm of every weight tensor: for name, param in model.named_parameters(): print(name, param.grad.norm().item()) If any layer displays None or 0.0000, its computational graph is detached.
9. Technical Specification & Examination Reference Matrix
Comprehensive reference matrix summarizing the complete Transformer architecture, component equations, computational roles, and academic examination definitions for B.Tech students.
Complete Transformer Architecture Technical Specification Matrix
TRANSFORMER ARCHITECTURAL SPECIFICATION MATRIX:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ COMPONENT MODULE        β”‚ MATHEMATICAL IMPLEMENTATION  β”‚ TENSOR INPUT     β”‚ TENSOR OUTPUT                 β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Token Embedding         β”‚ Embedding(vocab, d_model)·√d β”‚ (B, S) Tokens    β”‚ (B, S, d_model) Continuous    β”‚
β”‚ Positional Encoding     β”‚ Sin/Cos Geometric Wavelengthsβ”‚ (B, S, d_model)  β”‚ (B, S, d_model) Position-awareβ”‚
β”‚ Multi-Head Self-Attn    β”‚ MHA(Q=X, K=X, V=X, mask)     β”‚ (B, S, d_model)  β”‚ (B, S, d_model) Subspace mixedβ”‚
β”‚ Pre-LN Normalization    β”‚ LayerNorm(x)                 β”‚ (B, S, d_model)  β”‚ (B, S, d_model) Mean=0, Var=1 β”‚
β”‚ Residual Addition       β”‚ x + Dropout(SubLayer(LN(x))) β”‚ (B, S, d_model)  β”‚ (B, S, d_model) Identity highwβ”‚
β”‚ Feed-Forward Network    β”‚ ReLU(x W_1 + b_1) W_2 + b_2  β”‚ (B, S, d_model)  β”‚ (B, S, d_model) Key-value mem β”‚
β”‚ Multi-Head Cross-Attn   β”‚ MHA(Q=Y, K=H_enc, V=H_enc)   β”‚ Y: Target, H: Encβ”‚ (B, S_tgt, d_model) Cross-seq β”‚
β”‚ Target Causal Mask      β”‚ Lower-triangular (tril)      β”‚ (1, 1, S_tgt, S) β”‚ (B, 1, S_tgt, S_tgt) Causal   β”‚
β”‚ Generator Head          β”‚ Linear(d_model, vocab_size)  β”‚ (B, S_tgt, d)    β”‚ (B, S_tgt, |V|) Token Logits  β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ TOP 5 TRANSFORMER FROM SCRATCH AXIOMS FOR AI ENGINEERS:                                                   β”‚
β”‚ 1. Scale Embeddings by √d_model: Multiplies token representations to maintain signal dominance over staticβ”‚
β”‚    sinusoidal positional encodings [-1, 1].                                                               β”‚
β”‚ 2. Pre-LN Enables Depth: Always apply LayerNorm to the input of sub-layers (Pre-LN) rather than the       β”‚
β”‚    residual sum (Post-LN) to allow identity gradient flow across deep networks.                           β”‚
β”‚ 3. Masks Must Be 4D Broadcastable: Shape padding and causal masks as (B, 1, 1, S) and (1, 1, S, S) to     β”‚
β”‚    seamlessly broadcast across batch and attention head axes without memory replication.                  β”‚
β”‚ 4. Precompute Encoder Memory in Inference: In autoregressive generation, run the encoder ONCE; reuse the  β”‚
β”‚    resulting memory tensor across all subsequent decoding steps.                                          β”‚
β”‚ 5. Wrap Sub-Layers in nn.ModuleList: Standard Python lists prevent PyTorch from registering submodules,   β”‚
β”‚    silently cutting off gradient propagation during backpropagation.                                      β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Academic & Professional Standard: Building the complete Transformer architecture from scratch in pure PyTorch is the definitive milestone in deep learning systems engineering. Mastering the interactions between attention projections, sinusoidal embeddings, Pre-LN residual highways, causal masking logic, and autoregressive decoding loops equips engineers with the comprehensive technical foundation necessary to design, train, and innovate upon state-of-the-art foundation models.