File size: 34,697 Bytes
3877cdc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
"""Builds Knowledge_Distillation_Report.docx summarizing design, implementation, and evaluation."""
import datetime
from docx import Document
from docx.shared import Pt, Inches, RGBColor, Cm
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.oxml.ns import qn
from docx.oxml import OxmlElement

ASSETS = "/Users/reevechaitanya/Documents/2_Experimentation_n_Research/demo/report_assets"

ACCENT = RGBColor(0x1F, 0x4E, 0x79)
GREY = RGBColor(0x40, 0x40, 0x40)

doc = Document()

# ---------------------------------------------------------------------------
# Global style setup
# ---------------------------------------------------------------------------
normal = doc.styles["Normal"]
normal.font.name = "Calibri"
normal.font.size = Pt(11)
normal.paragraph_format.space_after = Pt(8)
normal.paragraph_format.line_spacing = 1.15

for i in range(1, 4):
    h = doc.styles[f"Heading {i}"]
    h.font.name = "Calibri"
    h.font.color.rgb = ACCENT
    h.font.bold = True
h1, h2, h3 = doc.styles["Heading 1"], doc.styles["Heading 2"], doc.styles["Heading 3"]
h1.font.size, h2.font.size, h3.font.size = Pt(20), Pt(15), Pt(12.5)
h1.paragraph_format.space_before, h2.paragraph_format.space_before, h3.paragraph_format.space_before = Pt(20), Pt(14), Pt(10)

for sec in doc.sections:
    sec.left_margin = Cm(2.2)
    sec.right_margin = Cm(2.2)
    sec.top_margin = Cm(1.8)
    sec.bottom_margin = Cm(1.8)


def add_page_number_footer(section):
    footer = section.footer
    p = footer.paragraphs[0]
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run = p.add_run()
    fld = OxmlElement("w:fldSimple")
    fld.set(qn("w:instr"), "PAGE")
    run._r.append(fld)


add_page_number_footer(doc.sections[0])


def h(text, level=1):
    doc.add_heading(text, level=level)


def p(text="", bold=False, italic=False, size=None, color=None, align=None, space_after=None):
    para = doc.add_paragraph()
    if align is not None:
        para.alignment = align
    if space_after is not None:
        para.paragraph_format.space_after = Pt(space_after)
    run = para.add_run(text)
    run.bold = bold
    run.italic = italic
    if size:
        run.font.size = Pt(size)
    if color:
        run.font.color.rgb = color
    return para


def rich(para, segments):
    """segments: list of (text, bold, italic) tuples appended to an existing paragraph."""
    for seg in segments:
        text = seg[0]
        bold = seg[1] if len(seg) > 1 else False
        italic = seg[2] if len(seg) > 2 else False
        run = para.add_run(text)
        run.bold = bold
        run.italic = italic
    return para


def bullets(items):
    # Special case used throughout this script: bullets([["Bold label", True], "plain description"])
    # is ONE bullet with a bold lead-in run followed by a normal-weight continuation run.
    if (len(items) == 2 and isinstance(items[0], (list, tuple)) and len(items[0]) == 2
            and isinstance(items[0][1], bool) and isinstance(items[1], str)):
        para = doc.add_paragraph(style="List Bullet")
        label, bold = items[0]
        lead_run = para.add_run(label)
        lead_run.bold = bold
        para.add_run(items[1])
        return
    for item in items:
        para = doc.add_paragraph(style="List Bullet")
        if isinstance(item, str):
            para.add_run(item)
        else:
            rich(para, item)


def formula_block(text):
    para = doc.add_paragraph()
    para.alignment = WD_ALIGN_PARAGRAPH.CENTER
    para.paragraph_format.space_before = Pt(6)
    para.paragraph_format.space_after = Pt(6)
    run = para.add_run(text)
    run.italic = True
    run.font.size = Pt(12)
    run.font.name = "Cambria Math"
    return para


