{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "8084aeae",
   "metadata": {},
   "source": [
    "# Week 3 Practical: LLM Efficiency Techniques\n",
    "\n",
    "## Training and Inference Optimization\n",
    "\n",
    "### Learning Objectives\n",
    "\n",
    "By the end of this practical session, you will:\n",
    "\n",
    "1. **Implement LoRA from scratch** (Exercise 1)\n",
    "   - Understand low-rank adaptation mechanics (W' = W + BA)\n",
    "   - Apply LoRA to DistilBERT attention layers\n",
    "   - Understand how to patch a neural networks (torch)\n",
    "   - Compare to full fine-tuning (~0.5% parameters, similar accuracy)\n",
    "\n",
    "2. **Implement INT8 Quantization** (Exercise 2)\n",
    "   - Quantize FFN layers manually using symmetric quantization\n",
    "   - Analyze accuracy/memory trade-offs (4x compression)\n",
    "   - Understand post-training quantization techniques\n",
    "\n",
    "3. **Use HuggingFace PEFT Library** (Exercise 3)\n",
    "   - Experiment with production PEFT methods (LoRA, Adapters, Prefix Tuning)\n",
    "   - Compare different parameter-efficient fine-tuning approaches\n",
    "   - Learn configuration patterns for real-world use\n",
    "\n",
    "4. **Benchmark Performance** (Exercise 4)\n",
    "   - Measure memory usage, training time, inference speed\n",
    "   - Compare all efficiency techniques systematically\n",
    "   - Understand real-world trade-offs for deployment decisions"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "93ccbc25",
   "metadata": {},
   "source": [
    "## Setup\n",
    "\n",
    "The next cell imports the necessary modules – just run it, no need to look at\n",
    "the details!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d818dd8a",
   "metadata": {
    "tags": [
     "colab",
     "pip",
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "# Installing required packages\n",
    "\n",
    "%pip install setuptools==80.9.0\n",
    "\n",
    "# Installing main packages\n",
    "\n",
    "%pip install evaluate==0.4.6\n",
    "%pip install matplotlib==3.10.8\n",
    "%pip install su-master-mind==2026.1.25.4\n",
    "%pip install torch==2.9.1\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8b00856e",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "outputs": [],
   "source": [
    "import math\n",
    "import time\n",
    "import evaluate\n",
    "import matplotlib.pyplot as plt\n",
    "import pandas as pd\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "from typing import List, Tuple\n",
    "from master_mind.teaching.hf import load_hf_dataset, load_hf_model, load_hf_tokenizer\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8a5dfce0",
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_best_device():\n",
    "    \"\"\"Returns the best device on this computer\"\"\"\n",
    "\n",
    "    if torch.cuda.is_available():\n",
    "        device = torch.device(\"cuda\")\n",
    "        total_memory = torch.cuda.get_device_properties(device).total_memory\n",
    "        print(f\"GPU Memory: {total_memory / 1e9:.1f} GB\")\n",
    "        print(f\"GPU Name: {torch.cuda.get_device_name(device)}\")\n",
    "    elif torch.backends.mps.is_available():\n",
    "        device = torch.device(\"mps\")\n",
    "    else:\n",
    "        device = torch.device(\"cpu\")\n",
    "    print(f\"Found device: {device}\")\n",
    "    return device\n",
    "\n",
    "\n",
    "device = get_best_device()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f417bd2c",
   "metadata": {},
   "source": [
    "### Load IMDB Dataset\n",
    "\n",
    "We'll use a subset of IMDB for faster experimentation with efficiency techniques."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0fcb1785",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"Loading IMDb dataset...\")\n",
    "dataset = load_hf_dataset(\n",
    "    \"imdb\",\n",
    "    split=\"train\",\n",
    ")\n",
    "dataset = dataset.map(lambda x: {\"labels\": x.pop(\"label\")})\n",
    "\n",
    "# Use a subset (for speed in efficiency experiments)\n",
    "dataset = dataset.shuffle(seed=42)\n",
    "\n",
    "# Default dataset configuration (can be modified for faster experimentation)\n",
    "dataset_size = 10_000\n",
    "eval_split = 0.05\n",
    "\n",
    "\n",
    "dataset = dataset.select(range(dataset_size))\n",
    "\n",
    "# Split into train/val\n",
    "train_val = dataset.train_test_split(test_size=eval_split, seed=42)\n",
    "train_dataset = train_val[\"train\"]\n",
    "eval_dataset = train_val[\"test\"]\n",
    "\n",
    "print(f\"Train: {len(train_dataset)}, Eval: {len(eval_dataset)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5a6645bf",
   "metadata": {},
   "source": [
    "### Load Pre-trained Sentiment Classifier\n",
    "\n",
    "Instead of training from scratch, we'll use a pre-trained DistilBERT model\n",
    "fine-tuned on SST-2 (Stanford Sentiment Treebank). This saves time and provides\n",
    "a strong baseline for our efficiency experiments."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6ca1ddc1",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"Loading pre-trained sentiment classifier...\")\n",
    "classifier_model_name = \"distilbert-base-uncased-finetuned-sst-2-english\"\n",
    "classifier_tokenizer = load_hf_tokenizer(classifier_model_name)\n",
    "classifier_model = load_hf_model(\n",
    "    classifier_model_name, AutoModelForSequenceClassification\n",
    ").to(device)\n",
    "\n",
    "print(f\"Model: {classifier_model_name}\")\n",
    "print(f\"Parameters: {sum(p.numel() for p in classifier_model.parameters()):,}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b7d73b23",
   "metadata": {},
   "source": [
    "### Tokenize Datasets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "50452464",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"Tokenizing datasets...\")\n",
    "\n",
    "\n",
    "def preprocess_function(examples):\n",
    "    return classifier_tokenizer(\n",
    "        examples[\"text\"], truncation=True, max_length=256, padding=\"max_length\"\n",
    "    )\n",
    "\n",
    "\n",
    "train_dataset = train_dataset.map(preprocess_function, batched=True)\n",
    "eval_dataset = eval_dataset.map(preprocess_function, batched=True)\n",
    "\n",
    "train_dataset.set_format(\"torch\", columns=[\"input_ids\", \"attention_mask\", \"labels\"])\n",
    "eval_dataset.set_format(\"torch\", columns=[\"input_ids\", \"attention_mask\", \"labels\"])\n",
    "\n",
    "print(\n",
    "    f\"Datasets tokenized with {len(train_dataset[0]['input_ids'])} tokens per example\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c4822702",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Evaluate baseline accuracy on IMDB dataset\n",
    "print(\"Evaluating baseline accuracy...\")\n",
    "classifier_model.eval()\n",
    "\n",
    "# Compute baseline accuracy\n",
    "accuracy_metric = evaluate.load(\"accuracy\")\n",
    "\n",
    "\n",
    "def compute_metrics(eval_pred):\n",
    "    logits, labels = eval_pred\n",
    "    predictions = logits.argmax(axis=-1)\n",
    "    return accuracy_metric.compute(predictions=predictions, references=labels)\n",
    "\n",
    "\n",
    "training_args = TrainingArguments(\n",
    "    output_dir=\"./outputs/practical-03/tmp\",\n",
    "    per_device_eval_batch_size=32,\n",
    "    report_to=None,\n",
    ")\n",
    "\n",
    "trainer = Trainer(\n",
    "    model=classifier_model,\n",
    "    args=training_args,\n",
    "    compute_metrics=compute_metrics,\n",
    ")\n",
    "\n",
    "prediction_output = trainer.predict(eval_dataset)\n",
    "classifier_accuracy = compute_metrics(\n",
    "    (prediction_output.predictions, prediction_output.label_ids)\n",
    ")[\"accuracy\"]\n",
    "\n",
    "print(f\"Baseline accuracy on IMDB: {classifier_accuracy:.4f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1c05a1c5",
   "metadata": {},
   "source": [
    "# IMDB statistics and baseline accuracy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cea27acd",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(f\"Device: {device}\")\n",
    "print(f\"Train samples: {len(train_dataset)}\")\n",
    "print(f\"Test samples: {len(eval_dataset)}\")\n",
    "print(f\"Model: {classifier_model_name}\")\n",
    "print(f\"Baseline accuracy: {classifier_accuracy:.4f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "890524f5",
   "metadata": {},
   "source": [
    "---\n",
    "# Exercise 1: Manual LoRA Implementation\n",
    "\n",
    "## What is LoRA?\n",
    "\n",
    "**LoRA (Low-Rank Adaptation)** is a parameter-efficient fine-tuning method\n",
    "that freezes the pre-trained model weights and injects trainable low-rank\n",
    "matrices into each layer.\n",
    "\n",
    "**Key Idea:** Instead of updating $W \\in \\mathbb{R}^{d \\times d}$ directly, we\n",
    "learn:\n",
    "\n",
    "$$W' = W + \\Delta W = W + BA$$\n",
    "\n",
    "where:\n",
    "- $A \\in \\mathbb{R}^{d \\times r}$ and $B \\in \\mathbb{R}^{r \\times d}$\n",
    "- $r \\ll d$ (rank, typically 4-16)\n",
    "- $W$ is frozen, only $A$ and $B$ are trained\n",
    "\n",
    "**Paper:** [LoRA: Low-Rank Adaptation of Large Language\n",
    "Models](https://arxiv.org/abs/2106.09685) (Hu et al., 2021)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "85f27331",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Step 1.1: Implement LoRALayer\n",
    "\n",
    "We'll implement a LoRA layer that wraps a standard PyTorch Linear layer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "80e5105c",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "class LoRALayer(nn.Module):\n",
    "    \"\"\"\n",
    "    LoRA (Low-Rank Adaptation) layer.\n",
    "\n",
    "    Implements: output = W @ x + (B @ A) @ x * (alpha / r)\n",
    "    where W is frozen, A and B are trainable.\n",
    "\n",
    "    Args:\n",
    "        original_layer: The linear layer to adapt\n",
    "        r: Rank of adaptation matrices (default: 8)\n",
    "        alpha: Scaling factor (default: 16, effective scale is alpha/r)\n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(\n",
    "        self,\n",
    "        original_layer: nn.Linear,\n",
    "        r: int = 8,\n",
    "        alpha: float = 16,\n",
    "    ):\n",
    "        # Initialize LoRA matrices A and B\n",
    "\n",
    "        # Initialize A with kaiming_uniform (standard init)\n",
    "        \n",
    "        # Initialize B with zeros (important: starts as identity)\n",
    "        \n",
    "        # Freeze original layer\n",
    "        \n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "    def forward(self, x: torch.Tensor) -> torch.Tensor:\n",
    "        # Implement LoRA forward pass\n",
    "\n",
    "        # Compute original output\n",
    "        \n",
    "        # Compute LoRA adaptation: B @ A @ x, scaled by alpha/r\n",
    "        \n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "    def merge_weights(self):\n",
    "        \"\"\"Merge LoRA weights into original layer for deployment.\"\"\"\n",
    "        # Optional: Implement weight merging\n",
    "\n",
    "        # This is for deployment - merge BA into W so no overhead\n",
    "        assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "32cd351e",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Step 1.2: Helper Functions\n",
    "\n",
    "These helper functions will apply LoRA to DistilBERT's attention layers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c6bf3e82",
   "metadata": {
    "lines_to_next_cell": 2,
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "def apply_lora_to_distilbert(\n",
    "    model: nn.Module,\n",
    "    r: int = 8,\n",
    "    alpha: float = 16,\n",
    "    target_modules: List[str] = None,\n",
    ") -> List[nn.Parameter]:\n",
    "    \"\"\"\n",
    "    Apply LoRA to specific modules in DistilBERT.\n",
    "\n",
    "    Args:\n",
    "        model: DistilBERT model\n",
    "        r: LoRA rank\n",
    "        alpha: LoRA alpha\n",
    "        target_modules: Which attention matrices to adapt (q_lin, k_lin, v_lin, out_lin)\n",
    "\n",
    "    Returns:\n",
    "        List of LoRA parameters to optimize\n",
    "    \"\"\"\n",
    "    if target_modules is None:\n",
    "        target_modules = [\"q_lin\", \"v_lin\"]\n",
    "\n",
    "    lora_params = []\n",
    "\n",
    "    # Iterate through transformer layers\n",
    "    for i, layer in enumerate(model.distilbert.transformer.layer):\n",
    "        attention = layer.attention\n",
    "\n",
    "        for module_name in target_modules:\n",
    "            if hasattr(attention, module_name):\n",
    "                original_layer = getattr(attention, module_name)\n",
    "                if isinstance(original_layer, LoRALayer):\n",
    "                    # Do not modify the layer again\n",
    "                    continue\n",
    "\n",
    "                # Replace with LoRA layer\n",
    "                lora_layer = LoRALayer(original_layer, r=r, alpha=alpha)\n",
    "                setattr(attention, module_name, lora_layer)\n",
    "\n",
    "                # Collect LoRA parameters\n",
    "                lora_params.extend([lora_layer.A.weight, lora_layer.B.weight])\n",
    "\n",
    "                print(f\"Applied LoRA to layer {i} -> {module_name}\")\n",
    "\n",
    "    return lora_params\n",
    "\n",
    "\n",
    "def count_trainable_parameters(model: nn.Module) -> Tuple[int, int]:\n",
    "    \"\"\"\n",
    "    Count trainable vs total parameters.\n",
    "\n",
    "    Returns:\n",
    "        (trainable_params, total_params)\n",
    "    \"\"\"\n",
    "    trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
    "    total = sum(p.numel() for p in model.parameters())\n",
    "    return trainable, total"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0bd8e0db",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load base model\n",
    "lora_model = load_hf_model(\n",
    "    classifier_model_name,\n",
    "    AutoModelForSequenceClassification,\n",
    "    num_labels=2,\n",
    ").to(device)\n",
    "\n",
    "# And look at its parameters\n",
    "lora_model"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8e82e41a",
   "metadata": {},
   "source": [
    "## Step 1.3: Apply LoRA and Train\n",
    "\n",
    "Now let's apply LoRA to a DistilBERT model and fine-tune it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b6b7c7c4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Setup LoRA training\n",
    "\n",
    "# Freeze ALL model parameters first\n",
    "\n",
    "# Apply LoRA to attention layers (q_lin and v_lin)\n",
    "\n",
    "# Count trainable parameters\n",
    "\n",
    "assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cc9a2208",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Train LoRA model\n",
    "\n",
    "# Default training configuration (can be reduced for faster experimentation)\n",
    "num_epochs = 2\n",
    "logging_steps = 100\n",
    "\n",
    "\n",
    "print(f\"\\nTraining LoRA model ({num_epochs} epochs)...\")\n",
    "\n",
    "training_args = TrainingArguments(\n",
    "    output_dir=\"./outputs/practical-03/lora-distillbert-imdb\",\n",
    "    num_train_epochs=num_epochs,\n",
    "    per_device_train_batch_size=32,\n",
    "    per_device_eval_batch_size=32,\n",
    "    warmup_steps=50,\n",
    "    weight_decay=0.01,\n",
    "    logging_steps=logging_steps,\n",
    "    eval_strategy=\"epoch\",\n",
    "    save_strategy=\"epoch\",\n",
    "    load_best_model_at_end=True,\n",
    "    report_to=None,\n",
    ")\n",
    "\n",
    "trainer = Trainer(\n",
    "    model=lora_model,\n",
    "    args=training_args,\n",
    "    train_dataset=train_dataset,\n",
    "    eval_dataset=eval_dataset,\n",
    "    compute_metrics=compute_metrics,\n",
    ")\n",
    "\n",
    "trainer.train()\n",
    "\n",
    "# Evaluate\n",
    "lora_results = trainer.evaluate()\n",
    "print(f\"\\nLoRA model accuracy: {lora_results['eval_accuracy']:.4f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1f16c5f9",
   "metadata": {},
   "source": [
    "## Step 1.4: Compare to Baseline\n",
    "\n",
    "Let's compare LoRA to full fine-tuning.\n",
    "\n",
    "### COMPARISON: LoRA vs Full Fine-tuning"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c2beea87",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Compare results\n",
    "\n",
    "# Full fine-tuning baseline (from distillbert_imdb.py)\n",
    "baseline_accuracy = classifier_accuracy\n",
    "print(f\"Full fine-tuning: {baseline_accuracy:.4f} accuracy, 66M trainable params\")\n",
    "print(\n",
    "    f\"LoRA (r=8):       {lora_results['eval_accuracy']:.4f} accuracy, \"\n",
    "    f\"{trainable:,} trainable params\"\n",
    ")\n",
    "print(f\"\\nParameter reduction: {100 * (1 - trainable / 66e6):.2f}%\")\n",
    "print(\n",
    "    f\"Accuracy drop: {100 * (baseline_accuracy - lora_results['eval_accuracy']):.2f}%\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "adf6572f",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Visualization\n",
    "fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))\n",
    "\n",
    "# Parameters comparison\n",
    "methods = [\"Full FT\", \"LoRA (r=8)\"]\n",
    "params = [66e6, trainable]\n",
    "colors = [\"steelblue\", \"coral\"]\n",
    "\n",
    "ax1.bar(methods, params, color=colors)\n",
    "ax1.set_ylabel(\"Trainable Parameters\")\n",
    "ax1.set_title(\"Parameter Efficiency\")\n",
    "ax1.set_yscale(\"log\")\n",
    "for i, (method, param) in enumerate(zip(methods, params)):\n",
    "    ax1.text(i, param, f\"{param / 1e6:.1f}M\", ha=\"center\", va=\"bottom\")\n",
    "\n",
    "# Accuracy comparison\n",
    "accuracies = [baseline_accuracy, lora_results[\"eval_accuracy\"]]\n",
    "ax2.bar(methods, accuracies, color=colors)\n",
    "ax2.set_ylabel(\"Accuracy\")\n",
    "ax2.set_title(\"Model Accuracy\")\n",
    "ax2.set_ylim([0.80, 0.95])\n",
    "for i, (method, acc) in enumerate(zip(methods, accuracies)):\n",
    "    ax2.text(i, acc, f\"{acc:.3f}\", ha=\"center\", va=\"bottom\")\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c8dab1ab",
   "metadata": {},
   "source": [
    "## Exercise 1 Extension: Experiment with Rank\n",
    "\n",
    "Try different LoRA ranks and see the trade-off between parameters and accuracy."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9cb03316",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Experiment with different ranks\n",
    "\n",
    "    # Apply LoRA\n",
    "    \n",
    "    # Count params\n",
    "    \n",
    "    # Train (1 epoch for speed)\n",
    "    \n",
    "    # Evaluate\n",
    "    \n",
    "# Plot results\n",
    "\n",
    "assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "38f540a6",
   "metadata": {},
   "source": [
    "---\n",
    "# Exercise 2: Manual INT8 Quantization\n",
    "\n",
    "## What is Quantization?\n",
    "\n",
    "**Quantization** converts high-precision floating-point weights (FP32: 32\n",
    "bits) to low-precision integers (INT8: 8 bits).\n",
    "\n",
    "**Symmetric Quantization Formula:**\n",
    "\n",
    "$$\\text{quantized} =\n",
    "\\text{round}\\left(\\frac{\\text{original}}{\\text{scale}}\\right)$$\n",
    "\n",
    "where:\n",
    "\n",
    "$$\\text{scale} = \\frac{\\max(|\\text{original}|)}{127}$$\n",
    "\n",
    "**Dequantization:**\n",
    "\n",
    "$$\\text{dequantized} = \\text{quantized} \\times \\text{scale}$$"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bdd2b955",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Step 2.1: Implement Quantization Functions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dba2d490",
   "metadata": {},
   "outputs": [],
   "source": [
    "def quantize_tensor(\n",
    "    tensor: torch.Tensor,\n",
    "    bits: int = 8,\n",
    ") -> Tuple[torch.Tensor, float]:\n",
    "    \"\"\"\n",
    "    Quantize tensor to INT8 using symmetric quantization.\n",
    "\n",
    "    Args:\n",
    "        tensor: FP32 tensor to quantize\n",
    "        bits: Number of bits (default: 8)\n",
    "\n",
    "    Returns:\n",
    "        quantized: INT8 tensor\n",
    "        scale: Scale factor for dequantization\n",
    "    \"\"\"\n",
    "    # Implement symmetric INT8 quantization\n",
    "\n",
    "    # Compute scale factor\n",
    "    \n",
    "    # Quantize: divide by scale, round, clamp to INT8 range\n",
    "    \n",
    "    assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "\n",
    "def dequantize_tensor(\n",
    "    quantized: torch.Tensor,\n",
    "    scale: float,\n",
    ") -> torch.Tensor:\n",
    "    \"\"\"\n",
    "    Dequantize INT8 tensor back to FP32.\n",
    "\n",
    "    Args:\n",
    "        quantized: INT8 tensor\n",
    "        scale: Scale factor from quantization\n",
    "\n",
    "    Returns:\n",
    "        dequantized: FP32 tensor\n",
    "    \"\"\"\n",
    "    # Implement dequantization\n",
    "\n",
    "    # Convert to float and multiply by scale\n",
    "    \n",
    "    assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d6d2e785",
   "metadata": {},
   "source": [
    "## Step 2.2: Test Quantization\n",
    "\n",
    "Let's test our quantization on a sample tensor."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b368f049",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Test quantization\n",
    "test_tensor = torch.randn(1000, 768)\n",
    "print(f\"Original tensor: shape={test_tensor.shape}, dtype={test_tensor.dtype}\")\n",
    "print(f\"Original range: [{test_tensor.min():.4f}, {test_tensor.max():.4f}]\")\n",
    "print(f\"Original memory: {test_tensor.nbytes / 1e6:.2f} MB\")\n",
    "\n",
    "# Quantize\n",
    "quantized, scale = quantize_tensor(test_tensor)\n",
    "print(f\"\\nQuantized tensor: shape={quantized.shape}, dtype={quantized.dtype}\")\n",
    "print(f\"Quantized range: [{quantized.min()}, {quantized.max()}]\")\n",
    "print(f\"Quantized memory: {quantized.nbytes / 1e6:.2f} MB\")\n",
    "print(f\"Scale factor: {scale:.6f}\")\n",
    "print(f\"Memory reduction: {test_tensor.nbytes / quantized.nbytes:.1f}x\")\n",
    "\n",
    "# Dequantize\n",
    "dequantized = dequantize_tensor(quantized, scale)\n",
    "print(f\"\\nDequantized tensor: shape={dequantized.shape}, dtype={dequantized.dtype}\")\n",
    "print(f\"Dequantized range: [{dequantized.min():.4f}, {dequantized.max():.4f}]\")\n",
    "\n",
    "# Measure error\n",
    "mse = ((test_tensor - dequantized) ** 2).mean()\n",
    "print(f\"\\nReconstruction MSE: {mse:.6f}\")\n",
    "print(f\"Relative error: {(mse / test_tensor.var()).sqrt():.4f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "37109b1d",
   "metadata": {},
   "source": [
    "## Step 2.3: Visualize Quantization Error"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fe7ef4c0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Visualize weight distributions\n",
    "fig, axes = plt.subplots(1, 3, figsize=(15, 4))\n",
    "\n",
    "# Original\n",
    "axes[0].hist(test_tensor.flatten().numpy(), bins=100, alpha=0.7, color=\"blue\")\n",
    "axes[0].set_title(\"Original (FP32)\")\n",
    "axes[0].set_xlabel(\"Value\")\n",
    "axes[0].set_ylabel(\"Frequency\")\n",
    "\n",
    "# Quantized\n",
    "axes[1].hist(quantized.flatten().numpy(), bins=50, alpha=0.7, color=\"orange\")\n",
    "axes[1].set_title(\"Quantized (INT8)\")\n",
    "axes[1].set_xlabel(\"Value\")\n",
    "\n",
    "# Dequantized vs Original\n",
    "axes[2].scatter(\n",
    "    test_tensor.flatten().numpy()[::100],\n",
    "    dequantized.flatten().numpy()[::100],\n",
    "    alpha=0.3,\n",
    "    s=1,\n",
    ")\n",
    "axes[2].plot([-4, 4], [-4, 4], \"r--\", label=\"Perfect reconstruction\")\n",
    "axes[2].set_title(\"Dequantized vs Original\")\n",
    "axes[2].set_xlabel(\"Original\")\n",
    "axes[2].set_ylabel(\"Dequantized\")\n",
    "axes[2].legend()\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "773061bf",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Step 2.4: Implement Quantized Linear Layer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "507525ba",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "class QuantizedLinear(nn.Module):\n",
    "    \"\"\"\n",
    "    Quantized linear layer for FFN.\n",
    "\n",
    "    Stores weights in INT8, dequantizes during forward pass.\n",
    "    This is post-training quantization (PTQ).\n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(self, linear: nn.Linear):\n",
    "        # Initialize quantized linear layer\n",
    "\n",
    "        # Quantize weight matrix\n",
    "        \n",
    "        # Store as buffer (not parameter - don't train)\n",
    "        \n",
    "        # Keep bias as float (small, not worth quantizing)\n",
    "        \n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "    def forward(self, x: torch.Tensor) -> torch.Tensor:\n",
    "        # Forward pass with dequantization\n",
    "\n",
    "        # Dequantize weights on the fly\n",
    "        \n",
    "        # Apply linear transformation\n",
    "        \n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "    def get_memory_size(self) -> float:\n",
    "        \"\"\"Returns memory size in MB.\"\"\"\n",
    "        size = self.weight_quantized.nbytes  # INT8 weights\n",
    "        if self.bias is not None:\n",
    "            size += self.bias.nbytes\n",
    "        return size / 1e6"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1f68bb9a",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Step 2.5: Quantize DistilBERT FFN Layers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "89ab0cc5",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "def quantize_distilbert_ffn(model: nn.Module) -> nn.Module:\n",
    "    \"\"\"\n",
    "    Quantize all FFN layers (lin1, lin2) in DistilBERT.\n",
    "\n",
    "    Args:\n",
    "        model: DistilBERT model\n",
    "\n",
    "    Returns:\n",
    "        Model with quantized FFN layers\n",
    "    \"\"\"\n",
    "    for i, layer in enumerate(model.distilbert.transformer.layer):\n",
    "        ffn = layer.ffn\n",
    "\n",
    "        # Quantize lin1 (768 -> 3072)\n",
    "        ffn.lin1 = QuantizedLinear(ffn.lin1)\n",
    "\n",
    "        # Quantize lin2 (3072 -> 768)\n",
    "        ffn.lin2 = QuantizedLinear(ffn.lin2)\n",
    "\n",
    "        print(f\"Quantized layer {i} FFN (lin1, lin2)\")\n",
    "\n",
    "    return model\n",
    "\n",
    "\n",
    "def measure_model_size(model: nn.Module) -> float:\n",
    "    \"\"\"\n",
    "    Measure model size in MB.\n",
    "\n",
    "    Returns:\n",
    "        Size in MB\n",
    "    \"\"\"\n",
    "    size = 0\n",
    "    for param in model.parameters():\n",
    "        size += param.numel() * param.element_size()\n",
    "    for buffer in model.buffers():\n",
    "        size += buffer.numel() * buffer.element_size()\n",
    "    return size / 1e6"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0c9f962d",
   "metadata": {},
   "source": [
    "## Step 2.6: Quantize and Evaluate"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6f561a84",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Quantize model and analyze results\n",
    "\n",
    "# Measure original size\n",
    "# Quantize FFN layers\n",
    "\n",
    "# Measure quantized size\n",
    "assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "# Evaluate accuracy\n",
    "quantized_model.eval()\n",
    "from transformers import Trainer\n",
    "\n",
    "trainer_quant = Trainer(\n",
    "    model=quantized_model,\n",
    "    args=TrainingArguments(output_dir=\"./outputs/practical-03/tmp\", report_to=None),\n",
    "    compute_metrics=compute_metrics,\n",
    ")\n",
    "prediction_output = trainer_quant.predict(eval_dataset)\n",
    "quantized_accuracy = compute_metrics(\n",
    "    (prediction_output.predictions, prediction_output.label_ids)\n",
    ")[\"accuracy\"]\n",
    "\n",
    "print(f\"\\nOriginal accuracy: {baseline_accuracy:.4f}\")\n",
    "print(f\"Quantized accuracy: {quantized_accuracy:.4f}\")\n",
    "print(f\"Accuracy drop: {100 * (baseline_accuracy - quantized_accuracy):.2f}%\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f37ab626",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Visualization\n",
    "fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))\n",
    "\n",
    "# Memory comparison\n",
    "methods = [\"FP32\", \"INT8\"]\n",
    "sizes = [size_before, size_after]\n",
    "colors = [\"steelblue\", \"coral\"]\n",
    "\n",
    "ax1.bar(methods, sizes, color=colors)\n",
    "ax1.set_ylabel(\"Model Size (MB)\")\n",
    "ax1.set_title(\"Memory Efficiency\")\n",
    "for i, (method, size) in enumerate(zip(methods, sizes)):\n",
    "    ax1.text(i, size, f\"{size:.1f} MB\", ha=\"center\", va=\"bottom\")\n",
    "\n",
    "# Accuracy comparison\n",
    "accuracies = [baseline_accuracy, quantized_accuracy]\n",
    "ax2.bar(methods, accuracies, color=colors)\n",
    "ax2.set_ylabel(\"Accuracy\")\n",
    "ax2.set_title(\"Model Accuracy\")\n",
    "ax2.set_ylim([0.80, 0.95])\n",
    "for i, (method, acc) in enumerate(zip(methods, accuracies)):\n",
    "    ax2.text(i, acc, f\"{acc:.3f}\", ha=\"center\", va=\"bottom\")\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "680da94e",
   "metadata": {},
   "source": [
    "---\n",
    "# Exercise 3: HuggingFace PEFT Library\n",
    "\n",
    "## Introduction to PEFT\n",
    "\n",
    "The [PEFT (Parameter-Efficient Fine-Tuning) library by\n",
    "HuggingFace](https://huggingface.co/blog/peft) provides production-ready\n",
    "implementations of various efficiency methods:\n",
    "\n",
    "- **LoRA**: Low-rank adaptation (we implemented this in Exercise 1)\n",
    "- **Adapters**: Bottleneck layers inserted after transformer blocks\n",
    "- **Prefix Tuning**: Learnable \"virtual tokens\" prepended to input\n",
    "- **IA3**: Learned element-wise rescaling of activations\n",
    "\n",
    "**Benefits:**\n",
    "- Battle-tested implementations\n",
    "- Easy to switch between methods\n",
    "- Modular: One base model, many task-specific adapters\n",
    "- Active development and community support"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e1f1b3aa",
   "metadata": {
    "incorrectly_encoded_metadata": "tags="
   },
   "outputs": [],
   "source": [
    "from peft import (\n",
    "    IA3Config,\n",
    "    LoraConfig,\n",
    "    PeftModel,\n",
    "    get_peft_model,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ce033fe8",
   "metadata": {},
   "source": [
    "## Step 3.2: LoRA with PEFT"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e76d6035",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Configure LoRA using PEFT library\n",
    "\n",
    "# Configure LoRA\n",
    "\n",
    "# Apply LoRA\n",
    "\n",
    "assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6f7a3a6a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Train PEFT LoRA model\n",
    "training_args_peft = TrainingArguments(\n",
    "    output_dir=\"./outputs/practical-03/peft-lora-distillbert-imdb\",\n",
    "    num_train_epochs=num_epochs,  # Use same config as manual LoRA\n",
    "    per_device_train_batch_size=32,\n",
    "    per_device_eval_batch_size=32,\n",
    "    warmup_steps=50,\n",
    "    weight_decay=0.01,\n",
    "    logging_steps=logging_steps,  # Use same config as manual LoRA\n",
    "    eval_strategy=\"epoch\",\n",
    "    save_strategy=\"epoch\",\n",
    "    load_best_model_at_end=True,\n",
    "    report_to=None,\n",
    ")\n",
    "\n",
    "trainer_peft = Trainer(\n",
    "    model=peft_lora_model,\n",
    "    args=training_args_peft,\n",
    "    train_dataset=train_dataset,\n",
    "    eval_dataset=eval_dataset,\n",
    "    compute_metrics=compute_metrics,\n",
    ")\n",
    "\n",
    "trainer_peft.train()\n",
    "peft_lora_results = trainer_peft.evaluate()\n",
    "print(f\"PEFT LoRA accuracy: {peft_lora_results['eval_accuracy']:.4f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d528d68b",
   "metadata": {},
   "source": [
    "## Step 3.3: Compare Other PEFT Methods"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9410dcf5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Compare different PEFT methods\n",
    "\n",
    "# Define configurations\n",
    "\n",
    "    # Load fresh base model\n",
    "    \n",
    "    # Apply PEFT\n",
    "    \n",
    "    # Train\n",
    "    \n",
    "    # Evaluate\n",
    "    \n",
    "# Display results\n",
    "\n",
    "assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1d0f9846",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Visualization\n",
    "fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5))\n",
    "\n",
    "# Trainable parameters\n",
    "methods = df_peft[\"Method\"].tolist()\n",
    "params = df_peft[\"Trainable Params\"].tolist()\n",
    "colors = plt.cm.Set3(range(len(methods)))\n",
    "\n",
    "ax1.barh(methods, params, color=colors)\n",
    "ax1.set_xlabel(\"Trainable Parameters\")\n",
    "ax1.set_title(\"Parameter Efficiency\")\n",
    "ax1.set_xscale(\"log\")\n",
    "for i, (method, param) in enumerate(zip(methods, params)):\n",
    "    ax1.text(param, i, f\"  {param / 1e6:.2f}M\", va=\"center\")\n",
    "\n",
    "# Accuracy\n",
    "accuracies = df_peft[\"Accuracy\"].tolist()\n",
    "ax2.barh(methods, accuracies, color=colors)\n",
    "ax2.set_xlabel(\"Accuracy\")\n",
    "ax2.set_title(\"Model Accuracy\")\n",
    "ax2.set_xlim([0.80, 0.95])\n",
    "for i, (method, acc) in enumerate(zip(methods, accuracies)):\n",
    "    ax2.text(acc, i, f\"  {acc:.3f}\", va=\"center\")\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b6cc4e33",
   "metadata": {},
   "source": [
    "## Step 3.4: Save and Load PEFT Adapters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "38919e53",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Save and load PEFT adapter\n",
    "\n",
    "# Save adapter (only the adapter weights, not the base model)\n",
    "\n",
    "# Load adapter back\n",
    "\n",
    "assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "04e5b499",
   "metadata": {},
   "source": [
    "---\n",
    "# Project: Performance Benchmarking\n",
    "\n",
    "## Introduction\n",
    "\n",
    "Now that we've explored various efficiency techniques, you can\n",
    "study their effect on:\n",
    "\n",
    "- **Memory**: Model size (MB)\n",
    "- **Training Time**: Time per epoch (seconds)\n",
    "- **Inference Speed**: Samples per second\n",
    "- **Accuracy**: Test set accuracy\n",
    "\n",
    "This will help us understand real-world trade-offs and make informed\n",
    "decisions."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
