KatInterview

Debugging Custom Transformer Encoders and Classification Pipelines

Machine LearningModel answer
HardModel answerMachine Learningtransformersdeep-learningnlp

Last 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:

  1. 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.
  2. 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.