def set_cell_shading(cell, hex_color):
    tc_pr = cell._tc.get_or_add_tcPr()
    shd = OxmlElement("w:shd")
    shd.set(qn("w:val"), "clear")
    shd.set(qn("w:fill"), hex_color)
    tc_pr.append(shd)


def add_table(headers, rows, col_widths=None, header_color="1F4E79"):
    table = doc.add_table(rows=1, cols=len(headers))
    table.style = "Table Grid"
    table.alignment = WD_TABLE_ALIGNMENT.CENTER
    hdr_cells = table.rows[0].cells
    for i, htext in enumerate(headers):
        hdr_cells[i].text = ""
        run = hdr_cells[i].paragraphs[0].add_run(htext)
        run.bold = True
        run.font.color.rgb = RGBColor(0xFF, 0xFF, 0xFF)
        run.font.size = Pt(10.5)
        set_cell_shading(hdr_cells[i], header_color)
        hdr_cells[i].paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
    for row in rows:
        cells = table.add_row().cells
        for i, val in enumerate(row):
            cells[i].text = ""
            run = cells[i].paragraphs[0].add_run(str(val))
            run.font.size = Pt(10.5)
            cells[i].paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER if i > 0 else WD_ALIGN_PARAGRAPH.LEFT
    if col_widths:
        for i, w in enumerate(col_widths):
            for row in table.rows:
                row.cells[i].width = Inches(w)
    doc.add_paragraph()
    return table


def add_image(path, width=5.8, caption=None):
    doc.add_picture(path, width=Inches(width))
    last_paragraph = doc.paragraphs[-1]
    last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
    if caption:
        cap = doc.add_paragraph()
        cap.alignment = WD_ALIGN_PARAGRAPH.CENTER
        run = cap.add_run(caption)
        run.italic = True
        run.font.size = Pt(9.5)
        run.font.color.rgb = GREY


# ---------------------------------------------------------------------------
# Title page
# ---------------------------------------------------------------------------
title_p = doc.add_paragraph()
title_p.alignment = WD_ALIGN_PARAGRAPH.CENTER
title_p.paragraph_format.space_before = Pt(120)
run = title_p.add_run("Knowledge Distillation on the Banking77 Intent Dataset")
run.bold = True
run.font.size = Pt(26)
run.font.color.rgb = ACCENT

sub_p = doc.add_paragraph()
sub_p.alignment = WD_ALIGN_PARAGRAPH.CENTER
sub_p.paragraph_format.space_before = Pt(10)
run = sub_p.add_run("Design, Implementation, and Evaluation Report")
run.font.size = Pt(16)
run.font.color.rgb = GREY

sub2 = doc.add_paragraph()
sub2.alignment = WD_ALIGN_PARAGRAPH.CENTER
sub2.paragraph_format.space_before = Pt(4)
run = sub2.add_run("Compressing a Fine-Tuned BERT Teacher into a Compact CPU-Deployable Transformer Student")
run.font.size = Pt(12)
run.italic = True
run.font.color.rgb = GREY

meta_p = doc.add_paragraph()
meta_p.alignment = WD_ALIGN_PARAGRAPH.CENTER
meta_p.paragraph_format.space_before = Pt(60)
meta_lines = [
    f"Generated: {datetime.date.today().strftime('%B %d, %Y')}",
    "Source notebook: knowledge_distillation_assignment.ipynb",
    "Dataset: PolyAI/banking77 (77-class banking intent classification)",
    "Environment: conda env agn_env, Python 3.12, Apple Silicon (MPS + CPU)",
]
for i, line in enumerate(meta_lines):
    if i > 0:
        meta_p.add_run("\n")
    r = meta_p.add_run(line)
    r.font.size = Pt(11)
    r.font.color.rgb = GREY

doc.add_page_break()

