Debugging Custom Transformer Encoders and Classification Pipelines
Machine LearningModel answerLast updated
Diagnose subtle implementation errors in PyTorch multi-head attention blocks and build an end-to-end data analysis and model evaluation workflow.
Custom implementations of transformer architectures frequently suffer from silent correctness issues—bugs that run without throwing errors but lead to degraded performance, poor gradient flow, or invalid attention weights.
Suppose you are auditing a PyTorch implementation of a custom multi-head transformer sequence classifier. Four core functional unit tests are currently failing, covering bugs across attention dimension slicing, score normalization, masking logic, tensor reshaping, and pooling strategies.
Your objective is to:
- Transformer Diagnostics & Fixes: Detail a step-by-step invariant testing strategy to detect subtle attention bugs. Provide a complete, fully functioning PyTorch implementation of a multi-head attention block and a downstream classification model that resolves standard architectural defects.
- Data Analysis & Training Workflow: Explain the end-to-end process for preparing a real-world text classification dataset (profiling class imbalance, handling missing values, avoiding leakage across splits) and setting up a robust baseline, training loop, and evaluation protocol using appropriate metrics.
Hints
Hint 1
Verify that multi-head projections correctly separate heads using transpose after view, preventing mixing of token and head indices.
Hint 2
Check that key/padding attention masks contain negative infinity values before applying softmax across dim=-1.
Hint 3
Ensure spatial aggregation for sequence classification uses masked pooling rather than naive sequence averaging over zero-padded tokens.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Part 1: Diagnostic Framework & Attention Layer Implementation
When debugging custom deep neural network layers like multi-head attention (MHA), traditional runtime exceptions rarely catch logical errors. A systematic, invariant-driven testing approach is necessary.
Invariant-Based Diagnostic Rules
- Sum-to-One Property: The attention probabilities across key positions for any query must sum to $1.0$. If rows do not sum to $1$, inspect the reduction dimension in
F.softmax(must bedim=-1). - Mask Isolation: Padding tokens must receive zero attention weight post-softmax. Verify that pre-softmax scores at masked positions are replaced with $-\infty$ (or
-1e9for floating-point safety), not $0$. - Head Independence: Unrolling head dimensions via
.view(B, H, T, d_k)directly scrambles sequence ordering. Verify that multi-head splits use.view(B, T, H, d_k).transpose(1, 2)so spatial time-steps remain intact. - Causal Invariance (if applicable): Modifying input tokens at position $t' > t$ should not alter output embeddings at step $t$.
- Overfit Sanity Check: A functional model should reach nearly zero loss when trained on a single mini-batch ($B=4$) within 50 to 100 gradient steps.
Common Failure Modes in Custom Transformers
| Component | Bug Type | Code Sickness | Correct Behavior |
|---|---|---|---|
| Attention Softmax | Axis mismatch | F.softmax(scores, dim=-2) | Compute normalization over key sequence length using dim=-1. |
| Attention Scaling | Missing scale factor | scores = q @ k.transpose(...) | Scale raw dot products by $\frac{1}{\sqrt{d_k}}$ to prevent gradient saturation. |
| Mask Value | Post-softmax or zero-masking | scores.masked_fill(mask, 0.0) | Fill masked slots prior to softmax with float('-inf') (or -1e9). |
| Head Separation | Dimension corruption | x.view(B, H, T, d_k) | Split channel space first, then swap dimensions: .view(B, T, H, d_k).transpose(1, 2). |
| Head Aggregation | Memory non-contiguity | attn_out.transpose(1,2).view(...) | Call .contiguous() post-transpose before reshaping back to original model dimension. |
| Sequence Pooling | Unmasked mean | x.mean(dim=1) | Compute a length-normalized masked sum that ignores zero-padded token embeddings. |
Corrected PyTorch Architecture Reference Implementation
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class MultiHeadAttention(nn.Module):
def __init__(self, d_model: int, n_heads: int, dropout: float = 0.1, causal: bool = False):
super().__init__()
assert d_model % n_heads == 0, "d_model must be divisible by n_heads"
self.d_model = d_model
self.n_heads = n_heads
self.d_k = d_model // n_heads
self.causal = causal
self.qkv_proj = nn.Linear(d_model, 3 * d_model)
self.out_proj = nn.Linear(d_model, d_model)
self.dropout = nn.Dropout(dropout)
def forward(self, x: torch.Tensor, pad_mask: torch.Tensor = None) -> torch.Tensor:
"""
x: Input tensor of shape (B, T, d_model)
pad_mask: Tensor of shape (B, T) where 1 indicates valid token and 0 indicates padding
"""
B, T, C = x.shape
# 1. Linear projection and head splitting
qkv = self.qkv_proj(x) # (B, T, 3 * d_model)
q, k, v = qkv.chunk(3, dim=-1)
# Reshape to (B, H, T, d_k) safely
q = q.view(B, T, self.n_heads, self.d_k).transpose(1, 2)
k = k.view(B, T, self.n_heads, self.d_k).transpose(1, 2)
v = v.view(B, T, self.n_heads, self.d_k).transpose(1, 2)
# 2. Scaled Dot-Product Attention
scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.d_k) # (B, H, T, T)
# 3. Apply causal masking if required
if self.causal:
causal_mask = torch.tril(torch.ones((T, T), device=x.device, dtype=torch.bool))
scores = scores.masked_fill(~causal_mask, float('-inf'))
# 4. Broadcast and apply padding mask
if pad_mask is not None:
# Reshape pad_mask to (B, 1, 1, T) for proper broadcasting
expanded_pad_mask = pad_mask.unsqueeze(1).unsqueeze(2) == 0
scores = scores.masked_fill(expanded_pad_mask, float('-inf'))
# 5. Softmax along key dimension
attn_weights = F.softmax(scores, dim=-1)
# Handle zero-row edge cases (e.g., fully masked sequences)
attn_weights = torch.nan_to_num(attn_weights, nan=0.0)
attn_weights = self.dropout(attn_weights)
# 6. Recombine multi-head representations
context = torch.matmul(attn_weights, v) # (B, H, T, d_k)
context = context.transpose(1, 2).contiguous().view(B, T, C)
return self.out_proj(context)
class TransformerSequenceClassifier(nn.Module):
def __init__(self, d_model: int, n_heads: int, num_classes: int, dropout: float = 0.1):
super().__init__()
self.attention = MultiHeadAttention(d_model, n_heads, dropout=dropout)
self.norm = nn.LayerNorm(d_model)
self.classifier = nn.Linear(d_model, num_classes)
def forward(self, x: torch.Tensor, pad_mask: torch.Tensor = None) -> torch.Tensor:
# Pre-LN residual block connection
x = x + self.attention(self.norm(x), pad_mask=pad_mask)
# Masked Average Pooling across sequence length (dim=1)
if pad_mask is not None:
mask_expanded = pad_mask.unsqueeze(-1).float() # (B, T, 1)
sum_embeddings = torch.sum(x * mask_expanded, dim=1)
valid_counts = torch.clamp(mask_expanded.sum(dim=1), min=1e-9)
pooled = sum_embeddings / valid_counts
else:
pooled = x.mean(dim=1)
return self.classifier(pooled)
Part 2: Exploratory Data Analysis & Evaluation Pipeline
Building a successful model pipeline requires auditing data dynamics before running training loops.
Data Exploration Checklist
- Label Balance: Check class distributions. High skew (e.g., 90:10 imbalance) renders standard Accuracy uninformative. Use Macro F1-Score, Balanced Accuracy, or PR-AUC, and apply class weighting inside loss functions like
nn.CrossEntropyLoss(weight=weights). - Missing Values & Corruption: Detect null strings or invalid tokens. Drop or impute systematically before tokenization.
- Sequence Length Profiles: Analyze 95th and 99th percentile token lengths. Truncating contexts too aggressively removes important signals, while excessively long contexts cause quadratic MHA memory blowups.
- Data Leakage Checks: Ensure identical text samples do not exist in both training and testing sets due to duplicate raw entries or near-duplicate scraping. Fit processing tools (standardizers, vectorizers) exclusively on training splits.
End-to-End Training and Metric Logging Protocol
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from sklearn.metrics import classification_report, roc_auc_score
def train_epoch(model: nn.Module, dataloader: DataLoader, optimizer: torch.optim.Optimizer, criterion: nn.Module, device: str):
model.train()
total_loss = 0.0
for batch_x, batch_mask, batch_y in dataloader:
batch_x, batch_mask, batch_y = batch_x.to(device), batch_mask.to(device), batch_y.to(device)
optimizer.zero_grad()
logits = model(batch_x, pad_mask=batch_mask)
loss = criterion(logits, batch_y)
loss.backward()
# Clip gradients to avoid exploding gradients in transformer stacks
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
optimizer.step()
total_loss += loss.item() * batch_x.size(0)
return total_loss / len(dataloader.dataset)
@torch.no_grad()
def evaluate_model(model: nn.Module, dataloader: DataLoader, device: str):
model.eval()
all_preds = []
all_targets = []
for batch_x, batch_mask, batch_y in dataloader:
batch_x, batch_mask = batch_x.to(device), batch_mask.to(device)
logits = model(batch_x, pad_mask=batch_mask)
probs = F.softmax(logits, dim=-1)
all_preds.append(probs.cpu())
all_targets.append(batch_y)
all_preds = torch.cat(all_preds, dim=0).numpy()
all_targets = torch.cat(all_targets, dim=0).numpy()
pred_labels = all_preds.argmax(axis=1)
print(classification_report(all_targets, pred_labels, digits=4))
if all_preds.shape[1] == 2:
auc = roc_auc_score(all_targets, all_preds[:, 1])
print(f"ROC-AUC: {auc:.4f}")