data / demo /build_notebook.py
reevec's picture
Upload 8 files
3877cdc verified
Raw
History Blame Contribute Delete
45.3 kB
"""Builds knowledge_distillation_assignment.ipynb from scratch via nbformat."""
import nbformat as nbf
nb = nbf.v4.new_notebook()
cells = []
def md(src):
cells.append(nbf.v4.new_markdown_cell(src))
def code(src):
cells.append(nbf.v4.new_code_cell(src))
# ---------------------------------------------------------------------------
# Title
# ---------------------------------------------------------------------------
md(r"""# Knowledge Distillation on `PolyAI/banking77`
**Assignment:** Compress a high-capacity fine-tuned Transformer ("Teacher") into a compact, CPU-friendly
Transformer ("Student") via knowledge distillation, and quantify what is gained and lost in the process.
**Dataset:** [`PolyAI/banking77`](https://huggingface.co/datasets/PolyAI/banking77) — 77-way fine-grained
banking-intent classification, 10,003 train / 3,080 test utterances.
**Environment:** conda env `agn_env` (Python 3.12), Apple Silicon (MPS acceleration used for teacher
fine-tuning; the student is trained and benchmarked on **CPU only**, matching its target deployment profile).
| Module | Tasks |
|---|---|
| 1. Teacher Labeling & Student Setup | Task 1: Teacher fine-tuning & soft-label generation · Task 2: Student tokenizer alignment |
| 2. Distillation Architecture & Training | Task 3: Compact student transformer · Task 4: Distillation loss & training |
| 3. Comparative Analysis & Benchmarking | Task 5: Accuracy vs. compression · Task 6: Deployment metrics |
""")
# ---------------------------------------------------------------------------
# Setup
# ---------------------------------------------------------------------------
md("## Setup\n\nInstall dependencies directly into the active `agn_env` environment (safe to re-run — a no-op if already satisfied), then import everything used below.")
code(r"""# Ensure required libraries are present in the active (agn_env) kernel.
import sys
!{sys.executable} -m pip install -q torch transformers datasets scikit-learn psutil evaluate accelerate tokenizers ipykernel matplotlib
""")
code(r"""import os
import gc
import json
import time
import random
import tempfile
import subprocess
from collections import OrderedDict
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
import matplotlib.pyplot as plt
from IPython.display import display, Markdown
from datasets import load_dataset
from transformers import (
AutoTokenizer,
BertForSequenceClassification,
TrainingArguments,
Trainer,
DataCollatorWithPadding,
)
from tokenizers import Tokenizer as HFTokenizer
from tokenizers.models import WordPiece
from tokenizers.trainers import WordPieceTrainer
from tokenizers.pre_tokenizers import Whitespace
from tokenizers.normalizers import BertNormalizer
from tokenizers.processors import TemplateProcessing
from sklearn.metrics import accuracy_score, f1_score
import psutil
SEED = 42
random.seed(SEED)
np.random.seed(SEED)
torch.manual_seed(SEED)
TRAIN_DEVICE = torch.device("mps") if torch.backends.mps.is_available() else torch.device("cpu")
CPU_DEVICE = torch.device("cpu")
STUDENT_DEVICE = CPU_DEVICE # student is trained + benchmarked on CPU throughout: this is the point of the exercise
print(f"Teacher training device : {TRAIN_DEVICE}")
print(f"Student device (always) : {STUDENT_DEVICE}")
""")
# ---------------------------------------------------------------------------
# Module 1 / Task 1
# ---------------------------------------------------------------------------
md("""## Module 1: Teacher Labeling & Student Setup
### Task 1 — Teacher Integration & Soft-Label Generation
We fine-tune `bert-base-uncased` (110M parameters) end-to-end on banking77 as our **Teacher**. Once
fine-tuned, we run one no-grad forward pass over the *entire* training set to cache the Teacher's raw
77-dimensional **logits** for every example. These cached logits are the "soft labels" used by the
distillation loss in Task 4 — they are computed once, up front, so the (comparatively expensive) Teacher
never needs to run again during Student training.""")
code(r"""# Load banking77. The original PolyAI/banking77 repo only ships a loading *script*, which recent
# versions of `datasets` (>=4.0) no longer execute. We fall back to a verified parquet mirror with
# identical contents (10,003 train / 3,080 test / same 77 ClassLabel names) if the script path fails.
try:
raw_datasets = load_dataset("PolyAI/banking77")
dataset_source = "PolyAI/banking77"
except Exception as e:
print(f"Could not load PolyAI/banking77 directly ({type(e).__name__}); "
f"falling back to the parquet mirror legacy-datasets/banking77.")
raw_datasets = load_dataset("legacy-datasets/banking77")
dataset_source = "legacy-datasets/banking77 (parquet mirror of PolyAI/banking77)"
train_raw = raw_datasets["train"]
test_raw = raw_datasets["test"]
label_names = train_raw.features["label"].names
num_labels = len(label_names)
print(f"Loaded from : {dataset_source}")
print(f"Train examples : {len(train_raw)}")
print(f"Test examples : {len(test_raw)}")
print(f"Classes : {num_labels}")
print(f"\nSample row: {train_raw[0]}")
print(f"First 10 intents: {label_names[:10]}")
""")
code(r"""TEACHER_NAME = "bert-base-uncased"
teacher_tokenizer = AutoTokenizer.from_pretrained(TEACHER_NAME)
def teacher_tokenize(batch):
return teacher_tokenizer(batch["text"], truncation=True, max_length=64)
train_enc = train_raw.map(teacher_tokenize, batched=True)
test_enc = test_raw.map(teacher_tokenize, batched=True)
train_enc = train_enc.rename_column("label", "labels")
test_enc = test_enc.rename_column("label", "labels")
train_enc.set_format(type="torch", columns=["input_ids", "attention_mask", "labels"])
test_enc.set_format(type="torch", columns=["input_ids", "attention_mask", "labels"])
teacher_data_collator = DataCollatorWithPadding(tokenizer=teacher_tokenizer)
print("Tokenized train/test sets ready for the Teacher.")
""")
code(r"""teacher_model = BertForSequenceClassification.from_pretrained(TEACHER_NAME, num_labels=num_labels)
def compute_metrics(eval_pred):
logits, labels = eval_pred
preds = np.argmax(logits, axis=-1)
return {
"accuracy": accuracy_score(labels, preds),
"macro_f1": f1_score(labels, preds, average="macro"),
}
teacher_training_args = TrainingArguments(
output_dir="./teacher_ckpt",
num_train_epochs=3,
per_device_train_batch_size=32,
per_device_eval_batch_size=64,
learning_rate=3e-5,
weight_decay=0.01,
eval_strategy="epoch",
save_strategy="no",
logging_steps=50,
report_to="none",
seed=SEED,
)
trainer = Trainer(
model=teacher_model,
args=teacher_training_args,
train_dataset=train_enc,
eval_dataset=test_enc,
data_collator=teacher_data_collator,
compute_metrics=compute_metrics,
)
teacher_train_start = time.time()
trainer.train()
teacher_train_seconds = time.time() - teacher_train_start
print(f"\nTeacher fine-tuning took {teacher_train_seconds/60:.1f} minutes")
""")
code(r"""teacher_eval_metrics = trainer.evaluate()
print("Teacher eval metrics (test set):", teacher_eval_metrics)
""")
code(r"""# Cache soft labels: one no-grad forward pass over the FULL training set, in original (unshuffled)
# order, so teacher_train_logits[i] corresponds exactly to train_raw[i] by index.
teacher_model.eval()
teacher_model.to(TRAIN_DEVICE)
@torch.no_grad()
def get_teacher_logits(dataset, batch_size=64):
loader = DataLoader(dataset, batch_size=batch_size, shuffle=False, collate_fn=teacher_data_collator)
all_logits = []
for batch in loader:
inputs = {k: v.to(TRAIN_DEVICE) for k, v in batch.items() if k != "labels"}
outputs = teacher_model(**inputs)
all_logits.append(outputs.logits.detach().cpu())
return torch.cat(all_logits, dim=0)
teacher_train_logits = get_teacher_logits(train_enc)
teacher_test_logits = get_teacher_logits(test_enc)
print(f"Cached teacher train logits: {teacher_train_logits.shape}")
print(f"Cached teacher test logits : {teacher_test_logits.shape}")
assert teacher_train_logits.shape[0] == len(train_raw)
""")
md(r"""#### Why soft labels carry "dark knowledge"
A one-hot hard label for the utterance *"I am still waiting on my card?"* says only: **the correct class is
`card_arrival`, and every other one of the 77 classes is equally, absolutely wrong.** That is not true, and
it is not what the Teacher actually believes. The Teacher's full softmax distribution over 77 classes might
look like `card_arrival: 0.62, card_delivery_estimate: 0.21, lost_or_stolen_card: 0.05, ...` — it correctly
picks `card_arrival`, but it also encodes *how confusable* the other intents are with it.
This matters a great deal on a fine-grained, semantically overlapping taxonomy like banking77, which
contains many near-duplicate intents (`card_arrival` vs. `card_delivery_estimate`, `declined_card_payment`
vs. `declined_cash_withdrawal`, `top_up_failed` vs. `pending_top_up`, ...). Training only against a hard
label throws away exactly the information that describes *why* those pairs are confusable — the relative
geometry of the Teacher's learned decision boundary. Training against the full distribution instead:
1. **Transfers inter-class similarity structure.** The relative magnitudes of the non-argmax probabilities
act as a learned "confusion prior" — pairs of intents the Teacher finds similar get correlated soft
targets across many training examples, which is a much richer training signal than 76 identical zeros.
2. **Provides a smoother, higher-entropy target**, which acts as an implicit regularizer: the Student is not
forced to drive its logits to ±∞ to satisfy a one-hot target, so its learned representations generalize
better on held-out data, especially with the very limited parameter budget a compact Student has.
3. **Effectively gives more supervision per example.** A hard label is `log2(77) ≈ 6.3` bits of information at
best (which class). A soft label is a full probability vector — many more effective bits — so a Student
with less capacity and less data than the Teacher can still recover much of the Teacher's decision
surface from the *same* training set.
4. **Raising the temperature $T$ before softmax** (used in Task 4) further amplifies the small
probabilities on non-target classes, which is precisely where most of this structural information lives —
at $T{=}1$, those probabilities are so close to zero that gradients from them barely register.
""")
# ---------------------------------------------------------------------------
# Task 2
# ---------------------------------------------------------------------------
md("""### Task 2 — Student Tokenizer Alignment
The Student will use its **own** compact WordPiece tokenizer (trained from scratch on the banking77 corpus,
with a vocabulary roughly 10x smaller than BERT's), rather than reusing the Teacher's `bert-base-uncased`
tokenizer. This section builds that tokenizer and demonstrates how it segments text differently from the
Teacher's.""")
code(r"""student_tok_backend = HFTokenizer(WordPiece(unk_token="[UNK]"))
student_tok_backend.normalizer = BertNormalizer(lowercase=True)
student_tok_backend.pre_tokenizer = Whitespace()
STUDENT_VOCAB_SIZE_TARGET = 3000
wp_trainer = WordPieceTrainer(
vocab_size=STUDENT_VOCAB_SIZE_TARGET,
special_tokens=["[PAD]", "[UNK]", "[CLS]", "[SEP]"],
min_frequency=1,
)
corpus_texts = train_raw["text"]
student_tok_backend.train_from_iterator(corpus_texts, wp_trainer)
student_tok_backend.post_processor = TemplateProcessing(
single="[CLS] $A [SEP]",
special_tokens=[
("[CLS]", student_tok_backend.token_to_id("[CLS]")),
("[SEP]", student_tok_backend.token_to_id("[SEP]")),
],
)
STUDENT_VOCAB_SIZE = student_tok_backend.get_vocab_size()
STUDENT_PAD_ID = student_tok_backend.token_to_id("[PAD]")
STUDENT_MAX_LEN = 32
print(f"Student vocab size : {STUDENT_VOCAB_SIZE}")
print(f"Teacher vocab size : {teacher_tokenizer.vocab_size}")
print(f"Vocab compression : {teacher_tokenizer.vocab_size / STUDENT_VOCAB_SIZE:.1f}x smaller")
""")
code(r"""sample_texts = [train_raw[i]["text"] for i in [0, 1, 2, 3, 4]]
rows = []
for t in sample_texts:
teacher_toks = teacher_tokenizer.tokenize(t)
student_toks = student_tok_backend.encode(t).tokens
rows.append({
"text": t,
"teacher_n_tokens": len(teacher_toks),
"teacher_tokens": " ".join(teacher_toks),
"student_n_tokens": len(student_toks),
"student_tokens": " ".join(student_toks),
})
tokenization_comparison = pd.DataFrame(rows)
tokenization_comparison
""")
code(r"""def student_encode_batch(texts, max_len=STUDENT_MAX_LEN, pad_id=STUDENT_PAD_ID):
encs = student_tok_backend.encode_batch(list(texts))
input_ids, attn = [], []
for e in encs:
ids = e.ids[:max_len]
pad_len = max_len - len(ids)
attention = [1] * len(ids) + [0] * pad_len
ids = ids + [pad_id] * pad_len
input_ids.append(ids)
attn.append(attention)
return torch.tensor(input_ids, dtype=torch.long), torch.tensor(attn, dtype=torch.long)
_demo_ids, _demo_attn = student_encode_batch(sample_texts[:2])
print("Example padded student input_ids shape:", _demo_ids.shape)
print(_demo_ids)
""")
md(r"""#### Handling the vocabulary mismatch between Teacher and Student
A naive version of logit distillation — as used in **token-level** distillation for tasks like
sequence-to-sequence generation or token classification — requires the Teacher's and Student's output
sequences to line up position-by-position, which breaks immediately if the two models tokenize the same
text into different numbers of tokens (which they always will here: the Teacher's ~30k-token vocabulary
segments text far more coarsely than the Student's ~3k-token vocabulary, as the comparison table above
shows — the Student consistently needs *more* subword pieces for the same utterance).
**Why this is not actually a hard problem for us:** distillation here is **sequence classification**, not
sequence generation. The Teacher does not produce a per-token output that would need to line up with the
Student's per-token output — it produces exactly **one 77-dimensional probability vector per example**,
regardless of how many tokens that example was split into internally. So the only alignment that matters is
at the **example (row) level**, not the token level:
- **Strategy used:** compute Teacher logits once per raw-text example (Task 1), indexed by the example's
position in the (unshuffled) training set. Independently tokenize the *same* raw text with the Student's
own tokenizer for the Student's forward pass. Join the two by index — `teacher_train_logits[i]` always
corresponds to `train_raw[i]`, no matter how differently `train_raw[i]["text"]` was tokenized by each
side. This is implemented directly in `BankingStudentDataset` below.
- **Residual risk, and why it's acceptable here:** a much smaller vocabulary means more aggressive subword
splitting and a higher `[UNK]` rate, which *can* lose lexical signal the Teacher had access to via its
richer vocabulary. We mitigate this by training the Student tokenizer directly on in-domain banking77
text (rather than a generic corpus), so the ~3k tokens it does have are the ones that matter most for this
task's vocabulary (e.g. "card", "transfer", "pin", "exchange" are highly likely to survive intact as
whole-word tokens instead of being fragmented).
""")
# ---------------------------------------------------------------------------
# Module 2 / Task 3
# ---------------------------------------------------------------------------
md("""## Module 2: Distillation Architecture & Training
### Task 3 — Compact Student Transformer Construction
A small, hand-built encoder-only Transformer: learned token + positional embeddings, 4 Transformer encoder
layers (hidden size 256, 4 attention heads, feed-forward size 512), mean-pooling over non-padding tokens,
and a linear classification head to 77 classes. Built directly from `nn.Module` / `nn.TransformerEncoderLayer`
primitives rather than repurposing a pretrained architecture, and sized to run comfortably on CPU.""")
code(r"""class CompactStudentTransformer(nn.Module):
def __init__(self, vocab_size, num_labels, hidden_size=256, num_layers=4, num_heads=4,
ffn_size=512, max_len=32, dropout=0.1, pad_id=0):
super().__init__()
self.pad_id = pad_id
self.token_embedding = nn.Embedding(vocab_size, hidden_size, padding_idx=pad_id)
self.position_embedding = nn.Embedding(max_len, hidden_size)
encoder_layer = nn.TransformerEncoderLayer(
d_model=hidden_size,
nhead=num_heads,
dim_feedforward=ffn_size,
dropout=dropout,
activation="gelu",
batch_first=True,
)
self.encoder = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
self.dropout = nn.Dropout(dropout)
self.classifier = nn.Linear(hidden_size, num_labels)
def forward(self, input_ids, attention_mask):
seq_len = input_ids.size(1)
positions = torch.arange(seq_len, device=input_ids.device).unsqueeze(0)
x = self.token_embedding(input_ids) + self.position_embedding(positions)
pad_mask = attention_mask == 0 # True where padded -> ignored by attention
x = self.encoder(x, src_key_padding_mask=pad_mask)
mask = attention_mask.unsqueeze(-1).float()
pooled = (x * mask).sum(dim=1) / mask.sum(dim=1).clamp(min=1e-6)
return self.classifier(self.dropout(pooled))
# inspect.getsource() cannot recover source for classes defined inside a notebook cell executed by
# nbconvert (no backing file for linecache to read), so we keep an explicit copy of this class's source
# alongside it for the subprocess-isolated benchmarking worker script in Task 6.
STUDENT_CLASS_SOURCE = '''class CompactStudentTransformer(nn.Module):
def __init__(self, vocab_size, num_labels, hidden_size=256, num_layers=4, num_heads=4,
ffn_size=512, max_len=32, dropout=0.1, pad_id=0):
super().__init__()
self.pad_id = pad_id
self.token_embedding = nn.Embedding(vocab_size, hidden_size, padding_idx=pad_id)
self.position_embedding = nn.Embedding(max_len, hidden_size)
encoder_layer = nn.TransformerEncoderLayer(
d_model=hidden_size,
nhead=num_heads,
dim_feedforward=ffn_size,
dropout=dropout,
activation="gelu",
batch_first=True,
)
self.encoder = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
self.dropout = nn.Dropout(dropout)
self.classifier = nn.Linear(hidden_size, num_labels)
def forward(self, input_ids, attention_mask):
seq_len = input_ids.size(1)
positions = torch.arange(seq_len, device=input_ids.device).unsqueeze(0)
x = self.token_embedding(input_ids) + self.position_embedding(positions)
pad_mask = attention_mask == 0 # True where padded -> ignored by attention
x = self.encoder(x, src_key_padding_mask=pad_mask)
mask = attention_mask.unsqueeze(-1).float()
pooled = (x * mask).sum(dim=1) / mask.sum(dim=1).clamp(min=1e-6)
return self.classifier(self.dropout(pooled))
'''
STUDENT_CONFIG = dict(
vocab_size=STUDENT_VOCAB_SIZE,
num_labels=num_labels,
hidden_size=256,
num_layers=4,
num_heads=4,
ffn_size=512,
max_len=STUDENT_MAX_LEN,
dropout=0.1,
pad_id=STUDENT_PAD_ID,
)
def build_student():
torch.manual_seed(SEED)
return CompactStudentTransformer(**STUDENT_CONFIG)
_probe = build_student()
def count_params(module):
return sum(p.numel() for p in module.parameters())
total_student_params = count_params(_probe)
embedding_params = count_params(_probe.token_embedding) + count_params(_probe.position_embedding)
encoder_params = count_params(_probe.encoder)
classifier_params = count_params(_probe.classifier)
teacher_params = count_params(teacher_model)
print("Student parameter breakdown")
print("-" * 40)
print(f" Token + position embeddings : {embedding_params:,}")
print(f" Transformer encoder (4 layers): {encoder_params:,}")
print(f" Classification head : {classifier_params:,}")
print(f" TOTAL : {total_student_params:,}")
print()
print(f"Teacher (bert-base-uncased) TOTAL: {teacher_params:,}")
print(f"Compression ratio: {teacher_params / total_student_params:,.1f}x fewer parameters")
del _probe
""")
code(r"""display(Markdown(f'''
#### Interpretation
The compact Student has **{total_student_params:,} parameters** against the Teacher's
**{teacher_params:,}** — a **{teacher_params/total_student_params:,.1f}x** reduction. Roughly
**{embedding_params/total_student_params:.0%}** of the Student's budget sits in its embedding table alone,
which is the direct payoff of Task 2's small, domain-specific vocabulary ({STUDENT_VOCAB_SIZE} tokens vs.
BERT's {teacher_tokenizer.vocab_size}): most of a Transformer's parameter count for short-sequence
classification tasks scales with `vocab_size x hidden_size`, so shrinking the vocabulary is one of the single
highest-leverage compression decisions available, independent of how many encoder layers are kept.
'''))
""")
# ---------------------------------------------------------------------------
# Task 4
# ---------------------------------------------------------------------------
md("""### Task 4 — Distillation Loss Function
$$\\text{Loss} = \\alpha \\cdot T^2 \\cdot \\text{KL}\\big(P_{\\text{student}}^T \\,\\|\\, P_{\\text{teacher}}^T\\big) + (1-\\alpha)\\cdot \\text{CE}(y_{\\text{student}}, y_{\\text{true}})$$
with $T = 4.0$ and $\\alpha = 0.7$. The $T^2$ scaling (Hinton et al., 2015) compensates for the fact that
raising the temperature shrinks the magnitude of the gradients coming from the soft-label term by roughly
$1/T^2$ relative to the hard-label term, so without it the KD loss would be under-weighted relative to
$\\alpha$ once a large $T$ is introduced.""")
code(r"""class DistillationLoss(nn.Module):
def __init__(self, temperature=4.0, alpha=0.7):
super().__init__()
self.T = temperature
self.alpha = alpha
self.kl = nn.KLDivLoss(reduction="batchmean")
self.ce = nn.CrossEntropyLoss()
def forward(self, student_logits, teacher_logits, true_labels):
student_log_probs_T = F.log_softmax(student_logits / self.T, dim=-1)
teacher_probs_T = F.softmax(teacher_logits / self.T, dim=-1)
kd_loss = self.kl(student_log_probs_T, teacher_probs_T) * (self.T ** 2)
ce_loss = self.ce(student_logits, true_labels)
total = self.alpha * kd_loss + (1 - self.alpha) * ce_loss
return total, kd_loss.detach(), ce_loss.detach()
class BankingStudentDataset(Dataset):
# Joins raw text (re-tokenized with the STUDENT tokenizer) to cached TEACHER logits by row index.
def __init__(self, texts, labels, teacher_logits=None):
self.input_ids, self.attention_mask = student_encode_batch(texts)
self.labels = torch.tensor(labels, dtype=torch.long)
self.teacher_logits = teacher_logits
def __len__(self):
return len(self.labels)
def __getitem__(self, idx):
item = {
"input_ids": self.input_ids[idx],
"attention_mask": self.attention_mask[idx],
"labels": self.labels[idx],
}
if self.teacher_logits is not None:
item["teacher_logits"] = self.teacher_logits[idx]
return item
train_texts, train_labels = train_raw["text"], train_raw["label"]
test_texts, test_labels = test_raw["text"], test_raw["label"]
distill_train_dataset = BankingStudentDataset(train_texts, train_labels, teacher_logits=teacher_train_logits)
baseline_train_dataset = BankingStudentDataset(train_texts, train_labels, teacher_logits=None)
student_test_dataset = BankingStudentDataset(test_texts, test_labels, teacher_logits=None)
print(f"Distillation train set: {len(distill_train_dataset)} examples (with cached teacher logits)")
print(f"Baseline train set : {len(baseline_train_dataset)} examples (hard labels only)")
""")
code(r"""def train_student(model, dataset, device, epochs=8, batch_size=32, lr=3e-4,
distill=False, temperature=4.0, alpha=0.7, log_prefix="student"):
model.to(device)
loader = DataLoader(dataset, batch_size=batch_size, shuffle=True)
optimizer = torch.optim.AdamW(model.parameters(), lr=lr)
ce_loss_fn = nn.CrossEntropyLoss()
distill_loss_fn = DistillationLoss(temperature=temperature, alpha=alpha) if distill else None
history = {"total": [], "kd": [], "ce": []}
model.train()
for epoch in range(epochs):
totals, kds, ces = [], [], []
for batch in loader:
input_ids = batch["input_ids"].to(device)
attention_mask = batch["attention_mask"].to(device)
labels = batch["labels"].to(device)
optimizer.zero_grad()
logits = model(input_ids, attention_mask)
if distill:
teacher_logits = batch["teacher_logits"].to(device)
loss, kd, ce = distill_loss_fn(logits, teacher_logits, labels)
kds.append(kd.item())
ces.append(ce.item())
else:
loss = ce_loss_fn(logits, labels)
loss.backward()
optimizer.step()
totals.append(loss.item())
avg_total = float(np.mean(totals))
history["total"].append(avg_total)
if distill:
history["kd"].append(float(np.mean(kds)))
history["ce"].append(float(np.mean(ces)))
print(f"[{log_prefix}] epoch {epoch+1}/{epochs} - loss {avg_total:.4f} "
f"(kd {history['kd'][-1]:.4f}, ce {history['ce'][-1]:.4f})")
else:
print(f"[{log_prefix}] epoch {epoch+1}/{epochs} - loss {avg_total:.4f}")
return history
STUDENT_EPOCHS = 8
""")
code(r"""torch.manual_seed(SEED)
distilled_student = build_student()
distill_start = time.time()
distill_history = train_student(
distilled_student, distill_train_dataset, STUDENT_DEVICE,
epochs=STUDENT_EPOCHS, batch_size=32, lr=3e-4,
distill=True, temperature=4.0, alpha=0.7, log_prefix="distilled",
)
distill_seconds = time.time() - distill_start
print(f"\nDistilled student training took {distill_seconds:.1f}s on {STUDENT_DEVICE}")
""")
code(r"""fig, axes = plt.subplots(1, 2, figsize=(11, 4))
axes[0].plot(distill_history["total"], marker="o", label="total loss")
axes[0].set_title("Distilled student: total loss")
axes[0].set_xlabel("epoch"); axes[0].set_ylabel("loss"); axes[0].legend()
axes[1].plot(distill_history["kd"], marker="o", label="KD term (KL, T-scaled)")
axes[1].plot(distill_history["ce"], marker="s", label="CE term (hard labels)")
axes[1].set_title("Distilled student: loss components")
axes[1].set_xlabel("epoch"); axes[1].set_ylabel("loss"); axes[1].legend()
plt.tight_layout()
plt.show()
""")
md("""**Interpretation:** the CE component (against ground-truth hard labels) typically drops faster and
further than the KD component, because a 3000-token-vocabulary, 4-layer Student can quickly memorize the
*correct class* for a small, well-separated training set, while matching the Teacher's *full smoothed
distribution* over 77 classes at $T{=}4$ is a strictly harder target — the KD term keeps providing a
non-trivial gradient signal well after the CE term has largely converged, which is exactly the regime where
distillation is doing useful work beyond what hard labels alone would teach.""")
# ---------------------------------------------------------------------------
# Module 3 / Task 5
# ---------------------------------------------------------------------------
md("""## Module 3: Comparative Analysis & Benchmarking
### Task 5 — Accuracy vs. Compression Evaluation
We now train an **identical-architecture baseline Student** from scratch using plain cross-entropy on
ground-truth labels only (no Teacher signal at all), so any accuracy difference between it and the
distilled Student isolates the effect of distillation itself, holding architecture, tokenizer, optimizer,
and epoch budget fixed.""")
code(r"""torch.manual_seed(SEED)
baseline_student = build_student()
baseline_start = time.time()
baseline_history = train_student(
baseline_student, baseline_train_dataset, STUDENT_DEVICE,
epochs=STUDENT_EPOCHS, batch_size=32, lr=3e-4,
distill=False, log_prefix="baseline",
)
baseline_seconds = time.time() - baseline_start
print(f"\nBaseline student training took {baseline_seconds:.1f}s on {STUDENT_DEVICE}")
""")
code(r"""plt.figure(figsize=(6, 4))
plt.plot(baseline_history["total"], marker="o", label="Baseline student (CE only)")
plt.plot(distill_history["total"], marker="s", label="Distilled student (KD + CE)")
plt.title("Training loss: baseline vs. distilled student")
plt.xlabel("epoch"); plt.ylabel("loss (not directly comparable in scale)"); plt.legend()
plt.tight_layout()
plt.show()
""")
code(r"""@torch.no_grad()
def evaluate_student(model, dataset, device, batch_size=64):
model.eval()
model.to(device)
loader = DataLoader(dataset, batch_size=batch_size, shuffle=False)
all_preds, all_labels = [], []
for batch in loader:
input_ids = batch["input_ids"].to(device)
attention_mask = batch["attention_mask"].to(device)
logits = model(input_ids, attention_mask)
all_preds.extend(torch.argmax(logits, dim=-1).cpu().numpy().tolist())
all_labels.extend(batch["labels"].numpy().tolist())
return np.array(all_preds), np.array(all_labels)
teacher_pred_output = trainer.predict(test_enc)
teacher_test_preds = np.argmax(teacher_pred_output.predictions, axis=-1)
teacher_test_labels = np.array(test_raw["label"])
baseline_preds, baseline_labels = evaluate_student(baseline_student, student_test_dataset, STUDENT_DEVICE)
distilled_preds, distilled_labels = evaluate_student(distilled_student, student_test_dataset, STUDENT_DEVICE)
def summarize(name, preds, labels):
return {
"Model": name,
"Accuracy": accuracy_score(labels, preds),
"Macro F1": f1_score(labels, preds, average="macro"),
"Weighted F1": f1_score(labels, preds, average="weighted"),
}
results_df = pd.DataFrame([
summarize("Teacher (bert-base-uncased)", teacher_test_preds, teacher_test_labels),
summarize("Student — WITHOUT distillation", baseline_preds, baseline_labels),
summarize("Student — WITH distillation", distilled_preds, distilled_labels),
])
results_df[["Accuracy", "Macro F1", "Weighted F1"]] = results_df[["Accuracy", "Macro F1", "Weighted F1"]].round(4)
results_df
""")
code(r"""def to_markdown_table(df):
header = "| " + " | ".join(df.columns) + " |"
sep = "|" + "|".join(["---"] * len(df.columns)) + "|"
rows = ["| " + " | ".join(str(v) for v in row) + " |" for row in df.values]
return "\n".join([header, sep] + rows)
teacher_acc = results_df.loc[0, "Accuracy"]
baseline_acc = results_df.loc[1, "Accuracy"]
distilled_acc = results_df.loc[2, "Accuracy"]
recovery = (distilled_acc - baseline_acc) / max(teacher_acc - baseline_acc, 1e-9) * 100
retention = distilled_acc / teacher_acc * 100
if distilled_acc >= teacher_acc:
gap_line = (
f"- Adding the Teacher's soft labels (identical architecture, identical data, identical epoch budget — "
f"only the loss function differs) raises the Student to **{distilled_acc:.1%}** accuracy, which "
f"**fully closes** the gap to the Teacher's **{teacher_acc:.1%}** and slightly surpasses it."
)
retention_line = (
f"- Remarkably, the distilled Student's **{distilled_acc:.1%}** accuracy matches — and here, "
f"slightly exceeds — the Teacher's **{teacher_acc:.1%}**, at **{teacher_params/total_student_params:,.0f}x** "
f"fewer parameters. This is a stronger-than-typical (though not unheard of) outcome: the Teacher was "
f"only fine-tuned for a few epochs, so its own decision boundary still carries some noise, and the "
f"test set is a few thousand examples, so a couple of points either way is within normal variance. "
f"The soft-label targets act as a strong regularizer that helps the tiny Student generalize at least "
f"as well on this held-out set — that does **not** mean the Student has absorbed *all* of the "
f"Teacher's knowledge, only that on this test split and this metric, distillation fully closed the gap."
)
else:
gap_line = (
f"- Adding the Teacher's soft labels (identical architecture, identical data, identical epoch budget — "
f"only the loss function differs) raises the Student to **{distilled_acc:.1%}** accuracy, closing "
f"**{recovery:.0f}%** of the accuracy gap between the undistilled Student and the Teacher."
)
retention_line = (
f"- The distilled Student retains **{retention:.1f}%** of the Teacher's accuracy at a fraction of its "
f"parameter count — this is the central empirical claim of knowledge distillation: dark knowledge in "
f"the soft labels lets a small model recover much more of a large model's decision surface than the "
f"same small model could learn from hard labels alone."
)
display(Markdown(f'''
#### Comparison table
{to_markdown_table(results_df)}
#### Interpretation
- The undistilled Student, trained only on hard labels with a **{teacher_params/total_student_params:,.0f}x**
smaller architecture and a **{STUDENT_EPOCHS}**-epoch budget over the same {len(train_raw)} examples,
reaches **{baseline_acc:.1%}** accuracy — a substantial gap below the Teacher's **{teacher_acc:.1%}**,
as expected given how much capacity was removed.
{gap_line}
{retention_line}
'''))
""")
# ---------------------------------------------------------------------------
# Task 6
# ---------------------------------------------------------------------------
md("""### Task 6 — Deployment Metrics Analysis
We measure three deployment-relevant metrics for the Teacher vs. the (distilled) Student:
1. **Disk size** — serialized `state_dict` size on disk.
2. **CPU inference latency** — mean wall-clock time per single-example (`batch_size=1`) forward pass on CPU.
3. **Peak process RAM** — measured in an **isolated subprocess per model** (via `resource.getrusage`), so
the Teacher's ~440MB footprint doesn't contaminate the Student's measurement just because both happen to
be loaded in the same notebook kernel.""")
code(r"""def get_model_disk_size_mb(state_dict):
with tempfile.NamedTemporaryFile(suffix=".pt") as f:
torch.save(state_dict, f.name)
f.flush()
size_bytes = os.path.getsize(f.name)
return size_bytes / (1024 ** 2)
teacher_size_mb = get_model_disk_size_mb(teacher_model.state_dict())
student_size_mb = get_model_disk_size_mb(distilled_student.state_dict())
print(f"Teacher disk size : {teacher_size_mb:,.1f} MB")
print(f"Student disk size : {student_size_mb:,.1f} MB")
print(f"Size reduction : {teacher_size_mb/student_size_mb:,.1f}x smaller")
""")
code(r"""@torch.no_grad()
def measure_teacher_cpu_latency(model, tokenizer, texts, n_warmup=5, n_runs=50):
model.to(CPU_DEVICE)
model.eval()
encs = [tokenizer(t, return_tensors="pt", truncation=True, max_length=64) for t in texts]
for i in range(n_warmup):
model(**encs[i % len(encs)])
times = []
for i in range(n_runs):
enc = encs[i % len(encs)]
start = time.perf_counter()
model(**enc)
times.append((time.perf_counter() - start) * 1000)
return float(np.mean(times)), float(np.std(times))
@torch.no_grad()
def measure_student_cpu_latency(model, texts, n_warmup=5, n_runs=50):
model.to(CPU_DEVICE)
model.eval()
ids, attn = student_encode_batch(texts)
for i in range(n_warmup):
idx = i % len(texts)
model(ids[idx].unsqueeze(0), attn[idx].unsqueeze(0))
times = []
for i in range(n_runs):
idx = i % len(texts)
start = time.perf_counter()
model(ids[idx].unsqueeze(0), attn[idx].unsqueeze(0))
times.append((time.perf_counter() - start) * 1000)
return float(np.mean(times)), float(np.std(times))
latency_sample_texts = test_texts[:20]
teacher_latency_mean, teacher_latency_std = measure_teacher_cpu_latency(teacher_model, teacher_tokenizer, latency_sample_texts)
student_latency_mean, student_latency_std = measure_student_cpu_latency(distilled_student, latency_sample_texts)
print(f"Teacher CPU latency : {teacher_latency_mean:.2f} +/- {teacher_latency_std:.2f} ms/query")
print(f"Student CPU latency : {student_latency_mean:.2f} +/- {student_latency_std:.2f} ms/query")
print(f"Speedup : {teacher_latency_mean/student_latency_mean:,.1f}x faster")
""")
code(r"""# Peak RAM, measured per model in an isolated subprocess so each number reflects ONLY that model's
# footprint (loading both Teacher and Student into one long-lived kernel would make ru_maxrss monotonically
# dominated by whichever model was loaded first).
teacher_worker_src = (
"import sys, resource, torch\n"
"from transformers import BertForSequenceClassification, AutoTokenizer\n"
"model_dir = sys.argv[1]\n"
"model = BertForSequenceClassification.from_pretrained(model_dir)\n"
"tokenizer = AutoTokenizer.from_pretrained(model_dir)\n"
"model.eval()\n"
"texts = ['I am still waiting on my card?'] * 30\n"
"with torch.no_grad():\n"
" for t in texts:\n"
" enc = tokenizer(t, return_tensors='pt', truncation=True, max_length=64)\n"
" model(**enc)\n"
"print(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)\n"
)
student_class_src = STUDENT_CLASS_SOURCE
student_worker_src = (
"import sys, json, resource, torch\n"
"import torch.nn as nn\n"
"from tokenizers import Tokenizer as HFTokenizer\n\n"
+ student_class_src + "\n\n"
"model_dir = sys.argv[1]\n"
"cfg = json.load(open(model_dir + '/config.json'))\n"
"model = CompactStudentTransformer(**cfg)\n"
"model.load_state_dict(torch.load(model_dir + '/weights.pt', map_location='cpu'))\n"
"model.eval()\n"
"tok = HFTokenizer.from_file(model_dir + '/tokenizer.json')\n"
"texts = ['I am still waiting on my card?'] * 30\n"
"with torch.no_grad():\n"
" for t in texts:\n"
" ids = tok.encode(t).ids[:cfg['max_len']]\n"
" pad_len = cfg['max_len'] - len(ids)\n"
" attn = [1]*len(ids) + [0]*pad_len\n"
" ids = ids + [cfg['pad_id']]*pad_len\n"
" input_ids = torch.tensor([ids])\n"
" attention_mask = torch.tensor([attn])\n"
" model(input_ids, attention_mask)\n"
"print(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)\n"
)
with tempfile.TemporaryDirectory() as tmp_root:
teacher_dir = os.path.join(tmp_root, "teacher")
student_dir = os.path.join(tmp_root, "student")
os.makedirs(teacher_dir, exist_ok=True)
os.makedirs(student_dir, exist_ok=True)
teacher_model.save_pretrained(teacher_dir)
teacher_tokenizer.save_pretrained(teacher_dir)
torch.save(distilled_student.state_dict(), os.path.join(student_dir, "weights.pt"))
with open(os.path.join(student_dir, "config.json"), "w") as f:
json.dump(STUDENT_CONFIG, f)
student_tok_backend.save(os.path.join(student_dir, "tokenizer.json"))
teacher_worker_path = os.path.join(tmp_root, "teacher_worker.py")
student_worker_path = os.path.join(tmp_root, "student_worker.py")
with open(teacher_worker_path, "w") as f:
f.write(teacher_worker_src)
with open(student_worker_path, "w") as f:
f.write(student_worker_src)
teacher_ram_out = subprocess.run(
[sys.executable, teacher_worker_path, teacher_dir],
capture_output=True, text=True, check=True,
)
student_ram_out = subprocess.run(
[sys.executable, student_worker_path, student_dir],
capture_output=True, text=True, check=True,
)
_bytes_per_unit = 1 # macOS ru_maxrss is already in bytes
teacher_peak_ram_mb = int(teacher_ram_out.stdout.strip()) * _bytes_per_unit / (1024 ** 2)
student_peak_ram_mb = int(student_ram_out.stdout.strip()) * _bytes_per_unit / (1024 ** 2)
print(f"Teacher peak RAM (isolated process) : {teacher_peak_ram_mb:,.1f} MB")
print(f"Student peak RAM (isolated process) : {student_peak_ram_mb:,.1f} MB")
print(f"RAM reduction : {teacher_peak_ram_mb/student_peak_ram_mb:,.1f}x smaller")
""")
code(r"""deployment_df = pd.DataFrame([
{"Metric": "Disk size (MB)", "Teacher": round(teacher_size_mb, 1), "Student": round(student_size_mb, 1),
"Reduction": f"{teacher_size_mb/student_size_mb:.1f}x"},
{"Metric": "CPU latency (ms/query)", "Teacher": round(teacher_latency_mean, 2), "Student": round(student_latency_mean, 2),
"Reduction": f"{teacher_latency_mean/student_latency_mean:.1f}x"},
{"Metric": "Peak RAM (MB)", "Teacher": round(teacher_peak_ram_mb, 1), "Student": round(student_peak_ram_mb, 1),
"Reduction": f"{teacher_peak_ram_mb/student_peak_ram_mb:.1f}x"},
])
deployment_df
""")
code(r"""accuracy_retained_pct = distilled_acc / teacher_acc * 100
size_reduction_x = teacher_size_mb / student_size_mb
latency_reduction_x = teacher_latency_mean / student_latency_mean
ram_reduction_x = teacher_peak_ram_mb / student_peak_ram_mb
if distilled_acc >= teacher_acc:
accuracy_summary_line = (
f"while matching (here, slightly exceeding) its accuracy on the exact same 77-way classification task."
)
accuracy_tradeoff_bullet = (
f"- **Accuracy trade-off** — in this run there isn't one: the distilled Student's accuracy is at "
f"least as high as the Teacher's, so the size/latency/RAM wins below come essentially for free on "
f"this test set. That is a favorable outcome, not a guarantee — it reflects a lightly-fine-tuned "
f"Teacher and a modest-size test set as much as it reflects the Student's quality, so a production "
f"rollout should still monitor accuracy on live traffic rather than assuming this margin holds "
f"indefinitely as data drifts."
)
else:
accuracy_summary_line = (
f"while retaining **{accuracy_retained_pct:.1f}%** of its accuracy on the exact same 77-way "
f"classification task."
)
accuracy_tradeoff_bullet = (
f"- **Accuracy trade-off** — the real cost is the **{100-accuracy_retained_pct:.1f} percentage "
f"points** of relative accuracy given up. Whether that is acceptable depends entirely on the "
f"product: for a first-pass intent router that falls back to a human agent or a larger cloud model "
f"on low confidence, this trade is usually a clear win — the compute/latency/cost savings at massive "
f"query volume outweigh a modest accuracy gap. For a fully autonomous decision with no fallback "
f"(e.g. auto-approving a refund), the remaining gap to the Teacher may still be too large to deploy "
f"the Student *alone*."
)
display(Markdown(f'''
#### Deployment-readiness analysis
{to_markdown_table(deployment_df)}
The distilled Student is **{size_reduction_x:.1f}x smaller on disk**, **{latency_reduction_x:.1f}x faster**
per CPU query, and uses **{ram_reduction_x:.1f}x less peak RAM** than the Teacher, {accuracy_summary_line}
**Is this deployment-ready for edge/mobile?**
- **Size and RAM** — at ~{student_size_mb:.0f}MB on disk and ~{student_peak_ram_mb:.0f}MB of peak RAM, the
Student comfortably fits within the memory budgets of edge devices and mobile apps, where a
{teacher_size_mb:.0f}MB+ BERT-base checkpoint is frequently a non-starter (app-store bundle-size limits,
low-RAM Android devices, on-device model caches).
- **Latency** — {student_latency_mean:.1f}ms/query on CPU is well within the range needed for a responsive,
synchronous UI interaction (e.g. intent routing as a user types), whereas the Teacher's
{teacher_latency_mean:.1f}ms/query, multiplied across a request queue on a resource-constrained device,
would noticeably degrade perceived responsiveness.
{accuracy_tradeoff_bullet}
- **Practical recommendation** — deploy the distilled Student as the default path, and route low-confidence
predictions (small margin between the top-2 softmax probabilities) to the Teacher or a human reviewer.
This captures most of the size/latency/RAM benefits demonstrated above while bounding the accuracy risk
to only the genuinely ambiguous cases — which is exactly the scenario dark-knowledge distillation is
suited for, since the Student was trained to mimic the Teacher's *confidence structure*, not just its
argmax.
'''))
""")
nb["cells"] = cells
with open("knowledge_distillation_assignment.ipynb", "w") as f:
nbf.write(nb, f)
print(f"Notebook written with {len(cells)} cells.")