Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

Knowledge Distillation Benchmark Suite — Yahoo Answers Topics

A from-first-principles benchmark of modern knowledge distillation techniques: fine-tuning a pretrained transformer teacher, distilling it into a compact from-scratch student through a layered ablation stack (logit KD → feature distillation → attention transfer), and evaluating the accuracy / latency / model-size trade-off at every stage — including a from-scratch baseline, multi-seed statistical reporting, INT8 post-training quantization, and a robustness check under input perturbation.


Objective

Distillation tutorials and papers almost always report results where each added technique monotonically improves accuracy. This project set out to test that assumption directly rather than assume it: build the full ablation stack, measure every stage independently with multiple seeds, and report what actually happens — including where the expected improvements don't materialize.

Design goals:

  • Start from a real pretrained transformer teacher (not a from-scratch teacher), matching how distillation is done in practice.
  • Use a dataset hard enough to be meaningful (not a 4-class toy problem) but tractable for a solo GPU-hour budget (not a 150-class benchmark).
  • Report every stage with 3-seed mean ± std, not single lucky runs.
  • Measure the full deployment picture — accuracy, parameter count, model size, and CPU inference latency — not accuracy alone.
  • Include a robustness slice (perturbed test inputs) to check whether distillation degrades generalization, not just clean-set accuracy.

Dataset

Yahoo Answers Topics — 10-class topic classification over real user-written Q&A text (question title + best answer), subsampled to 12,000 train / 6,000 test rows for tractable multi-seed iteration.

Why this dataset, and why not the original candidates

Dataset Classes Verdict
AG News 4 Too easy — ~92-94% ceiling even for small models, doesn't stress-test distillation
CLINC150 150 Too large for a solo multi-seed ablation study on a Colab GPU budget
20 Newsgroups 20 Tried first, abandoned. See below.
Yahoo Answers Topics 10 Used. Real benchmark, no metadata leakage, believable ceiling

20 Newsgroups was the original choice but was dropped after diagnosis: its raw form leaks the label through message headers (Newsgroups:, mailing-list signatures, etc.), letting models hit 90%+ by reading metadata rather than content. Stripping headers/footers/quotes removes the leak but also caps accuracy around 65-80% for reasons that have nothing to do with model or training quality — making it hard to distinguish "model needs tuning" from "dataset ceiling reached." Yahoo Answers Topics has no such artifact: it's plain text with a well-documented, literature-consistent accuracy ceiling (~70-75% for strong models), driven by genuine class overlap (e.g. Society & Culture vs Politics & Government) rather than a data quirk.


Architecture

Teacher: distilbert-base-uncased, fine-tuned end-to-end on the classification task.

Student: a from-scratch 4-layer Transformer encoder (TinyStudent) — dim 256, 4 attention heads, no pretraining — roughly 6× fewer parameters than the teacher.

Model Parameters Size (fp32)
Teacher (DistilBERT, fine-tuned) ~66M ~268 MB
Student (TinyStudent) ~11.0M ~42 MB

Method: the ablation stack

