reevec commited on
Commit
3877cdc
·
verified ·
1 Parent(s): fe8a8c4

Upload 8 files

Browse files
.gitattributes CHANGED
@@ -55,3 +55,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
55
  *.webp filter=lfs diff=lfs merge=lfs -text
56
  Assignment[[:space:]]I.pdf filter=lfs diff=lfs merge=lfs -text
57
  Assignment-2A-PromptingAsSystemDesign.pdf filter=lfs diff=lfs merge=lfs -text
 
 
55
  *.webp filter=lfs diff=lfs merge=lfs -text
56
  Assignment[[:space:]]I.pdf filter=lfs diff=lfs merge=lfs -text
57
  Assignment-2A-PromptingAsSystemDesign.pdf filter=lfs diff=lfs merge=lfs -text
58
+ demo/Knowledge_Distillation_Report_Group85.pdf filter=lfs diff=lfs merge=lfs -text
demo/Knowledge_Distillation_Report_Group85.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:62ad408a156b9cec054031868ef0b849a0759d0bc8f2deb6aa63039fbf39c51f
3
+ size 125251
demo/build_notebook.py ADDED
@@ -0,0 +1,971 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Builds knowledge_distillation_assignment.ipynb from scratch via nbformat."""
2
+ import nbformat as nbf
3
+
4
+ nb = nbf.v4.new_notebook()
5
+ cells = []
6
+
7
+ def md(src):
8
+ cells.append(nbf.v4.new_markdown_cell(src))
9
+
10
+ def code(src):
11
+ cells.append(nbf.v4.new_code_cell(src))
12
+
13
+ # ---------------------------------------------------------------------------
14
+ # Title
15
+ # ---------------------------------------------------------------------------
16
+ md(r"""# Knowledge Distillation on `PolyAI/banking77`
17
+
18
+ **Assignment:** Compress a high-capacity fine-tuned Transformer ("Teacher") into a compact, CPU-friendly
19
+ Transformer ("Student") via knowledge distillation, and quantify what is gained and lost in the process.
20
+
21
+ **Dataset:** [`PolyAI/banking77`](https://huggingface.co/datasets/PolyAI/banking77) — 77-way fine-grained
22
+ banking-intent classification, 10,003 train / 3,080 test utterances.
23
+
24
+ **Environment:** conda env `agn_env` (Python 3.12), Apple Silicon (MPS acceleration used for teacher
25
+ fine-tuning; the student is trained and benchmarked on **CPU only**, matching its target deployment profile).
26
+
27
+ | Module | Tasks |
28
+ |---|---|
29
+ | 1. Teacher Labeling & Student Setup | Task 1: Teacher fine-tuning & soft-label generation · Task 2: Student tokenizer alignment |
30
+ | 2. Distillation Architecture & Training | Task 3: Compact student transformer · Task 4: Distillation loss & training |
31
+ | 3. Comparative Analysis & Benchmarking | Task 5: Accuracy vs. compression · Task 6: Deployment metrics |
32
+ """)
33
+
34
+ # ---------------------------------------------------------------------------
35
+ # Setup
36
+ # ---------------------------------------------------------------------------
37
+ 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.")
38
+
39
+ code(r"""# Ensure required libraries are present in the active (agn_env) kernel.
40
+ import sys
41
+ !{sys.executable} -m pip install -q torch transformers datasets scikit-learn psutil evaluate accelerate tokenizers ipykernel matplotlib
42
+ """)
43
+
44
+ code(r"""import os
45
+ import gc
46
+ import json
47
+ import time
48
+ import random
49
+ import tempfile
50
+ import subprocess
51
+ from collections import OrderedDict
52
+
53
+ import numpy as np
54
+ import pandas as pd
55
+ import torch
56
+ import torch.nn as nn
57
+ import torch.nn.functional as F
58
+ from torch.utils.data import Dataset, DataLoader
59
+ import matplotlib.pyplot as plt
60
+ from IPython.display import display, Markdown
61
+
62
+ from datasets import load_dataset
63
+ from transformers import (
64
+ AutoTokenizer,
65
+ BertForSequenceClassification,
66
+ TrainingArguments,
67
+ Trainer,
68
+ DataCollatorWithPadding,
69
+ )
70
+ from tokenizers import Tokenizer as HFTokenizer
71
+ from tokenizers.models import WordPiece
72
+ from tokenizers.trainers import WordPieceTrainer
73
+ from tokenizers.pre_tokenizers import Whitespace
74
+ from tokenizers.normalizers import BertNormalizer
75
+ from tokenizers.processors import TemplateProcessing
76
+
77
+ from sklearn.metrics import accuracy_score, f1_score
78
+
79
+ import psutil
80
+
81
+ SEED = 42
82
+ random.seed(SEED)
83
+ np.random.seed(SEED)
84
+ torch.manual_seed(SEED)
85
+
86
+ TRAIN_DEVICE = torch.device("mps") if torch.backends.mps.is_available() else torch.device("cpu")
87
+ CPU_DEVICE = torch.device("cpu")
88
+ STUDENT_DEVICE = CPU_DEVICE # student is trained + benchmarked on CPU throughout: this is the point of the exercise
89
+
90
+ print(f"Teacher training device : {TRAIN_DEVICE}")
91
+ print(f"Student device (always) : {STUDENT_DEVICE}")
92
+ """)
93
+
94
+ # ---------------------------------------------------------------------------
95
+ # Module 1 / Task 1
96
+ # ---------------------------------------------------------------------------
97
+ md("""## Module 1: Teacher Labeling & Student Setup
98
+
99
+ ### Task 1 — Teacher Integration & Soft-Label Generation
100
+
101
+ We fine-tune `bert-base-uncased` (110M parameters) end-to-end on banking77 as our **Teacher**. Once
102
+ fine-tuned, we run one no-grad forward pass over the *entire* training set to cache the Teacher's raw
103
+ 77-dimensional **logits** for every example. These cached logits are the "soft labels" used by the
104
+ distillation loss in Task 4 — they are computed once, up front, so the (comparatively expensive) Teacher
105
+ never needs to run again during Student training.""")
106
+
107
+ code(r"""# Load banking77. The original PolyAI/banking77 repo only ships a loading *script*, which recent
108
+ # versions of `datasets` (>=4.0) no longer execute. We fall back to a verified parquet mirror with
109
+ # identical contents (10,003 train / 3,080 test / same 77 ClassLabel names) if the script path fails.
110
+ try:
111
+ raw_datasets = load_dataset("PolyAI/banking77")
112
+ dataset_source = "PolyAI/banking77"
113
+ except Exception as e:
114
+ print(f"Could not load PolyAI/banking77 directly ({type(e).__name__}); "
115
+ f"falling back to the parquet mirror legacy-datasets/banking77.")
116
+ raw_datasets = load_dataset("legacy-datasets/banking77")
117
+ dataset_source = "legacy-datasets/banking77 (parquet mirror of PolyAI/banking77)"
118
+
119
+ train_raw = raw_datasets["train"]
120
+ test_raw = raw_datasets["test"]
121
+ label_names = train_raw.features["label"].names
122
+ num_labels = len(label_names)
123
+
124
+ print(f"Loaded from : {dataset_source}")
125
+ print(f"Train examples : {len(train_raw)}")
126
+ print(f"Test examples : {len(test_raw)}")
127
+ print(f"Classes : {num_labels}")
128
+ print(f"\nSample row: {train_raw[0]}")
129
+ print(f"First 10 intents: {label_names[:10]}")
130
+ """)
131
+
132
+ code(r"""TEACHER_NAME = "bert-base-uncased"
133
+ teacher_tokenizer = AutoTokenizer.from_pretrained(TEACHER_NAME)
134
+
135
+ def teacher_tokenize(batch):
136
+ return teacher_tokenizer(batch["text"], truncation=True, max_length=64)
137
+
138
+ train_enc = train_raw.map(teacher_tokenize, batched=True)
139
+ test_enc = test_raw.map(teacher_tokenize, batched=True)
140
+
141
+ train_enc = train_enc.rename_column("label", "labels")
142
+ test_enc = test_enc.rename_column("label", "labels")
143
+ train_enc.set_format(type="torch", columns=["input_ids", "attention_mask", "labels"])
144
+ test_enc.set_format(type="torch", columns=["input_ids", "attention_mask", "labels"])
145
+
146
+ teacher_data_collator = DataCollatorWithPadding(tokenizer=teacher_tokenizer)
147
+ print("Tokenized train/test sets ready for the Teacher.")
148
+ """)
149
+
150
+ code(r"""teacher_model = BertForSequenceClassification.from_pretrained(TEACHER_NAME, num_labels=num_labels)
151
+
152
+ def compute_metrics(eval_pred):
153
+ logits, labels = eval_pred
154
+ preds = np.argmax(logits, axis=-1)
155
+ return {
156
+ "accuracy": accuracy_score(labels, preds),
157
+ "macro_f1": f1_score(labels, preds, average="macro"),
158
+ }
159
+
160
+ teacher_training_args = TrainingArguments(
161
+ output_dir="./teacher_ckpt",
162
+ num_train_epochs=3,
163
+ per_device_train_batch_size=32,
164
+ per_device_eval_batch_size=64,
165
+ learning_rate=3e-5,
166
+ weight_decay=0.01,
167
+ eval_strategy="epoch",
168
+ save_strategy="no",
169
+ logging_steps=50,
170
+ report_to="none",
171
+ seed=SEED,
172
+ )
173
+
174
+ trainer = Trainer(
175
+ model=teacher_model,
176
+ args=teacher_training_args,
177
+ train_dataset=train_enc,
178
+ eval_dataset=test_enc,
179
+ data_collator=teacher_data_collator,
180
+ compute_metrics=compute_metrics,
181
+ )
182
+
183
+ teacher_train_start = time.time()
184
+ trainer.train()
185
+ teacher_train_seconds = time.time() - teacher_train_start
186
+ print(f"\nTeacher fine-tuning took {teacher_train_seconds/60:.1f} minutes")
187
+ """)
188
+
189
+ code(r"""teacher_eval_metrics = trainer.evaluate()
190
+ print("Teacher eval metrics (test set):", teacher_eval_metrics)
191
+ """)
192
+
193
+ code(r"""# Cache soft labels: one no-grad forward pass over the FULL training set, in original (unshuffled)
194
+ # order, so teacher_train_logits[i] corresponds exactly to train_raw[i] by index.
195
+ teacher_model.eval()
196
+ teacher_model.to(TRAIN_DEVICE)
197
+
198
+ @torch.no_grad()
199
+ def get_teacher_logits(dataset, batch_size=64):
200
+ loader = DataLoader(dataset, batch_size=batch_size, shuffle=False, collate_fn=teacher_data_collator)
201
+ all_logits = []
202
+ for batch in loader:
203
+ inputs = {k: v.to(TRAIN_DEVICE) for k, v in batch.items() if k != "labels"}
204
+ outputs = teacher_model(**inputs)
205
+ all_logits.append(outputs.logits.detach().cpu())
206
+ return torch.cat(all_logits, dim=0)
207
+
208
+ teacher_train_logits = get_teacher_logits(train_enc)
209
+ teacher_test_logits = get_teacher_logits(test_enc)
210
+
211
+ print(f"Cached teacher train logits: {teacher_train_logits.shape}")
212
+ print(f"Cached teacher test logits : {teacher_test_logits.shape}")
213
+ assert teacher_train_logits.shape[0] == len(train_raw)
214
+ """)
215
+
216
+ md(r"""#### Why soft labels carry "dark knowledge"
217
+
218
+ A one-hot hard label for the utterance *"I am still waiting on my card?"* says only: **the correct class is
219
+ `card_arrival`, and every other one of the 77 classes is equally, absolutely wrong.** That is not true, and
220
+ it is not what the Teacher actually believes. The Teacher's full softmax distribution over 77 classes might
221
+ look like `card_arrival: 0.62, card_delivery_estimate: 0.21, lost_or_stolen_card: 0.05, ...` — it correctly
222
+ picks `card_arrival`, but it also encodes *how confusable* the other intents are with it.
223
+
224
+ This matters a great deal on a fine-grained, semantically overlapping taxonomy like banking77, which
225
+ contains many near-duplicate intents (`card_arrival` vs. `card_delivery_estimate`, `declined_card_payment`
226
+ vs. `declined_cash_withdrawal`, `top_up_failed` vs. `pending_top_up`, ...). Training only against a hard
227
+ label throws away exactly the information that describes *why* those pairs are confusable — the relative
228
+ geometry of the Teacher's learned decision boundary. Training against the full distribution instead:
229
+
230
+ 1. **Transfers inter-class similarity structure.** The relative magnitudes of the non-argmax probabilities
231
+ act as a learned "confusion prior" — pairs of intents the Teacher finds similar get correlated soft
232
+ targets across many training examples, which is a much richer training signal than 76 identical zeros.
233
+ 2. **Provides a smoother, higher-entropy target**, which acts as an implicit regularizer: the Student is not
234
+ forced to drive its logits to ±∞ to satisfy a one-hot target, so its learned representations generalize
235
+ better on held-out data, especially with the very limited parameter budget a compact Student has.
236
+ 3. **Effectively gives more supervision per example.** A hard label is `log2(77) ≈ 6.3` bits of information at
237
+ best (which class). A soft label is a full probability vector — many more effective bits — so a Student
238
+ with less capacity and less data than the Teacher can still recover much of the Teacher's decision
239
+ surface from the *same* training set.
240
+ 4. **Raising the temperature $T$ before softmax** (used in Task 4) further amplifies the small
241
+ probabilities on non-target classes, which is precisely where most of this structural information lives —
242
+ at $T{=}1$, those probabilities are so close to zero that gradients from them barely register.
243
+ """)
244
+
245
+ # ---------------------------------------------------------------------------
246
+ # Task 2
247
+ # ---------------------------------------------------------------------------
248
+ md("""### Task 2 — Student Tokenizer Alignment
249
+
250
+ The Student will use its **own** compact WordPiece tokenizer (trained from scratch on the banking77 corpus,
251
+ with a vocabulary roughly 10x smaller than BERT's), rather than reusing the Teacher's `bert-base-uncased`
252
+ tokenizer. This section builds that tokenizer and demonstrates how it segments text differently from the
253
+ Teacher's.""")
254
+
255
+ code(r"""student_tok_backend = HFTokenizer(WordPiece(unk_token="[UNK]"))
256
+ student_tok_backend.normalizer = BertNormalizer(lowercase=True)
257
+ student_tok_backend.pre_tokenizer = Whitespace()
258
+
259
+ STUDENT_VOCAB_SIZE_TARGET = 3000
260
+ wp_trainer = WordPieceTrainer(
261
+ vocab_size=STUDENT_VOCAB_SIZE_TARGET,
262
+ special_tokens=["[PAD]", "[UNK]", "[CLS]", "[SEP]"],
263
+ min_frequency=1,
264
+ )
265
+
266
+ corpus_texts = train_raw["text"]
267
+ student_tok_backend.train_from_iterator(corpus_texts, wp_trainer)
268
+
269
+ student_tok_backend.post_processor = TemplateProcessing(
270
+ single="[CLS] $A [SEP]",
271
+ special_tokens=[
272
+ ("[CLS]", student_tok_backend.token_to_id("[CLS]")),
273
+ ("[SEP]", student_tok_backend.token_to_id("[SEP]")),
274
+ ],
275
+ )
276
+
277
+ STUDENT_VOCAB_SIZE = student_tok_backend.get_vocab_size()
278
+ STUDENT_PAD_ID = student_tok_backend.token_to_id("[PAD]")
279
+ STUDENT_MAX_LEN = 32
280
+
281
+ print(f"Student vocab size : {STUDENT_VOCAB_SIZE}")
282
+ print(f"Teacher vocab size : {teacher_tokenizer.vocab_size}")
283
+ print(f"Vocab compression : {teacher_tokenizer.vocab_size / STUDENT_VOCAB_SIZE:.1f}x smaller")
284
+ """)
285
+
286
+ code(r"""sample_texts = [train_raw[i]["text"] for i in [0, 1, 2, 3, 4]]
287
+ rows = []
288
+ for t in sample_texts:
289
+ teacher_toks = teacher_tokenizer.tokenize(t)
290
+ student_toks = student_tok_backend.encode(t).tokens
291
+ rows.append({
292
+ "text": t,
293
+ "teacher_n_tokens": len(teacher_toks),
294
+ "teacher_tokens": " ".join(teacher_toks),
295
+ "student_n_tokens": len(student_toks),
296
+ "student_tokens": " ".join(student_toks),
297
+ })
298
+
299
+ tokenization_comparison = pd.DataFrame(rows)
300
+ tokenization_comparison
301
+ """)
302
+
303
+ code(r"""def student_encode_batch(texts, max_len=STUDENT_MAX_LEN, pad_id=STUDENT_PAD_ID):
304
+ encs = student_tok_backend.encode_batch(list(texts))
305
+ input_ids, attn = [], []
306
+ for e in encs:
307
+ ids = e.ids[:max_len]
308
+ pad_len = max_len - len(ids)
309
+ attention = [1] * len(ids) + [0] * pad_len
310
+ ids = ids + [pad_id] * pad_len
311
+ input_ids.append(ids)
312
+ attn.append(attention)
313
+ return torch.tensor(input_ids, dtype=torch.long), torch.tensor(attn, dtype=torch.long)
314
+
315
+ _demo_ids, _demo_attn = student_encode_batch(sample_texts[:2])
316
+ print("Example padded student input_ids shape:", _demo_ids.shape)
317
+ print(_demo_ids)
318
+ """)
319
+
320
+ md(r"""#### Handling the vocabulary mismatch between Teacher and Student
321
+
322
+ A naive version of logit distillation — as used in **token-level** distillation for tasks like
323
+ sequence-to-sequence generation or token classification — requires the Teacher's and Student's output
324
+ sequences to line up position-by-position, which breaks immediately if the two models tokenize the same
325
+ text into different numbers of tokens (which they always will here: the Teacher's ~30k-token vocabulary
326
+ segments text far more coarsely than the Student's ~3k-token vocabulary, as the comparison table above
327
+ shows — the Student consistently needs *more* subword pieces for the same utterance).
328
+
329
+ **Why this is not actually a hard problem for us:** distillation here is **sequence classification**, not
330
+ sequence generation. The Teacher does not produce a per-token output that would need to line up with the
331
+ Student's per-token output — it produces exactly **one 77-dimensional probability vector per example**,
332
+ regardless of how many tokens that example was split into internally. So the only alignment that matters is
333
+ at the **example (row) level**, not the token level:
334
+
335
+ - **Strategy used:** compute Teacher logits once per raw-text example (Task 1), indexed by the example's
336
+ position in the (unshuffled) training set. Independently tokenize the *same* raw text with the Student's
337
+ own tokenizer for the Student's forward pass. Join the two by index — `teacher_train_logits[i]` always
338
+ corresponds to `train_raw[i]`, no matter how differently `train_raw[i]["text"]` was tokenized by each
339
+ side. This is implemented directly in `BankingStudentDataset` below.
340
+ - **Residual risk, and why it's acceptable here:** a much smaller vocabulary means more aggressive subword
341
+ splitting and a higher `[UNK]` rate, which *can* lose lexical signal the Teacher had access to via its
342
+ richer vocabulary. We mitigate this by training the Student tokenizer directly on in-domain banking77
343
+ text (rather than a generic corpus), so the ~3k tokens it does have are the ones that matter most for this
344
+ task's vocabulary (e.g. "card", "transfer", "pin", "exchange" are highly likely to survive intact as
345
+ whole-word tokens instead of being fragmented).
346
+ """)
347
+
348
+ # ---------------------------------------------------------------------------
349
+ # Module 2 / Task 3
350
+ # ---------------------------------------------------------------------------
351
+ md("""## Module 2: Distillation Architecture & Training
352
+
353
+ ### Task 3 — Compact Student Transformer Construction
354
+
355
+ A small, hand-built encoder-only Transformer: learned token + positional embeddings, 4 Transformer encoder
356
+ layers (hidden size 256, 4 attention heads, feed-forward size 512), mean-pooling over non-padding tokens,
357
+ and a linear classification head to 77 classes. Built directly from `nn.Module` / `nn.TransformerEncoderLayer`
358
+ primitives rather than repurposing a pretrained architecture, and sized to run comfortably on CPU.""")
359
+
360
+ code(r"""class CompactStudentTransformer(nn.Module):
361
+ def __init__(self, vocab_size, num_labels, hidden_size=256, num_layers=4, num_heads=4,
362
+ ffn_size=512, max_len=32, dropout=0.1, pad_id=0):
363
+ super().__init__()
364
+ self.pad_id = pad_id
365
+ self.token_embedding = nn.Embedding(vocab_size, hidden_size, padding_idx=pad_id)
366
+ self.position_embedding = nn.Embedding(max_len, hidden_size)
367
+ encoder_layer = nn.TransformerEncoderLayer(
368
+ d_model=hidden_size,
369
+ nhead=num_heads,
370
+ dim_feedforward=ffn_size,
371
+ dropout=dropout,
372
+ activation="gelu",
373
+ batch_first=True,
374
+ )
375
+ self.encoder = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
376
+ self.dropout = nn.Dropout(dropout)
377
+ self.classifier = nn.Linear(hidden_size, num_labels)
378
+
379
+ def forward(self, input_ids, attention_mask):
380
+ seq_len = input_ids.size(1)
381
+ positions = torch.arange(seq_len, device=input_ids.device).unsqueeze(0)
382
+ x = self.token_embedding(input_ids) + self.position_embedding(positions)
383
+ pad_mask = attention_mask == 0 # True where padded -> ignored by attention
384
+ x = self.encoder(x, src_key_padding_mask=pad_mask)
385
+ mask = attention_mask.unsqueeze(-1).float()
386
+ pooled = (x * mask).sum(dim=1) / mask.sum(dim=1).clamp(min=1e-6)
387
+ return self.classifier(self.dropout(pooled))
388
+
389
+
390
+ # inspect.getsource() cannot recover source for classes defined inside a notebook cell executed by
391
+ # nbconvert (no backing file for linecache to read), so we keep an explicit copy of this class's source
392
+ # alongside it for the subprocess-isolated benchmarking worker script in Task 6.
393
+ STUDENT_CLASS_SOURCE = '''class CompactStudentTransformer(nn.Module):
394
+ def __init__(self, vocab_size, num_labels, hidden_size=256, num_layers=4, num_heads=4,
395
+ ffn_size=512, max_len=32, dropout=0.1, pad_id=0):
396
+ super().__init__()
397
+ self.pad_id = pad_id
398
+ self.token_embedding = nn.Embedding(vocab_size, hidden_size, padding_idx=pad_id)
399
+ self.position_embedding = nn.Embedding(max_len, hidden_size)
400
+ encoder_layer = nn.TransformerEncoderLayer(
401
+ d_model=hidden_size,
402
+ nhead=num_heads,
403
+ dim_feedforward=ffn_size,
404
+ dropout=dropout,
405
+ activation="gelu",
406
+ batch_first=True,
407
+ )
408
+ self.encoder = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
409
+ self.dropout = nn.Dropout(dropout)
410
+ self.classifier = nn.Linear(hidden_size, num_labels)
411
+
412
+ def forward(self, input_ids, attention_mask):
413
+ seq_len = input_ids.size(1)
414
+ positions = torch.arange(seq_len, device=input_ids.device).unsqueeze(0)
415
+ x = self.token_embedding(input_ids) + self.position_embedding(positions)
416
+ pad_mask = attention_mask == 0 # True where padded -> ignored by attention
417
+ x = self.encoder(x, src_key_padding_mask=pad_mask)
418
+ mask = attention_mask.unsqueeze(-1).float()
419
+ pooled = (x * mask).sum(dim=1) / mask.sum(dim=1).clamp(min=1e-6)
420
+ return self.classifier(self.dropout(pooled))
421
+ '''
422
+
423
+
424
+ STUDENT_CONFIG = dict(
425
+ vocab_size=STUDENT_VOCAB_SIZE,
426
+ num_labels=num_labels,
427
+ hidden_size=256,
428
+ num_layers=4,
429
+ num_heads=4,
430
+ ffn_size=512,
431
+ max_len=STUDENT_MAX_LEN,
432
+ dropout=0.1,
433
+ pad_id=STUDENT_PAD_ID,
434
+ )
435
+
436
+ def build_student():
437
+ torch.manual_seed(SEED)
438
+ return CompactStudentTransformer(**STUDENT_CONFIG)
439
+
440
+ _probe = build_student()
441
+
442
+ def count_params(module):
443
+ return sum(p.numel() for p in module.parameters())
444
+
445
+ total_student_params = count_params(_probe)
446
+ embedding_params = count_params(_probe.token_embedding) + count_params(_probe.position_embedding)
447
+ encoder_params = count_params(_probe.encoder)
448
+ classifier_params = count_params(_probe.classifier)
449
+ teacher_params = count_params(teacher_model)
450
+
451
+ print("Student parameter breakdown")
452
+ print("-" * 40)
453
+ print(f" Token + position embeddings : {embedding_params:,}")
454
+ print(f" Transformer encoder (4 layers): {encoder_params:,}")
455
+ print(f" Classification head : {classifier_params:,}")
456
+ print(f" TOTAL : {total_student_params:,}")
457
+ print()
458
+ print(f"Teacher (bert-base-uncased) TOTAL: {teacher_params:,}")
459
+ print(f"Compression ratio: {teacher_params / total_student_params:,.1f}x fewer parameters")
460
+ del _probe
461
+ """)
462
+
463
+ code(r"""display(Markdown(f'''
464
+ #### Interpretation
465
+
466
+ The compact Student has **{total_student_params:,} parameters** against the Teacher's
467
+ **{teacher_params:,}** — a **{teacher_params/total_student_params:,.1f}x** reduction. Roughly
468
+ **{embedding_params/total_student_params:.0%}** of the Student's budget sits in its embedding table alone,
469
+ which is the direct payoff of Task 2's small, domain-specific vocabulary ({STUDENT_VOCAB_SIZE} tokens vs.
470
+ BERT's {teacher_tokenizer.vocab_size}): most of a Transformer's parameter count for short-sequence
471
+ classification tasks scales with `vocab_size x hidden_size`, so shrinking the vocabulary is one of the single
472
+ highest-leverage compression decisions available, independent of how many encoder layers are kept.
473
+ '''))
474
+ """)
475
+
476
+ # ---------------------------------------------------------------------------
477
+ # Task 4
478
+ # ---------------------------------------------------------------------------
479
+ md("""### Task 4 — Distillation Loss Function
480
+
481
+ $$\\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}})$$
482
+
483
+ with $T = 4.0$ and $\\alpha = 0.7$. The $T^2$ scaling (Hinton et al., 2015) compensates for the fact that
484
+ raising the temperature shrinks the magnitude of the gradients coming from the soft-label term by roughly
485
+ $1/T^2$ relative to the hard-label term, so without it the KD loss would be under-weighted relative to
486
+ $\\alpha$ once a large $T$ is introduced.""")
487
+
488
+ code(r"""class DistillationLoss(nn.Module):
489
+ def __init__(self, temperature=4.0, alpha=0.7):
490
+ super().__init__()
491
+ self.T = temperature
492
+ self.alpha = alpha
493
+ self.kl = nn.KLDivLoss(reduction="batchmean")
494
+ self.ce = nn.CrossEntropyLoss()
495
+
496
+ def forward(self, student_logits, teacher_logits, true_labels):
497
+ student_log_probs_T = F.log_softmax(student_logits / self.T, dim=-1)
498
+ teacher_probs_T = F.softmax(teacher_logits / self.T, dim=-1)
499
+ kd_loss = self.kl(student_log_probs_T, teacher_probs_T) * (self.T ** 2)
500
+ ce_loss = self.ce(student_logits, true_labels)
501
+ total = self.alpha * kd_loss + (1 - self.alpha) * ce_loss
502
+ return total, kd_loss.detach(), ce_loss.detach()
503
+
504
+
505
+ class BankingStudentDataset(Dataset):
506
+ # Joins raw text (re-tokenized with the STUDENT tokenizer) to cached TEACHER logits by row index.
507
+ def __init__(self, texts, labels, teacher_logits=None):
508
+ self.input_ids, self.attention_mask = student_encode_batch(texts)
509
+ self.labels = torch.tensor(labels, dtype=torch.long)
510
+ self.teacher_logits = teacher_logits
511
+
512
+ def __len__(self):
513
+ return len(self.labels)
514
+
515
+ def __getitem__(self, idx):
516
+ item = {
517
+ "input_ids": self.input_ids[idx],
518
+ "attention_mask": self.attention_mask[idx],
519
+ "labels": self.labels[idx],
520
+ }
521
+ if self.teacher_logits is not None:
522
+ item["teacher_logits"] = self.teacher_logits[idx]
523
+ return item
524
+
525
+
526
+ train_texts, train_labels = train_raw["text"], train_raw["label"]
527
+ test_texts, test_labels = test_raw["text"], test_raw["label"]
528
+
529
+ distill_train_dataset = BankingStudentDataset(train_texts, train_labels, teacher_logits=teacher_train_logits)
530
+ baseline_train_dataset = BankingStudentDataset(train_texts, train_labels, teacher_logits=None)
531
+ student_test_dataset = BankingStudentDataset(test_texts, test_labels, teacher_logits=None)
532
+
533
+ print(f"Distillation train set: {len(distill_train_dataset)} examples (with cached teacher logits)")
534
+ print(f"Baseline train set : {len(baseline_train_dataset)} examples (hard labels only)")
535
+ """)
536
+
537
+ code(r"""def train_student(model, dataset, device, epochs=8, batch_size=32, lr=3e-4,
538
+ distill=False, temperature=4.0, alpha=0.7, log_prefix="student"):
539
+ model.to(device)
540
+ loader = DataLoader(dataset, batch_size=batch_size, shuffle=True)
541
+ optimizer = torch.optim.AdamW(model.parameters(), lr=lr)
542
+ ce_loss_fn = nn.CrossEntropyLoss()
543
+ distill_loss_fn = DistillationLoss(temperature=temperature, alpha=alpha) if distill else None
544
+
545
+ history = {"total": [], "kd": [], "ce": []}
546
+ model.train()
547
+ for epoch in range(epochs):
548
+ totals, kds, ces = [], [], []
549
+ for batch in loader:
550
+ input_ids = batch["input_ids"].to(device)
551
+ attention_mask = batch["attention_mask"].to(device)
552
+ labels = batch["labels"].to(device)
553
+
554
+ optimizer.zero_grad()
555
+ logits = model(input_ids, attention_mask)
556
+
557
+ if distill:
558
+ teacher_logits = batch["teacher_logits"].to(device)
559
+ loss, kd, ce = distill_loss_fn(logits, teacher_logits, labels)
560
+ kds.append(kd.item())
561
+ ces.append(ce.item())
562
+ else:
563
+ loss = ce_loss_fn(logits, labels)
564
+
565
+ loss.backward()
566
+ optimizer.step()
567
+ totals.append(loss.item())
568
+
569
+ avg_total = float(np.mean(totals))
570
+ history["total"].append(avg_total)
571
+ if distill:
572
+ history["kd"].append(float(np.mean(kds)))
573
+ history["ce"].append(float(np.mean(ces)))
574
+ print(f"[{log_prefix}] epoch {epoch+1}/{epochs} - loss {avg_total:.4f} "
575
+ f"(kd {history['kd'][-1]:.4f}, ce {history['ce'][-1]:.4f})")
576
+ else:
577
+ print(f"[{log_prefix}] epoch {epoch+1}/{epochs} - loss {avg_total:.4f}")
578
+ return history
579
+
580
+ STUDENT_EPOCHS = 8
581
+ """)
582
+
583
+ code(r"""torch.manual_seed(SEED)
584
+ distilled_student = build_student()
585
+
586
+ distill_start = time.time()
587
+ distill_history = train_student(
588
+ distilled_student, distill_train_dataset, STUDENT_DEVICE,
589
+ epochs=STUDENT_EPOCHS, batch_size=32, lr=3e-4,
590
+ distill=True, temperature=4.0, alpha=0.7, log_prefix="distilled",
591
+ )
592
+ distill_seconds = time.time() - distill_start
593
+ print(f"\nDistilled student training took {distill_seconds:.1f}s on {STUDENT_DEVICE}")
594
+ """)
595
+
596
+ code(r"""fig, axes = plt.subplots(1, 2, figsize=(11, 4))
597
+ axes[0].plot(distill_history["total"], marker="o", label="total loss")
598
+ axes[0].set_title("Distilled student: total loss")
599
+ axes[0].set_xlabel("epoch"); axes[0].set_ylabel("loss"); axes[0].legend()
600
+
601
+ axes[1].plot(distill_history["kd"], marker="o", label="KD term (KL, T-scaled)")
602
+ axes[1].plot(distill_history["ce"], marker="s", label="CE term (hard labels)")
603
+ axes[1].set_title("Distilled student: loss components")
604
+ axes[1].set_xlabel("epoch"); axes[1].set_ylabel("loss"); axes[1].legend()
605
+ plt.tight_layout()
606
+ plt.show()
607
+ """)
608
+
609
+ md("""**Interpretation:** the CE component (against ground-truth hard labels) typically drops faster and
610
+ further than the KD component, because a 3000-token-vocabulary, 4-layer Student can quickly memorize the
611
+ *correct class* for a small, well-separated training set, while matching the Teacher's *full smoothed
612
+ distribution* over 77 classes at $T{=}4$ is a strictly harder target — the KD term keeps providing a
613
+ non-trivial gradient signal well after the CE term has largely converged, which is exactly the regime where
614
+ distillation is doing useful work beyond what hard labels alone would teach.""")
615
+
616
+ # ---------------------------------------------------------------------------
617
+ # Module 3 / Task 5
618
+ # ---------------------------------------------------------------------------
619
+ md("""## Module 3: Comparative Analysis & Benchmarking
620
+
621
+ ### Task 5 — Accuracy vs. Compression Evaluation
622
+
623
+ We now train an **identical-architecture baseline Student** from scratch using plain cross-entropy on
624
+ ground-truth labels only (no Teacher signal at all), so any accuracy difference between it and the
625
+ distilled Student isolates the effect of distillation itself, holding architecture, tokenizer, optimizer,
626
+ and epoch budget fixed.""")
627
+
628
+ code(r"""torch.manual_seed(SEED)
629
+ baseline_student = build_student()
630
+
631
+ baseline_start = time.time()
632
+ baseline_history = train_student(
633
+ baseline_student, baseline_train_dataset, STUDENT_DEVICE,
634
+ epochs=STUDENT_EPOCHS, batch_size=32, lr=3e-4,
635
+ distill=False, log_prefix="baseline",
636
+ )
637
+ baseline_seconds = time.time() - baseline_start
638
+ print(f"\nBaseline student training took {baseline_seconds:.1f}s on {STUDENT_DEVICE}")
639
+ """)
640
+
641
+ code(r"""plt.figure(figsize=(6, 4))
642
+ plt.plot(baseline_history["total"], marker="o", label="Baseline student (CE only)")
643
+ plt.plot(distill_history["total"], marker="s", label="Distilled student (KD + CE)")
644
+ plt.title("Training loss: baseline vs. distilled student")
645
+ plt.xlabel("epoch"); plt.ylabel("loss (not directly comparable in scale)"); plt.legend()
646
+ plt.tight_layout()
647
+ plt.show()
648
+ """)
649
+
650
+ code(r"""@torch.no_grad()
651
+ def evaluate_student(model, dataset, device, batch_size=64):
652
+ model.eval()
653
+ model.to(device)
654
+ loader = DataLoader(dataset, batch_size=batch_size, shuffle=False)
655
+ all_preds, all_labels = [], []
656
+ for batch in loader:
657
+ input_ids = batch["input_ids"].to(device)
658
+ attention_mask = batch["attention_mask"].to(device)
659
+ logits = model(input_ids, attention_mask)
660
+ all_preds.extend(torch.argmax(logits, dim=-1).cpu().numpy().tolist())
661
+ all_labels.extend(batch["labels"].numpy().tolist())
662
+ return np.array(all_preds), np.array(all_labels)
663
+
664
+
665
+ teacher_pred_output = trainer.predict(test_enc)
666
+ teacher_test_preds = np.argmax(teacher_pred_output.predictions, axis=-1)
667
+ teacher_test_labels = np.array(test_raw["label"])
668
+
669
+ baseline_preds, baseline_labels = evaluate_student(baseline_student, student_test_dataset, STUDENT_DEVICE)
670
+ distilled_preds, distilled_labels = evaluate_student(distilled_student, student_test_dataset, STUDENT_DEVICE)
671
+
672
+ def summarize(name, preds, labels):
673
+ return {
674
+ "Model": name,
675
+ "Accuracy": accuracy_score(labels, preds),
676
+ "Macro F1": f1_score(labels, preds, average="macro"),
677
+ "Weighted F1": f1_score(labels, preds, average="weighted"),
678
+ }
679
+
680
+ results_df = pd.DataFrame([
681
+ summarize("Teacher (bert-base-uncased)", teacher_test_preds, teacher_test_labels),
682
+ summarize("Student — WITHOUT distillation", baseline_preds, baseline_labels),
683
+ summarize("Student — WITH distillation", distilled_preds, distilled_labels),
684
+ ])
685
+ results_df[["Accuracy", "Macro F1", "Weighted F1"]] = results_df[["Accuracy", "Macro F1", "Weighted F1"]].round(4)
686
+ results_df
687
+ """)
688
+
689
+ code(r"""def to_markdown_table(df):
690
+ header = "| " + " | ".join(df.columns) + " |"
691
+ sep = "|" + "|".join(["---"] * len(df.columns)) + "|"
692
+ rows = ["| " + " | ".join(str(v) for v in row) + " |" for row in df.values]
693
+ return "\n".join([header, sep] + rows)
694
+
695
+ teacher_acc = results_df.loc[0, "Accuracy"]
696
+ baseline_acc = results_df.loc[1, "Accuracy"]
697
+ distilled_acc = results_df.loc[2, "Accuracy"]
698
+ recovery = (distilled_acc - baseline_acc) / max(teacher_acc - baseline_acc, 1e-9) * 100
699
+ retention = distilled_acc / teacher_acc * 100
700
+
701
+ if distilled_acc >= teacher_acc:
702
+ gap_line = (
703
+ f"- Adding the Teacher's soft labels (identical architecture, identical data, identical epoch budget — "
704
+ f"only the loss function differs) raises the Student to **{distilled_acc:.1%}** accuracy, which "
705
+ f"**fully closes** the gap to the Teacher's **{teacher_acc:.1%}** and slightly surpasses it."
706
+ )
707
+ retention_line = (
708
+ f"- Remarkably, the distilled Student's **{distilled_acc:.1%}** accuracy matches — and here, "
709
+ f"slightly exceeds — the Teacher's **{teacher_acc:.1%}**, at **{teacher_params/total_student_params:,.0f}x** "
710
+ f"fewer parameters. This is a stronger-than-typical (though not unheard of) outcome: the Teacher was "
711
+ f"only fine-tuned for a few epochs, so its own decision boundary still carries some noise, and the "
712
+ f"test set is a few thousand examples, so a couple of points either way is within normal variance. "
713
+ f"The soft-label targets act as a strong regularizer that helps the tiny Student generalize at least "
714
+ f"as well on this held-out set — that does **not** mean the Student has absorbed *all* of the "
715
+ f"Teacher's knowledge, only that on this test split and this metric, distillation fully closed the gap."
716
+ )
717
+ else:
718
+ gap_line = (
719
+ f"- Adding the Teacher's soft labels (identical architecture, identical data, identical epoch budget — "
720
+ f"only the loss function differs) raises the Student to **{distilled_acc:.1%}** accuracy, closing "
721
+ f"**{recovery:.0f}%** of the accuracy gap between the undistilled Student and the Teacher."
722
+ )
723
+ retention_line = (
724
+ f"- The distilled Student retains **{retention:.1f}%** of the Teacher's accuracy at a fraction of its "
725
+ f"parameter count — this is the central empirical claim of knowledge distillation: dark knowledge in "
726
+ f"the soft labels lets a small model recover much more of a large model's decision surface than the "
727
+ f"same small model could learn from hard labels alone."
728
+ )
729
+
730
+ display(Markdown(f'''
731
+ #### Comparison table
732
+
733
+ {to_markdown_table(results_df)}
734
+
735
+ #### Interpretation
736
+
737
+ - The undistilled Student, trained only on hard labels with a **{teacher_params/total_student_params:,.0f}x**
738
+ smaller architecture and a **{STUDENT_EPOCHS}**-epoch budget over the same {len(train_raw)} examples,
739
+ reaches **{baseline_acc:.1%}** accuracy — a substantial gap below the Teacher's **{teacher_acc:.1%}**,
740
+ as expected given how much capacity was removed.
741
+ {gap_line}
742
+ {retention_line}
743
+ '''))
744
+ """)
745
+
746
+ # ---------------------------------------------------------------------------
747
+ # Task 6
748
+ # ---------------------------------------------------------------------------
749
+ md("""### Task 6 — Deployment Metrics Analysis
750
+
751
+ We measure three deployment-relevant metrics for the Teacher vs. the (distilled) Student:
752
+
753
+ 1. **Disk size** — serialized `state_dict` size on disk.
754
+ 2. **CPU inference latency** — mean wall-clock time per single-example (`batch_size=1`) forward pass on CPU.
755
+ 3. **Peak process RAM** — measured in an **isolated subprocess per model** (via `resource.getrusage`), so
756
+ the Teacher's ~440MB footprint doesn't contaminate the Student's measurement just because both happen to
757
+ be loaded in the same notebook kernel.""")
758
+
759
+ code(r"""def get_model_disk_size_mb(state_dict):
760
+ with tempfile.NamedTemporaryFile(suffix=".pt") as f:
761
+ torch.save(state_dict, f.name)
762
+ f.flush()
763
+ size_bytes = os.path.getsize(f.name)
764
+ return size_bytes / (1024 ** 2)
765
+
766
+ teacher_size_mb = get_model_disk_size_mb(teacher_model.state_dict())
767
+ student_size_mb = get_model_disk_size_mb(distilled_student.state_dict())
768
+
769
+ print(f"Teacher disk size : {teacher_size_mb:,.1f} MB")
770
+ print(f"Student disk size : {student_size_mb:,.1f} MB")
771
+ print(f"Size reduction : {teacher_size_mb/student_size_mb:,.1f}x smaller")
772
+ """)
773
+
774
+ code(r"""@torch.no_grad()
775
+ def measure_teacher_cpu_latency(model, tokenizer, texts, n_warmup=5, n_runs=50):
776
+ model.to(CPU_DEVICE)
777
+ model.eval()
778
+ encs = [tokenizer(t, return_tensors="pt", truncation=True, max_length=64) for t in texts]
779
+ for i in range(n_warmup):
780
+ model(**encs[i % len(encs)])
781
+ times = []
782
+ for i in range(n_runs):
783
+ enc = encs[i % len(encs)]
784
+ start = time.perf_counter()
785
+ model(**enc)
786
+ times.append((time.perf_counter() - start) * 1000)
787
+ return float(np.mean(times)), float(np.std(times))
788
+
789
+ @torch.no_grad()
790
+ def measure_student_cpu_latency(model, texts, n_warmup=5, n_runs=50):
791
+ model.to(CPU_DEVICE)
792
+ model.eval()
793
+ ids, attn = student_encode_batch(texts)
794
+ for i in range(n_warmup):
795
+ idx = i % len(texts)
796
+ model(ids[idx].unsqueeze(0), attn[idx].unsqueeze(0))
797
+ times = []
798
+ for i in range(n_runs):
799
+ idx = i % len(texts)
800
+ start = time.perf_counter()
801
+ model(ids[idx].unsqueeze(0), attn[idx].unsqueeze(0))
802
+ times.append((time.perf_counter() - start) * 1000)
803
+ return float(np.mean(times)), float(np.std(times))
804
+
805
+ latency_sample_texts = test_texts[:20]
806
+ teacher_latency_mean, teacher_latency_std = measure_teacher_cpu_latency(teacher_model, teacher_tokenizer, latency_sample_texts)
807
+ student_latency_mean, student_latency_std = measure_student_cpu_latency(distilled_student, latency_sample_texts)
808
+
809
+ print(f"Teacher CPU latency : {teacher_latency_mean:.2f} +/- {teacher_latency_std:.2f} ms/query")
810
+ print(f"Student CPU latency : {student_latency_mean:.2f} +/- {student_latency_std:.2f} ms/query")
811
+ print(f"Speedup : {teacher_latency_mean/student_latency_mean:,.1f}x faster")
812
+ """)
813
+
814
+ code(r"""# Peak RAM, measured per model in an isolated subprocess so each number reflects ONLY that model's
815
+ # footprint (loading both Teacher and Student into one long-lived kernel would make ru_maxrss monotonically
816
+ # dominated by whichever model was loaded first).
817
+ teacher_worker_src = (
818
+ "import sys, resource, torch\n"
819
+ "from transformers import BertForSequenceClassification, AutoTokenizer\n"
820
+ "model_dir = sys.argv[1]\n"
821
+ "model = BertForSequenceClassification.from_pretrained(model_dir)\n"
822
+ "tokenizer = AutoTokenizer.from_pretrained(model_dir)\n"
823
+ "model.eval()\n"
824
+ "texts = ['I am still waiting on my card?'] * 30\n"
825
+ "with torch.no_grad():\n"
826
+ " for t in texts:\n"
827
+ " enc = tokenizer(t, return_tensors='pt', truncation=True, max_length=64)\n"
828
+ " model(**enc)\n"
829
+ "print(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)\n"
830
+ )
831
+
832
+ student_class_src = STUDENT_CLASS_SOURCE
833
+ student_worker_src = (
834
+ "import sys, json, resource, torch\n"
835
+ "import torch.nn as nn\n"
836
+ "from tokenizers import Tokenizer as HFTokenizer\n\n"
837
+ + student_class_src + "\n\n"
838
+ "model_dir = sys.argv[1]\n"
839
+ "cfg = json.load(open(model_dir + '/config.json'))\n"
840
+ "model = CompactStudentTransformer(**cfg)\n"
841
+ "model.load_state_dict(torch.load(model_dir + '/weights.pt', map_location='cpu'))\n"
842
+ "model.eval()\n"
843
+ "tok = HFTokenizer.from_file(model_dir + '/tokenizer.json')\n"
844
+ "texts = ['I am still waiting on my card?'] * 30\n"
845
+ "with torch.no_grad():\n"
846
+ " for t in texts:\n"
847
+ " ids = tok.encode(t).ids[:cfg['max_len']]\n"
848
+ " pad_len = cfg['max_len'] - len(ids)\n"
849
+ " attn = [1]*len(ids) + [0]*pad_len\n"
850
+ " ids = ids + [cfg['pad_id']]*pad_len\n"
851
+ " input_ids = torch.tensor([ids])\n"
852
+ " attention_mask = torch.tensor([attn])\n"
853
+ " model(input_ids, attention_mask)\n"
854
+ "print(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)\n"
855
+ )
856
+
857
+ with tempfile.TemporaryDirectory() as tmp_root:
858
+ teacher_dir = os.path.join(tmp_root, "teacher")
859
+ student_dir = os.path.join(tmp_root, "student")
860
+ os.makedirs(teacher_dir, exist_ok=True)
861
+ os.makedirs(student_dir, exist_ok=True)
862
+
863
+ teacher_model.save_pretrained(teacher_dir)
864
+ teacher_tokenizer.save_pretrained(teacher_dir)
865
+
866
+ torch.save(distilled_student.state_dict(), os.path.join(student_dir, "weights.pt"))
867
+ with open(os.path.join(student_dir, "config.json"), "w") as f:
868
+ json.dump(STUDENT_CONFIG, f)
869
+ student_tok_backend.save(os.path.join(student_dir, "tokenizer.json"))
870
+
871
+ teacher_worker_path = os.path.join(tmp_root, "teacher_worker.py")
872
+ student_worker_path = os.path.join(tmp_root, "student_worker.py")
873
+ with open(teacher_worker_path, "w") as f:
874
+ f.write(teacher_worker_src)
875
+ with open(student_worker_path, "w") as f:
876
+ f.write(student_worker_src)
877
+
878
+ teacher_ram_out = subprocess.run(
879
+ [sys.executable, teacher_worker_path, teacher_dir],
880
+ capture_output=True, text=True, check=True,
881
+ )
882
+ student_ram_out = subprocess.run(
883
+ [sys.executable, student_worker_path, student_dir],
884
+ capture_output=True, text=True, check=True,
885
+ )
886
+
887
+ _bytes_per_unit = 1 # macOS ru_maxrss is already in bytes
888
+ teacher_peak_ram_mb = int(teacher_ram_out.stdout.strip()) * _bytes_per_unit / (1024 ** 2)
889
+ student_peak_ram_mb = int(student_ram_out.stdout.strip()) * _bytes_per_unit / (1024 ** 2)
890
+
891
+ print(f"Teacher peak RAM (isolated process) : {teacher_peak_ram_mb:,.1f} MB")
892
+ print(f"Student peak RAM (isolated process) : {student_peak_ram_mb:,.1f} MB")
893
+ print(f"RAM reduction : {teacher_peak_ram_mb/student_peak_ram_mb:,.1f}x smaller")
894
+ """)
895
+
896
+ code(r"""deployment_df = pd.DataFrame([
897
+ {"Metric": "Disk size (MB)", "Teacher": round(teacher_size_mb, 1), "Student": round(student_size_mb, 1),
898
+ "Reduction": f"{teacher_size_mb/student_size_mb:.1f}x"},
899
+ {"Metric": "CPU latency (ms/query)", "Teacher": round(teacher_latency_mean, 2), "Student": round(student_latency_mean, 2),
900
+ "Reduction": f"{teacher_latency_mean/student_latency_mean:.1f}x"},
901
+ {"Metric": "Peak RAM (MB)", "Teacher": round(teacher_peak_ram_mb, 1), "Student": round(student_peak_ram_mb, 1),
902
+ "Reduction": f"{teacher_peak_ram_mb/student_peak_ram_mb:.1f}x"},
903
+ ])
904
+ deployment_df
905
+ """)
906
+
907
+ code(r"""accuracy_retained_pct = distilled_acc / teacher_acc * 100
908
+ size_reduction_x = teacher_size_mb / student_size_mb
909
+ latency_reduction_x = teacher_latency_mean / student_latency_mean
910
+ ram_reduction_x = teacher_peak_ram_mb / student_peak_ram_mb
911
+
912
+ if distilled_acc >= teacher_acc:
913
+ accuracy_summary_line = (
914
+ f"while matching (here, slightly exceeding) its accuracy on the exact same 77-way classification task."
915
+ )
916
+ accuracy_tradeoff_bullet = (
917
+ f"- **Accuracy trade-off** — in this run there isn't one: the distilled Student's accuracy is at "
918
+ f"least as high as the Teacher's, so the size/latency/RAM wins below come essentially for free on "
919
+ f"this test set. That is a favorable outcome, not a guarantee — it reflects a lightly-fine-tuned "
920
+ f"Teacher and a modest-size test set as much as it reflects the Student's quality, so a production "
921
+ f"rollout should still monitor accuracy on live traffic rather than assuming this margin holds "
922
+ f"indefinitely as data drifts."
923
+ )
924
+ else:
925
+ accuracy_summary_line = (
926
+ f"while retaining **{accuracy_retained_pct:.1f}%** of its accuracy on the exact same 77-way "
927
+ f"classification task."
928
+ )
929
+ accuracy_tradeoff_bullet = (
930
+ f"- **Accuracy trade-off** — the real cost is the **{100-accuracy_retained_pct:.1f} percentage "
931
+ f"points** of relative accuracy given up. Whether that is acceptable depends entirely on the "
932
+ f"product: for a first-pass intent router that falls back to a human agent or a larger cloud model "
933
+ f"on low confidence, this trade is usually a clear win — the compute/latency/cost savings at massive "
934
+ f"query volume outweigh a modest accuracy gap. For a fully autonomous decision with no fallback "
935
+ f"(e.g. auto-approving a refund), the remaining gap to the Teacher may still be too large to deploy "
936
+ f"the Student *alone*."
937
+ )
938
+
939
+ display(Markdown(f'''
940
+ #### Deployment-readiness analysis
941
+
942
+ {to_markdown_table(deployment_df)}
943
+
944
+ The distilled Student is **{size_reduction_x:.1f}x smaller on disk**, **{latency_reduction_x:.1f}x faster**
945
+ per CPU query, and uses **{ram_reduction_x:.1f}x less peak RAM** than the Teacher, {accuracy_summary_line}
946
+
947
+ **Is this deployment-ready for edge/mobile?**
948
+
949
+ - **Size and RAM** — at ~{student_size_mb:.0f}MB on disk and ~{student_peak_ram_mb:.0f}MB of peak RAM, the
950
+ Student comfortably fits within the memory budgets of edge devices and mobile apps, where a
951
+ {teacher_size_mb:.0f}MB+ BERT-base checkpoint is frequently a non-starter (app-store bundle-size limits,
952
+ low-RAM Android devices, on-device model caches).
953
+ - **Latency** — {student_latency_mean:.1f}ms/query on CPU is well within the range needed for a responsive,
954
+ synchronous UI interaction (e.g. intent routing as a user types), whereas the Teacher's
955
+ {teacher_latency_mean:.1f}ms/query, multiplied across a request queue on a resource-constrained device,
956
+ would noticeably degrade perceived responsiveness.
957
+ {accuracy_tradeoff_bullet}
958
+ - **Practical recommendation** — deploy the distilled Student as the default path, and route low-confidence
959
+ predictions (small margin between the top-2 softmax probabilities) to the Teacher or a human reviewer.
960
+ This captures most of the size/latency/RAM benefits demonstrated above while bounding the accuracy risk
961
+ to only the genuinely ambiguous cases — which is exactly the scenario dark-knowledge distillation is
962
+ suited for, since the Student was trained to mimic the Teacher's *confidence structure*, not just its
963
+ argmax.
964
+ '''))
965
+ """)
966
+
967
+ nb["cells"] = cells
968
+ with open("knowledge_distillation_assignment.ipynb", "w") as f:
969
+ nbf.write(nb, f)
970
+
971
+ print(f"Notebook written with {len(cells)} cells.")
demo/build_pdf_report.py ADDED
@@ -0,0 +1,585 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Builds Knowledge_Distillation_Report_Group85.pdf via ReportLab (weasyprint unavailable: missing
2
+ native Pango/GObject libs on this system). Produces a cover page, bookmarked TOC, styled section
3
+ headings, tables, formula callouts, and the two loss-curve figures extracted from the executed notebook.
4
+ """
5
+ import os
6
+ from reportlab.lib.pagesizes import A4
7
+ from reportlab.lib.units import cm, inch
8
+ from reportlab.lib import colors
9
+ from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
10
+ from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_JUSTIFY
11
+ from reportlab.platypus import (
12
+ BaseDocTemplate, PageTemplate, Frame, Paragraph, Spacer, Table, TableStyle,
13
+ Image, PageBreak, NextPageTemplate, FrameBreak, KeepTogether, ListFlowable, ListItem,
14
+ )
15
+ from reportlab.platypus.tableofcontents import TableOfContents
16
+ from reportlab.pdfgen import canvas as canvas_mod
17
+ from PIL import Image as PILImage
18
+
19
+ ASSETS = "/Users/reevechaitanya/Documents/2_Experimentation_n_Research/demo/report_assets"
20
+ OUT_PATH = "/Users/reevechaitanya/Documents/2_Experimentation_n_Research/demo/Knowledge_Distillation_Report_Group85.pdf"
21
+
22
+ PAGE_W, PAGE_H = A4
23
+ MARGIN = 2.0 * cm
24
+ CONTENT_W = PAGE_W - 2 * MARGIN
25
+
26
+ ACCENT = colors.HexColor("#1F4E79")
27
+ ACCENT_LIGHT = colors.HexColor("#DCE6F1")
28
+ GREY = colors.HexColor("#404040")
29
+ LIGHT_GREY = colors.HexColor("#F2F2F2")
30
+ BORDER_GREY = colors.HexColor("#9AA7B0")
31
+ GOOD_GREEN = colors.HexColor("#2E7D32")
32
+
33
+ # ---------------------------------------------------------------------------
34
+ # Styles
35
+ # ---------------------------------------------------------------------------
36
+ base = getSampleStyleSheet()
37
+
38
+ styles = {}
39
+ styles["CoverTitle"] = ParagraphStyle("CoverTitle", parent=base["Title"], fontName="Helvetica-Bold",
40
+ fontSize=25, leading=30, textColor=ACCENT, alignment=TA_CENTER,
41
+ spaceAfter=6)
42
+ styles["CoverSub"] = ParagraphStyle("CoverSub", parent=base["Normal"], fontName="Helvetica",
43
+ fontSize=13, leading=18, textColor=GREY, alignment=TA_CENTER,
44
+ spaceAfter=4)
45
+ styles["CoverMeta"] = ParagraphStyle("CoverMeta", parent=base["Normal"], fontName="Helvetica",
46
+ fontSize=11, leading=16, textColor=GREY, alignment=TA_CENTER)
47
+ styles["CoverLabel"] = ParagraphStyle("CoverLabel", parent=base["Normal"], fontName="Helvetica-Bold",
48
+ fontSize=11, leading=15, textColor=ACCENT, alignment=TA_LEFT)
49
+ styles["CoverValue"] = ParagraphStyle("CoverValue", parent=base["Normal"], fontName="Helvetica",
50
+ fontSize=11, leading=15, textColor=GREY, alignment=TA_LEFT)
51
+
52
+ styles["H1"] = ParagraphStyle("H1", parent=base["Heading1"], fontName="Helvetica-Bold", fontSize=17,
53
+ leading=21, textColor=colors.white, spaceBefore=0, spaceAfter=0,
54
+ backColor=ACCENT, borderPadding=(6, 8, 6, 8), alignment=TA_LEFT)
55
+ styles["H2"] = ParagraphStyle("H2", parent=base["Heading2"], fontName="Helvetica-Bold", fontSize=13.5,
56
+ leading=17, textColor=ACCENT, spaceBefore=14, spaceAfter=6,
57
+ borderColor=ACCENT, borderWidth=0, alignment=TA_LEFT)
58
+ styles["H3"] = ParagraphStyle("H3", parent=base["Heading3"], fontName="Helvetica-Bold", fontSize=11.5,
59
+ leading=15, textColor=colors.HexColor("#B35A00"), spaceBefore=10,
60
+ spaceAfter=4, alignment=TA_LEFT)
61
+ styles["Body"] = ParagraphStyle("Body", parent=base["Normal"], fontName="Helvetica", fontSize=10,
62
+ leading=14.5, textColor=colors.black, alignment=TA_JUSTIFY,
63
+ spaceAfter=7)
64
+ styles["Bullet"] = ParagraphStyle("Bullet", parent=styles["Body"], leftIndent=14, bulletIndent=2,
65
+ spaceAfter=5)
66
+ styles["Caption"] = ParagraphStyle("Caption", parent=base["Normal"], fontName="Helvetica-Oblique",
67
+ fontSize=9, leading=12, textColor=GREY, alignment=TA_CENTER,
68
+ spaceAfter=10, spaceBefore=2)
69
+ styles["Formula"] = ParagraphStyle("Formula", parent=base["Normal"], fontName="Courier-Bold",
70
+ fontSize=10.5, leading=16, textColor=ACCENT, alignment=TA_CENTER,
71
+ backColor=colors.HexColor("#EEF3F9"), borderColor=ACCENT,
72
+ borderWidth=1, borderPadding=10, spaceBefore=8, spaceAfter=10)
73
+ styles["CalloutLabel"] = ParagraphStyle("CalloutLabel", parent=base["Normal"], fontName="Helvetica-Bold",
74
+ fontSize=9.5, leading=13, textColor=colors.white,
75
+ backColor=colors.HexColor("#B35A00"), borderPadding=(4, 6, 4, 6),
76
+ alignment=TA_LEFT)
77
+ styles["TOCHeading"] = ParagraphStyle("TOCHeading", parent=base["Heading1"], fontName="Helvetica-Bold",
78
+ fontSize=17, textColor=ACCENT, spaceAfter=14)
79
+
80
+
81
+ def P(text, style="Body"):
82
+ return Paragraph(text, styles[style])
83
+
84
+
85
+ def heading(text, level=1, bookmark=None):
86
+ if level == 1:
87
+ st = "H1"
88
+ elif level == 2:
89
+ st = "H2"
90
+ else:
91
+ st = "H3"
92
+ para = Paragraph(text, styles[st])
93
+ clean_text = (bookmark or text).replace(" ", " ").replace("&", "&")
94
+ para._bookmark_name = clean_text
95
+ para._bookmark_level = level
96
+ return para
97
+
98
+
99
+ def bullet(text):
100
+ return Paragraph(f"•  {text}", styles["Bullet"])
101
+
102
+
103
+ def formula(text):
104
+ return Table([[Paragraph(text, styles["Formula"])]], colWidths=[CONTENT_W],
105
+ style=TableStyle([
106
+ ("BOX", (0, 0), (-1, -1), 1, ACCENT),
107
+ ("BACKGROUND", (0, 0), (-1, -1), colors.HexColor("#EEF3F9")),
108
+ ("TOPPADDING", (0, 0), (-1, -1), 10),
109
+ ("BOTTOMPADDING", (0, 0), (-1, -1), 10),
110
+ ]))
111
+
112
+
113
+ def data_table(headers, rows, col_widths=None, note=None):
114
+ if col_widths is None:
115
+ col_widths = [CONTENT_W / len(headers)] * len(headers)
116
+ header_row = [Paragraph(f"<b>{h}</b>", ParagraphStyle("th", parent=base["Normal"], fontName="Helvetica-Bold",
117
+ fontSize=9.5, textColor=colors.white, alignment=TA_CENTER))
118
+ for h in headers]
119
+ body_rows = []
120
+ for row in rows:
121
+ cells = []
122
+ for i, val in enumerate(row):
123
+ align = TA_LEFT if i == 0 else TA_CENTER
124
+ cells.append(Paragraph(str(val), ParagraphStyle("td", parent=base["Normal"], fontName="Helvetica",
125
+ fontSize=9.5, alignment=align, leading=12.5)))
126
+ body_rows.append(cells)
127
+ data = [header_row] + body_rows
128
+ t = Table(data, colWidths=col_widths, repeatRows=1)
129
+ style_cmds = [
130
+ ("BACKGROUND", (0, 0), (-1, 0), ACCENT),
131
+ ("GRID", (0, 0), (-1, -1), 0.6, BORDER_GREY),
132
+ ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
133
+ ("TOPPADDING", (0, 0), (-1, -1), 5),
134
+ ("BOTTOMPADDING", (0, 0), (-1, -1), 5),
135
+ ("LEFTPADDING", (0, 0), (-1, -1), 6),
136
+ ("RIGHTPADDING", (0, 0), (-1, -1), 6),
137
+ ]
138
+ for r in range(1, len(data)):
139
+ if r % 2 == 0:
140
+ style_cmds.append(("BACKGROUND", (0, r), (-1, r), LIGHT_GREY))
141
+ t.setStyle(TableStyle(style_cmds))
142
+ flowables = [t]
143
+ if note:
144
+ flowables.append(Paragraph(note, styles["Caption"]))
145
+ return KeepTogether(flowables) if note else t
146
+
147
+
148
+ def scaled_image(path, max_width):
149
+ with PILImage.open(path) as im:
150
+ w, h = im.size
151
+ ratio = h / w
152
+ return Image(path, width=max_width, height=max_width * ratio)
153
+
154
+
155
+ def image_with_caption(path, max_width, caption):
156
+ img = scaled_image(path, max_width)
157
+ cap = Paragraph(caption, styles["Caption"])
158
+ return KeepTogether([img, cap])
159
+
160
+
161
+ # ---------------------------------------------------------------------------
162
+ # Doc template: cover (blank) + content (header/footer, TOC bookmarks)
163
+ # ---------------------------------------------------------------------------
164
+ REPORT_TITLE = "Knowledge Distillation on Banking77 — Group 85"
165
+
166
+
167
+ def draw_cover_background(cv, doc_):
168
+ cv.saveState()
169
+ cv.setFillColor(ACCENT)
170
+ cv.rect(0, PAGE_H - 1.3 * cm, PAGE_W, 1.3 * cm, fill=1, stroke=0)
171
+ cv.setFillColor(ACCENT)
172
+ cv.rect(0, 0, PAGE_W, 0.6 * cm, fill=1, stroke=0)
173
+ cv.restoreState()
174
+
175
+
176
+ def draw_content_frame(cv, doc_):
177
+ cv.saveState()
178
+ cv.setStrokeColor(BORDER_GREY)
179
+ cv.setLineWidth(0.6)
180
+ cv.line(MARGIN, PAGE_H - 1.15 * cm, PAGE_W - MARGIN, PAGE_H - 1.15 * cm)
181
+ cv.setFont("Helvetica", 8.5)
182
+ cv.setFillColor(GREY)
183
+ cv.drawString(MARGIN, PAGE_H - 0.95 * cm, "Conversational AI — Assignment-2 (PS1)")
184
+ cv.drawRightString(PAGE_W - MARGIN, PAGE_H - 0.95 * cm, "Group 85 — Knowledge Distillation Report")
185
+
186
+ cv.line(MARGIN, 1.1 * cm, PAGE_W - MARGIN, 1.1 * cm)
187
+ cv.setFont("Helvetica", 8.5)
188
+ cv.drawString(MARGIN, 0.75 * cm, "Knowledge_Distillation_Report_Group85.pdf")
189
+ cv.drawRightString(PAGE_W - MARGIN, 0.75 * cm, f"Page {doc_.page}")
190
+ cv.restoreState()
191
+
192
+
193
+ class ReportDocTemplate(BaseDocTemplate):
194
+ def afterFlowable(self, flowable):
195
+ if hasattr(flowable, "_bookmark_name"):
196
+ text = flowable._bookmark_name
197
+ level = flowable._bookmark_level
198
+ key = f"bm_{id(flowable)}"
199
+ self.canv.bookmarkPage(key)
200
+ self.canv.addOutlineEntry(text, key, level - 1, level == 1)
201
+ self.notify("TOCEntry", (level - 1, text, self.page, key))
202
+
203
+
204
+ doc = ReportDocTemplate(
205
+ OUT_PATH, pagesize=A4,
206
+ leftMargin=MARGIN, rightMargin=MARGIN, topMargin=MARGIN, bottomMargin=MARGIN,
207
+ title="Knowledge Distillation Report — Group 85",
208
+ author="Group 85 (R. Priji Rajendran, Reeve Chaitanya, Sahil Verma, Vankala N Sai Krishna Kumar)",
209
+ subject="Conversational AI — Assignment-2 (PS1): Knowledge Distillation on Banking77",
210
+ )
211
+
212
+ cover_frame = Frame(0, 0, PAGE_W, PAGE_H, id="cover", leftPadding=2.4 * cm, rightPadding=2.4 * cm,
213
+ topPadding=3.2 * cm, bottomPadding=2.4 * cm)
214
+ content_frame = Frame(MARGIN, MARGIN, CONTENT_W, PAGE_H - 2 * MARGIN - 0.3 * cm, id="content")
215
+
216
+ doc.addPageTemplates([
217
+ PageTemplate(id="Cover", frames=[cover_frame], onPage=draw_cover_background),
218
+ PageTemplate(id="Content", frames=[content_frame], onPage=draw_content_frame),
219
+ ])
220
+
221
+ story = []
222
+
223
+ # ---------------------------------------------------------------------------
224
+ # Cover page
225
+ # ---------------------------------------------------------------------------
226
+ story.append(Spacer(1, 1.4 * cm))
227
+ story.append(P("CONVERSATIONAL AI", "CoverSub"))
228
+ story.append(Spacer(1, 0.3 * cm))
229
+ story.append(P("Knowledge Distillation on the Banking77 Intent Dataset", "CoverTitle"))
230
+ story.append(P("Compressing a Fine-Tuned BERT Teacher into a Compact, CPU-Deployable Student Transformer", "CoverSub"))
231
+ story.append(Spacer(1, 1.0 * cm))
232
+
233
+ cover_info = Table(
234
+ [
235
+ [P("Course Name", "CoverLabel"), P("Conversational AI", "CoverValue")],
236
+ [P("Assignment", "CoverLabel"), P("Assignment-2 (PS1)", "CoverValue")],
237
+ [P("Group ID", "CoverLabel"), P("Group 85", "CoverValue")],
238
+ [P("Dataset", "CoverLabel"), P("PolyAI/banking77 (77-class banking intent classification)", "CoverValue")],
239
+ ],
240
+ colWidths=[4.5 * cm, 10.5 * cm],
241
+ )
242
+ cover_info.setStyle(TableStyle([
243
+ ("BOX", (0, 0), (-1, -1), 1, ACCENT),
244
+ ("INNERGRID", (0, 0), (-1, -1), 0.5, colors.HexColor("#B9C9DA")),
245
+ ("BACKGROUND", (0, 0), (0, -1), ACCENT_LIGHT),
246
+ ("TOPPADDING", (0, 0), (-1, -1), 7),
247
+ ("BOTTOMPADDING", (0, 0), (-1, -1), 7),
248
+ ("LEFTPADDING", (0, 0), (-1, -1), 10),
249
+ ]))
250
+ story.append(cover_info)
251
+ story.append(Spacer(1, 1.0 * cm))
252
+
253
+ story.append(P("Team Members", "CoverLabel"))
254
+ story.append(Spacer(1, 0.2 * cm))
255
+ team_rows = [
256
+ ["Name", "BITS ID"],
257
+ ["R. Priji Rajendran", "2024AD05222"],
258
+ ["Reeve Chaitanya", "2024AD05225"],
259
+ ["Sahil Verma", "2024AD05230"],
260
+ ["Vankala N Sai Krishna Kumar", "2024AD05334"],
261
+ ]
262
+ story.append(data_table(team_rows[0], team_rows[1:], col_widths=[9.5 * cm, 5.5 * cm]))
263
+ story.append(Spacer(1, 1.4 * cm))
264
+ story.append(P("Source notebook: knowledge_distillation_assignment.ipynb (fully executed, end-to-end)", "CoverMeta"))
265
+ story.append(P("Environment: conda env agn_env · Python 3.12 · Apple Silicon (MPS + CPU)", "CoverMeta"))
266
+
267
+ story.append(NextPageTemplate("Content"))
268
+ story.append(PageBreak())
269
+
270
+ # ---------------------------------------------------------------------------
271
+ # Table of contents
272
+ # ---------------------------------------------------------------------------
273
+ story.append(P("Table of Contents", "TOCHeading"))
274
+ toc = TableOfContents()
275
+ toc.levelStyles = [
276
+ ParagraphStyle("TOC0", fontName="Helvetica-Bold", fontSize=11, leading=16, leftIndent=0, textColor=ACCENT),
277
+ ParagraphStyle("TOC1", fontName="Helvetica", fontSize=10, leading=14, leftIndent=14, textColor=GREY),
278
+ ]
279
+ story.append(toc)
280
+ story.append(PageBreak())
281
+
282
+ # ---------------------------------------------------------------------------
283
+ # 1. Executive Summary & System Architecture
284
+ # ---------------------------------------------------------------------------
285
+ story.append(heading("1.&nbsp; Executive Summary and System Architecture", 1))
286
+ story.append(Spacer(1, 8))
287
+ story.append(P(
288
+ "This report documents the design, implementation, and empirical evaluation of a knowledge "
289
+ "distillation pipeline that compresses a large, fine-tuned Transformer (“Teacher”) into a "
290
+ "compact, CPU-deployable Transformer (“Student”), on the PolyAI/banking77 dataset — a 77-class, "
291
+ "fine-grained banking-intent classification task with 10,003 training and 3,080 test utterances. "
292
+ "The complete pipeline was implemented and executed end-to-end in a single Jupyter notebook "
293
+ "(<b>knowledge_distillation_assignment.ipynb</b>) inside the conda environment <b>agn_env</b> "
294
+ "(Python 3.12) on Apple Silicon; the Teacher was fine-tuned with MPS acceleration, while the Student "
295
+ "was deliberately trained and benchmarked entirely on CPU — the profile it is designed to be "
296
+ "deployed under."
297
+ ))
298
+ story.append(P(
299
+ "<b>Pipeline overview:</b> <b>bert-base-uncased</b> (110M parameters) is fine-tuned end-to-end on "
300
+ "banking77 to serve as the Teacher. Its full 77-way softmax distribution (“soft labels”) is cached "
301
+ "for every training example. A custom, hand-built 4-layer encoder-only Transformer — using its own "
302
+ "compact, domain-trained WordPiece tokenizer — is then trained as the Student, using a combined "
303
+ "Kullback–Leibler (KL) divergence + cross-entropy loss that blends the Teacher's soft labels with the "
304
+ "ground-truth hard labels. A second, architecturally identical Student is trained on hard labels only, "
305
+ "as a control, to isolate the effect of distillation itself."
306
+ ))
307
+ story.append(P(
308
+ "<b>Motivation for edge-oriented compression:</b> a 110M-parameter, ~420MB BERT checkpoint is "
309
+ "frequently impractical to ship inside a mobile app, run on a low-RAM edge device, or serve at low "
310
+ "latency on constrained hardware. Knowledge distillation offers a route to recover most of that "
311
+ "model's task accuracy in a footprint small enough for such environments, by training the small model "
312
+ "against the large model's full output distribution rather than only its predicted class — the "
313
+ "technique explored and quantified throughout this report."
314
+ ))
315
+
316
+ arch_rows = [
317
+ ["Component", "Specification"],
318
+ ["Teacher", "bert-base-uncased, fine-tuned 3 epochs on banking77 (109,541,453 parameters)"],
319
+ ["Student", "Custom 4-layer encoder-only Transformer, hidden size 256, 4 heads (2,904,397 parameters)"],
320
+ ["Student tokenizer", "WordPiece, 3,000-token vocabulary, trained from scratch on the banking77 corpus"],
321
+ ["Distillation loss", "α·T²·KL(soft student ‖ soft teacher) + (1−α)·CE(student, true label), T=4.0, α=0.7"],
322
+ ["Training devices", "Teacher: Apple MPS · Student: CPU (training and inference)"],
323
+ ]
324
+ story.append(Spacer(1, 4))
325
+ story.append(data_table(arch_rows[0], arch_rows[1:], col_widths=[3.6 * cm, 11.4 * cm]))
326
+
327
+ story.append(PageBreak())
328
+
329
+ # ---------------------------------------------------------------------------
330
+ # 2. Module 1
331
+ # ---------------------------------------------------------------------------
332
+ story.append(heading("2.&nbsp; Module 1: Teacher Labeling and Student Setup", 1))
333
+
334
+ story.append(heading("2.1&nbsp; Task 1 Analysis — Soft Labels, Temperature, and Dark Knowledge", 2))
335
+ story.append(P(
336
+ "bert-base-uncased was fine-tuned end-to-end on banking77 (3 epochs, batch size 32, learning rate "
337
+ "3e-5, weight decay 0.01, Hugging Face Trainer on MPS). After fine-tuning, one no-gradient forward "
338
+ "pass was run over the full, unshuffled training set to cache the Teacher's raw 77-dimensional "
339
+ "logits for every example — the “soft labels” used for distillation."
340
+ ))
341
+ story.append(data_table(
342
+ ["Metric (test set)", "Value"],
343
+ [["Evaluation loss", "0.839"], ["Accuracy", "87.56%"], ["Macro F1", "0.868"],
344
+ ["Total parameters", "109,541,453"], ["Cached logits shape (train / test)", "[10,003 × 77] / [3,080 × 77]"]],
345
+ col_widths=[6.5 * cm, 8.5 * cm],
346
+ ))
347
+ story.append(heading("Why soft labels carry “dark knowledge”", 3))
348
+ story.append(P(
349
+ "A one-hot hard label for “I am still waiting on my card?” states only that the correct class is "
350
+ "<i>card_arrival</i>, and that every other one of the 77 classes is equally, absolutely wrong. That is "
351
+ "not what the Teacher believes: its softmax output might place 62% probability on <i>card_arrival</i>, "
352
+ "21% on the closely related <i>card_delivery_estimate</i>, and small residual mass elsewhere — it "
353
+ "still predicts the right class, but it also encodes how confusable the other intents are with it."
354
+ ))
355
+ story.append(bullet("<b>Transfers inter-class similarity structure</b> — the relative magnitude of non-target probabilities is a learned “confusion prior” that a one-hot vector cannot express, which matters a great deal on a taxonomy with many near-duplicate intents like banking77's (e.g. <i>declined_card_payment</i> vs. <i>declined_cash_withdrawal</i>)."))
356
+ story.append(bullet("<b>Acts as an implicit regularizer</b> — a smoother, higher-entropy target does not force the Student's logits toward extreme values to satisfy a one-hot target, improving generalization, especially for a Student with a very small parameter budget."))
357
+ story.append(bullet("<b>Supplies more effective supervision per example</b> — a hard label carries at most log₂(77) ≈ 6.3 bits of information; a full probability vector carries substantially more, letting a smaller, more data-constrained Student recover more of the Teacher's decision surface from the same training set."))
358
+ story.append(bullet("<b>Is amplified by temperature scaling (T)</b> — dividing both models' logits by T &gt; 1 before the softmax flattens both distributions, inflating the small probabilities on non-target classes — exactly where most of the structural “dark knowledge” lives, since at T=1 those probabilities are too close to zero to produce a useful gradient. This project uses T = 4.0 (Task 4)."))
359
+
360
+ story.append(heading("2.2&nbsp; Task 2 Analysis — Tokenizer Alignment Between Teacher and Student", 2))
361
+ story.append(P(
362
+ "Rather than reusing the Teacher's ~30k-token BERT vocabulary, the Student is given its own compact "
363
+ "WordPiece tokenizer, trained from scratch directly on the banking77 training corpus (target "
364
+ "vocabulary size 3,000, BERT-style lowercasing, [CLS]/[SEP] template post-processing). This is a "
365
+ "deliberate compression lever: embedding-table size scales with vocab_size × hidden_size, so a "
366
+ "10x-smaller, domain-concentrated vocabulary directly shrinks the Student's parameter count "
367
+ "(quantified in Task 3)."
368
+ ))
369
+ story.append(data_table(
370
+ ["Property", "Teacher (BERT)", "Student (custom WordPiece)"],
371
+ [["Vocabulary size", "30,522", "3,000"], ["Vocabulary compression", "—", "10.2x smaller"]],
372
+ col_widths=[5.5 * cm, 4.5 * cm, 5.0 * cm],
373
+ ))
374
+ story.append(Spacer(1, 4))
375
+ story.append(data_table(
376
+ ["Sample utterance", "Teacher tokens", "Student tokens (incl. [CLS]/[SEP])"],
377
+ [
378
+ ["“I am still waiting on my card?”", "8", "10"],
379
+ ["“What can I do if my card still hasn't arrived...”", "16", "18"],
380
+ ["“I have been waiting over a week. Is the card...”", "14", "16"],
381
+ ["“Can I track my card while it is in the process...”", "14", "16"],
382
+ ["“How do I know if I will get my card, or if it...”", "17", "19"],
383
+ ],
384
+ col_widths=[8.5 * cm, 3.0 * cm, 3.5 * cm],
385
+ ))
386
+ story.append(heading("Alignment strategy", 3))
387
+ story.append(P(
388
+ "On these five common, in-domain examples the Student's token count equals the Teacher's plus exactly "
389
+ "two — the [CLS]/[SEP] markers the Student's counts include and the Teacher's tokenize() call does "
390
+ "not — meaning the two vocabularies segment frequent, in-domain phrasing about equally coarsely. The "
391
+ "cost of the much smaller vocabulary shows up on rarer or compound words, via more aggressive subword "
392
+ "splitting and a higher effective [UNK] rate, rather than on everyday vocabulary."
393
+ ))
394
+ story.append(P(
395
+ "A more fundamental design question is how to align a Teacher and Student that tokenize the same text "
396
+ "differently. A naive token-level distillation scheme — as used for sequence-to-sequence or "
397
+ "token-classification tasks — requires the two models' output sequences to line up position-by-position, "
398
+ "which breaks immediately once tokenizers disagree on token counts. That problem does not apply here, "
399
+ "because this is <b>sequence classification</b>: the Teacher emits exactly one 77-way probability "
400
+ "vector per example, independent of its internal token count. The only alignment that matters is "
401
+ "therefore at the <b>example (row) level</b>:"
402
+ ))
403
+ story.append(bullet("<b>Strategy used</b> — Teacher logits are computed once per raw-text example and cached, indexed by that example's position in the unshuffled training set. The same raw text is independently re-tokenized with the Student's own tokenizer. The two are joined purely by row index inside the training Dataset class, so teacher_logits[i] always corresponds to example i regardless of how differently each side tokenized its text."))
404
+ story.append(bullet("<b>Residual risk and mitigation</b> — a much smaller vocabulary can lose lexical signal on rare words; this is mitigated by training the Student tokenizer directly on in-domain banking77 text, so its limited token budget is spent on vocabulary that actually matters for this task."))
405
+
406
+ story.append(PageBreak())
407
+
408
+ # ---------------------------------------------------------------------------
409
+ # 3. Module 2
410
+ # ---------------------------------------------------------------------------
411
+ story.append(heading("3.&nbsp; Module 2: Distillation Architecture and Training Details", 1))
412
+
413
+ story.append(heading("3.1&nbsp; Task 3 — Compact Student Transformer Architecture", 2))
414
+ story.append(P(
415
+ "The Student is a small, hand-built encoder-only Transformer, assembled directly from PyTorch "
416
+ "<b>nn.Module</b> / <b>nn.TransformerEncoderLayer</b> primitives rather than repurposing a pretrained "
417
+ "architecture, and sized to train and run comfortably on CPU."
418
+ ))
419
+ story.append(data_table(
420
+ ["Architecture parameter", "Value"],
421
+ [
422
+ ["Vocabulary size", "3,000 (Task 2 tokenizer)"], ["Hidden size", "256"], ["Encoder layers", "4"],
423
+ ["Attention heads", "4"], ["Feed-forward size", "512"], ["Max sequence length", "32"],
424
+ ["Dropout", "0.1"], ["Pooling", "Mean-pooling over non-padding token positions"],
425
+ ["Output head", "Linear layer to 77 classes"],
426
+ ],
427
+ col_widths=[6.0 * cm, 9.0 * cm],
428
+ ))
429
+ story.append(heading("Parameter breakdown vs. Teacher", 3))
430
+ story.append(data_table(
431
+ ["Component", "Parameters"],
432
+ [
433
+ ["Token + position embeddings", "776,192"], ["Transformer encoder (4 layers)", "2,108,416"],
434
+ ["Classification head", "19,789"], ["Student total", "<b>2,904,397</b>"],
435
+ ["Teacher total (bert-base-uncased)", "<b>109,541,453</b>"],
436
+ ["Compression ratio", "<b>37.7x fewer parameters</b>"],
437
+ ],
438
+ col_widths=[8.0 * cm, 7.0 * cm],
439
+ ))
440
+ story.append(P(
441
+ "Roughly 27% of the Student's parameter budget sits in its embedding table alone — the direct payoff "
442
+ "of Task 2's small, domain-specific vocabulary. Because a Transformer's parameter count for "
443
+ "short-sequence classification scales with vocab_size × hidden_size, shrinking the vocabulary is one "
444
+ "of the single highest-leverage compression decisions available, independent of encoder depth or width."
445
+ ))
446
+
447
+ story.append(heading("3.2&nbsp; Task 4 — Distillation Loss Function", 2))
448
+ story.append(P("The Student is trained against a single combined objective, blending distillation and supervised signal:"))
449
+ story.append(formula(
450
+ "Loss = α · T² · KL( P<sub>student</sub><sup>T</sup> ‖ P<sub>teacher</sub><sup>T</sup> ) "
451
+ "+ (1−α) · CE( y<sub>student</sub>, y<sub>true</sub> )"
452
+ ))
453
+ story.append(P(
454
+ "with temperature <b>T = 4.0</b> and weighting <b>α = 0.7</b>. The KL term compares the Student's and "
455
+ "Teacher's softmax outputs after both are divided by T (softening both distributions and amplifying "
456
+ "the small, informative probabilities on non-target classes); the T² multiplier (Hinton et al., 2015) "
457
+ "compensates for the fact that raising T shrinks the KD gradient magnitude by roughly 1/T² relative to "
458
+ "the hard-label term, so without it the KD loss would be under-weighted once a large T is introduced. "
459
+ "The CE term is ordinary cross-entropy against the true label, ensuring the Student never loses sight "
460
+ "of the actual classification objective while learning to mimic the Teacher's distribution."
461
+ ))
462
+ story.append(heading("Training configuration", 3))
463
+ story.append(data_table(
464
+ ["Hyperparameter", "Distilled Student", "Baseline Student (control)"],
465
+ [
466
+ ["Loss", "α·T²·KL + (1−α)·CE", "CE only (hard labels)"],
467
+ ["Optimizer", "AdamW, lr 3e-4", "AdamW, lr 3e-4"],
468
+ ["Epochs / batch size", "8 / 32", "8 / 32"],
469
+ ["Device", "CPU", "CPU"],
470
+ ["Training time", "130.8 s", "127.6 s"],
471
+ ],
472
+ col_widths=[4.5 * cm, 5.25 * cm, 5.25 * cm],
473
+ ))
474
+ story.append(Spacer(1, 6))
475
+ story.append(data_table(
476
+ ["Epoch", "Total loss", "KD component", "CE component"],
477
+ [
478
+ ["1", "1.142", "0.556", "2.508"], ["2", "0.559", "0.306", "1.150"],
479
+ ["3", "0.387", "0.217", "0.786"], ["4", "0.301", "0.174", "0.598"],
480
+ ["5", "0.248", "0.148", "0.482"], ["6", "0.211", "0.132", "0.396"],
481
+ ["7", "0.184", "0.118", "0.337"], ["8", "0.166", "0.110", "0.297"],
482
+ ],
483
+ col_widths=[2.5 * cm, 4.17 * cm, 4.17 * cm, 4.17 * cm],
484
+ ))
485
+ story.append(image_with_caption(
486
+ f"{ASSETS}/distill_loss_curves.png", 13.5 * cm,
487
+ "Figure 1. Distilled student training: total loss (left) and its KD vs. CE components (right) across 8 epochs.",
488
+ ))
489
+ story.append(P(
490
+ "The CE component drops faster and further than the KD component throughout training: with only "
491
+ "3,000 vocabulary tokens and 4 layers, the Student can quickly memorize the single correct class for a "
492
+ "small, well-separated training set, whereas matching the Teacher's full smoothed distribution over "
493
+ "77 classes at T=4 is a strictly harder target. The KD term keeps supplying a non-trivial gradient "
494
+ "signal well after the CE term has largely converged — exactly the regime in which distillation "
495
+ "contributes information beyond what hard labels alone would teach."
496
+ ))
497
+
498
+ story.append(PageBreak())
499
+
500
+ # ---------------------------------------------------------------------------
501
+ # 4. Module 3
502
+ # ---------------------------------------------------------------------------
503
+ story.append(heading("4.&nbsp; Module 3: Experimental Results and Benchmarking", 1))
504
+
505
+ story.append(heading("4.1&nbsp; Task 5 — Accuracy vs. Compression Evaluation", 2))
506
+ story.append(P(
507
+ "To isolate the effect of distillation from the effect of the compact architecture alone, a second, "
508
+ "architecturally identical Student is trained with plain cross-entropy on ground-truth labels only "
509
+ "(no Teacher signal). All three models are evaluated on the same held-out 3,080-example test set using "
510
+ "scikit-learn's accuracy_score and f1_score (macro and weighted)."
511
+ ))
512
+ story.append(data_table(
513
+ ["Model", "Accuracy", "Macro F1", "Weighted F1"],
514
+ [
515
+ ["Teacher (bert-base-uncased)", "87.56%", "0.868", "0.868"],
516
+ ["Student — without distillation", "83.47%", "0.836", "0.836"],
517
+ ["Student — with distillation", "<b>87.44%</b>", "<b>0.874</b>", "<b>0.874</b>"],
518
+ ],
519
+ col_widths=[6.5 * cm, 3.0 * cm, 2.9 * cm, 2.9 * cm],
520
+ ))
521
+ story.append(image_with_caption(
522
+ f"{ASSETS}/baseline_vs_distilled_loss.png", 9.5 * cm,
523
+ "Figure 2. Training loss: baseline student (CE only) vs. distilled student (KD + CE). The two loss compositions are not directly comparable in scale.",
524
+ ))
525
+ story.append(P(
526
+ "The undistilled Student, trained only on hard labels with a 37.7x smaller architecture, reaches "
527
+ "83.5% accuracy — a 4.1-point gap below the Teacher's 87.6%, as expected given how much capacity was "
528
+ "removed. Adding the Teacher's soft labels — architecture, data, and epoch budget held fixed, "
529
+ "changing only the loss function — raises the Student to 87.4% accuracy, <b>closing 97% of the "
530
+ "accuracy gap</b> between the undistilled Student and the Teacher, and retaining <b>99.9%</b> of the "
531
+ "Teacher's accuracy at a fraction of its parameter count. This is the central empirical claim of "
532
+ "knowledge distillation demonstrated directly: dark knowledge in the Teacher's soft labels lets a "
533
+ "small model recover far more of a large model's decision surface than the same small model could "
534
+ "learn from hard labels alone. This closeness also partly reflects that the Teacher itself is only a "
535
+ "lightly (3-epoch) fine-tuned model and the test set is a few thousand examples — a point or two either "
536
+ "way is within normal run-to-run variance."
537
+ ))
538
+
539
+ story.append(heading("4.2&nbsp; Task 6 — Deployment Metrics Benchmarking", 2))
540
+ story.append(P(
541
+ "Accuracy alone does not determine deployability. Three deployment-relevant metrics were measured for "
542
+ "the Teacher and the distilled Student: on-disk model size, CPU inference latency, and peak process "
543
+ "RAM. Peak RAM was measured in an <b>isolated subprocess per model</b> (via resource.getrusage) rather "
544
+ "than in the shared notebook kernel, since peak RSS is monotonically non-decreasing for the life of a "
545
+ "process — loading both models into one kernel would let the Teacher's larger footprint contaminate "
546
+ "any subsequent reading taken for the Student."
547
+ ))
548
+ story.append(data_table(
549
+ ["Metric", "Teacher", "Student", "Compression / Speedup"],
550
+ [
551
+ ["Model size on disk (MB)", "417.9", "11.1", "<b>37.7x smaller</b>"],
552
+ ["CPU inference latency (ms/query)", "27.76 ± 3.07", "1.18 ± 0.09", "<b>23.5x faster</b>"],
553
+ ["Peak RAM (MB, isolated process)", "893.8", "237.0", "<b>3.8x smaller</b>"],
554
+ ],
555
+ col_widths=[5.5 * cm, 3.0 * cm, 3.0 * cm, 3.8 * cm],
556
+ ))
557
+
558
+ story.append(PageBreak())
559
+
560
+ # ---------------------------------------------------------------------------
561
+ # 5. Deployment Readiness
562
+ # ---------------------------------------------------------------------------
563
+ story.append(heading("5.&nbsp; Deployment Readiness and Engineering Inferences", 1))
564
+ story.append(P(
565
+ "The distilled Student is <b>37.7x smaller on disk</b>, <b>23.5x faster</b> per CPU query, and uses "
566
+ "<b>3.8x less peak RAM</b> than the Teacher, while retaining <b>99.9%</b> of its accuracy on the same "
567
+ "77-way classification task. In this run there is essentially no accuracy cost to weigh against those "
568
+ "savings — a favourable outcome rather than a guarantee, since it partly reflects a lightly fine-tuned "
569
+ "Teacher and a modest-size test set; a production rollout should still monitor accuracy on live "
570
+ "traffic rather than assume this margin holds indefinitely as the input distribution drifts."
571
+ ))
572
+ story.append(bullet("<b>Size and RAM</b> — at ~11MB on disk and ~237MB of peak RAM, the Student comfortably fits within the memory budgets of edge devices and mobile apps, where a 418MB+ BERT-base checkpoint is frequently a non-starter (app-store bundle-size limits, low-RAM Android devices, on-device model caches)."))
573
+ story.append(bullet("<b>Latency</b> — 1.2ms/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 27.8ms/query, multiplied across a request queue on a resource-constrained device, would noticeably degrade perceived responsiveness."))
574
+ story.append(bullet("<b>Accuracy trade-off</b> — in this run there is effectively no trade-off; the size/latency/RAM wins come essentially for free on this test set. Whether that generalizes depends on the product: for a first-pass intent router that falls back to a human agent or a larger cloud model on low confidence, distillation is a clear win even when some accuracy gap does exist. For a fully autonomous decision with no fallback (e.g. auto-approving a refund), any residual gap to the Teacher may still argue for keeping the Teacher, or a human, in the loop."))
575
+ story.append(bullet("<b>Practical recommendation</b> — 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 demonstrated size/latency/RAM benefits while bounding accuracy risk to only the genuinely ambiguous cases — exactly the scenario dark-knowledge distillation is suited for, since the Student was trained to mimic the Teacher's confidence structure, not just its arg-max."))
576
+
577
+ story.append(heading("Key takeaways", 2))
578
+ story.append(bullet("<b>Dark knowledge transfers real signal</b> — distillation closed 97% of the accuracy gap between an undistilled and a distilled Student sharing the same 37.7x-smaller architecture, using only a change of loss function — no additional data, parameters, or training time."))
579
+ story.append(bullet("<b>Vocabulary size is a first-order compression lever</b> — a domain-trained, 10x-smaller Student tokenizer removed roughly a quarter of the Student's total parameter budget on its own, independent of encoder depth or width."))
580
+ story.append(bullet("<b>Sequence-classification distillation avoids the hardest alignment problem</b> — because the Teacher produces one probability vector per example rather than per token, tokenizer mismatch only requires row-level index alignment, not token-level alignment."))
581
+ story.append(bullet("<b>The compression payoff is large and, in this run, the accuracy cost is negligible</b> — 37.7x smaller, 23.5x faster, 3.8x less RAM, for 99.9% of the Teacher's test accuracy, making the distilled Student a strong candidate for edge/mobile deployment, ideally paired with a confidence-based fallback to the Teacher for the hardest cases."))
582
+
583
+
584
+ doc.multiBuild(story)
585
+ print(f"PDF written to {OUT_PATH}")
demo/build_report.py ADDED
@@ -0,0 +1,688 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Builds Knowledge_Distillation_Report.docx summarizing design, implementation, and evaluation."""
2
+ import datetime
3
+ from docx import Document
4
+ from docx.shared import Pt, Inches, RGBColor, Cm
5
+ from docx.enum.text import WD_ALIGN_PARAGRAPH
6
+ from docx.enum.table import WD_TABLE_ALIGNMENT
7
+ from docx.oxml.ns import qn
8
+ from docx.oxml import OxmlElement
9
+
10
+ ASSETS = "/Users/reevechaitanya/Documents/2_Experimentation_n_Research/demo/report_assets"
11
+
12
+ ACCENT = RGBColor(0x1F, 0x4E, 0x79)
13
+ GREY = RGBColor(0x40, 0x40, 0x40)
14
+
15
+ doc = Document()
16
+
17
+ # ---------------------------------------------------------------------------
18
+ # Global style setup
19
+ # ---------------------------------------------------------------------------
20
+ normal = doc.styles["Normal"]
21
+ normal.font.name = "Calibri"
22
+ normal.font.size = Pt(11)
23
+ normal.paragraph_format.space_after = Pt(8)
24
+ normal.paragraph_format.line_spacing = 1.15
25
+
26
+ for i in range(1, 4):
27
+ h = doc.styles[f"Heading {i}"]
28
+ h.font.name = "Calibri"
29
+ h.font.color.rgb = ACCENT
30
+ h.font.bold = True
31
+ h1, h2, h3 = doc.styles["Heading 1"], doc.styles["Heading 2"], doc.styles["Heading 3"]
32
+ h1.font.size, h2.font.size, h3.font.size = Pt(20), Pt(15), Pt(12.5)
33
+ h1.paragraph_format.space_before, h2.paragraph_format.space_before, h3.paragraph_format.space_before = Pt(20), Pt(14), Pt(10)
34
+
35
+ for sec in doc.sections:
36
+ sec.left_margin = Cm(2.2)
37
+ sec.right_margin = Cm(2.2)
38
+ sec.top_margin = Cm(1.8)
39
+ sec.bottom_margin = Cm(1.8)
40
+
41
+
42
+ def add_page_number_footer(section):
43
+ footer = section.footer
44
+ p = footer.paragraphs[0]
45
+ p.alignment = WD_ALIGN_PARAGRAPH.CENTER
46
+ run = p.add_run()
47
+ fld = OxmlElement("w:fldSimple")
48
+ fld.set(qn("w:instr"), "PAGE")
49
+ run._r.append(fld)
50
+
51
+
52
+ add_page_number_footer(doc.sections[0])
53
+
54
+
55
+ def h(text, level=1):
56
+ doc.add_heading(text, level=level)
57
+
58
+
59
+ def p(text="", bold=False, italic=False, size=None, color=None, align=None, space_after=None):
60
+ para = doc.add_paragraph()
61
+ if align is not None:
62
+ para.alignment = align
63
+ if space_after is not None:
64
+ para.paragraph_format.space_after = Pt(space_after)
65
+ run = para.add_run(text)
66
+ run.bold = bold
67
+ run.italic = italic
68
+ if size:
69
+ run.font.size = Pt(size)
70
+ if color:
71
+ run.font.color.rgb = color
72
+ return para
73
+
74
+
75
+ def rich(para, segments):
76
+ """segments: list of (text, bold, italic) tuples appended to an existing paragraph."""
77
+ for seg in segments:
78
+ text = seg[0]
79
+ bold = seg[1] if len(seg) > 1 else False
80
+ italic = seg[2] if len(seg) > 2 else False
81
+ run = para.add_run(text)
82
+ run.bold = bold
83
+ run.italic = italic
84
+ return para
85
+
86
+
87
+ def bullets(items):
88
+ # Special case used throughout this script: bullets([["Bold label", True], "plain description"])
89
+ # is ONE bullet with a bold lead-in run followed by a normal-weight continuation run.
90
+ if (len(items) == 2 and isinstance(items[0], (list, tuple)) and len(items[0]) == 2
91
+ and isinstance(items[0][1], bool) and isinstance(items[1], str)):
92
+ para = doc.add_paragraph(style="List Bullet")
93
+ label, bold = items[0]
94
+ lead_run = para.add_run(label)
95
+ lead_run.bold = bold
96
+ para.add_run(items[1])
97
+ return
98
+ for item in items:
99
+ para = doc.add_paragraph(style="List Bullet")
100
+ if isinstance(item, str):
101
+ para.add_run(item)
102
+ else:
103
+ rich(para, item)
104
+
105
+
106
+ def formula_block(text):
107
+ para = doc.add_paragraph()
108
+ para.alignment = WD_ALIGN_PARAGRAPH.CENTER
109
+ para.paragraph_format.space_before = Pt(6)
110
+ para.paragraph_format.space_after = Pt(6)
111
+ run = para.add_run(text)
112
+ run.italic = True
113
+ run.font.size = Pt(12)
114
+ run.font.name = "Cambria Math"
115
+ return para
116
+
117
+
118
+ def set_cell_shading(cell, hex_color):
119
+ tc_pr = cell._tc.get_or_add_tcPr()
120
+ shd = OxmlElement("w:shd")
121
+ shd.set(qn("w:val"), "clear")
122
+ shd.set(qn("w:fill"), hex_color)
123
+ tc_pr.append(shd)
124
+
125
+
126
+ def add_table(headers, rows, col_widths=None, header_color="1F4E79"):
127
+ table = doc.add_table(rows=1, cols=len(headers))
128
+ table.style = "Table Grid"
129
+ table.alignment = WD_TABLE_ALIGNMENT.CENTER
130
+ hdr_cells = table.rows[0].cells
131
+ for i, htext in enumerate(headers):
132
+ hdr_cells[i].text = ""
133
+ run = hdr_cells[i].paragraphs[0].add_run(htext)
134
+ run.bold = True
135
+ run.font.color.rgb = RGBColor(0xFF, 0xFF, 0xFF)
136
+ run.font.size = Pt(10.5)
137
+ set_cell_shading(hdr_cells[i], header_color)
138
+ hdr_cells[i].paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
139
+ for row in rows:
140
+ cells = table.add_row().cells
141
+ for i, val in enumerate(row):
142
+ cells[i].text = ""
143
+ run = cells[i].paragraphs[0].add_run(str(val))
144
+ run.font.size = Pt(10.5)
145
+ cells[i].paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER if i > 0 else WD_ALIGN_PARAGRAPH.LEFT
146
+ if col_widths:
147
+ for i, w in enumerate(col_widths):
148
+ for row in table.rows:
149
+ row.cells[i].width = Inches(w)
150
+ doc.add_paragraph()
151
+ return table
152
+
153
+
154
+ def add_image(path, width=5.8, caption=None):
155
+ doc.add_picture(path, width=Inches(width))
156
+ last_paragraph = doc.paragraphs[-1]
157
+ last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
158
+ if caption:
159
+ cap = doc.add_paragraph()
160
+ cap.alignment = WD_ALIGN_PARAGRAPH.CENTER
161
+ run = cap.add_run(caption)
162
+ run.italic = True
163
+ run.font.size = Pt(9.5)
164
+ run.font.color.rgb = GREY
165
+
166
+
167
+ # ---------------------------------------------------------------------------
168
+ # Title page
169
+ # ---------------------------------------------------------------------------
170
+ title_p = doc.add_paragraph()
171
+ title_p.alignment = WD_ALIGN_PARAGRAPH.CENTER
172
+ title_p.paragraph_format.space_before = Pt(120)
173
+ run = title_p.add_run("Knowledge Distillation on the Banking77 Intent Dataset")
174
+ run.bold = True
175
+ run.font.size = Pt(26)
176
+ run.font.color.rgb = ACCENT
177
+
178
+ sub_p = doc.add_paragraph()
179
+ sub_p.alignment = WD_ALIGN_PARAGRAPH.CENTER
180
+ sub_p.paragraph_format.space_before = Pt(10)
181
+ run = sub_p.add_run("Design, Implementation, and Evaluation Report")
182
+ run.font.size = Pt(16)
183
+ run.font.color.rgb = GREY
184
+
185
+ sub2 = doc.add_paragraph()
186
+ sub2.alignment = WD_ALIGN_PARAGRAPH.CENTER
187
+ sub2.paragraph_format.space_before = Pt(4)
188
+ run = sub2.add_run("Compressing a Fine-Tuned BERT Teacher into a Compact CPU-Deployable Transformer Student")
189
+ run.font.size = Pt(12)
190
+ run.italic = True
191
+ run.font.color.rgb = GREY
192
+
193
+ meta_p = doc.add_paragraph()
194
+ meta_p.alignment = WD_ALIGN_PARAGRAPH.CENTER
195
+ meta_p.paragraph_format.space_before = Pt(60)
196
+ meta_lines = [
197
+ f"Generated: {datetime.date.today().strftime('%B %d, %Y')}",
198
+ "Source notebook: knowledge_distillation_assignment.ipynb",
199
+ "Dataset: PolyAI/banking77 (77-class banking intent classification)",
200
+ "Environment: conda env agn_env, Python 3.12, Apple Silicon (MPS + CPU)",
201
+ ]
202
+ for i, line in enumerate(meta_lines):
203
+ if i > 0:
204
+ meta_p.add_run("\n")
205
+ r = meta_p.add_run(line)
206
+ r.font.size = Pt(11)
207
+ r.font.color.rgb = GREY
208
+
209
+ doc.add_page_break()
210
+
211
+ # ---------------------------------------------------------------------------
212
+ # 1. Introduction
213
+ # ---------------------------------------------------------------------------
214
+ h("1. Introduction and Objective", 1)
215
+ p(
216
+ "Large fine-tuned Transformers such as BERT deliver strong accuracy on text classification tasks but "
217
+ "are frequently too large, too slow, and too memory-hungry to deploy on edge devices, mobile "
218
+ "applications, or latency-sensitive services. Knowledge distillation addresses this by transferring "
219
+ "the behaviour of a large “Teacher” model into a much smaller “Student” model, using the "
220
+ "Teacher's full output probability distribution — not just its predicted class — as a richer training "
221
+ "signal."
222
+ )
223
+ p(
224
+ "This report documents the design, implementation, and evaluation of an end-to-end knowledge "
225
+ "distillation pipeline built for the 77-class Banking77 intent-classification dataset, structured "
226
+ "around three modules and six tasks:"
227
+ )
228
+ add_table(
229
+ ["Module", "Tasks"],
230
+ [
231
+ ["1. Teacher Labeling & Student Setup", "Task 1: Teacher fine-tuning & soft-label generation\nTask 2: Student tokenizer alignment"],
232
+ ["2. Distillation Architecture & Training", "Task 3: Compact student transformer\nTask 4: Distillation loss function & training"],
233
+ ["3. Comparative Analysis & Benchmarking", "Task 5: Accuracy vs. compression evaluation\nTask 6: Deployment metrics analysis"],
234
+ ],
235
+ col_widths=[2.6, 3.7],
236
+ )
237
+ p(
238
+ "All code was implemented and executed end-to-end in a single Jupyter notebook "
239
+ "(knowledge_distillation_assignment.ipynb) inside the conda environment agn_env (Python 3.12) on an "
240
+ "Apple Silicon machine. The Teacher was fine-tuned using MPS acceleration; the Student was deliberately "
241
+ "trained and benchmarked entirely on CPU, since CPU-only inference is the target deployment profile "
242
+ "this exercise is optimizing for."
243
+ )
244
+
245
+ # ---------------------------------------------------------------------------
246
+ # 2. Dataset
247
+ # ---------------------------------------------------------------------------
248
+ h("2. Dataset", 1)
249
+ p(
250
+ "Banking77 is a fine-grained intent-classification dataset of customer-support utterances for a "
251
+ "banking app, labelled with one of 77 narrow, often semantically overlapping intents (e.g. "
252
+ "card_arrival vs. card_delivery_estimate, declined_card_payment vs. declined_cash_withdrawal). This "
253
+ "makes it a good stress test for distillation: the fine granularity of the label space means the "
254
+ "relative similarity between classes — the information that soft labels carry and hard labels do "
255
+ "not — is directly relevant to classification accuracy."
256
+ )
257
+ add_table(
258
+ ["Property", "Value"],
259
+ [
260
+ ["Source", "PolyAI/banking77 (loaded via a verified parquet mirror, legacy-datasets/banking77, after the original repository's script-based loader was found incompatible with the installed datasets library version)"],
261
+ ["Training examples", "10,003"],
262
+ ["Test examples", "3,080"],
263
+ ["Number of classes", "77"],
264
+ ["Example text", "“I am still waiting on my card?” → label: card_arrival"],
265
+ ],
266
+ col_widths=[2.0, 4.3],
267
+ )
268
+
269
+ doc.add_page_break()
270
+
271
+ # ---------------------------------------------------------------------------
272
+ # Module 1
273
+ # ---------------------------------------------------------------------------
274
+ h("3. Module 1: Teacher Labeling and Student Setup", 1)
275
+
276
+ h("3.1 Task 1 — Teacher Integration and Soft-Label Generation", 2)
277
+
278
+ h("Design", 3)
279
+ p(
280
+ "bert-base-uncased (110M parameters) was selected as the Teacher for its strong general-purpose "
281
+ "language representations and its established track record on intent-classification benchmarks. "
282
+ "The design goal was twofold: (1) fine-tune it into a strong classifier for banking77, and (2) cache "
283
+ "its full 77-way probability distribution — not just its hard prediction — for every training "
284
+ "example, so that the Student never needs the (comparatively expensive) Teacher to run again during "
285
+ "its own training."
286
+ )
287
+
288
+ h("Implementation", 3)
289
+ bullets([
290
+ "Tokenization: bert-base-uncased's own WordPiece tokenizer, sequences truncated to 64 tokens.",
291
+ "Model: transformers.BertForSequenceClassification.from_pretrained(\"bert-base-uncased\", num_labels=77) — the pretrained encoder weights are kept; a new randomly-initialized 77-way classification head is trained from scratch.",
292
+ "Training: Hugging Face Trainer, 3 epochs, batch size 32 (train) / 64 (eval), learning rate 3e-5, weight decay 0.01, evaluated each epoch on the test set, run on Apple Silicon MPS.",
293
+ "Soft-label caching: one no-gradient forward pass over the full, unshuffled training set (and separately the test set) immediately after fine-tuning, producing a [10003 × 77] and a [3080 × 77] logits tensor respectively. Because the pass is unshuffled, teacher_train_logits[i] corresponds exactly to training example i by index — this index-based join is what Task 2 relies on.",
294
+ ])
295
+
296
+ h("Results", 3)
297
+ add_table(
298
+ ["Metric (test set)", "Value"],
299
+ [
300
+ ["Evaluation loss", "0.839"],
301
+ ["Accuracy", "87.6%"],
302
+ ["Macro F1", "0.868"],
303
+ ["Total parameters", "109,541,453"],
304
+ ["Cached train logits shape", "[10,003, 77]"],
305
+ ["Cached test logits shape", "[3,080, 77]"],
306
+ ],
307
+ col_widths=[3.0, 3.0],
308
+ )
309
+
310
+ h("Interpretation — Why Soft Labels Carry “Dark Knowledge”", 3)
311
+ p(
312
+ "A one-hot hard label for “I am still waiting on my card?” states only that the correct class is "
313
+ "card_arrival and that all 76 other classes are equally, absolutely wrong. That is not what the "
314
+ "Teacher actually believes: its softmax distribution might place 62% probability on card_arrival, "
315
+ "21% on the closely related card_delivery_estimate, and small residual mass on a handful of other "
316
+ "intents. Training against the full distribution rather than the arg-max alone:"
317
+ )
318
+ bullets([
319
+ ["Transfers inter-class similarity structure. ", True],
320
+ "The relative magnitude of non-target probabilities encodes which intents the Teacher finds confusable with which — a signal entirely absent from a one-hot vector, and especially valuable on a taxonomy with many near-duplicate intents like banking77's.",
321
+ ])
322
+ bullets([
323
+ ["Acts as an implicit regularizer. ", True],
324
+ "A smoother, higher-entropy target does not force the Student's logits toward extreme values to satisfy a one-hot target, which tends to improve generalization — particularly important for a Student with a very small parameter budget.",
325
+ ])
326
+ bullets([
327
+ ["Supplies more effective supervision per example. ", True],
328
+ "A hard label carries at most log₂(77) ≈ 6.3 bits of information (which class); a full probability vector carries substantially more, letting a smaller, more data-constrained Student recover more of the Teacher's decision surface from the same training set.",
329
+ ])
330
+ bullets([
331
+ ["Is amplified by temperature scaling. ", True],
332
+ "Raising the softmax temperature T before distillation (used in Task 4) inflates the small probabilities on non-target classes — exactly where most of this structural information lives, since at T=1 those probabilities are too close to zero to produce a useful gradient.",
333
+ ])
334
+
335
+ h("3.2 Task 2 — Student Tokenizer Alignment", 2)
336
+
337
+ h("Design", 3)
338
+ p(
339
+ "Rather than reusing the Teacher's ~30k-token BERT vocabulary, the Student is given its own compact "
340
+ "WordPiece tokenizer trained from scratch, directly on the banking77 training corpus. This keeps the "
341
+ "Student's vocabulary small (a major lever on parameter count, since embedding-table size scales with "
342
+ "vocab_size × hidden_size) while concentrating that small vocabulary on the words that actually appear "
343
+ "in this domain."
344
+ )
345
+
346
+ h("Implementation", 3)
347
+ bullets([
348
+ "Backend: tokenizers.Tokenizer with a WordPiece model, BERT-style lowercasing normalizer, whitespace pre-tokenizer, and [CLS]/[SEP] template post-processing.",
349
+ "Trained via WordPieceTrainer with a target vocabulary size of 3,000 tokens and special tokens [PAD], [UNK], [CLS], [SEP], directly on the 10,003 raw training utterances.",
350
+ "A helper (student_encode_batch) pads/truncates every example to a fixed 32-token sequence length for the Student's fixed-size batched forward pass.",
351
+ ])
352
+
353
+ h("Results — Tokenizer Comparison", 3)
354
+ add_table(
355
+ ["Property", "Teacher (BERT)", "Student (custom WordPiece)"],
356
+ [
357
+ ["Vocabulary size", "30,522", "3,000"],
358
+ ["Vocabulary compression", "—", "10.2x smaller"],
359
+ ],
360
+ col_widths=[2.4, 2.0, 2.4],
361
+ )
362
+ p("Side-by-side tokenization of five sample utterances:", bold=False)
363
+ add_table(
364
+ ["Utterance (truncated)", "Teacher tokens", "Student tokens (incl. [CLS]/[SEP])"],
365
+ [
366
+ ["I am still waiting on my card?", "8", "10"],
367
+ ["What can I do if my card still hasn't arrived...", "16", "18"],
368
+ ["I have been waiting over a week. Is the card...", "14", "16"],
369
+ ["Can I track my card while it is in the process...", "14", "16"],
370
+ ["How do I know if I will get my card, or if it...", "17", "19"],
371
+ ],
372
+ col_widths=[3.6, 1.4, 1.9],
373
+ )
374
+
375
+ h("Interpretation — Handling the Vocabulary Mismatch", 3)
376
+ p(
377
+ "On these five common, in-domain examples, the Student's token count is exactly the Teacher's count "
378
+ "plus two — the [CLS]/[SEP] markers the Student's tokens include and the Teacher's tokenize() call "
379
+ "does not. In other words, for frequent, in-vocabulary phrasing the domain-trained 3,000-token "
380
+ "vocabulary segments text about as coarsely as BERT's 30,522-token vocabulary; the cost of a much "
381
+ "smaller vocabulary shows up on rarer or compound words not well represented in the 10,003-example "
382
+ "training corpus, via more aggressive subword splitting and a higher effective [UNK] rate, rather "
383
+ "than on everyday vocabulary."
384
+ )
385
+ p(
386
+ "A more fundamental question this task addresses is how to align Teacher and Student when they "
387
+ "tokenize the same text differently. A naive token-level distillation scheme — as used in "
388
+ "sequence-to-sequence or token-classification distillation — requires the Teacher's and Student's "
389
+ "output sequences to line up position by position, which breaks immediately once the two tokenizers "
390
+ "produce different token counts for the same input. That problem does not apply here, because "
391
+ "distillation in this project is over sequence classification: the Teacher emits exactly one 77-way "
392
+ "probability vector per example, regardless of how many tokens that example was split into "
393
+ "internally. The only alignment that matters is therefore at the example level, not the token level:"
394
+ )
395
+ bullets([
396
+ ["Strategy used: ", True],
397
+ "Teacher logits are computed once per raw-text example (Task 1) and cached indexed by the example's position in the unshuffled training set. The same raw text is independently re-tokenized with the Student's own tokenizer for the Student's forward pass. The two are joined purely by row index inside BankingStudentDataset — teacher_train_logits[i] always corresponds to train_raw[i], irrespective of how differently each tokenizer segmented that row's text.",
398
+ ])
399
+ bullets([
400
+ ["Residual risk and mitigation: ", True],
401
+ "A much smaller vocabulary does risk losing lexical signal on rare words the Teacher could represent more precisely. This is mitigated by training the Student tokenizer directly on in-domain banking77 text, so its limited token budget is spent on the vocabulary that actually matters for this task rather than a generic corpus.",
402
+ ])
403
+
404
+ doc.add_page_break()
405
+
406
+ # ---------------------------------------------------------------------------
407
+ # Module 2
408
+ # ---------------------------------------------------------------------------
409
+ h("4. Module 2: Distillation Architecture and Training", 1)
410
+
411
+ h("4.1 Task 3 — Compact Student Transformer Construction", 2)
412
+
413
+ h("Design", 3)
414
+ p(
415
+ "The Student is a small, hand-built encoder-only Transformer — assembled directly from PyTorch "
416
+ "nn.Module / nn.TransformerEncoderLayer primitives rather than reusing a pretrained architecture — "
417
+ "sized deliberately small enough to train and run comfortably on CPU."
418
+ )
419
+ add_table(
420
+ ["Architecture parameter", "Value"],
421
+ [
422
+ ["Vocabulary size", "3,000 (Task 2 tokenizer)"],
423
+ ["Hidden size", "256"],
424
+ ["Encoder layers", "4"],
425
+ ["Attention heads", "4"],
426
+ ["Feed-forward size", "512"],
427
+ ["Max sequence length", "32"],
428
+ ["Dropout", "0.1"],
429
+ ["Pooling", "Mean-pooling over non-padding token positions"],
430
+ ["Output head", "Linear layer to 77 classes"],
431
+ ],
432
+ col_widths=[2.6, 3.7],
433
+ )
434
+
435
+ h("Implementation", 3)
436
+ p(
437
+ "Forward pass: token embeddings and learned positional embeddings are summed, passed through 4 "
438
+ "stacked TransformerEncoderLayers with a padding mask (src_key_padding_mask) derived from the "
439
+ "attention mask so padded positions are ignored by self-attention, mean-pooled over valid (non-pad) "
440
+ "token positions, and projected through a linear classifier to 77 logits."
441
+ )
442
+
443
+ h("Results — Parameter Breakdown", 3)
444
+ add_table(
445
+ ["Component", "Parameters"],
446
+ [
447
+ ["Token + position embeddings", "776,192"],
448
+ ["Transformer encoder (4 layers)", "2,108,416"],
449
+ ["Classification head", "19,789"],
450
+ ["Student total", "2,904,397"],
451
+ ["Teacher total (bert-base-uncased)", "109,541,453"],
452
+ ["Compression ratio", "37.7x fewer parameters"],
453
+ ],
454
+ col_widths=[3.4, 2.9],
455
+ )
456
+
457
+ h("Interpretation", 3)
458
+ p(
459
+ "The Student uses 37.7x fewer parameters than the Teacher. Roughly 27% of that budget sits in the "
460
+ "embedding table alone — the direct payoff of Task 2's small, domain-specific vocabulary (3,000 vs. "
461
+ "BERT's 30,522 tokens). Because a Transformer's parameter count for short-sequence classification "
462
+ "scales with vocab_size × hidden_size, shrinking the vocabulary is one of the single highest-leverage "
463
+ "compression decisions available, independent of how many encoder layers are ultimately kept."
464
+ )
465
+
466
+ h("4.2 Task 4 — Distillation Loss Function", 2)
467
+
468
+ h("Design", 3)
469
+ p("The Student is trained with a combined objective:")
470
+ formula_block(
471
+ "Loss = α · T² · KL(Pᵨtudent, Pᵀeacher at temperature T) + (1 − α) · CE(yᵨtudent, yᵀrue)"
472
+ )
473
+ p(
474
+ "with temperature T = 4.0 and weighting α = 0.7. The KL term is computed between the Student's and "
475
+ "Teacher's softmax distributions after both are divided by T (which softens both distributions and "
476
+ "amplifies the small, informative probabilities on non-target classes); the T² multiplier (Hinton et "
477
+ "al., 2015) compensates for the fact that raising T shrinks the magnitude of the gradients coming from "
478
+ "the soft-label term by roughly 1/T² relative to the hard-label term, so without it the KD loss would "
479
+ "be under-weighted once a large T is introduced. The CE term is ordinary cross-entropy against the "
480
+ "true ground-truth label, ensuring the Student never loses sight of the actual classification "
481
+ "objective even while learning to mimic the Teacher's distribution."
482
+ )
483
+
484
+ h("Implementation", 3)
485
+ bullets([
486
+ "DistillationLoss(nn.Module): computes log_softmax(student_logits / T), softmax(teacher_logits / T), combines them via nn.KLDivLoss(reduction=\"batchmean\") scaled by T², and blends with nn.CrossEntropyLoss(student_logits, true_labels) using the α / (1−α) weights above.",
487
+ "BankingStudentDataset joins each example's Student-tokenized input with its cached Teacher logits and true label by row index (the alignment strategy from Task 2).",
488
+ "Training loop: AdamW optimizer, learning rate 3e-4, batch size 32, 8 epochs, executed entirely on CPU.",
489
+ ])
490
+
491
+ h("Results", 3)
492
+ add_table(
493
+ ["Epoch", "Total loss", "KD component", "CE component"],
494
+ [
495
+ ["1", "1.142", "0.556", "2.508"],
496
+ ["2", "0.559", "0.306", "1.150"],
497
+ ["3", "0.387", "0.217", "0.786"],
498
+ ["4", "0.301", "0.174", "0.598"],
499
+ ["5", "0.248", "0.148", "0.482"],
500
+ ["6", "0.211", "0.132", "0.396"],
501
+ ["7", "0.184", "0.118", "0.337"],
502
+ ["8", "0.166", "0.110", "0.297"],
503
+ ],
504
+ col_widths=[1.0, 1.8, 1.9, 1.9],
505
+ )
506
+ p(f"Total distilled-student training time: 130.8 seconds on CPU (8 epochs, 10,003 examples).")
507
+ add_image(f"{ASSETS}/distill_loss_curves.png", width=6.2,
508
+ caption="Figure 1. Distilled student training: total loss (left) and its KD vs. CE components (right) across 8 epochs.")
509
+
510
+ h("Interpretation", 3)
511
+ p(
512
+ "The CE component drops faster and further than the KD component throughout training. This is "
513
+ "expected: with only 3,000 vocabulary tokens and 4 layers, the Student can quickly memorize the "
514
+ "single correct class for a small, reasonably well-separated training set, whereas matching the "
515
+ "Teacher's full smoothed distribution over 77 classes at T=4 is a strictly harder target. The KD term "
516
+ "keeps supplying a non-trivial gradient signal well after the CE term has largely converged — this is "
517
+ "exactly the regime in which distillation contributes information beyond what hard labels alone would "
518
+ "teach the Student."
519
+ )
520
+
521
+ doc.add_page_break()
522
+
523
+ # ---------------------------------------------------------------------------
524
+ # Module 3
525
+ # ---------------------------------------------------------------------------
526
+ h("5. Module 3: Comparative Analysis and Benchmarking", 1)
527
+
528
+ h("5.1 Task 5 — Accuracy vs. Compression Evaluation", 2)
529
+
530
+ h("Design", 3)
531
+ p(
532
+ "To isolate the effect of distillation itself from the effect of the compact architecture, a second "
533
+ "“baseline” Student is trained: identical architecture, identical tokenizer, identical optimizer "
534
+ "and epoch budget as the distilled Student, but trained with plain cross-entropy against ground-truth "
535
+ "labels only, with no Teacher signal at all. Any accuracy gap between the two Students is then "
536
+ "attributable to distillation alone."
537
+ )
538
+
539
+ h("Implementation", 3)
540
+ p(
541
+ "The baseline Student is trained with the same train_student() routine used for the distilled Student, "
542
+ "but with distill=False, for 8 epochs, batch size 32, learning rate 3e-4, AdamW, on CPU (127.6 seconds "
543
+ "total). All three models — Teacher, baseline Student, distilled Student — are then evaluated on "
544
+ "the same held-out 3,080-example test set using scikit-learn's accuracy_score and f1_score (macro and "
545
+ "weighted)."
546
+ )
547
+ add_image(f"{ASSETS}/baseline_vs_distilled_loss.png", width=5.0,
548
+ caption="Figure 2. Training loss: baseline student (cross-entropy only) vs. distilled student (KD + CE). Note the two loss compositions are not directly comparable in scale.")
549
+
550
+ h("Results — Comparison Table", 3)
551
+ add_table(
552
+ ["Model", "Accuracy", "Macro F1", "Weighted F1"],
553
+ [
554
+ ["Teacher (bert-base-uncased)", "87.56%", "0.868", "0.868"],
555
+ ["Student — without distillation", "83.47%", "0.836", "0.836"],
556
+ ["Student — with distillation", "87.44%", "0.874", "0.874"],
557
+ ],
558
+ col_widths=[3.0, 1.6, 1.4, 1.5],
559
+ )
560
+
561
+ h("Interpretation", 3)
562
+ p(
563
+ "The undistilled Student, trained only on hard labels with a 37.7x smaller architecture, reaches "
564
+ "83.5% accuracy — a substantial (4.1-point) gap below the Teacher's 87.6%, as expected given how "
565
+ "much capacity was removed. Adding the Teacher's soft labels — with the architecture, data, and "
566
+ "epoch budget held fixed, changing only the loss function — raises the Student to 87.4% accuracy, "
567
+ "closing 97% of the accuracy gap between the undistilled Student and the Teacher. In this run, the "
568
+ "distilled Student retains 99.9% of the Teacher's accuracy (and slightly exceeds it on Macro/Weighted "
569
+ "F1) at a fraction of the parameter count. This is the central empirical claim of knowledge "
570
+ "distillation being demonstrated directly: dark knowledge in the Teacher's soft labels lets a small "
571
+ "model recover far more of a large model's decision surface than the same small model could learn "
572
+ "from hard labels alone. It is worth noting the closeness of Teacher and distilled-Student accuracy "
573
+ "also reflects that the Teacher itself is a modestly fine-tuned (3-epoch) model and the test set is a "
574
+ "few thousand examples — a couple of points either way is within normal run-to-run variance, and this "
575
+ "particular run should be read as “distillation closed essentially all of the accuracy gap,” not as "
576
+ "proof the Student's internal representation matches the Teacher's."
577
+ )
578
+
579
+ h("5.2 Task 6 — Deployment Metrics Analysis", 2)
580
+
581
+ h("Design", 3)
582
+ p(
583
+ "Accuracy alone does not determine deployability. Three deployment-relevant metrics are measured for "
584
+ "the Teacher and the distilled Student: on-disk model size, CPU inference latency, and peak process "
585
+ "RAM — the three resource axes that typically gate whether a model fits on an edge or mobile device."
586
+ )
587
+
588
+ h("Implementation", 3)
589
+ bullets([
590
+ ["Disk size: ", True],
591
+ "each model's state_dict is serialized with torch.save to a temporary file and measured with os.path.getsize.",
592
+ ])
593
+ bullets([
594
+ ["CPU latency: ", True],
595
+ "both models are moved to CPU; after a short warm-up, single-example (batch size 1) forward passes are timed with time.perf_counter over 50 runs, reporting mean ± standard deviation in milliseconds per query.",
596
+ ])
597
+ bullets([
598
+ ["Peak RAM: ", True],
599
+ "measured per model in an isolated subprocess (via resource.getrusage(RUSAGE_SELF).ru_maxrss) rather than in the shared notebook kernel. This is a deliberate methodological choice: peak RSS is monotonically non-decreasing for the life of a process, so if both models were loaded into the same long-lived kernel, the Teacher's much larger footprint would contaminate any “peak RAM” reading taken afterward for the Student. Running each model's load-and-infer cycle in its own fresh subprocess gives a fair, isolated reading for each.",
600
+ ])
601
+
602
+ h("Results — Deployment Metrics", 3)
603
+ add_table(
604
+ ["Metric", "Teacher", "Student", "Reduction"],
605
+ [
606
+ ["Disk size (MB)", "417.9", "11.1", "37.7x"],
607
+ ["CPU latency (ms/query)", "27.76 ± 3.07", "1.18 ± 0.09", "23.5x"],
608
+ ["Peak RAM (MB, isolated process)", "893.8", "237.0", "3.8x"],
609
+ ],
610
+ col_widths=[3.0, 1.7, 1.7, 1.3],
611
+ )
612
+
613
+ h("Interpretation — Deployment Readiness", 3)
614
+ p(
615
+ "The distilled Student is 37.7x smaller on disk, 23.5x faster per CPU query, and uses 3.8x less peak "
616
+ "RAM than the Teacher, while retaining 99.9% of its accuracy on the same 77-way classification task. "
617
+ "In this run there is essentially no accuracy trade-off to weigh against those savings — which is a "
618
+ "favourable outcome rather than a guarantee, since it partly reflects a lightly fine-tuned Teacher and "
619
+ "a modest-size test set; a production rollout should still monitor accuracy on live traffic rather "
620
+ "than assuming this margin holds indefinitely as the input distribution drifts."
621
+ )
622
+ bullets([
623
+ ["Size and RAM. ", True],
624
+ "At ~11MB on disk and ~237MB of peak RAM, the Student comfortably fits within the memory budgets of edge devices and mobile apps, where a 418MB+ BERT-base checkpoint is frequently a non-starter (app-store bundle-size limits, low-RAM Android devices, on-device model caches).",
625
+ ])
626
+ bullets([
627
+ ["Latency. ", True],
628
+ "1.2ms/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 27.8ms/query, multiplied across a request queue on a resource-constrained device, would noticeably degrade perceived responsiveness.",
629
+ ])
630
+ bullets([
631
+ ["Practical recommendation. ", True],
632
+ "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 demonstrated size/latency/RAM benefits while bounding accuracy risk to only the genuinely ambiguous cases — exactly the scenario dark-knowledge distillation is suited for, since the Student was trained to mimic the Teacher's confidence structure, not just its arg-max.",
633
+ ])
634
+ bullets([
635
+ ["When the Student alone would not suffice. ", True],
636
+ "For a fully autonomous decision with no fallback path (e.g. auto-approving a refund), any residual gap to the Teacher — even a small one — may still argue for keeping the Teacher, or a human, in the loop.",
637
+ ])
638
+
639
+ doc.add_page_break()
640
+
641
+ # ---------------------------------------------------------------------------
642
+ # 6. Conclusion
643
+ # ---------------------------------------------------------------------------
644
+ h("6. Conclusion and Key Takeaways", 1)
645
+ bullets([
646
+ ["Dark knowledge transfers real signal. ", True],
647
+ "Distillation closed roughly 97% of the accuracy gap between an undistilled and a distilled Student sharing the same 37.7x-smaller architecture, using only a change of loss function — no additional data, parameters, or training time.",
648
+ ])
649
+ bullets([
650
+ ["Vocabulary size is a first-order compression lever. ", True],
651
+ "A domain-trained, 10x-smaller Student tokenizer removed roughly a quarter of the Student's total parameter budget on its own, independent of encoder depth or width.",
652
+ ])
653
+ bullets([
654
+ ["Sequence-classification distillation avoids the hardest alignment problem. ", True],
655
+ "Because the Teacher produces one probability vector per example rather than per token, Teacher/Student tokenizer mismatch only requires row-level index alignment, not token-level alignment — a substantially simpler engineering problem than seq2seq or token-classification distillation would pose.",
656
+ ])
657
+ bullets([
658
+ ["The compression/latency/RAM payoff is large and the accuracy cost, in this run, is negligible. ", True],
659
+ "37.7x smaller on disk, 23.5x faster on CPU, 3.8x less peak RAM, for 99.9% of the Teacher's test accuracy — making the distilled Student a strong candidate for edge or mobile deployment, ideally paired with a confidence-based fallback to the Teacher for the hardest cases.",
660
+ ])
661
+
662
+ # ---------------------------------------------------------------------------
663
+ # 7. Environment & Reproducibility
664
+ # ---------------------------------------------------------------------------
665
+ h("7. Environment and Reproducibility", 1)
666
+ add_table(
667
+ ["Item", "Value"],
668
+ [
669
+ ["Conda environment", "agn_env"],
670
+ ["Python version", "3.12.8"],
671
+ ["Key libraries", "torch, transformers, datasets, tokenizers, scikit-learn, psutil, accelerate, evaluate"],
672
+ ["Hardware", "Apple Silicon (M-series), MPS acceleration for Teacher fine-tuning"],
673
+ ["Teacher training device", "MPS"],
674
+ ["Student training/inference device", "CPU (by design, matching the deployment target)"],
675
+ ["Random seed", "42 (Python, NumPy, PyTorch)"],
676
+ ["Source artifact", "knowledge_distillation_assignment.ipynb (single, end-to-end executed notebook)"],
677
+ ],
678
+ col_widths=[2.4, 3.9],
679
+ )
680
+ p(
681
+ "The notebook can be re-executed top-to-bottom via jupyter nbconvert --to notebook --execute --inplace "
682
+ "knowledge_distillation_assignment.ipynb inside the agn_env environment. Minor variation (typically "
683
+ "within 1–2 accuracy points) between runs is expected due to non-deterministic operations in "
684
+ "MPS-accelerated training and dataloader shuffling order."
685
+ )
686
+
687
+ doc.save("/Users/reevechaitanya/Documents/2_Experimentation_n_Research/demo/Knowledge_Distillation_Report.docx")
688
+ print("Report written.")
demo/knowledge_distillation_assignment.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
demo/nbconvert_run.log ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ [NbConvertApp] Converting notebook knowledge_distillation_assignment.ipynb to notebook
2
+ [IPKernelApp] WARNING | Kernel is running over TCP without encryption. All communication (including code and outputs) is sent in plain text and is susceptible to eavesdropping. Use IPC transport or launch with kernel manager-provisioned CurveZMQ keys to enable transport encryption.
3
+
4
+
5
+
6
+ [NbConvertApp] Writing 206530 bytes to knowledge_distillation_assignment.ipynb
demo/report_assets/baseline_vs_distilled_loss.png ADDED

Git LFS Details

  • SHA256: a03a49b52e2e584ba7b04bdb83ebb40dea311e4a8b7cd46cec13e0cc452508f3
  • Pointer size: 130 Bytes
  • Size of remote file: 29.5 kB
demo/report_assets/distill_loss_curves.png ADDED

Git LFS Details

  • SHA256: a227b67248bd14a84ce6d5b4f187d0744daa36f19777206cb91aca1c7cc2b3ae
  • Pointer size: 130 Bytes
  • Size of remote file: 40.3 kB