{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "add38bb0",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# Week 1 Practical: Language Models & Transformers\n",
    "\n",
    "## Foundations: Tokenization, Embeddings, Attention\n",
    "\n",
    "### Learning Objectives\n",
    "\n",
    "By the end of this practical session, you will:\n",
    "\n",
    "1. **Understand tokenization algorithms** (Exercise 1)\n",
    "   - Compare BPE, WordPiece, and SentencePiece\n",
    "   - Train tokenizers on custom corpora\n",
    "   - Understand how tokenization affects model input\n",
    "\n",
    "2. **Analyze contextualized embeddings** (Exercise 2)\n",
    "   - Explore how token representations change across transformer layers\n",
    "   - Visualize word sense disambiguation (polysemy)\n",
    "   - Investigate coreference resolution in embeddings\n",
    "\n",
    "3. **Visualize attention mechanisms** (Exercise 3)\n",
    "   - Use BertViz to explore attention patterns\n",
    "   - Identify different attention head specializations\n",
    "   - Understand how attention evolves through layers\n",
    "\n",
    "4. **Implement self-attention from scratch** (Exercise 4)\n",
    "   - Build a multi-head self-attention model\n",
    "   - Train it on a toy task requiring positional reasoning\n",
    "   - Analyze what attention patterns emerge during training"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3a34b8b1",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "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": "4054a3f4",
   "metadata": {
    "lines_to_next_cell": 0,
    "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 su-master-mind==2026.1.25.4\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "926963b9",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import random\n",
    "import tempfile\n",
    "import warnings\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import sentencepiece as spm\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "import torch.optim as optim\n",
    "from bertviz import head_view, model_view\n",
    "from IPython.display import HTML, display\n",
    "from master_mind.teaching.hf import load_hf_model, load_hf_tokenizer\n",
    "from sklearn.decomposition import PCA\n",
    "from sklearn.metrics.pairwise import cosine_similarity\n",
    "from tokenizers import Tokenizer\n",
    "from tokenizers.models import BPE, WordPiece\n",
    "from tokenizers.pre_tokenizers import ByteLevel, Whitespace\n",
    "from tokenizers.trainers import BpeTrainer, WordPieceTrainer\n",
    "from torch.utils.data import DataLoader, Dataset, random_split\n",
    "from tqdm.autonotebook import tqdm\n",
    "from transformers import AutoModel\n",
    "\n",
    "warnings.filterwarnings(\"ignore\")\n",
    "\n",
    "\n",
    "def get_best_device():\n",
    "    \"\"\"Returns the best device on this computer\"\"\"\n",
    "    import torch\n",
    "\n",
    "    if torch.cuda.is_available():\n",
    "        device = torch.device(\"cuda\")\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": "b641a04e",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "# Exercise 1: Tokenization\n",
    "\n",
    "In this exercise, we will first look at how BPE tokenizes sentences. We will\n",
    "then compare BPE, WordPiece and SentencePiece.\n",
    "\n",
    "\n",
    "## 1. Byte Pair Encoding (BPE)\n",
    "\n",
    "**Paper:** [Neural Machine Translation of Rare Words with Subword\n",
    "Units](https://arxiv.org/abs/1508.07909) (Sennrich et al., 2016)\n",
    "\n",
    "### How It Works\n",
    "\n",
    "1. Start with a **character-level vocabulary** (or bytes for byte-level BPE)\n",
    "2. Find the **most frequent adjacent pair** of tokens in the corpus\n",
    "3. Merge that pair into a single new token\n",
    "4. Repeat until vocabulary size is achieved\n",
    "\n",
    "## 2. WordPiece\n",
    "\n",
    "**Papers:**\n",
    "- [Japanese and Korean Voice\n",
    "  Search](https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/37842.pdf)\n",
    "  (Schuster & Nakajima, 2012)\n",
    "- Adopted and popularized in [BERT](https://arxiv.org/abs/1810.04805) (Devlin\n",
    "  et al., 2019)\n",
    "\n",
    "### How It Works\n",
    "\n",
    "1. Start with a **character-level vocabulary**\n",
    "2. For each possible pair, compute a **likelihood score**: `likelihood =\n",
    "   count(pair) / (count(first) × count(second))`\n",
    "3. Merge the pair with the **highest likelihood** (not frequency)\n",
    "4. Repeat N times\n",
    "\n",
    "\n",
    "## 3. SentencePiece (Unigram)\n",
    "\n",
    "**Paper:** [Subword Regularization: Improving Neural Network Translation\n",
    "Models with Multiple Subword Candidates](https://arxiv.org/abs/1804.10959)\n",
    "(Kudo 2018)\n",
    "\n",
    "### How It Works\n",
    "\n",
    "1. Start with a **large initial vocabulary** (all chars + common substrings,\n",
    "   e.g using BPE)\n",
    "2. Iteratively **remove the token** that decrease the least the likelihood\n",
    "3. Continue until target vocabulary size is reached"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9955d5a2",
   "metadata": {},
   "source": [
    "## Basic Tokenization\n",
    "\n",
    "We first load a tokenizer (from HuggingFace) – here, a *WordPiece* tokenizer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "65630349",
   "metadata": {},
   "outputs": [],
   "source": [
    "tokenizer = load_hf_tokenizer(\"distilbert-base-uncased\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5899828a",
   "metadata": {},
   "source": [
    "We can now tokenize any text using the `tokenize` method:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "702c5e6c",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "text = \"The quick brown fox jumps.\"\n",
    "tokens = tokenizer.tokenize(text)\n",
    "print(f\"Text: {text}\")\n",
    "print(f\"Tokens: {tokens}\")\n",
    "print(f\"Num tokens: {len(tokens)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "966cca79",
   "metadata": {},
   "source": [
    "Notice that the above tokenization segments the text into word units. This is\n",
    "not always the case as shown in the example below:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f74bc62c",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "test_words = [\"hello\", \"internationalization\", \"COVID-19\"]\n",
    "for word in test_words:\n",
    "    tokens = tokenizer.tokenize(word)\n",
    "    print(f\"{word:30s} -> {tokens}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dd0c0a97",
   "metadata": {},
   "source": [
    "## Tokenizing for Transformers\n",
    "\n",
    "When using the tokenizer for a Transformer, we use token ids rather than\n",
    "tokens. The call `tokenizer(text).input_ids` returns these ids, which can be\n",
    "decoded with `tokenizer.convert_ids_to_tokens`. Notice how extra tokens\n",
    "(`[CLS]` at the beginning, `[SEP]` at the end) are added by default."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d434b2a9",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "ids = tokenizer(text).input_ids\n",
    "tokens = tokenizer.convert_ids_to_tokens(ids)\n",
    "print(f\"{ids} -> {tokens}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9de35c58",
   "metadata": {},
   "source": [
    "Finally, when using a Transformer, as with most models, we use batches of text. Here, we use two new options, `return_tensors` that ensure that we get PyTorch tensors as outputs, and `padding` that adds padding tokens when the length of the tokenized sentences are not the same."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4930cb4c",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "tokenized = tokenizer(\n",
    "    [\"the quick brown fox jumps.\", \"the squirrel jumps.\"],\n",
    "    return_tensors=\"pt\",\n",
    "    padding=True,\n",
    ")\n",
    "\n",
    "print(tokenized.input_ids)\n",
    "print(tokenized.attention_mask)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2bc6bf41",
   "metadata": {},
   "source": [
    "**Question:** What is the purpose of `attention_mask`?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c01f1422",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Step 1.4: Training new tokenizers\n",
    "\n",
    "In the next cell, we define the `TokenizerTrainer` class that allows to *train* tokenizers.\n",
    "\n",
    "### Understanding the `TokenizerTrainer` Class\n",
    "\n",
    "This class trains three different tokenizers (BPE, WordPiece, and SentencePiece) on a given corpus and allows you to compare their behavior.\n",
    "\n",
    "**Key methods:**\n",
    "- `__init__(corpus, vocab_size)`: Trains all three tokenizers on the given corpus\n",
    "- `encode_bpe(text)`, `encode_wp(text)`, `encode_sp(text)`: Tokenize text with each algorithm\n",
    "- `compare(text)`: Returns tokenization results from all three tokenizers\n",
    "- `get_vocab_*()`: Retrieve the learned vocabulary for each tokenizer\n",
    "\n",
    "**Helper function:**\n",
    "- `print_comparison(name, corpus, examples, vocab_size)`: Trains tokenizers and compares their outputs on example texts\n",
    "\n",
    "The implementation is hidden below, but you can expand it if you want to see the details."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0f66005b",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "class TokenizerTrainer:\n",
    "    \"\"\"Trains both BPE and SentencePiece on the same corpus in the constructor.\"\"\"\n",
    "\n",
    "    def __init__(self, corpus: str, vocab_size: int = 50, suppress_output: bool = True):\n",
    "        \"\"\"\n",
    "        Initialize and train both tokenizers.\n",
    "\n",
    "        Args:\n",
    "            corpus: Text corpus to train on\n",
    "            vocab_size: Target vocabulary size\n",
    "            suppress_output: Whether to suppress SentencePiece training logs\n",
    "        \"\"\"\n",
    "        # Create temporary file for corpus\n",
    "        with tempfile.NamedTemporaryFile(mode=\"w\", suffix=\".txt\", delete=False) as f:\n",
    "            f.write(corpus)\n",
    "            corpus_file = f.name\n",
    "\n",
    "        # Train both tokenizers immediately\n",
    "        self.tokenizer_bpe = self._train_bpe(corpus_file, vocab_size)\n",
    "        self.tokenizer_sp = self._train_sentencepiece(\n",
    "            corpus_file, vocab_size, suppress_output\n",
    "        )\n",
    "        self.tokenizer_wp = self._train_wordpiece(corpus_file, vocab_size)\n",
    "\n",
    "    @staticmethod\n",
    "    def _train_bpe(corpus_file: str, vocab_size: int) -> Tokenizer:\n",
    "        \"\"\"Train and return BPE tokenizer.\"\"\"\n",
    "        tokenizer = Tokenizer(BPE())\n",
    "        tokenizer.pre_tokenizer = ByteLevel()\n",
    "        trainer = BpeTrainer(\n",
    "            vocab_size=vocab_size, min_frequency=1, special_tokens=[\"[UNK]\"]\n",
    "        )\n",
    "        tokenizer.train([corpus_file], trainer)\n",
    "        tokenizer.model.unk_token = \"[UNK]\"\n",
    "        return tokenizer\n",
    "\n",
    "    @staticmethod\n",
    "    def _train_wordpiece(corpus_file: str, vocab_size: int) -> Tokenizer:\n",
    "        \"\"\"Train and return WordPiece tokenizer.\"\"\"\n",
    "        tokenizer = Tokenizer(WordPiece(unk_token=\"[UNK]\"))\n",
    "        tokenizer.pre_tokenizer = Whitespace()\n",
    "        trainer = WordPieceTrainer(\n",
    "            vocab_size=vocab_size, min_frequency=1, special_tokens=[\"[UNK]\"]\n",
    "        )\n",
    "        tokenizer.train([corpus_file], trainer)\n",
    "        return tokenizer\n",
    "\n",
    "    @staticmethod\n",
    "    def _train_sentencepiece(corpus_file: str, vocab_size: int, suppress_output: bool):\n",
    "        \"\"\"Train and return SentencePiece tokenizer (with optional output suppression).\"\"\"\n",
    "        sp_prefix = os.path.join(tempfile.gettempdir(), f\"sp_model_{os.getpid()}\")\n",
    "\n",
    "        if suppress_output:\n",
    "            # Redirect file descriptors 1 (stdout) and 2 (stderr) to /dev/null\n",
    "            # This works for C++ subprocesses, unlike contextlib.redirect_*\n",
    "            devnull_fd = os.open(os.devnull, os.O_WRONLY)\n",
    "            old_stdout = os.dup(1)\n",
    "            old_stderr = os.dup(2)\n",
    "\n",
    "            try:\n",
    "                os.dup2(devnull_fd, 1)\n",
    "                os.dup2(devnull_fd, 2)\n",
    "\n",
    "                spm.SentencePieceTrainer.train(\n",
    "                    input=corpus_file,\n",
    "                    model_prefix=sp_prefix,\n",
    "                    vocab_size=vocab_size,\n",
    "                    model_type=\"bpe\",\n",
    "                    character_coverage=1.0,\n",
    "                )\n",
    "            finally:\n",
    "                os.dup2(old_stdout, 1)\n",
    "                os.dup2(old_stderr, 2)\n",
    "                os.close(old_stdout)\n",
    "                os.close(old_stderr)\n",
    "                os.close(devnull_fd)\n",
    "        else:\n",
    "            spm.SentencePieceTrainer.train(\n",
    "                input=corpus_file,\n",
    "                model_prefix=sp_prefix,\n",
    "                vocab_size=vocab_size,\n",
    "                model_type=\"bpe\",\n",
    "                character_coverage=1.0,\n",
    "            )\n",
    "\n",
    "        return spm.SentencePieceProcessor(model_file=f\"{sp_prefix}.model\")\n",
    "\n",
    "    def encode_bpe(self, text: str) -> list[str]:\n",
    "        \"\"\"Encode text with BPE.\"\"\"\n",
    "        return self.tokenizer_bpe.encode(text).tokens\n",
    "\n",
    "    def encode_wp(self, text: str) -> list[str]:\n",
    "        \"\"\"Encode text with WordPiece.\"\"\"\n",
    "        return self.tokenizer_wp.encode(text).tokens\n",
    "\n",
    "    def encode_sp(self, text: str) -> list[str]:\n",
    "        \"\"\"Encode text with SentencePiece.\"\"\"\n",
    "        ids = self.tokenizer_sp.encode(text, out_type=int)\n",
    "        return [self.tokenizer_sp.id_to_piece(i) for i in ids]\n",
    "\n",
    "    def compare(self, text: str) -> tuple[list[str], list[str]]:\n",
    "        \"\"\"Encode text with both tokenizers and return results.\"\"\"\n",
    "        return self.encode_bpe(text), self.encode_sp(text), self.encode_wp(text)\n",
    "\n",
    "    def get_vocab_sp(self) -> dict[int, str]:\n",
    "        \"\"\"Get SentencePiece vocabulary as {id: piece} dict.\"\"\"\n",
    "        vocab_size = self.tokenizer_sp.vocab_size()\n",
    "        return {self.tokenizer_sp.id_to_piece(i): i for i in range(vocab_size)}\n",
    "\n",
    "    def get_vocab_bpe(self) -> dict[int, str]:\n",
    "        \"\"\"Get BPE vocabulary as {id: token} dict.\"\"\"\n",
    "        return self.tokenizer_bpe.get_vocab()\n",
    "\n",
    "    def get_vocab_wp(self) -> dict[int, str]:\n",
    "        \"\"\"Get WordPiece vocabulary as {id: token} dict.\"\"\"\n",
    "        return self.tokenizer_wp.get_vocab()\n",
    "\n",
    "\n",
    "def print_comparison(name: str, corpus: str, examples: list[str], vocab_size: int = 50):\n",
    "    \"\"\"\n",
    "    Helper to train and compare tokenizers.\n",
    "\n",
    "    Args:\n",
    "        name: Name of this comparison (printed as header)\n",
    "        corpus: Corpus to train on\n",
    "        examples: List of text examples to encode and compare\n",
    "        vocab_size: Vocabulary size for training\n",
    "    \"\"\"\n",
    "    trainer = TokenizerTrainer(corpus, vocab_size=vocab_size)\n",
    "\n",
    "    print(\"\\n\" + \"-\" * 80)\n",
    "    print(f\"--- {name} ---\")\n",
    "    print(\"-\" * 80 + \"\\n\")\n",
    "\n",
    "    for example in examples:\n",
    "        bpe_tokens, sp_tokens, wp_tokens = trainer.compare(example)\n",
    "        print(f\"Text: {example!r}\")\n",
    "        print(f\"  BPE:           {bpe_tokens}\")\n",
    "        print(f\"  SentencePiece: {sp_tokens}\")\n",
    "        print(f\"  WordPiece:     {wp_tokens}\")\n",
    "        print()\n",
    "\n",
    "    return trainer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8d27746e",
   "metadata": {},
   "outputs": [],
   "source": [
    "corpus = (\n",
    "    \"\"\"book booker booking booked bookshelf bookcase bookkeeper\n",
    "reading reader readers reads reading bookshelf\n",
    "teacher teaching teaches taught classroom\n",
    "learning learner learns learned education\n",
    "running runner runs run quickly running\n",
    "\"\"\"\n",
    "    * 10\n",
    ")\n",
    "\n",
    "examples = [\n",
    "    \"book\",\n",
    "    \"booker\",\n",
    "    \"booking\",\n",
    "    \"booked\",\n",
    "    \"bookshelf\",\n",
    "    \"book shelf\",\n",
    "    \"bookshélf\",\n",
    "]\n",
    "\n",
    "trainer = print_comparison(\n",
    "    \"BPE vs SentencePiece Space Handling\", corpus, examples, vocab_size=50\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d663f6f0",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "display(HTML(\"<b>BPE vocabulary</b>\"))\n",
    "print(\" \".join(sorted([k for k, v in trainer.get_vocab_bpe().items()])))\n",
    "\n",
    "display(HTML(\"<b>WordPiece vocabulary</b>\"))\n",
    "print(\" \".join(sorted([k for k, v in trainer.get_vocab_wp().items()])))\n",
    "\n",
    "display(HTML(\"<b>SentencePiece vocabulary</b>\"))\n",
    "print(\" \".join(sorted([k for k, v in trainer.get_vocab_sp().items()])))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5b8f225f",
   "metadata": {},
   "source": [
    "**Exercise:** Try to find small datasets such that the WordPiece, BPE and/or SentencePiece behave differently, and try to explain why.\n",
    "\n",
    "**Tips for exploration:**\n",
    "- Try corpora with different characteristics (repetitive patterns, rare characters, different word lengths)\n",
    "- Look at how each algorithm handles spaces and special characters\n",
    "- Compare the vocabularies learned by each tokenizer\n",
    "- Experiment with different vocabulary sizes to see how it affects tokenization\n",
    "\n",
    "**Example questions to investigate:**\n",
    "- How do the algorithms handle words not seen during training?\n",
    "- What happens with accented characters or special symbols?\n",
    "- How does vocabulary size affect the granularity of tokenization?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2ca2ddde",
   "metadata": {},
   "outputs": [],
   "source": [
    "# [[STUDENT]]...\n",
    "\n",
    "assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1877d934",
   "metadata": {},
   "source": [
    "# Exercise 2: Looking at (contextual) embeddings\n",
    "\n",
    "The goal of this exercise is to look at how embeddings evolve within a transformer.\n",
    "We will use a few sentences containing an ambiguous English word, \"lead\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "53641e65",
   "metadata": {},
   "outputs": [],
   "source": [
    "pd.DataFrame(\n",
    "    [\n",
    "        [\"guide\", \"The captain will lead the team to victory.\"],\n",
    "        [\"guide\", \"She leads him by the hand through the dark corridor.\"],\n",
    "    ],\n",
    "    columns=[\"marker\", \"sentence\"],\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4cc0430c",
   "metadata": {},
   "outputs": [],
   "source": [
    "df_sentences = pd.DataFrame(\n",
    "    [\n",
    "        # Sense 1: \"lead\" (verb) = to guide or direct\n",
    "        [\"guide\", \"The captain will lead the team to victory.\"],\n",
    "        [\"guide\", \"They lead him by the hand through the dark corridor.\"],\n",
    "        [\"guide\", \"The roads lead to the village.\"],\n",
    "        [\"guide\", \"These evidences lead us to believe he is guilty.\"],\n",
    "        [\"guide\", \"Good teachers lead students to discover answers themselves.\"],\n",
    "        # Sense 2: \"lead\" (noun) = the metal (pronounced \"led\")\n",
    "        [\"metal\", \"The old pipes contained lead and needed replacement.\"],\n",
    "        [\"metal\", \"Lead is a toxic heavy metal.\"],\n",
    "        [\"metal\", \"The artist used lead in the stained glass window.\"],\n",
    "        [\"metal\", \"Lead weights are used in fishing.\"],\n",
    "        [\"metal\", \"Gasoline with lead was banned decades ago.\"],\n",
    "        # Sense 3: \"lead\" (noun) = main role or position\n",
    "        [\"main\", \"She played the lead in the school play.\"],\n",
    "        [\"main\", \"The lead singer of the band quit yesterday.\"],\n",
    "        [\"main\", \"He took the lead in the race.\"],\n",
    "        [\"main\", \"The company currently has a lead of 10 points.\"],\n",
    "        [\"main\", \"Our team has a commanding lead in the championship.\"],\n",
    "        # Sense 4: \"lead\" (noun) = a clue or tip\n",
    "        [\"clue\", \"The detective followed a promising lead.\"],\n",
    "        [\"clue\", \"We got a new lead on the missing person.\"],\n",
    "        [\"clue\", \"The tip provided a solid lead for the investigation.\"],\n",
    "        [\"clue\", \"Sale lead were distributed to the team.\"],\n",
    "    ],\n",
    "    columns=[\"marker\", \"sentence\"],\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8e0b87ee",
   "metadata": {},
   "source": [
    "In this exercise, we use [DistillBERT](https://huggingface.co/distilbert/distilbert-base-uncased), a small model.\n",
    "\n",
    "In the next cell, we load an encoder model, `distilbert-base-uncased`, and its associated tokenizer.\n",
    "\n",
    "Have a look at the configuration and PyTorch model, and try to understand the architecture and settings of the model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0f7fbbc3",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "model_name = \"distilbert-base-uncased\"\n",
    "tokenizer = load_hf_tokenizer(model_name)\n",
    "model = load_hf_model(model_name, AutoModel, output_hidden_states=True)\n",
    "model.to(device)\n",
    "model.eval()\n",
    "\n",
    "print(\"Configuration\")\n",
    "print(model.config)\n",
    "print()\n",
    "\n",
    "print(\"Model\")\n",
    "print(model)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a02e8657",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Extract Embeddings Helper\n",
    "\n",
    "### Understanding the `process_sentences` function\n",
    "\n",
    "The `process_sentences(df, model, tokenizer)` function processes a DataFrame of sentences through a transformer model and extracts embeddings at all layers.\n",
    "\n",
    "**Input:**\n",
    "- `df`: A DataFrame with a 'sentence' column (and potentially other metadata columns)\n",
    "- `model`: A transformer model (must have `output_hidden_states=True`)\n",
    "- `tokenizer`: The corresponding tokenizer\n",
    "\n",
    "**Output:**\n",
    "- `df_out`: An expanded DataFrame where each row represents one token, with columns:\n",
    "  - Original columns from input df\n",
    "  - `ix`: Global token index (unique across all sentences)\n",
    "  - `sentence_ix`: Index of the source sentence\n",
    "  - `token_ix`: Position of token within its sentence\n",
    "  - `token`: The actual token string\n",
    "- `embeddings`: A list indexed by `ix`, where each entry contains embeddings from all layers:\n",
    "  - `embeddings[ix][0]`: Word embedding (layer 0, before any transformer processing)\n",
    "  - `embeddings[ix][1]`: Output of 1st transformer layer\n",
    "  - `embeddings[ix][n]`: Output of nth transformer layer\n",
    "\n",
    "**Usage example:** After processing, you can select tokens of interest from `df_out` and visualize their embeddings across layers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "94d615b0",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "@torch.no_grad\n",
    "def process_sentences(\n",
    "    df: pd.DataFrame, model, tokenizer\n",
    ") -> tuple[pd.DataFrame, list[torch.Tensor]]:\n",
    "    \"\"\"\n",
    "    Process sentences through a transformer encoder.\n",
    "\n",
    "    Returns:\n",
    "        - DataFrame with columns: [original columns] + ix, sentence_ix, token_ix, token\n",
    "        - List of embeddings indexed by ix: [word_embedding, layer_1, ..., layer_n]\n",
    "    \"\"\"\n",
    "    device = next(model.parameters()).device\n",
    "    model.eval()\n",
    "\n",
    "    rows = []\n",
    "    embeddings = []\n",
    "    global_ix = 0\n",
    "\n",
    "    for sentence_ix, row in tqdm(df.iterrows(), total=len(df)):\n",
    "        sentence = row[\"sentence\"]\n",
    "\n",
    "        # Tokenize\n",
    "        encoded = tokenizer(sentence, return_tensors=\"pt\").to(device)\n",
    "\n",
    "        # Get all hidden states\n",
    "        outputs = model(**encoded, output_hidden_states=True)\n",
    "\n",
    "        # Extract token info\n",
    "        tokens = tokenizer.convert_ids_to_tokens(encoded[\"input_ids\"][0])\n",
    "\n",
    "        word_embeddings = model.embeddings.word_embeddings(encoded[\"input_ids\"])[0].to(\n",
    "            \"cpu\"\n",
    "        )\n",
    "\n",
    "        # Skip special tokens at start/end if needed\n",
    "        for token_ix, token in enumerate(tokens):\n",
    "            # Collect all layer embeddings for this token\n",
    "            token_embeddings = [word_embeddings[token_ix]] + [\n",
    "                outputs.hidden_states[layer_idx][0, token_ix].cpu()\n",
    "                for layer_idx in range(len(outputs.hidden_states))\n",
    "            ]\n",
    "\n",
    "            embeddings.append(token_embeddings)\n",
    "\n",
    "            # Create row\n",
    "            new_row = row.to_dict()\n",
    "            new_row.update(\n",
    "                {\n",
    "                    \"ix\": global_ix,\n",
    "                    \"sentence_ix\": sentence_ix,\n",
    "                    \"token_ix\": token_ix,\n",
    "                    \"token\": token,\n",
    "                }\n",
    "            )\n",
    "            rows.append(new_row)\n",
    "\n",
    "            global_ix += 1\n",
    "\n",
    "    df_out = pd.DataFrame(rows)\n",
    "    return df_out, embeddings\n",
    "\n",
    "\n",
    "df, embeddings = process_sentences(df_sentences, model, tokenizer)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "af11cce8",
   "metadata": {},
   "source": [
    "### Understanding the Visualization Helper Functions\n",
    "\n",
    "The following cells define several helper functions for analyzing and visualizing embeddings. These functions are hidden but documented here:\n",
    "\n",
    "#### `compute_pca_projection(df_selection, embeddings, layer_ix)`\n",
    "Reduces high-dimensional embeddings to 2D using PCA for visualization.\n",
    "- **Returns:** DataFrame with added `x1`, `x2` columns (the 2D coordinates)\n",
    "\n",
    "#### `show_pca_projection(df_selection, embeddings, layer_ix, group=None, grey=None, label=None)`\n",
    "Visualizes embeddings in 2D space after PCA projection.\n",
    "- `group`: pandas Series for coloring points by category (e.g., word sense)\n",
    "- `grey`: pandas bool Series to mark points as grey (background context)\n",
    "- `label`: pandas bool Series to show token labels on the plot\n",
    "- **Use case:** See how tokens cluster based on context/meaning\n",
    "\n",
    "#### `show_similarities(df_selection, embeddings, layer_ix, group=None, similarity='cosine')`\n",
    "Creates a heatmap showing pairwise similarities between token embeddings.\n",
    "- `similarity`: 'cosine' (normalized) or 'inner' (dot product)\n",
    "- `group`: pandas Series to organize and group tokens in the heatmap\n",
    "- **Use case:** Quantify how similar different token occurrences are\n",
    "\n",
    "**How to use these functions:**\n",
    "1. Select tokens from `df` (e.g., `df[df.token == \"lead\"]`)\n",
    "2. Choose a layer to analyze (0 = word embeddings, 1-6 = transformer layers for DistilBERT)\n",
    "3. Optionally specify grouping (e.g., by word sense) for better visualization"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ef77c2f3",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "def compute_pca_projection(\n",
    "    df_selection: pd.DataFrame, embeddings: list[torch.Tensor], layer_ix: int\n",
    ") -> pd.DataFrame:\n",
    "    \"\"\"\n",
    "    Compute 2D PCA projection for selected tokens at a given layer.\n",
    "\n",
    "    Args:\n",
    "        df_selection: Selected rows from df_out\n",
    "        embeddings: List of embeddings from process_sentences\n",
    "        layer_ix: Which layer to project (0 = token embeddings, 1+ = transformer layers)\n",
    "\n",
    "    Returns:\n",
    "        DataFrame with x1, x2 columns added\n",
    "    \"\"\"\n",
    "    # Extract embeddings for selected tokens\n",
    "    token_embeddings = []\n",
    "    for ix in df_selection[\"ix\"].values:\n",
    "        token_embeddings.append(embeddings[ix][layer_ix].numpy())\n",
    "\n",
    "    # Stack into matrix\n",
    "    X = np.stack(token_embeddings)\n",
    "\n",
    "    # Apply PCA\n",
    "    pca = PCA(n_components=2)\n",
    "    projections = pca.fit_transform(X)\n",
    "\n",
    "    # Add to dataframe\n",
    "    df_result = df_selection.copy()\n",
    "    df_result[\"x1\"] = projections[:, 0]\n",
    "    df_result[\"x2\"] = projections[:, 1]\n",
    "\n",
    "    return df_result\n",
    "\n",
    "\n",
    "def show_pca_projection(\n",
    "    df_selection,\n",
    "    embeddings,\n",
    "    layer_ix,\n",
    "    group=None,\n",
    "    grey=None,\n",
    "    label=None,\n",
    "    figsize=(6, 5),\n",
    "):\n",
    "    \"\"\"\n",
    "    Visualize PCA projection with optional grouping and labeling.\n",
    "\n",
    "    Args:\n",
    "        df_selection: Selected rows from df_out\n",
    "        embeddings: List of embeddings from process_sentences\n",
    "        layer_ix: Which layer to project\n",
    "        group: Optional pandas Series (same length as df_selection) with group identifiers to color points\n",
    "        grey: Optional pandas bool Series (same length as df_selection) marking points as grey\n",
    "        label: Optional pandas bool Series (same length as df_selection) indicating which tokens to label\n",
    "    \"\"\"\n",
    "    # Compute PCA\n",
    "    df_pca = compute_pca_projection(df_selection, embeddings, layer_ix)\n",
    "\n",
    "    fig, ax = plt.subplots(figsize=figsize)\n",
    "\n",
    "    # Get indices for proper alignment with Series\n",
    "    indices = df_pca.index\n",
    "\n",
    "    # Handle grouping and coloring\n",
    "    if group is not None:\n",
    "        groups = group.loc[indices].unique()\n",
    "        colors = plt.cm.tab10(np.linspace(0, 1, len(groups)))\n",
    "        group_colors = {g: colors[i] for i, g in enumerate(groups)}\n",
    "\n",
    "        for group_val in groups:\n",
    "            mask = group.loc[indices] == group_val\n",
    "            if grey is not None:\n",
    "                mask = mask & ~grey.loc[indices]\n",
    "\n",
    "            ax.scatter(\n",
    "                df_pca.loc[mask, \"x1\"],\n",
    "                df_pca.loc[mask, \"x2\"],\n",
    "                c=[group_colors[group_val]],\n",
    "                label=str(group_val),\n",
    "                alpha=0.7,\n",
    "                s=50,\n",
    "            )\n",
    "    else:\n",
    "        ax.scatter(df_pca[\"x1\"], df_pca[\"x2\"], alpha=0.7, s=50, color=\"steelblue\")\n",
    "\n",
    "    # Grey points (not in any group)\n",
    "    if grey is not None:\n",
    "        grey_mask = grey.loc[indices]\n",
    "        ax.scatter(\n",
    "            df_pca.loc[grey_mask, \"x1\"],\n",
    "            df_pca.loc[grey_mask, \"x2\"],\n",
    "            c=\"lightgrey\",\n",
    "            alpha=0.5,\n",
    "            s=50,\n",
    "        )\n",
    "\n",
    "    # Add token labels where indicated\n",
    "    if label is not None:\n",
    "        label_mask = label.loc[indices]\n",
    "        for idx in df_pca.loc[label_mask].index:\n",
    "            row = df_pca.loc[idx]\n",
    "            ax.annotate(row[\"token\"], (row[\"x1\"], row[\"x2\"]), fontsize=9)\n",
    "\n",
    "    ax.set_xlabel(\"PC1\")\n",
    "    ax.set_ylabel(\"PC2\")\n",
    "    if group is not None:\n",
    "        ax.legend(title=\"Group\")\n",
    "    ax.set_title(f\"PCA Projection (Layer {layer_ix})\")\n",
    "\n",
    "    plt.tight_layout()\n",
    "    plt.show()\n",
    "\n",
    "\n",
    "def show_similarities(\n",
    "    df_selection, embeddings, layer_ix, group=None, similarity=\"cosine\", figsize=(6, 5)\n",
    "):\n",
    "    \"\"\"\n",
    "    Visualize token similarities as a heatmap with optional group dividers.\n",
    "\n",
    "    Args:\n",
    "        df_selection: Selected rows from df_out\n",
    "        embeddings: List of embeddings from process_sentences\n",
    "        layer_ix: Which layer to use\n",
    "        group: Optional pandas Series (same length as df_selection) to group and organize tokens\n",
    "        similarity: 'cosine' or 'inner'\n",
    "    \"\"\"\n",
    "    # Extract embeddings for selected tokens\n",
    "    token_embeddings = []\n",
    "    for ix in df_selection[\"ix\"].values:\n",
    "        token_embeddings.append(embeddings[ix][layer_ix].numpy())\n",
    "\n",
    "    X = np.stack(token_embeddings)\n",
    "\n",
    "    # Compute similarity matrix\n",
    "    if similarity == \"cosine\":\n",
    "        sim_matrix = cosine_similarity(X)\n",
    "    elif similarity == \"inner\":\n",
    "        sim_matrix = np.dot(X, X.T)\n",
    "    else:\n",
    "        raise ValueError(\"similarity must be 'cosine' or 'inner'\")\n",
    "\n",
    "    # Create labels and optionally reorder by group\n",
    "    tokens = df_selection[\"token\"].values\n",
    "    sentence_ixs = df_selection[\"sentence_ix\"].values\n",
    "    indices = df_selection.index\n",
    "    group_boundaries = []\n",
    "\n",
    "    if group is not None:\n",
    "        group_vals = group.loc[indices].values\n",
    "        sort_idx = np.argsort(group_vals)\n",
    "\n",
    "        sim_matrix = sim_matrix[np.ix_(sort_idx, sort_idx)]\n",
    "        tokens = tokens[sort_idx]\n",
    "        sentence_ixs = sentence_ixs[sort_idx]\n",
    "        group_vals = group_vals[sort_idx]\n",
    "\n",
    "        labels = [\n",
    "            f\"{token}(s{sentence_ixs[i]}, {group_vals[i]})\"\n",
    "            for i, token in enumerate(tokens)\n",
    "        ]\n",
    "\n",
    "        # Find group boundaries\n",
    "        for i in range(1, len(group_vals)):\n",
    "            if group_vals[i] != group_vals[i - 1]:\n",
    "                group_boundaries.append(i - 0.5)\n",
    "    else:\n",
    "        labels = [f\"{token}(s{sentence_ixs[i]})\" for i, token in enumerate(tokens)]\n",
    "\n",
    "    # Plot\n",
    "    fig, ax = plt.subplots(figsize=figsize)\n",
    "\n",
    "    # Set vmin/vmax only for cosine\n",
    "    if similarity == \"cosine\":\n",
    "        im = ax.imshow(sim_matrix, cmap=\"coolwarm\", aspect=\"auto\", vmin=-1, vmax=1)\n",
    "    else:\n",
    "        im = ax.imshow(sim_matrix, cmap=\"coolwarm\", aspect=\"auto\")\n",
    "\n",
    "    ax.set_xticks(np.arange(len(labels)))\n",
    "    ax.set_yticks(np.arange(len(labels)))\n",
    "    ax.set_xticklabels(labels, rotation=45, ha=\"right\", fontsize=9)\n",
    "    ax.set_yticklabels(labels, fontsize=9)\n",
    "\n",
    "    # Draw group dividers\n",
    "    for boundary in group_boundaries:\n",
    "        ax.axhline(y=boundary, color=\"black\", linewidth=2)\n",
    "        ax.axvline(x=boundary, color=\"black\", linewidth=2)\n",
    "\n",
    "    cbar = plt.colorbar(im, ax=ax)\n",
    "    cbar.set_label(similarity)\n",
    "    ax.set_title(f\"Token Similarities - {similarity} (Layer {layer_ix})\")\n",
    "\n",
    "    plt.tight_layout()\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cba4c23d",
   "metadata": {},
   "outputs": [],
   "source": [
    "df[df.token == \"lead\"].head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e59a493f",
   "metadata": {},
   "outputs": [],
   "source": [
    "df_lead = df[df.token == \"lead\"]\n",
    "\n",
    "show_pca_projection(df_lead, embeddings, layer_ix=6, group=df_lead.marker)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "75922570",
   "metadata": {},
   "outputs": [],
   "source": [
    "show_similarities(df_lead, embeddings, layer_ix=2, group=df.marker, similarity=\"inner\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0bba0bf9",
   "metadata": {},
   "source": [
    "**Question:** How can you interpret those results?\n",
    "\n",
    "**Things to consider:**\n",
    "- Do embeddings of \"lead\" with the same meaning cluster together?\n",
    "- How do the embeddings change across different layers? (Try comparing layer 0, 3, and 6)\n",
    "- What does high/low cosine similarity tell you about contextual understanding?\n",
    "- Are the word embeddings (layer 0) context-aware, or does contextualization happen in later layers?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7e1f0dc7",
   "metadata": {},
   "source": [
    "## Exercise: Coreference Resolution\n",
    "\n",
    "Now, try to use the same kind of analysis to look into another linguistic phenomenon: **coreference** (anaphora resolution).\n",
    "\n",
    "**Background:** Coreference occurs when different words refer to the same entity. For example:\n",
    "- \"John went to the store. **He** bought milk.\" — \"He\" refers to \"John\"\n",
    "- \"The cat chased **its** tail.\" — \"its\" refers to \"The cat\"\n",
    "\n",
    "**Your task:**\n",
    "1. Create sentences with clear coreference relationships (pronouns referring to nouns)\n",
    "2. Process them through the model using `process_sentences`\n",
    "3. Use `show_pca_projection` and `show_similarities` to analyze:\n",
    "   - Do pronoun embeddings become similar to their referents in deeper layers?\n",
    "   - At which layer does the model seem to \"resolve\" coreferences?\n",
    "4. Try examples with ambiguous pronouns to see how the model handles them\n",
    "\n",
    "**Starter code below** shows a basic example. Try modifying it to explore different scenarios!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5d5f9915",
   "metadata": {},
   "outputs": [],
   "source": [
    "# [[STUDENT]]...\n",
    "\n",
    "assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "108a04e0",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "# Exercise 3: Attention Visualization with BertViz\n",
    "\n",
    "In this exercise, we'll visualize the attention patterns learned by the transformer model. Attention mechanisms allow the model to focus on different parts of the input when processing each token.\n",
    "\n",
    "**BertViz** provides interactive visualizations of attention weights across:\n",
    "- **Heads**: The model uses multiple attention heads (DistilBERT has 12 heads per layer)\n",
    "- **Layers**: DistilBERT has 6 layers, each learning different patterns\n",
    "\n",
    "**What to look for:**\n",
    "- Do certain heads specialize in specific patterns (e.g., attending to previous words, next words, or syntactic dependencies)?\n",
    "- How do attention patterns change across layers?\n",
    "- Can you identify heads that might be learning linguistic phenomena (syntax, semantics)?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d40c053e",
   "metadata": {},
   "source": [
    "## Step 3.1: Load Attention Model\n",
    "\n",
    "We load the same model but with `output_attentions=True` to extract attention weights."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3b61445a",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "model_attn = load_hf_model(model_name, AutoModel, output_attentions=True)\n",
    "model_attn.to(device)\n",
    "model_attn.eval()\n",
    "print(\"Model loaded\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ab868d2d",
   "metadata": {},
   "source": [
    "## Step 3.2: Head View\n",
    "\n",
    "The **head view** shows attention from each token to all other tokens, for each attention head.\n",
    "\n",
    "**How to use:**\n",
    "- Click on a token to see where it attends\n",
    "- Compare different heads to see if they learn different patterns\n",
    "- Darker lines = stronger attention\n",
    "\n",
    "**Try these experiments:**\n",
    "- Does \"the\" attend strongly to the noun it modifies?\n",
    "- Do verbs attend to their subjects or objects?\n",
    "- Try longer, more complex sentences to see clearer patterns"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f17c0f73",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "text = \"The cat sat on the mat.\"\n",
    "inputs = tokenizer.encode(text, return_tensors=\"pt\").to(device)\n",
    "tokens = tokenizer.convert_ids_to_tokens(inputs[0])\n",
    "\n",
    "with torch.no_grad():\n",
    "    outputs = model_attn(inputs, output_attentions=True)\n",
    "    attention = outputs[-1]\n",
    "\n",
    "print(f\"Text: {text}\")\n",
    "head_view(attention, tokens)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "73bac51b",
   "metadata": {},
   "source": [
    "## Step 3.3: Model View\n",
    "\n",
    "The **model view** shows attention across all layers and heads simultaneously, allowing you to see how attention patterns evolve through the network.\n",
    "\n",
    "**How to use:**\n",
    "- Rows = layers, Columns = heads\n",
    "- Click on any head to see its attention pattern\n",
    "- Compare early layers (bottom) vs. late layers (top)\n",
    "\n",
    "**Questions to explore:**\n",
    "- Do early layers capture local/syntactic patterns while later layers capture semantic relationships?\n",
    "- Which layer seems most important for understanding the sentence meaning?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f36d425e",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "text = \"Alice gave the book to Bob.\"\n",
    "inputs = tokenizer.encode(text, return_tensors=\"pt\").to(device)\n",
    "tokens = tokenizer.convert_ids_to_tokens(inputs[0])\n",
    "\n",
    "with torch.no_grad():\n",
    "    outputs = model_attn(inputs, output_attentions=True)\n",
    "    attention = outputs[-1]\n",
    "\n",
    "model_view(attention, tokens)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "908e66a6",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "# Exercise 4: Self-Attention Implementation\n",
    "\n",
    "In this exercise, we will implement multi-head self-attention. In order to test its behavior, we will use a simple toy dataset."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c6d3540d",
   "metadata": {},
   "source": [
    "## Token Matching Task\n",
    "\n",
    "For each token at position $i$ with value $t_i$, classify it as 1 if:\n",
    "1. The value $(t_i - 1)$ appears **somewhere before** position $i$, AND\n",
    "2. The value $(t_i + 1)$ appears **somewhere after** position $i$\n",
    "\n",
    "Otherwise classify as 0.\n",
    "\n",
    "**Example**: `5 3 4 1 5 6` → `0 0 1 0 1 0`\n",
    "\n",
    "| Pos | Token | Need (t-1) | Need (t+1) | Before? | After? | Label |\n",
    "|-----|-------|-----------|-----------|---------|--------|-------|\n",
    "| 0   | 5     | 4         | 6         | ✗       | ✓      | 0     |\n",
    "| 1   | 3     | 2         | 4         | ✗       | ✓      | 0     |\n",
    "| 2   | 4     | 3         | 5         | ✓ (pos 1) | ✓ (pos 4) | **1** |\n",
    "| 3   | 1     | 0         | 2         | ✗       | ✗      | 0     |\n",
    "| 4   | 5     | 4         | 6         | ✓ (pos 2) | ✓ (pos 5) | **1** |\n",
    "| 5   | 6     | 5         | 7         | ✓ (pos 4) | ✗      | 0     |\n",
    "\n",
    "**Example**: `1 2 3 2 3` → `0 1 1 0 0`\n",
    "\n",
    "| Pos | Token | Need (t-1) | Need (t+1) | Before? | After? | Label |\n",
    "|-----|-------|-----------|-----------|---------|--------|-------|\n",
    "| 0   | 1     | 0         | 2         | ✗       | ✓      | 0     |\n",
    "| 1   | 2     | 1         | 3         | ✓ (pos 0) | ✓ (pos 2) | **1** |\n",
    "| 2   | 3     | 2         | 4         | ✓ (pos 1) | ✗      | 0     |\n",
    "| 3   | 2     | 1         | 3         | ✓ (pos 0) | ✓ (pos 4) | **1** |\n",
    "| 4   | 3     | 2         | 4         | ✓ (pos 3) | ✗      | 0     |\n",
    "\n",
    "**Why this task for attention?** The model must learn to:\n",
    "1. Lookup what values need to be found (t-1 and t+1)\n",
    "2. Search the left context and right context\n",
    "3. Use attention patterns to gather evidence across positions"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cdc82bb3",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## The Toy Dataset\n",
    "\n",
    "### Understanding the `TokenMatchingDataset` Class\n",
    "\n",
    "This dataset generates sequences and labels for the token matching task described above.\n",
    "\n",
    "**Constructor parameters:**\n",
    "- `num_sequences`: Number of random sequences to generate\n",
    "- `seq_length`: Length of each sequence\n",
    "- `vocab_size`: Number of possible token values (0 to vocab_size-1)\n",
    "- `seed`: Random seed for reproducibility\n",
    "\n",
    "**Output format:**\n",
    "- `sequence`: A tensor of token IDs, e.g., `[5, 3, 4, 1, 5, 6]`\n",
    "- `labels`: Binary labels (0 or 1) for each position\n",
    "\n",
    "The dataset automatically computes labels based on the rule: label=1 if (t_i-1) appears before position i AND (t_i+1) appears after position i."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "82a5b358",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "class TokenMatchingDataset(Dataset):\n",
    "    def __init__(\n",
    "        self, num_sequences: int, seq_length: int, vocab_size: int, seed: int = None\n",
    "    ):\n",
    "        if seed is not None:\n",
    "            random.seed(seed)\n",
    "            torch.manual_seed(seed)\n",
    "\n",
    "        self.sequences = []\n",
    "        self.labels = []\n",
    "\n",
    "        for _ in range(num_sequences):\n",
    "            seq = torch.randint(0, vocab_size, (seq_length,))\n",
    "            labels = []\n",
    "\n",
    "            for i in range(seq_length):\n",
    "                t_i = seq[i].item()\n",
    "\n",
    "                # Check if t_i - 1 appears before position i\n",
    "                has_predecessor = any(seq[j].item() == t_i - 1 for j in range(i))\n",
    "\n",
    "                # Check if t_i + 1 appears after position i\n",
    "                has_successor = any(\n",
    "                    seq[j].item() == t_i + 1 for j in range(i + 1, seq_length)\n",
    "                )\n",
    "\n",
    "                label = 1 if (has_predecessor and has_successor) else 0\n",
    "                labels.append(label)\n",
    "\n",
    "            self.sequences.append(seq)\n",
    "            self.labels.append(torch.tensor(labels, dtype=torch.long))\n",
    "\n",
    "    def __len__(self):\n",
    "        return len(self.sequences)\n",
    "\n",
    "    def __getitem__(self, idx):\n",
    "        return {\n",
    "            \"sequence\": self.sequences[idx],\n",
    "            \"labels\": self.labels[idx],\n",
    "        }\n",
    "\n",
    "\n",
    "train_data = TokenMatchingDataset(200, 10, 6)\n",
    "val_data = TokenMatchingDataset(50, 10, 6)\n",
    "print(f\"Dataset: {len(train_data)} train, {len(val_data)} val\")\n",
    "\n",
    "print(train_data[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "729c5789",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Model Components\n",
    "\n",
    "### Positional Encoding\n",
    "\n",
    "Since self-attention doesn't inherently capture word order (it's permutation-invariant), we add **positional encodings** to give the model information about token positions.\n",
    "\n",
    "The `PositionalEncoding` class implements the sinusoidal positional encoding from the original Transformer paper:\n",
    "- Even dimensions use sine: $PE_{pos, 2i} = \\sin(pos / 10000^{2i/d})$\n",
    "- Odd dimensions use cosine: $PE_{pos, 2i+1} = \\cos(pos / 10000^{2i/d})$\n",
    "\n",
    "These are added to the token embeddings before passing through the attention mechanism."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8d113d8a",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "class PositionalEncoding(nn.Module):\n",
    "    def __init__(self, d_model, max_len=100):\n",
    "        super().__init__()\n",
    "        pe = torch.zeros(max_len, d_model)\n",
    "        pos = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)\n",
    "        div = torch.exp(\n",
    "            torch.arange(0, d_model, 2).float() * -(np.log(10000) / d_model)\n",
    "        )\n",
    "        pe[:, 0::2] = torch.sin(pos * div)\n",
    "        pe[:, 1::2] = torch.cos(pos * div)\n",
    "        self.register_buffer(\"pe\", pe.unsqueeze(0))\n",
    "\n",
    "    def forward(self, x):\n",
    "        return x + self.pe[:, : x.size(1), :]\n",
    "\n",
    "\n",
    "# -- Usage\n",
    "\n",
    "# Create a position embedding module\n",
    "pe = PositionalEncoding(128, 100)\n",
    "\n",
    "# Apply it to the output of a transformer (batch x max length x dimension)\n",
    "pe(torch.randn(2, 10, 128))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "488f7076",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Full Model Implementation\n",
    "\n",
    "### Understanding the Model Architecture\n",
    "\n",
    "Below we implement a complete self-attention model for the token matching task. The model consists of:\n",
    "\n",
    "1. **`Attention` class**: Implements scaled dot-product attention\n",
    "   - Computes attention scores: $\\text{scores} = QK^T / \\sqrt{d}$\n",
    "   - Applies softmax to get attention weights\n",
    "   - Returns weighted sum of values: $\\text{output} = \\text{softmax}(\\text{scores}) \\cdot V$\n",
    "\n",
    "2. **`SelfAttention` class**: The complete model with:\n",
    "   - **Token embeddings**: Convert token IDs to dense vectors\n",
    "   - **Positional encodings**: Add position information\n",
    "   - **Multi-head attention**: Learn multiple attention patterns simultaneously\n",
    "   - **Layer normalization**: Stabilize training\n",
    "   - **Classifier**: Final linear layer to predict 0 or 1 for each token\n",
    "\n",
    "### Implementation Exercise\n",
    "\n",
    "The `__init__` and `forward` methods have placeholders that you need to complete. The reference implementation is provided in the code but hidden from the notebook output.\n",
    "\n",
    "**Key concepts to implement:**\n",
    "- Multi-head attention: Split d-dimensional embeddings into `heads` separate attention computations\n",
    "- Each head works with dimension `d // heads`\n",
    "- Concatenate all head outputs and project with output layer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5c32cbcb",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "class Attention(nn.Module):\n",
    "    \"\"\"Scaled dot-product attention.\"\"\"\n",
    "\n",
    "    def forward(self, Q, K, V):\n",
    "        \"\"\"\n",
    "        Args:\n",
    "            Q: Query tensor of shape (B, L, d)\n",
    "            K: Key tensor of shape (B, L, d)\n",
    "            V: Value tensor of shape (B, L, d)\n",
    "\n",
    "        Returns:\n",
    "            output: Attention output of shape (B, L, d)\n",
    "            weights: Attention weights of shape (B, L, L)\n",
    "        \"\"\"\n",
    "        d = Q.size(-1)\n",
    "        # Compute attention scores: Q @ K^T / sqrt(d)\n",
    "        scores = torch.matmul(Q, K.transpose(-2, -1)) / np.sqrt(d)\n",
    "        # Apply softmax to get attention weights\n",
    "        weights = F.softmax(scores, dim=-1)\n",
    "        # Compute weighted sum of values\n",
    "        output = torch.matmul(weights, V)\n",
    "        return output, weights"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b8b9e4cc",
   "metadata": {},
   "outputs": [],
   "source": [
    "class SelfAttention(nn.Module):\n",
    "    def __init__(self, vocab_size=10, d=64, heads=4, max_len=64):\n",
    "        # Implement the initialization\n",
    "\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "    def forward(self, x):\n",
    "        # Implement the forward\n",
    "\n",
    "        assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "da59877e",
   "metadata": {},
   "source": [
    "## Training the Model on the Toy Dataset\n",
    "\n",
    "Now that the model has been defined, let's train it on our toy dataset.\n",
    "\n",
    "**Training details:**\n",
    "- **Loss function**: Binary Cross-Entropy with Logits (BCEWithLogitsLoss) - suitable for binary classification\n",
    "- **Optimizer**: AdamW with learning rate 1e-3 and weight decay for regularization\n",
    "- **Metrics**: Accuracy (percentage of correct predictions)\n",
    "- **Epochs**: 50 training iterations through the dataset\n",
    "\n",
    "**What to observe:**\n",
    "- Does the model achieve high accuracy (>90%)?\n",
    "- How quickly does it converge?\n",
    "- Is there overfitting (train accuracy >> val accuracy)?\n",
    "\n",
    "The training loop below will show progress and plot accuracy curves."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2c4a8b9a",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "vocab_size = 4\n",
    "seq_length = 10\n",
    "\n",
    "model = SelfAttention(vocab_size=vocab_size, d=36, heads=4, max_len=seq_length)\n",
    "model.to(device)\n",
    "\n",
    "dataset = TokenMatchingDataset(\n",
    "    num_sequences=3000, seq_length=seq_length, vocab_size=vocab_size, seed=42\n",
    ")\n",
    "train_set, val_set = random_split(dataset, [0.8, 0.2])\n",
    "\n",
    "train_loader = DataLoader(train_set, batch_size=32, shuffle=True)\n",
    "val_loader = DataLoader(val_set, batch_size=32, shuffle=False)\n",
    "\n",
    "criterion = nn.BCEWithLogitsLoss()\n",
    "optimizer = optim.AdamW(model.parameters(), lr=1e-3, weight_decay=1e-3)\n",
    "\n",
    "num_epochs = 50\n",
    "train_accs = []\n",
    "val_accs = []\n",
    "pb = tqdm(range(num_epochs))\n",
    "\n",
    "for epoch in pb:\n",
    "    # Training\n",
    "    model.train()\n",
    "    correct, total = 0, 0\n",
    "    for batch in tqdm(\n",
    "        train_loader, desc=f\"Epoch {epoch + 1}/{num_epochs}\", leave=False\n",
    "    ):\n",
    "        sequences = batch[\"sequence\"].to(device)\n",
    "        labels = batch[\"labels\"].float().to(device)\n",
    "\n",
    "        logits, _ = model(sequences)\n",
    "        loss = criterion(logits, labels)\n",
    "\n",
    "        optimizer.zero_grad()\n",
    "        loss.backward()\n",
    "        optimizer.step()\n",
    "\n",
    "        preds = (torch.sigmoid(logits) > 0.5).long()\n",
    "        correct += (preds == labels.long()).sum().item()\n",
    "        total += labels.numel()\n",
    "\n",
    "    train_acc = correct / total\n",
    "    train_accs.append(train_acc)\n",
    "\n",
    "    # Validation\n",
    "    model.eval()\n",
    "    correct, total = 0, 0\n",
    "    with torch.no_grad():\n",
    "        for batch in val_loader:\n",
    "            sequences = batch[\"sequence\"].to(device)\n",
    "            labels = batch[\"labels\"].float().to(device)\n",
    "            logits, _ = model(sequences)\n",
    "            preds = (torch.sigmoid(logits) > 0.5).long()\n",
    "            correct += (preds == labels.long()).sum().item()\n",
    "            total += labels.numel()\n",
    "\n",
    "    val_acc = correct / total\n",
    "    val_accs.append(val_acc)\n",
    "\n",
    "    pb.set_description(\n",
    "        f\"Epoch {epoch + 1}: Train Acc={train_acc:.4f}, Val Acc={val_acc:.4f}\"\n",
    "    )\n",
    "\n",
    "# Plot\n",
    "plt.figure(figsize=(10, 5))\n",
    "plt.plot(train_accs, label=\"Train Acc\")\n",
    "plt.plot(val_accs, label=\"Val Acc\")\n",
    "plt.xlabel(\"Epoch\")\n",
    "plt.ylabel(\"Accuracy\")\n",
    "plt.legend()\n",
    "plt.grid(True, alpha=0.3)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c5afd8f5",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "source": [
    "## Interpreting the Results\n",
    "\n",
    "**Question:** Can you explain what is happening by looking at the attention\n",
    "heads?\n",
    "\n",
    "**To investigate:**\n",
    "1. Look at the attention weights from the trained model\n",
    "2. Examine what patterns each head has learned:\n",
    "   - Does a head attend to specific token values or positions?\n",
    "   - Can you identify heads that look for predecessors (t-1) vs successors\n",
    "     (t+1)?\n",
    "3. Try visualizing attention for specific examples from the dataset\n",
    "4. Consider: How does the model solve this task using only attention?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6e4dd725",
   "metadata": {},
   "outputs": [],
   "source": [
    "#\n",
    "# Study the attention heads\n",
    "\n",
    "assert False, 'Not implemented yet'\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