Each stage is strictly additive on top of the previous loss:

  1. From-scratch baseline — student trained on hard labels only, no teacher involved. The control.
  2. Logit KD (Hinton et al.) — soft-label distillation: KL-divergence between temperature-softened student/teacher output distributions, combined with hard-label cross-entropy.
  3. + Feature distillation (DistilBERT-style) — adds MSE loss between projected student hidden states and corresponding teacher hidden states, layer-mapped by even spacing across depth.
  4. + Attention transfer (MiniLM-style) — adds MSE loss between student and teacher self-attention distributions (head-averaged for robustness to head-count mismatch).
  5. + INT8 dynamic quantization — post-training quantization of the classifier head (full-model quantization was attempted but is incompatible with PyTorch's nn.TransformerEncoderLayer fast-path attention kernel — see Known Issues).

All stages 1–4 are trained with 3 random seeds (13, 42, 1337); results below report mean ± standard deviation.


Results

Ablation table

Stage Accuracy (mean ± std) Params Size (MB) Latency (s/sample, CPU)
Teacher (fine-tuned DistilBERT) 70.21% ± 0.00 ~66M — —
Student, from scratch (no KD) 47.14% ± 1.28 11.0M 41.99 —
Student + logit KD 52.77% ± 0.41 11.0M 41.99 —
Student + feature distillation 52.71% ± 0.53 11.0M 41.99 —
Student + attention transfer 51.96% ± 0.45 11.0M 41.99 —
Student + INT8 quantization (classifier only) 52.07% 11.0M 10.50 0.0112 (vs. 0.0115 fp32)

(Per-seed accuracies available in results/*_metrics.json; raw notebook run in distillation_benchmark_final.ipynb.)

Robustness slice (accuracy on perturbed test inputs — random 10% word-drop)

Model Clean accuracy Perturbed accuracy Δ
Teacher 70.21% 69.48% −0.73 pts
Student (attention-transfer stage) 52.08% 51.05% −1.03 pts

The student degrades marginally more under perturbation than the teacher — consistent with reduced capacity, but the gap is small, suggesting distillation did not introduce disproportionate brittleness.

Pareto plot

See results/pareto.png for the accuracy-vs-latency trade-off curve across the stack.


Key finding

Logit-based KD captured essentially all of the achievable improvement. Going from a no-distillation baseline (47.1%) to logit KD alone (52.8%) recovered roughly a quarter of the teacher-student accuracy gap — a real, reproducible effect confirmed across 3 seeds (std ≈ 0.4 pts). Adding feature distillation on top produced no further improvement (52.71%, statistically indistinguishable from logit KD alone), and adding attention transfer on top of that decreased accuracy slightly (51.96%).

This runs counter to the common assumption — often implicit in tutorials and papers — that stacking more distillation signal monotonically helps. Likely explanations, in order of plausibility:

  1. Student capacity mismatch. Feature and attention transfer techniques (DistilBERT, MiniLM) were validated on students with considerably more capacity than a 4-layer/dim-256 model — there may simply not be enough room in this student to exploit the extra supervisory signal.
  2. Fixed loss weighting. BETA_FEATURE and GAMMA_ATTN were both set to 0.5 without a sweep; at this weighting the auxiliary losses may compete with, rather than complement, the primary KD signal.
  3. Data scale. 12K training examples is small relative to what these techniques were originally validated on; the extra loss terms may not have enough data to generalize their signal.

This is reported as a genuine empirical result rather than smoothed into a fabricated "more techniques, higher accuracy" narrative — a large part of the point of running a proper ablation is to find out which techniques actually earn their added complexity, not to assume they all do.


Repository structure

task.md                          # full spec, rubric tiers, run order
environment/requirements.txt     # pinned dependency list
oracle_solution/
  common.py                      # data loading, TinyStudent model, shared utils
  01_train_teacher.py            # fine-tune DistilBERT teacher
  02_train_student_baseline.py   # from-scratch student, 3 seeds
  distill_core.py                # shared distillation training loop (stages 03-05)
  03_distill_logits.py           # stage: logit KD
  04_distill_features.py         # stage: + feature distillation
  05_distill_attention.py        # stage: + attention transfer
  06_quantize.py                 # INT8 dynamic quantization + latency benchmark
  07_benchmark.py                # ablation table, Pareto plot, robustness slice
tests/
  test_pipeline.py               # offline smoke tests (model/data wiring, no GPU/Hub needed)
distillation_benchmark_final.ipynb  # full executed Colab run with all raw output

Reproducing this

Requires a Colab GPU runtime (T4 or better) for GPU-timed steps; quantization runs on CPU by design.

pip install -r environment/requirements.txt
python -m pytest tests/test_pipeline.py -v   # offline sanity check, ~10s

cd oracle_solution
python 01_train_teacher.py
python 02_train_student_baseline.py
python 03_distill_logits.py
python 04_distill_features.py
python 05_distill_attention.py
python 06_quantize.py
python 07_benchmark.py

Full commented walkthrough, including the exact issues hit and fixes applied during development, is in distillation_benchmark_final.ipynb.

Hyperparameters

Teacher Student (all stages)
Epochs 4 6
Batch size 16 32
Learning rate 2e-5 3e-4
Weight decay 0.01 —
KD temperature — 4.0
CE / KD loss weight — 0.3 / 0.7
Feature / attention loss weight — 0.5 / 0.5

Teacher epochs were deliberately kept low (4, with weight decay) after an earlier 6-epoch run showed train loss still falling sharply while test accuracy stayed flat — a clear overfitting signature on a 12K-row fine-tuning set.


Known issues

  • Full-model INT8 dynamic quantization fails on TinyStudent due to an incompatibility between PyTorch's torch.quantization.quantize_dynamic and nn.TransformerEncoderLayer's fast-path attention kernel (quantized linear layers inside self_attn return a callable instead of a tensor, which the fast-path device check doesn't handle — AttributeError: 'function' object has no attribute 'device'). Worked around by quantizing only the classifier head; full-model quantization would require either a custom attention implementation or migrating to torchao's newer quantization API (the legacy torch.ao.quantization path used here is itself deprecated as of PyTorch 2.10).
  • Dataset repo id changed upstream from yahoo_answers_topics to community-datasets/yahoo_answers_topics after HuggingFace's deprecation of unnamespaced community dataset scripts — common.py uses the current path.

Honest scope notes

  • This is a single-model-size, single-dataset study — findings about feature/attention distillation not helping are specific to this student scale and should not be generalized without further ablation across student sizes.
  • Loss-weight hyperparameters (BETA_FEATURE, GAMMA_ATTN) were not swept; the negative/flat result for those stages could partly reflect suboptimal weighting rather than a hard capacity ceiling.
  • TPU cross-hardware benchmarking (originally scoped as a stretch goal) was not run in this pass.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages