| """Builds Knowledge_Distillation_Report_Group85.pdf via ReportLab (weasyprint unavailable: missing |
| native Pango/GObject libs on this system). Produces a cover page, bookmarked TOC, styled section |
| headings, tables, formula callouts, and the two loss-curve figures extracted from the executed notebook. |
| """ |
| import os |
| from reportlab.lib.pagesizes import A4 |
| from reportlab.lib.units import cm, inch |
| from reportlab.lib import colors |
| from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle |
| from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_JUSTIFY |
| from reportlab.platypus import ( |
| BaseDocTemplate, PageTemplate, Frame, Paragraph, Spacer, Table, TableStyle, |
| Image, PageBreak, NextPageTemplate, FrameBreak, KeepTogether, ListFlowable, ListItem, |
| ) |
| from reportlab.platypus.tableofcontents import TableOfContents |
| from reportlab.pdfgen import canvas as canvas_mod |
| from PIL import Image as PILImage |
|
|
| ASSETS = "/Users/reevechaitanya/Documents/2_Experimentation_n_Research/demo/report_assets" |
| OUT_PATH = "/Users/reevechaitanya/Documents/2_Experimentation_n_Research/demo/Knowledge_Distillation_Report_Group85.pdf" |
|
|
| PAGE_W, PAGE_H = A4 |
| MARGIN = 2.0 * cm |
| CONTENT_W = PAGE_W - 2 * MARGIN |
|
|
| ACCENT = colors.HexColor("#1F4E79") |
| ACCENT_LIGHT = colors.HexColor("#DCE6F1") |
| GREY = colors.HexColor("#404040") |
| LIGHT_GREY = colors.HexColor("#F2F2F2") |
| BORDER_GREY = colors.HexColor("#9AA7B0") |
| GOOD_GREEN = colors.HexColor("#2E7D32") |
|
|
| |
| |
| |
| base = getSampleStyleSheet() |
|
|
| styles = {} |
| styles["CoverTitle"] = ParagraphStyle("CoverTitle", parent=base["Title"], fontName="Helvetica-Bold", |
| fontSize=25, leading=30, textColor=ACCENT, alignment=TA_CENTER, |
| spaceAfter=6) |
| styles["CoverSub"] = ParagraphStyle("CoverSub", parent=base["Normal"], fontName="Helvetica", |
| fontSize=13, leading=18, textColor=GREY, alignment=TA_CENTER, |
| spaceAfter=4) |
| styles["CoverMeta"] = ParagraphStyle("CoverMeta", parent=base["Normal"], fontName="Helvetica", |
| fontSize=11, leading=16, textColor=GREY, alignment=TA_CENTER) |
| styles["CoverLabel"] = ParagraphStyle("CoverLabel", parent=base["Normal"], fontName="Helvetica-Bold", |
| fontSize=11, leading=15, textColor=ACCENT, alignment=TA_LEFT) |
| styles["CoverValue"] = ParagraphStyle("CoverValue", parent=base["Normal"], fontName="Helvetica", |
| fontSize=11, leading=15, textColor=GREY, alignment=TA_LEFT) |
|
|
| styles["H1"] = ParagraphStyle("H1", parent=base["Heading1"], fontName="Helvetica-Bold", fontSize=17, |
| leading=21, textColor=colors.white, spaceBefore=0, spaceAfter=0, |
| backColor=ACCENT, borderPadding=(6, 8, 6, 8), alignment=TA_LEFT) |
| styles["H2"] = ParagraphStyle("H2", parent=base["Heading2"], fontName="Helvetica-Bold", fontSize=13.5, |
| leading=17, textColor=ACCENT, spaceBefore=14, spaceAfter=6, |
| borderColor=ACCENT, borderWidth=0, alignment=TA_LEFT) |
| styles["H3"] = ParagraphStyle("H3", parent=base["Heading3"], fontName="Helvetica-Bold", fontSize=11.5, |
| leading=15, textColor=colors.HexColor("#B35A00"), spaceBefore=10, |
| spaceAfter=4, alignment=TA_LEFT) |
| styles["Body"] = ParagraphStyle("Body", parent=base["Normal"], fontName="Helvetica", fontSize=10, |
| leading=14.5, textColor=colors.black, alignment=TA_JUSTIFY, |
| spaceAfter=7) |
| styles["Bullet"] = ParagraphStyle("Bullet", parent=styles["Body"], leftIndent=14, bulletIndent=2, |
| spaceAfter=5) |
| styles["Caption"] = ParagraphStyle("Caption", parent=base["Normal"], fontName="Helvetica-Oblique", |
| fontSize=9, leading=12, textColor=GREY, alignment=TA_CENTER, |
| spaceAfter=10, spaceBefore=2) |
| styles["Formula"] = ParagraphStyle("Formula", parent=base["Normal"], fontName="Courier-Bold", |
| fontSize=10.5, leading=16, textColor=ACCENT, alignment=TA_CENTER, |
| backColor=colors.HexColor("#EEF3F9"), borderColor=ACCENT, |
| borderWidth=1, borderPadding=10, spaceBefore=8, spaceAfter=10) |
| styles["CalloutLabel"] = ParagraphStyle("CalloutLabel", parent=base["Normal"], fontName="Helvetica-Bold", |
| fontSize=9.5, leading=13, textColor=colors.white, |
| backColor=colors.HexColor("#B35A00"), borderPadding=(4, 6, 4, 6), |
| alignment=TA_LEFT) |
| styles["TOCHeading"] = ParagraphStyle("TOCHeading", parent=base["Heading1"], fontName="Helvetica-Bold", |
| fontSize=17, textColor=ACCENT, spaceAfter=14) |
|
|
|
|
| def P(text, style="Body"): |
| return Paragraph(text, styles[style]) |
|
|
|
|
| def heading(text, level=1, bookmark=None): |
| if level == 1: |
| st = "H1" |
| elif level == 2: |
| st = "H2" |
| else: |
| st = "H3" |
| para = Paragraph(text, styles[st]) |
| clean_text = (bookmark or text).replace(" ", " ").replace("&", "&") |
| para._bookmark_name = clean_text |
| para._bookmark_level = level |
| return para |
|
|
|
|
| def bullet(text): |
| return Paragraph(f"β’ {text}", styles["Bullet"]) |
|
|
|
|
| def formula(text): |
| return Table([[Paragraph(text, styles["Formula"])]], colWidths=[CONTENT_W], |
| style=TableStyle([ |
| ("BOX", (0, 0), (-1, -1), 1, ACCENT), |
| ("BACKGROUND", (0, 0), (-1, -1), colors.HexColor("#EEF3F9")), |
| ("TOPPADDING", (0, 0), (-1, -1), 10), |
| ("BOTTOMPADDING", (0, 0), (-1, -1), 10), |
| ])) |
|
|
|
|
| def data_table(headers, rows, col_widths=None, note=None): |
| if col_widths is None: |
| col_widths = [CONTENT_W / len(headers)] * len(headers) |
| header_row = [Paragraph(f"<b>{h}</b>", ParagraphStyle("th", parent=base["Normal"], fontName="Helvetica-Bold", |
| fontSize=9.5, textColor=colors.white, alignment=TA_CENTER)) |
| for h in headers] |
| body_rows = [] |
| for row in rows: |
| cells = [] |
| for i, val in enumerate(row): |
| align = TA_LEFT if i == 0 else TA_CENTER |
| cells.append(Paragraph(str(val), ParagraphStyle("td", parent=base["Normal"], fontName="Helvetica", |
| fontSize=9.5, alignment=align, leading=12.5))) |
| body_rows.append(cells) |
| data = [header_row] + body_rows |
| t = Table(data, colWidths=col_widths, repeatRows=1) |
| style_cmds = [ |
| ("BACKGROUND", (0, 0), (-1, 0), ACCENT), |
| ("GRID", (0, 0), (-1, -1), 0.6, BORDER_GREY), |
| ("VALIGN", (0, 0), (-1, -1), "MIDDLE"), |
| ("TOPPADDING", (0, 0), (-1, -1), 5), |
| ("BOTTOMPADDING", (0, 0), (-1, -1), 5), |
| ("LEFTPADDING", (0, 0), (-1, -1), 6), |
| ("RIGHTPADDING", (0, 0), (-1, -1), 6), |
| ] |
| for r in range(1, len(data)): |
| if r % 2 == 0: |
| style_cmds.append(("BACKGROUND", (0, r), (-1, r), LIGHT_GREY)) |
| t.setStyle(TableStyle(style_cmds)) |
| flowables = [t] |
| if note: |
| flowables.append(Paragraph(note, styles["Caption"])) |
| return KeepTogether(flowables) if note else t |
|
|
|
|
| def scaled_image(path, max_width): |
| with PILImage.open(path) as im: |
| w, h = im.size |
| ratio = h / w |
| return Image(path, width=max_width, height=max_width * ratio) |
|
|
|
|
| def image_with_caption(path, max_width, caption): |
| img = scaled_image(path, max_width) |
| cap = Paragraph(caption, styles["Caption"]) |
| return KeepTogether([img, cap]) |
|
|
|
|
| |
| |
| |
| REPORT_TITLE = "Knowledge Distillation on Banking77 β Group 85" |
|
|
|
|
| def draw_cover_background(cv, doc_): |
| cv.saveState() |
| cv.setFillColor(ACCENT) |
| cv.rect(0, PAGE_H - 1.3 * cm, PAGE_W, 1.3 * cm, fill=1, stroke=0) |
| cv.setFillColor(ACCENT) |
| cv.rect(0, 0, PAGE_W, 0.6 * cm, fill=1, stroke=0) |
| cv.restoreState() |
|
|
|
|
| def draw_content_frame(cv, doc_): |
| cv.saveState() |
| cv.setStrokeColor(BORDER_GREY) |
| cv.setLineWidth(0.6) |
| cv.line(MARGIN, PAGE_H - 1.15 * cm, PAGE_W - MARGIN, PAGE_H - 1.15 * cm) |
| cv.setFont("Helvetica", 8.5) |
| cv.setFillColor(GREY) |
| cv.drawString(MARGIN, PAGE_H - 0.95 * cm, "Conversational AI β Assignment-2 (PS1)") |
| cv.drawRightString(PAGE_W - MARGIN, PAGE_H - 0.95 * cm, "Group 85 β Knowledge Distillation Report") |
|
|
| cv.line(MARGIN, 1.1 * cm, PAGE_W - MARGIN, 1.1 * cm) |
| cv.setFont("Helvetica", 8.5) |
| cv.drawString(MARGIN, 0.75 * cm, "Knowledge_Distillation_Report_Group85.pdf") |
| cv.drawRightString(PAGE_W - MARGIN, 0.75 * cm, f"Page {doc_.page}") |
| cv.restoreState() |
|
|
|
|
| class ReportDocTemplate(BaseDocTemplate): |
| def afterFlowable(self, flowable): |
| if hasattr(flowable, "_bookmark_name"): |
| text = flowable._bookmark_name |
| level = flowable._bookmark_level |
| key = f"bm_{id(flowable)}" |
| self.canv.bookmarkPage(key) |
| self.canv.addOutlineEntry(text, key, level - 1, level == 1) |
| self.notify("TOCEntry", (level - 1, text, self.page, key)) |
|
|
|
|
| doc = ReportDocTemplate( |
| OUT_PATH, pagesize=A4, |
| leftMargin=MARGIN, rightMargin=MARGIN, topMargin=MARGIN, bottomMargin=MARGIN, |
| title="Knowledge Distillation Report β Group 85", |
| author="Group 85 (R. Priji Rajendran, Reeve Chaitanya, Sahil Verma, Vankala N Sai Krishna Kumar)", |
| subject="Conversational AI β Assignment-2 (PS1): Knowledge Distillation on Banking77", |
| ) |
|
|
| cover_frame = Frame(0, 0, PAGE_W, PAGE_H, id="cover", leftPadding=2.4 * cm, rightPadding=2.4 * cm, |
| topPadding=3.2 * cm, bottomPadding=2.4 * cm) |
| content_frame = Frame(MARGIN, MARGIN, CONTENT_W, PAGE_H - 2 * MARGIN - 0.3 * cm, id="content") |
|
|
| doc.addPageTemplates([ |
| PageTemplate(id="Cover", frames=[cover_frame], onPage=draw_cover_background), |
| PageTemplate(id="Content", frames=[content_frame], onPage=draw_content_frame), |
| ]) |
|
|
| story = [] |
|
|
| |
| |
| |
| story.append(Spacer(1, 1.4 * cm)) |
| story.append(P("CONVERSATIONAL AI", "CoverSub")) |
| story.append(Spacer(1, 0.3 * cm)) |
| story.append(P("Knowledge Distillation on the Banking77 Intent Dataset", "CoverTitle")) |
| story.append(P("Compressing a Fine-Tuned BERT Teacher into a Compact, CPU-Deployable Student Transformer", "CoverSub")) |
| story.append(Spacer(1, 1.0 * cm)) |
|
|
| cover_info = Table( |
| [ |
| [P("Course Name", "CoverLabel"), P("Conversational AI", "CoverValue")], |
| [P("Assignment", "CoverLabel"), P("Assignment-2 (PS1)", "CoverValue")], |
| [P("Group ID", "CoverLabel"), P("Group 85", "CoverValue")], |
| [P("Dataset", "CoverLabel"), P("PolyAI/banking77 (77-class banking intent classification)", "CoverValue")], |
| ], |
| colWidths=[4.5 * cm, 10.5 * cm], |
| ) |
| cover_info.setStyle(TableStyle([ |
| ("BOX", (0, 0), (-1, -1), 1, ACCENT), |
| ("INNERGRID", (0, 0), (-1, -1), 0.5, colors.HexColor("#B9C9DA")), |
| ("BACKGROUND", (0, 0), (0, -1), ACCENT_LIGHT), |
| ("TOPPADDING", (0, 0), (-1, -1), 7), |
| ("BOTTOMPADDING", (0, 0), (-1, -1), 7), |
| ("LEFTPADDING", (0, 0), (-1, -1), 10), |
| ])) |
| story.append(cover_info) |
| story.append(Spacer(1, 1.0 * cm)) |
|
|
| story.append(P("Team Members", "CoverLabel")) |
| story.append(Spacer(1, 0.2 * cm)) |
| team_rows = [ |
| ["Name", "BITS ID"], |
| ["R. Priji Rajendran", "2024AD05222"], |
| ["Reeve Chaitanya", "2024AD05225"], |
| ["Sahil Verma", "2024AD05230"], |
| ["Vankala N Sai Krishna Kumar", "2024AD05334"], |
| ] |
| story.append(data_table(team_rows[0], team_rows[1:], col_widths=[9.5 * cm, 5.5 * cm])) |
| story.append(Spacer(1, 1.4 * cm)) |
| story.append(P("Source notebook: knowledge_distillation_assignment.ipynb (fully executed, end-to-end)", "CoverMeta")) |
| story.append(P("Environment: conda env agn_env Β· Python 3.12 Β· Apple Silicon (MPS + CPU)", "CoverMeta")) |
|
|
| story.append(NextPageTemplate("Content")) |
| story.append(PageBreak()) |
|
|
| |
| |
| |
| story.append(P("Table of Contents", "TOCHeading")) |
| toc = TableOfContents() |
| toc.levelStyles = [ |
| ParagraphStyle("TOC0", fontName="Helvetica-Bold", fontSize=11, leading=16, leftIndent=0, textColor=ACCENT), |
| ParagraphStyle("TOC1", fontName="Helvetica", fontSize=10, leading=14, leftIndent=14, textColor=GREY), |
| ] |
| story.append(toc) |
| story.append(PageBreak()) |
|
|
| |
| |
| |
| story.append(heading("1. Executive Summary and System Architecture", 1)) |
| story.append(Spacer(1, 8)) |
| story.append(P( |
| "This report documents the design, implementation, and empirical evaluation of a knowledge " |
| "distillation pipeline that compresses a large, fine-tuned Transformer (βTeacherβ) into a " |
| "compact, CPU-deployable Transformer (βStudentβ), on the PolyAI/banking77 dataset β a 77-class, " |
| "fine-grained banking-intent classification task with 10,003 training and 3,080 test utterances. " |
| "The complete pipeline was implemented and executed end-to-end in a single Jupyter notebook " |
| "(<b>knowledge_distillation_assignment.ipynb</b>) inside the conda environment <b>agn_env</b> " |
| "(Python 3.12) on Apple Silicon; the Teacher was fine-tuned with MPS acceleration, while the Student " |
| "was deliberately trained and benchmarked entirely on CPU β the profile it is designed to be " |
| "deployed under." |
| )) |
| story.append(P( |
| "<b>Pipeline overview:</b> <b>bert-base-uncased</b> (110M parameters) is fine-tuned end-to-end on " |
| "banking77 to serve as the Teacher. Its full 77-way softmax distribution (βsoft labelsβ) is cached " |
| "for every training example. A custom, hand-built 4-layer encoder-only Transformer β using its own " |
| "compact, domain-trained WordPiece tokenizer β is then trained as the Student, using a combined " |
| "KullbackβLeibler (KL) divergence + cross-entropy loss that blends the Teacher's soft labels with the " |
| "ground-truth hard labels. A second, architecturally identical Student is trained on hard labels only, " |
| "as a control, to isolate the effect of distillation itself." |
| )) |
| story.append(P( |
| "<b>Motivation for edge-oriented compression:</b> a 110M-parameter, ~420MB BERT checkpoint is " |
| "frequently impractical to ship inside a mobile app, run on a low-RAM edge device, or serve at low " |
| "latency on constrained hardware. Knowledge distillation offers a route to recover most of that " |
| "model's task accuracy in a footprint small enough for such environments, by training the small model " |
| "against the large model's full output distribution rather than only its predicted class β the " |
| "technique explored and quantified throughout this report." |
| )) |
|
|
| arch_rows = [ |
| ["Component", "Specification"], |
| ["Teacher", "bert-base-uncased, fine-tuned 3 epochs on banking77 (109,541,453 parameters)"], |
| ["Student", "Custom 4-layer encoder-only Transformer, hidden size 256, 4 heads (2,904,397 parameters)"], |
| ["Student tokenizer", "WordPiece, 3,000-token vocabulary, trained from scratch on the banking77 corpus"], |
| ["Distillation loss", "Ξ±Β·TΒ²Β·KL(soft student β soft teacher) + (1βΞ±)Β·CE(student, true label), T=4.0, Ξ±=0.7"], |
| ["Training devices", "Teacher: Apple MPS Β· Student: CPU (training and inference)"], |
| ] |
| story.append(Spacer(1, 4)) |
| story.append(data_table(arch_rows[0], arch_rows[1:], col_widths=[3.6 * cm, 11.4 * cm])) |
|
|
| story.append(PageBreak()) |
|
|
| |
| |
| |
| story.append(heading("2. Module 1: Teacher Labeling and Student Setup", 1)) |
|
|
| story.append(heading("2.1 Task 1 Analysis β Soft Labels, Temperature, and Dark Knowledge", 2)) |
| story.append(P( |
| "bert-base-uncased was fine-tuned end-to-end on banking77 (3 epochs, batch size 32, learning rate " |
| "3e-5, weight decay 0.01, Hugging Face Trainer on MPS). After fine-tuning, one no-gradient forward " |
| "pass was run over the full, unshuffled training set to cache the Teacher's raw 77-dimensional " |
| "logits for every example β the βsoft labelsβ used for distillation." |
| )) |
| story.append(data_table( |
| ["Metric (test set)", "Value"], |
| [["Evaluation loss", "0.839"], ["Accuracy", "87.56%"], ["Macro F1", "0.868"], |
| ["Total parameters", "109,541,453"], ["Cached logits shape (train / test)", "[10,003 Γ 77] / [3,080 Γ 77]"]], |
| col_widths=[6.5 * cm, 8.5 * cm], |
| )) |
| story.append(heading("Why soft labels carry βdark knowledgeβ", 3)) |
| story.append(P( |
| "A one-hot hard label for βI am still waiting on my card?β states only that the correct class is " |
| "<i>card_arrival</i>, and that every other one of the 77 classes is equally, absolutely wrong. That is " |
| "not what the Teacher believes: its softmax output might place 62% probability on <i>card_arrival</i>, " |
| "21% on the closely related <i>card_delivery_estimate</i>, and small residual mass elsewhere β it " |
| "still predicts the right class, but it also encodes how confusable the other intents are with it." |
| )) |
| 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>).")) |
| 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.")) |
| 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.")) |
| story.append(bullet("<b>Is amplified by temperature scaling (T)</b> β dividing both models' logits by T > 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).")) |
|
|
| story.append(heading("2.2 Task 2 Analysis β Tokenizer Alignment Between Teacher and Student", 2)) |
| story.append(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 (target " |
| "vocabulary size 3,000, BERT-style lowercasing, [CLS]/[SEP] template post-processing). This is a " |
| "deliberate compression lever: embedding-table size scales with vocab_size Γ hidden_size, so a " |
| "10x-smaller, domain-concentrated vocabulary directly shrinks the Student's parameter count " |
| "(quantified in Task 3)." |
| )) |
| story.append(data_table( |
| ["Property", "Teacher (BERT)", "Student (custom WordPiece)"], |
| [["Vocabulary size", "30,522", "3,000"], ["Vocabulary compression", "β", "10.2x smaller"]], |
| col_widths=[5.5 * cm, 4.5 * cm, 5.0 * cm], |
| )) |
| story.append(Spacer(1, 4)) |
| story.append(data_table( |
| ["Sample utterance", "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=[8.5 * cm, 3.0 * cm, 3.5 * cm], |
| )) |
| story.append(heading("Alignment strategy", 3)) |
| story.append(P( |
| "On these five common, in-domain examples the Student's token count equals the Teacher's plus exactly " |
| "two β the [CLS]/[SEP] markers the Student's counts include and the Teacher's tokenize() call does " |
| "not β meaning the two vocabularies segment frequent, in-domain phrasing about equally coarsely. The " |
| "cost of the much smaller vocabulary shows up on rarer or compound words, via more aggressive subword " |
| "splitting and a higher effective [UNK] rate, rather than on everyday vocabulary." |
| )) |
| story.append(P( |
| "A more fundamental design question is how to align a Teacher and Student that tokenize the same text " |
| "differently. A naive token-level distillation scheme β as used for sequence-to-sequence or " |
| "token-classification tasks β requires the two models' output sequences to line up position-by-position, " |
| "which breaks immediately once tokenizers disagree on token counts. That problem does not apply here, " |
| "because this is <b>sequence classification</b>: the Teacher emits exactly one 77-way probability " |
| "vector per example, independent of its internal token count. The only alignment that matters is " |
| "therefore at the <b>example (row) level</b>:" |
| )) |
| 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.")) |
| 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.")) |
|
|
| story.append(PageBreak()) |
|
|
| |
| |
| |
| story.append(heading("3. Module 2: Distillation Architecture and Training Details", 1)) |
|
|
| story.append(heading("3.1 Task 3 β Compact Student Transformer Architecture", 2)) |
| story.append(P( |
| "The Student is a small, hand-built encoder-only Transformer, assembled directly from PyTorch " |
| "<b>nn.Module</b> / <b>nn.TransformerEncoderLayer</b> primitives rather than repurposing a pretrained " |
| "architecture, and sized to train and run comfortably on CPU." |
| )) |
| story.append(data_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=[6.0 * cm, 9.0 * cm], |
| )) |
| story.append(heading("Parameter breakdown vs. Teacher", 3)) |
| story.append(data_table( |
| ["Component", "Parameters"], |
| [ |
| ["Token + position embeddings", "776,192"], ["Transformer encoder (4 layers)", "2,108,416"], |
| ["Classification head", "19,789"], ["Student total", "<b>2,904,397</b>"], |
| ["Teacher total (bert-base-uncased)", "<b>109,541,453</b>"], |
| ["Compression ratio", "<b>37.7x fewer parameters</b>"], |
| ], |
| col_widths=[8.0 * cm, 7.0 * cm], |
| )) |
| story.append(P( |
| "Roughly 27% of the Student's parameter budget sits in its embedding table alone β the direct payoff " |
| "of Task 2's small, domain-specific vocabulary. 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 encoder depth or width." |
| )) |
|
|
| story.append(heading("3.2 Task 4 β Distillation Loss Function", 2)) |
| story.append(P("The Student is trained against a single combined objective, blending distillation and supervised signal:")) |
| story.append(formula( |
| "Loss = Ξ± Β· TΒ² Β· KL( P<sub>student</sub><sup>T</sup> β P<sub>teacher</sub><sup>T</sup> ) " |
| "+ (1βΞ±) Β· CE( y<sub>student</sub>, y<sub>true</sub> )" |
| )) |
| story.append(P( |
| "with temperature <b>T = 4.0</b> and weighting <b>Ξ± = 0.7</b>. The KL term compares the Student's and " |
| "Teacher's softmax outputs after both are divided by T (softening both distributions and amplifying " |
| "the small, informative probabilities on non-target classes); the TΒ² multiplier (Hinton et al., 2015) " |
| "compensates for the fact that raising T shrinks the KD gradient magnitude 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 label, ensuring the Student never loses sight " |
| "of the actual classification objective while learning to mimic the Teacher's distribution." |
| )) |
| story.append(heading("Training configuration", 3)) |
| story.append(data_table( |
| ["Hyperparameter", "Distilled Student", "Baseline Student (control)"], |
| [ |
| ["Loss", "Ξ±Β·TΒ²Β·KL + (1βΞ±)Β·CE", "CE only (hard labels)"], |
| ["Optimizer", "AdamW, lr 3e-4", "AdamW, lr 3e-4"], |
| ["Epochs / batch size", "8 / 32", "8 / 32"], |
| ["Device", "CPU", "CPU"], |
| ["Training time", "130.8 s", "127.6 s"], |
| ], |
| col_widths=[4.5 * cm, 5.25 * cm, 5.25 * cm], |
| )) |
| story.append(Spacer(1, 6)) |
| story.append(data_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=[2.5 * cm, 4.17 * cm, 4.17 * cm, 4.17 * cm], |
| )) |
| story.append(image_with_caption( |
| f"{ASSETS}/distill_loss_curves.png", 13.5 * cm, |
| "Figure 1. Distilled student training: total loss (left) and its KD vs. CE components (right) across 8 epochs.", |
| )) |
| story.append(P( |
| "The CE component drops faster and further than the KD component throughout training: with only " |
| "3,000 vocabulary tokens and 4 layers, the Student can quickly memorize the single correct class for a " |
| "small, 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 β exactly the regime in which distillation " |
| "contributes information beyond what hard labels alone would teach." |
| )) |
|
|
| story.append(PageBreak()) |
|
|
| |
| |
| |
| story.append(heading("4. Module 3: Experimental Results and Benchmarking", 1)) |
|
|
| story.append(heading("4.1 Task 5 β Accuracy vs. Compression Evaluation", 2)) |
| story.append(P( |
| "To isolate the effect of distillation from the effect of the compact architecture alone, a second, " |
| "architecturally identical Student is trained with plain cross-entropy on ground-truth labels only " |
| "(no Teacher signal). All three models are evaluated on the same held-out 3,080-example test set using " |
| "scikit-learn's accuracy_score and f1_score (macro and weighted)." |
| )) |
| story.append(data_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", "<b>87.44%</b>", "<b>0.874</b>", "<b>0.874</b>"], |
| ], |
| col_widths=[6.5 * cm, 3.0 * cm, 2.9 * cm, 2.9 * cm], |
| )) |
| story.append(image_with_caption( |
| f"{ASSETS}/baseline_vs_distilled_loss.png", 9.5 * cm, |
| "Figure 2. Training loss: baseline student (CE only) vs. distilled student (KD + CE). The two loss compositions are not directly comparable in scale.", |
| )) |
| story.append(P( |
| "The undistilled Student, trained only on hard labels with a 37.7x smaller architecture, reaches " |
| "83.5% accuracy β a 4.1-point gap below the Teacher's 87.6%, as expected given how much capacity was " |
| "removed. Adding the Teacher's soft labels β architecture, data, and epoch budget held fixed, " |
| "changing only the loss function β raises the Student to 87.4% accuracy, <b>closing 97% of the " |
| "accuracy gap</b> between the undistilled Student and the Teacher, and retaining <b>99.9%</b> of the " |
| "Teacher's accuracy at a fraction of its parameter count. This is the central empirical claim of " |
| "knowledge distillation 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. This closeness also partly reflects that the Teacher itself is only a " |
| "lightly (3-epoch) fine-tuned model and the test set is a few thousand examples β a point or two either " |
| "way is within normal run-to-run variance." |
| )) |
|
|
| story.append(heading("4.2 Task 6 β Deployment Metrics Benchmarking", 2)) |
| story.append(P( |
| "Accuracy alone does not determine deployability. Three deployment-relevant metrics were measured for " |
| "the Teacher and the distilled Student: on-disk model size, CPU inference latency, and peak process " |
| "RAM. Peak RAM was measured in an <b>isolated subprocess per model</b> (via resource.getrusage) rather " |
| "than in the shared notebook kernel, since peak RSS is monotonically non-decreasing for the life of a " |
| "process β loading both models into one kernel would let the Teacher's larger footprint contaminate " |
| "any subsequent reading taken for the Student." |
| )) |
| story.append(data_table( |
| ["Metric", "Teacher", "Student", "Compression / Speedup"], |
| [ |
| ["Model size on disk (MB)", "417.9", "11.1", "<b>37.7x smaller</b>"], |
| ["CPU inference latency (ms/query)", "27.76 Β± 3.07", "1.18 Β± 0.09", "<b>23.5x faster</b>"], |
| ["Peak RAM (MB, isolated process)", "893.8", "237.0", "<b>3.8x smaller</b>"], |
| ], |
| col_widths=[5.5 * cm, 3.0 * cm, 3.0 * cm, 3.8 * cm], |
| )) |
|
|
| story.append(PageBreak()) |
|
|
| |
| |
| |
| story.append(heading("5. Deployment Readiness and Engineering Inferences", 1)) |
| story.append(P( |
| "The distilled Student is <b>37.7x smaller on disk</b>, <b>23.5x faster</b> per CPU query, and uses " |
| "<b>3.8x less peak RAM</b> than the Teacher, while retaining <b>99.9%</b> of its accuracy on the same " |
| "77-way classification task. In this run there is essentially no accuracy cost to weigh against those " |
| "savings β 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 assume this margin holds indefinitely as the input distribution drifts." |
| )) |
| 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).")) |
| 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.")) |
| 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.")) |
| 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.")) |
|
|
| story.append(heading("Key takeaways", 2)) |
| 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.")) |
| 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.")) |
| 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.")) |
| 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.")) |
|
|
|
|
| doc.multiBuild(story) |
| print(f"PDF written to {OUT_PATH}") |
|
|