Attention Mechanisms, Autoregressive vs Masked Models, and Metrics
Machine LearningModel answerLast updated
Explain attention in modern neural architectures, contrast autoregressive and bidirectional pretraining approaches, and discuss precision-recall tradeoffs.
Answer these three conceptual questions about machine learning fundamentals:
1. Attention-Based Architecture
Describe the core building blocks of an attention-based neural network block. What role does each component play?
2. Autoregressive vs Bidirectional Models
Compare two major approaches to language model pretraining:
- What are the fundamental architectural and objective differences?
- In what situations would you choose one approach over the other?
3. Classification Metrics
- Define precision and recall in terms of true positives, false positives, and false negatives.
- Demonstrate how adjusting a decision threshold affects the precision-recall tradeoff.
- Provide concrete scenarios where you would optimize for precision versus recall.
Hints
Hint 1
For attention, think about how information flows between positions and what prevents gradient issues in deep networks
Hint 2
Consider what each pretraining approach can and cannot do naturally - one predicts forward, one sees context from both directions
Hint 3
Remember that lowering thresholds typically increases the number of positive predictions, affecting both metric denominators
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Attention, Pretraining Paradigms, and Evaluation Metrics
This question tests whether you understand architectural design choices and can reason about model selection for real applications. Strong answers connect components to their purpose and link metrics to product impact.
1. Attention-Based Architecture
Modern attention blocks process sequences through several coordinated mechanisms:
Core Components
Positional Encoding Before any processing, we must inject position information since attention operations are position-agnostic. Common approaches include sinusoidal functions, learned embeddings, or rotary position encodings. Without this, the model cannot distinguish token order.
Self-Attention Mechanism Each input token generates three vectors via learned projections: query (Q), key (K), and value (V). The attention operation computes:
Attention(Q, K, V) = softmax(QK^T / sqrt(d_k)) V
The scaling factor sqrt(d_k) prevents dot products from growing large and pushing softmax into regions with vanishing gradients. Each token's output becomes a weighted combination of all value vectors, where weights derive from query-key compatibility scores.
Multi-Head Attention Rather than one attention operation, we split into multiple parallel heads operating on lower-dimensional subspaces. Different heads can specialize in different relationships—syntactic dependencies, semantic similarity, or positional patterns. Outputs concatenate and project back to the model dimension.
Feed-Forward Network After attention mixes information across positions, a position-wise MLP transforms each token representation independently. Typically expands to 4× the model dimension with a nonlinearity (GELU or ReLU), then projects back. This component stores much of the model's learned knowledge.
Residual Connections
Every sublayer wraps as x + Sublayer(x), creating direct gradient paths through arbitrarily deep stacks.
Layer Normalization
Stabilizes training by normalizing activations. Modern implementations typically use pre-normalization (x + Sublayer(LayerNorm(x))) rather than post-normalization for better training stability.
Architectural Variants
Causal vs Bidirectional Attention
- Bidirectional (encoder-style): each token attends to all positions
- Causal (decoder-style): token
tonly attends to positions ≤t, implemented via an upper-triangular mask
Computational Complexity Self-attention costs O(n²d) time and O(n²) memory for sequence length n. This quadratic scaling motivated efficiency innovations like sparse attention patterns, linear approximations, and optimized implementations like FlashAttention.
Simple Implementation
import numpy as np
def attention(Q, K, V, mask_future=False):
# Q, K, V shape: (seq_len, d_model)
d_k = Q.shape[-1]
scores = Q @ K.T / np.sqrt(d_k)
if mask_future:
n = len(scores)
mask = np.triu(np.ones((n, n)), k=1) == 1
scores[mask] = -np.inf
# Numerical stability
scores = scores - np.max(scores, axis=-1, keepdims=True)
weights = np.exp(scores) / np.sum(np.exp(scores), axis=-1, keepdims=True)
return weights @ V
2. Autoregressive vs Bidirectional Models
Key Differences
Architecture
- Autoregressive models (like GPT) use decoder-only stacks with causal masking
- Bidirectional models (like BERT) use encoder-only stacks with full attention
Pretraining Objective
- Autoregressive: maximize log P(x_t | x_1...x_{t-1}) for every token. The model learns to predict what comes next.
- Bidirectional: mask approximately 15% of tokens and predict them from surrounding context. Original BERT also included next-sentence prediction, though later work showed it adds minimal value.
Masking Strategy in BERT
Of masked positions: 80% replaced with [MASK], 10% with random tokens, 10% unchanged. This prevents the model from relying solely on the mask token itself.
Natural Capabilities
- Autoregressive models naturally generate text token-by-token
- Bidirectional models produce rich contextual embeddings but cannot generate fluently since they never learned left-to-right dependencies
When to Choose Each Approach
Prefer Bidirectional (Encoder) Models:
- Classification tasks: sentiment analysis, intent detection, content categorization
- Token-level tasks: named entity recognition, part-of-speech tagging
- Embedding generation for retrieval: document search, semantic similarity
- Scenarios requiring low latency and high throughput—a single forward pass through a 100M parameter encoder is far cheaper than multi-token generation from a billion-parameter model
Prefer Autoregressive (Decoder) Models:
- Text generation: summarization, creative writing, dialogue
- Tasks requiring step-by-step reasoning expressed in text
- Zero-shot or few-shot learning via prompting when labeled data is scarce
- Open-ended tasks where the output structure isn't predetermined
Modern Nuance Large autoregressive models now excel at "understanding" tasks too, and many embedding models derive from decoder architectures. The practical tradeoff often centers on inference cost and task flexibility rather than raw capability. Encoder-decoder hybrids (T5-style) offer middle ground for structured input-output mappings like translation.
3. Classification Metrics
Definitions
Precision = TP / (TP + FP) Among all items we predicted positive, what fraction are truly positive? Measures the cost of false alarms.
Recall = TP / (TP + FN)
Among all actual positives, what fraction did we identify? Measures completeness of detection.
Threshold Tradeoff
Consider a content filter scoring 1,000 items, where 100 truly violate policy:
| Threshold | Items Flagged | True Violations Caught | Precision | Recall |
|---|---|---|---|---|
| 0.8 | 40 | 35 | 35/40 = 0.875 | 35/100 = 0.35 |
| 0.5 | 120 | 80 | 80/120 = 0.667 | 80/100 = 0.80 |
| 0.2 | 300 | 95 | 95/300 = 0.317 | 95/100 = 0.95 |
Lowering the threshold flags more items, catching more true positives (recall increases) while also admitting more false positives (precision typically decreases). Raising the threshold has the opposite effect—fewer false positives but more missed detections.
Sweeping thresholds traces a precision-recall curve. Summary metrics include average precision (area under PR curve) and F1-score (harmonic mean: 2PR/(P+R)).
def compute_metrics(predictions, ground_truth, threshold):
tp = sum((p >= threshold) and g for p, g in zip(predictions, ground_truth))
fp = sum((p >= threshold) and not g for p, g in zip(predictions, ground_truth))
fn = sum((p < threshold) and g for p, g in zip(predictions, ground_truth))
precision = tp / (tp + fp) if (tp + fp) > 0 else 0.0
recall = tp / (tp + fn) if (tp + fn) > 0 else 0.0
return precision, recall
Scenario Selection
Prioritize Precision (minimize false positives):
- Account suspension systems: wrongly banning legitimate users damages trust and incurs support costs
- Promotional notifications: sending irrelevant suggestions annoys users and increases opt-out rates
- Automated content removal: false takedowns harm creators and platform reputation
- Medical screening alerts: unnecessary follow-ups waste resources and cause patient anxiety
Prioritize Recall (minimize false negatives):
- Fraud detection: missing a fraudulent transaction costs money and enables future attacks
- Safety-critical moderation: failing to catch harmful content (violence, CSAM) has severe consequences
- Disease screening: missing a serious condition in early stages can be life-threatening
- Security threat detection: undetected breaches can compromise entire systems
The optimal operating point depends on the relative costs of each error type and business constraints. In practice, you might set different thresholds for different severity classes or use multi-stage systems where high-precision first passes feed into high-recall second-stage review.