# ---------------------------------------------------------------------------
# 1. Introduction
# ---------------------------------------------------------------------------
h("1. Introduction and Objective", 1)
p(
    "Large fine-tuned Transformers such as BERT deliver strong accuracy on text classification tasks but "
    "are frequently too large, too slow, and too memory-hungry to deploy on edge devices, mobile "
    "applications, or latency-sensitive services. Knowledge distillation addresses this by transferring "
    "the behaviour of a large “Teacher” model into a much smaller “Student” model, using the "
    "Teacher's full output probability distribution — not just its predicted class — as a richer training "
    "signal."
)
p(
    "This report documents the design, implementation, and evaluation of an end-to-end knowledge "
    "distillation pipeline built for the 77-class Banking77 intent-classification dataset, structured "
    "around three modules and six tasks:"
)
add_table(
    ["Module", "Tasks"],
    [
        ["1. Teacher Labeling & Student Setup", "Task 1: Teacher fine-tuning & soft-label generation\nTask 2: Student tokenizer alignment"],
        ["2. Distillation Architecture & Training", "Task 3: Compact student transformer\nTask 4: Distillation loss function & training"],
        ["3. Comparative Analysis & Benchmarking", "Task 5: Accuracy vs. compression evaluation\nTask 6: Deployment metrics analysis"],
    ],
    col_widths=[2.6, 3.7],
)
p(
    "All code was implemented and executed end-to-end in a single Jupyter notebook "
    "(knowledge_distillation_assignment.ipynb) inside the conda environment agn_env (Python 3.12) on an "
    "Apple Silicon machine. The Teacher was fine-tuned using MPS acceleration; the Student was deliberately "
    "trained and benchmarked entirely on CPU, since CPU-only inference is the target deployment profile "
    "this exercise is optimizing for."
)

# ---------------------------------------------------------------------------
# 2. Dataset
# ---------------------------------------------------------------------------
h("2. Dataset", 1)
p(
    "Banking77 is a fine-grained intent-classification dataset of customer-support utterances for a "
    "banking app, labelled with one of 77 narrow, often semantically overlapping intents (e.g. "
    "card_arrival vs. card_delivery_estimate, declined_card_payment vs. declined_cash_withdrawal). This "
    "makes it a good stress test for distillation: the fine granularity of the label space means the "
    "relative similarity between classes — the information that soft labels carry and hard labels do "
    "not — is directly relevant to classification accuracy."
)
add_table(
    ["Property", "Value"],
    [
        ["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)"],
        ["Training examples", "10,003"],
        ["Test examples", "3,080"],
        ["Number of classes", "77"],
        ["Example text", "“I am still waiting on my card?” → label: card_arrival"],
    ],
    col_widths=[2.0, 4.3],
)

doc.add_page_break()

# ---------------------------------------------------------------------------
# Module 1
# ---------------------------------------------------------------------------
h("3. Module 1: Teacher Labeling and Student Setup", 1)

h("3.1 Task 1 — Teacher Integration and Soft-Label Generation", 2)

h("Design", 3)
p(
    "bert-base-uncased (110M parameters) was selected as the Teacher for its strong general-purpose "
    "language representations and its established track record on intent-classification benchmarks. "
    "The design goal was twofold: (1) fine-tune it into a strong classifier for banking77, and (2) cache "
    "its full 77-way probability distribution — not just its hard prediction — for every training "
    "example, so that the Student never needs the (comparatively expensive) Teacher to run again during "
    "its own training."
)

h("Implementation", 3)
bullets([
    "Tokenization: bert-base-uncased's own WordPiece tokenizer, sequences truncated to 64 tokens.",
    "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.",
    "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.",
    "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.",
])

h("Results", 3)
add_table(
    ["Metric (test set)", "Value"],
    [
        ["Evaluation loss", "0.839"],
        ["Accuracy", "87.6%"],
        ["Macro F1", "0.868"],
        ["Total parameters", "109,541,453"],
        ["Cached train logits shape", "[10,003, 77]"],
        ["Cached test logits shape", "[3,080, 77]"],
    ],
    col_widths=[3.0, 3.0],
)

