Architecture and Ensemble Trade-offs for Text Classifiers
Machine LearningModel answerLast updated
Compare sequential and attention-based architectures for long-text classification, then explain variance vs bias reduction in ensemble methods.
You're building a text classification pipeline that must handle documents of varying lengths—some short product reviews, others multi-page support tickets—with strict real-time serving requirements.
Part 1: Explain the core differences between recurrent architectures (like LSTMs) and self-attention models (like BERT-style encoders) across these dimensions:
- How each processes input and represents context
- Parallelization characteristics during training and inference
- Computational and memory scaling as document length increases
- Handling of long-range dependencies
Part 2: Describe bootstrap aggregation and gradient boosting. Explain what type of error each technique primarily addresses and when you'd choose one over the other in production.
Connect both parts: discuss practical considerations for deploying these architectures under latency constraints, and whether ensemble techniques make sense in this scenario.
Hints
Hint 1
Think about the path information must travel between distant tokens in each architecture
Hint 2
Consider how quadratic vs linear scaling affects both training speed and serving cost
Hint 3
Recall that averaging independent errors behaves differently than iteratively correcting mistakes
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Part 1: Sequential vs Attention-Based Architectures
Core Mechanisms
Recurrent models (LSTM/GRU) maintain a memory state that updates at each time step:
h_t = f(W_h · h_{t-1} + W_x · x_t + b)
LSTMs extend this with gating mechanisms—input, forget, and output gates—that control information flow through an additional cell state. For classification, you typically use the final hidden state from a bidirectional pass or pool across all time steps, then pass through a classification head.
Self-attention models compute interactions between all pairs of positions simultaneously. Each layer applies:
Attention(Q, K, V) = softmax((Q·K^T) / √d_k) · V
where queries, keys, and values are learned projections. BERT-style encoders stack these layers with residual connections and feed-forward networks. Position information comes from learned or sinusoidal encodings added to token embeddings. Classification uses a special [CLS] token or pooled representations.
Parallelization Characteristics
The fundamental difference is sequential depth:
-
LSTMs: Each hidden state depends on the previous one, creating a serial dependency chain of length n. During training, you must process all n steps sequentially within each layer. This underutilizes GPUs despite lower total computation.
-
Transformers: All positions are computed in parallel. Attention matrices for a batch can be computed as large matrix multiplications, which GPUs handle efficiently.
Training throughput: Transformers train far faster on modern hardware because they expose massive parallelism. A 512-token batch processes all positions simultaneously, while an LSTM must step through 512 time steps.
Inference latency: For single-sequence inference, transformers still win due to optimized matrix operations, but the gap narrows since you can't batch across positions within one document.
Scaling with Document Length
| Metric | LSTM | Transformer (standard) |
|---|---|---|
| Computation per layer | O(n·d²) | O(n²·d + n·d²) |
| Memory footprint | O(n·d) | O(n²) for attention scores |
| Operations between distant tokens | O(n) hops | O(1) direct connection |
Concrete example: Extending from 512 to 4096 tokens:
- LSTM: 8× more sequential steps, 8× the FLOPs, same memory per step
- Transformer: 64× more attention computation (quadratic scaling), 64× more attention memory
For a 12-layer BERT-base with 12 heads, that 4096-token document requires roughly 2.4 billion attention score computations per forward pass. This becomes prohibitive without sparse attention patterns.
Long-Range Dependencies
LSTMs compress all history into a fixed-size vector, creating an information bottleneck. Even with gating, signals must survive many multiplicative transformations. Empirically, effective context length rarely exceeds a few hundred tokens. The model doesn't fail abruptly at long ranges—it degrades gradually as important information gets overwritten.
Transformers allow any token to attend directly to any other token, making long-range relationships easy to capture. The limitation is the hard cutoff imposed by positional encodings and the pretraining length (e.g., 512 for original BERT). Extrapolating beyond trained lengths often fails.
Practical Approaches for Long Documents
Given tight latency requirements:
-
Hierarchical chunking: Split documents into 512-token windows, encode each in parallel (true batch parallelism across chunks), then aggregate the [CLS] embeddings with pooling or a lightweight attention layer. Simple mean pooling often works surprisingly well.
-
Strategic truncation: Use the first 256 and last 256 tokens. For many classification tasks, key information appears at document boundaries. Test this baseline—it's fast and often competitive.
-
Sparse attention patterns: Models like Longformer use sliding windows plus global attention on special tokens, reducing complexity to O(n·k) where k is window size. BigBird adds random attention. State-space models (S4, Mamba) achieve O(n) cost while preserving parallelism.
-
Model compression: Distill into a smaller student (6 layers instead of 12), quantize to INT8, and optimize with ONNX or TensorRT. This often gives 3-4× speedup with <2% accuracy loss.
Always benchmark against a simple baseline: TF-IDF features with logistic regression or a small CNN. This establishes the speed you must beat and the accuracy floor.
Part 2: Ensemble Methods
Bootstrap Aggregation (Bagging)
Process:
- Create B training sets by sampling with replacement from your data (same size as original)
- Train independent models on each bootstrap sample
- Average predictions (regression) or vote (classification)
Why variance decreases: If individual models have variance σ² and correlation ρ between predictions:
Var(ensemble) = ρ·σ² + ((1-ρ)/B)·σ²
As B increases, the uncorrelated component averages out. Random forests enhance this by also subsampling features at each split, which reduces ρ.
Bias remains roughly constant—you're averaging models of similar complexity trained on similar data.
Best use cases:
- High-variance base learners (deep decision trees, neural networks with different initializations)
- Noisy labels—averaging smooths out label errors
- When you want parallel training and free validation via out-of-bag samples
- When interpretability isn't critical
Gradient Boosting
Process: Build an additive model sequentially, where each new component corrects the ensemble's current errors:
F_m(x) = F_{m-1}(x) + ν·h_m(x)
Each h_m is trained to fit the negative gradient of the loss function with respect to current predictions. The learning rate ν (shrinkage) controls the contribution of each tree.
Why bias decreases: You're iteratively building a complex function from simple weak learners (typically shallow trees of depth 3-8). Each round reduces training error by targeting current mistakes. With proper regularization (shrinkage, tree depth limits, subsampling), this also controls variance.
Best use cases:
- Tabular data where XGBoost/LightGBM/CatBoost excel
- Clean labels—boosting will overfit to label noise by repeatedly focusing on mislabeled examples
- When you can afford careful tuning (learning rate, number of rounds, tree depth, early stopping)
- When maximum accuracy matters more than training speed
Key risk: Sequential training is slower, and the algorithm can chase outliers and label errors. AdaBoost is especially prone to this.
Connecting to the Scenario
Ensembles multiply inference cost. Five independently trained BERT models mean roughly 5× latency and 5× memory. Under strict serving constraints, this is often unacceptable.
Better alternatives:
- Distillation: Train an ensemble, then distill it into a single smaller student model. The student learns from the ensemble's soft predictions and often retains 95%+ of the accuracy at 1/5 the cost.
- Lightweight stacking: Use one transformer to generate embeddings, then feed those plus metadata features into a small gradient boosting model (50-100 trees). The GBDT adds <1ms of latency but can improve calibration and handle non-textual signals.
When bagging makes sense: If you're using smaller models (e.g., 6-layer distilled transformers) and can serve 3-5 models within your latency budget, bagging with different random seeds provides easy gains with no hyperparameter search.
When boosting makes sense: Rarely for neural text models. Boosting works best with weak tabular learners. For NLP, sequential boosting of neural networks is expensive and typically underperforms fine-tuning a single larger model.
Common Mistakes
-
"Transformers are always better": For very long sequences (>10k tokens) or streaming scenarios, recurrent or state-space models may be more practical.
-
"Ensembles always improve accuracy": Diminishing returns set in quickly. Going from 1 to 3 models helps significantly; going from 5 to 10 rarely justifies the cost.
-
"Boosting reduces variance": Its primary effect is bias reduction. With aggressive tuning it can reduce variance too, but that's not its core mechanism.
-
Ignoring the simple baseline: Before deploying a 12-layer transformer ensemble, verify that TF-IDF + logistic regression isn't 90% as accurate at 1% of the latency.
The right architecture depends on your constraints. A fast 6-layer distilled model often beats a slow ensemble of 12-layer models in production, even if the latter scores higher offline.