h("Interpretation — Why Soft Labels Carry “Dark Knowledge”", 3)
p(
    "A one-hot hard label for “I am still waiting on my card?” states only that the correct class is "
    "card_arrival and that all 76 other classes are equally, absolutely wrong. That is not what the "
    "Teacher actually believes: its softmax distribution might place 62% probability on card_arrival, "
    "21% on the closely related card_delivery_estimate, and small residual mass on a handful of other "
    "intents. Training against the full distribution rather than the arg-max alone:"
)
bullets([
    ["Transfers inter-class similarity structure. ", True],
    "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.",
])
bullets([
    ["Acts as an implicit regularizer. ", True],
    "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.",
])
bullets([
    ["Supplies more effective supervision per example. ", True],
    "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.",
])
bullets([
    ["Is amplified by temperature scaling. ", True],
    "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.",
])

h("3.2 Task 2 — Student Tokenizer Alignment", 2)

h("Design", 3)
p(
    "Rather than reusing the Teacher's ~30k-token BERT vocabulary, the Student is given its own compact "
    "WordPiece tokenizer trained from scratch, directly on the banking77 training corpus. This keeps the "
    "Student's vocabulary small (a major lever on parameter count, since embedding-table size scales with "
    "vocab_size × hidden_size) while concentrating that small vocabulary on the words that actually appear "
    "in this domain."
)

h("Implementation", 3)
bullets([
    "Backend: tokenizers.Tokenizer with a WordPiece model, BERT-style lowercasing normalizer, whitespace pre-tokenizer, and [CLS]/[SEP] template post-processing.",
    "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.",
    "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.",
])

h("Results — Tokenizer Comparison", 3)
add_table(
    ["Property", "Teacher (BERT)", "Student (custom WordPiece)"],
    [
        ["Vocabulary size", "30,522", "3,000"],
        ["Vocabulary compression", "—", "10.2x smaller"],
    ],
    col_widths=[2.4, 2.0, 2.4],
)
p("Side-by-side tokenization of five sample utterances:", bold=False)
add_table(
    ["Utterance (truncated)", "Teacher tokens", "Student tokens (incl. [CLS]/[SEP])"],
    [
        ["I am still waiting on my card?", "8", "10"],
        ["What can I do if my card still hasn't arrived...", "16", "18"],
        ["I have been waiting over a week. Is the card...", "14", "16"],
        ["Can I track my card while it is in the process...", "14", "16"],
        ["How do I know if I will get my card, or if it...", "17", "19"],
    ],
    col_widths=[3.6, 1.4, 1.9],
)

h("Interpretation — Handling the Vocabulary Mismatch", 3)
p(
    "On these five common, in-domain examples, the Student's token count is exactly the Teacher's count "
    "plus two — the [CLS]/[SEP] markers the Student's tokens include and the Teacher's tokenize() call "
    "does not. In other words, for frequent, in-vocabulary phrasing the domain-trained 3,000-token "
    "vocabulary segments text about as coarsely as BERT's 30,522-token vocabulary; the cost of a much "
    "smaller vocabulary shows up on rarer or compound words not well represented in the 10,003-example "
    "training corpus, via more aggressive subword splitting and a higher effective [UNK] rate, rather "
    "than on everyday vocabulary."
)
p(
    "A more fundamental question this task addresses is how to align Teacher and Student when they "
    "tokenize the same text differently. A naive token-level distillation scheme — as used in "
    "sequence-to-sequence or token-classification distillation — requires the Teacher's and Student's "
    "output sequences to line up position by position, which breaks immediately once the two tokenizers "
    "produce different token counts for the same input. That problem does not apply here, because "
    "distillation in this project is over sequence classification: the Teacher emits exactly one 77-way "
    "probability vector per example, regardless of how many tokens that example was split into "
    "internally. The only alignment that matters is therefore at the example level, not the token level:"
)
bullets([
    ["Strategy used: ", True],
    "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.",
])
bullets([
    ["Residual risk and mitigation: ", True],
    "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.",
])

doc.add_page_break()

# ---------------------------------------------------------------------------
# Module 2
# ---------------------------------------------------------------------------
h("4. Module 2: Distillation Architecture and Training", 1)

h("4.1 Task 3 — Compact Student Transformer Construction", 2)

h("Design", 3)
p(
    "The Student is a small, hand-built encoder-only Transformer — assembled directly from PyTorch "
    "nn.Module / nn.TransformerEncoderLayer primitives rather than reusing a pretrained architecture — "
    "sized deliberately small enough to train and run comfortably on CPU."
)
add_table(
    ["Architecture parameter", "Value"],
    [
        ["Vocabulary size", "3,000 (Task 2 tokenizer)"],
        ["Hidden size", "256"],
        ["Encoder layers", "4"],
        ["Attention heads", "4"],
        ["Feed-forward size", "512"],
        ["Max sequence length", "32"],
        ["Dropout", "0.1"],
        ["Pooling", "Mean-pooling over non-padding token positions"],
        ["Output head", "Linear layer to 77 classes"],
    ],
    col_widths=[2.6, 3.7],
)

h("Implementation", 3)
p(
    "Forward pass: token embeddings and learned positional embeddings are summed, passed through 4 "
    "stacked TransformerEncoderLayers with a padding mask (src_key_padding_mask) derived from the "
    "attention mask so padded positions are ignored by self-attention, mean-pooled over valid (non-pad) "
    "token positions, and projected through a linear classifier to 77 logits."
)

h("Results — Parameter Breakdown", 3)
add_table(
    ["Component", "Parameters"],
    [
        ["Token + position embeddings", "776,192"],
        ["Transformer encoder (4 layers)", "2,108,416"],
        ["Classification head", "19,789"],
        ["Student total", "2,904,397"],
        ["Teacher total (bert-base-uncased)", "109,541,453"],
        ["Compression ratio", "37.7x fewer parameters"],
    ],
    col_widths=[3.4, 2.9],
)

h("Interpretation", 3)
p(
    "The Student uses 37.7x fewer parameters than the Teacher. Roughly 27% of that budget sits in the "
    "embedding table alone — the direct payoff of Task 2's small, domain-specific vocabulary (3,000 vs. "
    "BERT's 30,522 tokens). Because a Transformer's parameter count for short-sequence classification "
    "scales with vocab_size × hidden_size, shrinking the vocabulary is one of the single highest-leverage "
    "compression decisions available, independent of how many encoder layers are ultimately kept."
)

h("4.2 Task 4 — Distillation Loss Function", 2)

h("Design", 3)
p("The Student is trained with a combined objective:")
formula_block(
    "Loss = α · T² · KL(Pᵨtudent, Pᵀeacher at temperature T)  +  (1 − α) · CE(yᵨtudent, yᵀrue)"
)
p(
    "with temperature T = 4.0 and weighting α = 0.7. The KL term is computed between the Student's and "
    "Teacher's softmax distributions after both are divided by T (which softens both distributions and "
    "amplifies the small, informative probabilities on non-target classes); the T² multiplier (Hinton et "
    "al., 2015) compensates for the fact that raising T shrinks the magnitude of the gradients coming from "
    "the soft-label term by roughly 1/T² relative to the hard-label term, so without it the KD loss would "
    "be under-weighted once a large T is introduced. The CE term is ordinary cross-entropy against the "
    "true ground-truth label, ensuring the Student never loses sight of the actual classification "
    "objective even while learning to mimic the Teacher's distribution."
)

h("Implementation", 3)
bullets([
    "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.",
    "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).",
    "Training loop: AdamW optimizer, learning rate 3e-4, batch size 32, 8 epochs, executed entirely on CPU.",
])

h("Results", 3)
add_table(
    ["Epoch", "Total loss", "KD component", "CE component"],
    [
        ["1", "1.142", "0.556", "2.508"],
        ["2", "0.559", "0.306", "1.150"],
        ["3", "0.387", "0.217", "0.786"],
        ["4", "0.301", "0.174", "0.598"],
        ["5", "0.248", "0.148", "0.482"],
        ["6", "0.211", "0.132", "0.396"],
        ["7", "0.184", "0.118", "0.337"],
        ["8", "0.166", "0.110", "0.297"],
    ],
    col_widths=[1.0, 1.8, 1.9, 1.9],
)
p(f"Total distilled-student training time: 130.8 seconds on CPU (8 epochs, 10,003 examples).")
add_image(f"{ASSETS}/distill_loss_curves.png", width=6.2,
           caption="Figure 1. Distilled student training: total loss (left) and its KD vs. CE components (right) across 8 epochs.")

h("Interpretation", 3)
p(
    "The CE component drops faster and further than the KD component throughout training. This is "
    "expected: with only 3,000 vocabulary tokens and 4 layers, the Student can quickly memorize the "
    "single correct class for a small, reasonably well-separated training set, whereas matching the "
    "Teacher's full smoothed distribution over 77 classes at T=4 is a strictly harder target. The KD term "
    "keeps supplying a non-trivial gradient signal well after the CE term has largely converged — this is "
    "exactly the regime in which distillation contributes information beyond what hard labels alone would "
    "teach the Student."
)

doc.add_page_break()

# ---------------------------------------------------------------------------
# Module 3
# ---------------------------------------------------------------------------
h("5. Module 3: Comparative Analysis and Benchmarking", 1)

h("5.1 Task 5 — Accuracy vs. Compression Evaluation", 2)

h("Design", 3)
p(
    "To isolate the effect of distillation itself from the effect of the compact architecture, a second "
    "“baseline” Student is trained: identical architecture, identical tokenizer, identical optimizer "
    "and epoch budget as the distilled Student, but trained with plain cross-entropy against ground-truth "
    "labels only, with no Teacher signal at all. Any accuracy gap between the two Students is then "
    "attributable to distillation alone."
)

h("Implementation", 3)
p(
    "The baseline Student is trained with the same train_student() routine used for the distilled Student, "
    "but with distill=False, for 8 epochs, batch size 32, learning rate 3e-4, AdamW, on CPU (127.6 seconds "
    "total). All three models — Teacher, baseline Student, distilled Student — are then evaluated on "
    "the same held-out 3,080-example test set using scikit-learn's accuracy_score and f1_score (macro and "
    "weighted)."
)
add_image(f"{ASSETS}/baseline_vs_distilled_loss.png", width=5.0,
           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.")

h("Results — Comparison Table", 3)
add_table(
    ["Model", "Accuracy", "Macro F1", "Weighted F1"],
    [
        ["Teacher (bert-base-uncased)", "87.56%", "0.868", "0.868"],
        ["Student — without distillation", "83.47%", "0.836", "0.836"],
        ["Student — with distillation", "87.44%", "0.874", "0.874"],
    ],
    col_widths=[3.0, 1.6, 1.4, 1.5],
)

h("Interpretation", 3)
p(
    "The undistilled Student, trained only on hard labels with a 37.7x smaller architecture, reaches "
    "83.5% accuracy — a substantial (4.1-point) gap below the Teacher's 87.6%, as expected given how "
    "much capacity was removed. Adding the Teacher's soft labels — with the architecture, data, and "
    "epoch budget held fixed, changing only the loss function — raises the Student to 87.4% accuracy, "
    "closing 97% of the accuracy gap between the undistilled Student and the Teacher. In this run, the "
    "distilled Student retains 99.9% of the Teacher's accuracy (and slightly exceeds it on Macro/Weighted "
    "F1) at a fraction of the parameter count. This is the central empirical claim of knowledge "
    "distillation being demonstrated directly: dark knowledge in the Teacher's soft labels lets a small "
    "model recover far more of a large model's decision surface than the same small model could learn "
    "from hard labels alone. It is worth noting the closeness of Teacher and distilled-Student accuracy "
    "also reflects that the Teacher itself is a modestly fine-tuned (3-epoch) model and the test set is a "
    "few thousand examples — a couple of points either way is within normal run-to-run variance, and this "
    "particular run should be read as “distillation closed essentially all of the accuracy gap,” not as "
    "proof the Student's internal representation matches the Teacher's."
)

h("5.2 Task 6 — Deployment Metrics Analysis", 2)

h("Design", 3)
p(
    "Accuracy alone does not determine deployability. Three deployment-relevant metrics are measured for "
    "the Teacher and the distilled Student: on-disk model size, CPU inference latency, and peak process "
    "RAM — the three resource axes that typically gate whether a model fits on an edge or mobile device."
)

h("Implementation", 3)
bullets([
    ["Disk size: ", True],
    "each model's state_dict is serialized with torch.save to a temporary file and measured with os.path.getsize.",
])
bullets([
    ["CPU latency: ", True],
    "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.",
])
bullets([
    ["Peak RAM: ", True],
    "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.",
])

h("Results — Deployment Metrics", 3)
add_table(
    ["Metric", "Teacher", "Student", "Reduction"],
    [
        ["Disk size (MB)", "417.9", "11.1", "37.7x"],
        ["CPU latency (ms/query)", "27.76 ± 3.07", "1.18 ± 0.09", "23.5x"],
        ["Peak RAM (MB, isolated process)", "893.8", "237.0", "3.8x"],
    ],
    col_widths=[3.0, 1.7, 1.7, 1.3],
)

h("Interpretation — Deployment Readiness", 3)
p(
    "The distilled Student is 37.7x smaller on disk, 23.5x faster per CPU query, and uses 3.8x less peak "
    "RAM than the Teacher, while retaining 99.9% of its accuracy on the same 77-way classification task. "
    "In this run there is essentially no accuracy trade-off to weigh against those savings — which is a "
    "favourable outcome rather than a guarantee, since it partly reflects a lightly fine-tuned Teacher and "
    "a modest-size test set; a production rollout should still monitor accuracy on live traffic rather "
    "than assuming this margin holds indefinitely as the input distribution drifts."
)
bullets([
    ["Size and RAM. ", True],
    "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).",
])
bullets([
    ["Latency. ", True],
    "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.",
])
bullets([
    ["Practical recommendation. ", True],
    "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.",
])
bullets([
    ["When the Student alone would not suffice. ", True],
    "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.",
])

doc.add_page_break()

# ---------------------------------------------------------------------------
# 6. Conclusion
# ---------------------------------------------------------------------------
h("6. Conclusion and Key Takeaways", 1)
bullets([
    ["Dark knowledge transfers real signal. ", True],
    "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.",
])
bullets([
    ["Vocabulary size is a first-order compression lever. ", True],
    "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.",
])
bullets([
    ["Sequence-classification distillation avoids the hardest alignment problem. ", True],
    "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.",
])
bullets([
    ["The compression/latency/RAM payoff is large and the accuracy cost, in this run, is negligible. ", True],
    "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.",
])

# ---------------------------------------------------------------------------
# 7. Environment & Reproducibility
# ---------------------------------------------------------------------------
h("7. Environment and Reproducibility", 1)
add_table(
    ["Item", "Value"],
    [
        ["Conda environment", "agn_env"],
        ["Python version", "3.12.8"],
        ["Key libraries", "torch, transformers, datasets, tokenizers, scikit-learn, psutil, accelerate, evaluate"],
        ["Hardware", "Apple Silicon (M-series), MPS acceleration for Teacher fine-tuning"],
        ["Teacher training device", "MPS"],
        ["Student training/inference device", "CPU (by design, matching the deployment target)"],
        ["Random seed", "42 (Python, NumPy, PyTorch)"],
        ["Source artifact", "knowledge_distillation_assignment.ipynb (single, end-to-end executed notebook)"],
    ],
    col_widths=[2.4, 3.9],
)
p(
    "The notebook can be re-executed top-to-bottom via jupyter nbconvert --to notebook --execute --inplace "
    "knowledge_distillation_assignment.ipynb inside the agn_env environment. Minor variation (typically "
    "within 1–2 accuracy points) between runs is expected due to non-deterministic operations in "
    "MPS-accelerated training and dataloader shuffling order."
)

doc.save("/Users/reevechaitanya/Documents/2_Experimentation_n_Research/demo/Knowledge_Distillation_Report.docx")
print("Report written.")