{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "309aa0e1",
   "metadata": {},
   "source": [
    "# Modern NLP, hands on\n",
    "\n",
    "Six short parts. Static word embeddings, contextual embeddings, attention\n",
    "built from scratch in NumPy, a look inside a real BERT, masked language\n",
    "modelling, and a fine tuned classifier. Run it top to bottom; a CPU runtime\n",
    "is enough throughout.\n",
    "\n",
    "This is the companion notebook to the site at playnlp.rajivchaitanya.com,\n",
    "where the same results are explorable in the browser. The site reads files\n",
    "produced by this code, so the two cannot disagree.\n",
    "\n",
    "| Part | Topic |\n",
    "|---|---|\n",
    "| 0 | Setup |\n",
    "| 1 | Static word embeddings (GloVe) |\n",
    "| 2 | Contextual embeddings (BERT) |\n",
    "| 3 | Attention from scratch (NumPy) |\n",
    "| 4 | Looking inside real BERT attention |\n",
    "| 5 | Masked language modelling |\n",
    "| 6 | Sentiment with a fine tuned transformer, plus exercises |\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d180ff4e",
   "metadata": {},
   "source": [
    "## Part 0. Setup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "98d61ef9",
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip -q install gensim\n",
    "import numpy as np, matplotlib.pyplot as plt, torch\n",
    "from transformers import AutoTokenizer, AutoModel, pipeline\n",
    "np.set_printoptions(precision=3, suppress=True)\n",
    "torch.manual_seed(0); np.random.seed(0)\n",
    "print(\"torch\", torch.__version__)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7b715687",
   "metadata": {},
   "source": [
    "## Part 1. Static word embeddings (GloVe)\n",
    "One vector per word type, learned from co-occurrence statistics. Geometry captures meaning, but a word has **one** vector no matter the context."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "409ece57",
   "metadata": {},
   "outputs": [],
   "source": [
    "import gensim.downloader as api\n",
    "glove = api.load(\"glove-wiki-gigaword-50\")   # 400k words, 50 dimensions\n",
    "print(glove[\"king\"][:8], \"... shape\", glove[\"king\"].shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c1fd3509",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Nearest neighbours: meaning as geometry\n",
    "for w in [\"engineer\", \"university\", \"python\"]:\n",
    "    print(w, \"->\", [x for x, _ in glove.most_similar(w, topn=6)])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "59660373",
   "metadata": {},
   "outputs": [],
   "source": [
    "# The famous analogy: king - man + woman\n",
    "print(glove.most_similar(positive=[\"king\", \"woman\"], negative=[\"man\"], topn=3))\n",
    "print(glove.most_similar(positive=[\"paris\", \"india\"], negative=[\"france\"], topn=3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "688adab2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2D picture of the space using PCA (done by hand with SVD)\n",
    "groups = {\n",
    "  \"countries\": [\"india\", \"france\", \"japan\", \"brazil\", \"canada\"],\n",
    "  \"capitals\":  [\"delhi\", \"paris\", \"tokyo\", \"brasilia\", \"ottawa\"],\n",
    "  \"animals\":   [\"tiger\", \"horse\", \"eagle\", \"dolphin\", \"rabbit\"],\n",
    "}\n",
    "words = [w for g in groups.values() for w in g]\n",
    "X = np.array([glove[w] for w in words]); X = X - X.mean(0)\n",
    "U, S, Vt = np.linalg.svd(X, full_matrices=False)\n",
    "P = X @ Vt[:2].T\n",
    "plt.figure(figsize=(7, 5))\n",
    "colors = [\"tab:blue\", \"tab:orange\", \"tab:green\"]\n",
    "i = 0\n",
    "for (name, ws), c in zip(groups.items(), colors):\n",
    "    for w in ws:\n",
    "        plt.scatter(*P[i], c=c); plt.annotate(w, P[i], fontsize=9); i += 1\n",
    "plt.title(\"GloVe vectors projected to 2D\"); plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "23c6ab07",
   "metadata": {},
   "outputs": [],
   "source": [
    "# The limitation: ONE vector for 'bank', whatever the sentence says\n",
    "print([x for x, _ in glove.most_similar(\"bank\", topn=8)])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b745fd9c",
   "metadata": {},
   "source": [
    "**Something to think about:** the neighbours of *bank* are mostly financial. What happened to the river sense?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6e3ea640",
   "metadata": {},
   "source": [
    "## Part 2. Contextual embeddings (BERT)\n",
    "BERT produces a different vector for each *occurrence* of a word, depending on the whole sentence."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "54b8fc45",
   "metadata": {},
   "outputs": [],
   "source": [
    "tok = AutoTokenizer.from_pretrained(\"bert-base-uncased\")\n",
    "bert = AutoModel.from_pretrained(\"bert-base-uncased\", output_attentions=True).eval()\n",
    "cfg = bert.config\n",
    "n_params = sum(p.numel() for p in bert.parameters())\n",
    "print(f\"layers={cfg.num_hidden_layers}, hidden={cfg.hidden_size}, heads={cfg.num_attention_heads}, params={n_params/1e6:.1f}M\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a6482295",
   "metadata": {},
   "outputs": [],
   "source": [
    "def word_vector(sentence, word, layer=-1):\n",
    "    enc = tok(sentence, return_tensors=\"pt\")\n",
    "    with torch.no_grad():\n",
    "        out = bert(**enc, output_hidden_states=True)\n",
    "    tokens = tok.convert_ids_to_tokens(enc[\"input_ids\"][0])\n",
    "    idx = tokens.index(word)\n",
    "    return out.hidden_states[layer][0, idx].numpy()\n",
    "\n",
    "sents = {\n",
    "  \"money1\": \"She deposited the cheque at the bank before noon.\",\n",
    "  \"money2\": \"The bank approved my education loan yesterday.\",\n",
    "  \"river1\": \"We sat on the bank of the river and watched the boats.\",\n",
    "  \"river2\": \"The flood washed away the muddy bank near the village.\",\n",
    "}\n",
    "V = {k: word_vector(s, \"bank\") for k, s in sents.items()}\n",
    "def cos(a, b): return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))\n",
    "keys = list(V)\n",
    "print(\"cosine similarity of 'bank' across sentences\")\n",
    "print(\" \" * 8, *[f\"{k:>7}\" for k in keys])\n",
    "for a in keys:\n",
    "    print(f\"{a:>7}\", *[f\"{cos(V[a], V[b]):7.2f}\" for b in keys])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1c0372e1",
   "metadata": {},
   "source": [
    "Same word, different vectors. Pairs within a sense (money with money, river with river) are more similar than pairs across senses. GloVe would give all four occurrences the identical vector, so every entry in this table would be 1.00."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1bb32943",
   "metadata": {},
   "source": [
    "## Part 3. Attention from scratch (NumPy)\n",
    "Scaled dot-product attention:\n",
    "\n",
    "$$\\text{Attention}(Q,K,V)=\\text{softmax}\\!\\left(\\frac{QK^\\top}{\\sqrt{d_k}}\\right)V$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a3228b7c",
   "metadata": {},
   "outputs": [],
   "source": [
    "def softmax(x, axis=-1):\n",
    "    x = x - x.max(axis=axis, keepdims=True)      # numerical stability\n",
    "    e = np.exp(x)\n",
    "    return e / e.sum(axis=axis, keepdims=True)\n",
    "\n",
    "def attention(Q, K, V, mask=None):\n",
    "    d_k = Q.shape[-1]\n",
    "    scores = Q @ K.T / np.sqrt(d_k)\n",
    "    if mask is not None:\n",
    "        scores = np.where(mask, scores, -1e9)\n",
    "    w = softmax(scores)\n",
    "    return w @ V, w\n",
    "\n",
    "tokens = [\"the\", \"cat\", \"sat\", \"on\", \"mat\"]\n",
    "T, d_model, d_k = len(tokens), 16, 8\n",
    "rng = np.random.default_rng(0)\n",
    "X  = rng.normal(size=(T, d_model))               # pretend these are token embeddings\n",
    "Wq = rng.normal(size=(d_model, d_k)); Wk = rng.normal(size=(d_model, d_k)); Wv = rng.normal(size=(d_model, d_k))\n",
    "Q, K, V = X @ Wq, X @ Wk, X @ Wv\n",
    "out, W = attention(Q, K, V)\n",
    "print(\"weights (each row sums to 1):\"); print(W); print(\"row sums\", W.sum(1))\n",
    "print(\"output shape\", out.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "07fa1664",
   "metadata": {},
   "outputs": [],
   "source": [
    "def heat(W, xt, yt, title):\n",
    "    plt.figure(figsize=(4.5, 4)); plt.imshow(W, cmap=\"Blues\", vmin=0, vmax=1)\n",
    "    plt.xticks(range(len(xt)), xt, rotation=45); plt.yticks(range(len(yt)), yt)\n",
    "    plt.xlabel(\"attended to (keys)\"); plt.ylabel(\"query token\"); plt.title(title); plt.colorbar(); plt.show()\n",
    "heat(W, tokens, tokens, \"Self-attention (random weights)\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "518fb287",
   "metadata": {},
   "source": [
    "**Why divide by $\\sqrt{d_k}$?** Dot products grow with dimension. Without scaling, softmax saturates and gradients vanish."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f5b3782e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Average over many random queries and keys: how peaked does softmax get?\n",
    "r = np.random.default_rng(42)\n",
    "for d in [4, 64, 512, 2048]:\n",
    "    q = r.normal(size=(500, 1, d)); k = r.normal(size=(500, 6, d))\n",
    "    raw = (q * k).sum(-1)                              # 500 trials of 6 dot products\n",
    "    pk_raw = np.mean([softmax(x).max() for x in raw])\n",
    "    pk_scaled = np.mean([softmax(x / np.sqrt(d)).max() for x in raw])\n",
    "    print(f\"d_k={d:5d} | mean max softmax weight, unscaled: {pk_raw:.2f} | scaled: {pk_scaled:.2f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "88b9fefb",
   "metadata": {},
   "source": [
    "### Causal mask (decoder style, as in GPT): a token may not look at the future"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4353cbec",
   "metadata": {},
   "outputs": [],
   "source": [
    "mask = np.tril(np.ones((T, T), dtype=bool))\n",
    "_, Wc = attention(Q, K, V, mask=mask)\n",
    "heat(Wc, tokens, tokens, \"Causal self-attention\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "770e1aa6",
   "metadata": {},
   "source": [
    "### Multi-head attention: split the model dimension into several smaller attention heads"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f6c6fa76",
   "metadata": {},
   "outputs": [],
   "source": [
    "def multi_head(X, n_heads, rng):\n",
    "    T, d_model = X.shape; dh = d_model // n_heads\n",
    "    heads = []\n",
    "    for h in range(n_heads):\n",
    "        Wq, Wk, Wv = [rng.normal(size=(d_model, dh)) for _ in range(3)]\n",
    "        o, w = attention(X @ Wq, X @ Wk, X @ Wv)\n",
    "        heads.append((o, w))\n",
    "    concat = np.concatenate([o for o, _ in heads], axis=-1)       # (T, d_model)\n",
    "    Wo = rng.normal(size=(d_model, d_model))\n",
    "    return concat @ Wo, [w for _, w in heads]\n",
    "\n",
    "y, head_w = multi_head(X, n_heads=4, rng=np.random.default_rng(1))\n",
    "print(\"output\", y.shape)\n",
    "fig, ax = plt.subplots(1, 4, figsize=(14, 3.2))\n",
    "for i, w in enumerate(head_w):\n",
    "    ax[i].imshow(w, cmap=\"Blues\", vmin=0, vmax=1); ax[i].set_title(f\"head {i}\")\n",
    "    ax[i].set_xticks(range(T)); ax[i].set_xticklabels(tokens, rotation=45); ax[i].set_yticks(range(T)); ax[i].set_yticklabels(tokens)\n",
    "plt.tight_layout(); plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "77b4739e",
   "metadata": {},
   "source": [
    "### Positional encoding: attention has no sense of order, so we add it"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8106e2ad",
   "metadata": {},
   "outputs": [],
   "source": [
    "def sinusoidal_pe(n_pos, d):\n",
    "    pos = np.arange(n_pos)[:, None]; i = np.arange(d)[None, :]\n",
    "    angle = pos / np.power(10000, (2 * (i // 2)) / d)\n",
    "    pe = np.zeros((n_pos, d)); pe[:, 0::2] = np.sin(angle[:, 0::2]); pe[:, 1::2] = np.cos(angle[:, 1::2])\n",
    "    return pe\n",
    "pe = sinusoidal_pe(50, 64)\n",
    "plt.figure(figsize=(7, 3.5)); plt.imshow(pe.T, aspect=\"auto\", cmap=\"RdBu\"); plt.xlabel(\"position\"); plt.ylabel(\"dimension\"); plt.title(\"Sinusoidal positional encoding\"); plt.colorbar(); plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "251c2cff",
   "metadata": {},
   "source": [
    "**Check:** with no positional encoding, shuffling the input tokens only shuffles the outputs. Verify it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "35b6bc86",
   "metadata": {},
   "outputs": [],
   "source": [
    "perm = rng.permutation(T)\n",
    "o1, _ = attention(X @ Wq, X @ Wk, X @ Wv)\n",
    "o2, _ = attention(X[perm] @ Wq, X[perm] @ Wk, X[perm] @ Wv)\n",
    "print(\"permutation equivariant:\", np.allclose(o1[perm], o2))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dfda13f7",
   "metadata": {},
   "source": [
    "## Part 4. Looking inside real BERT attention\n",
    "Which words does *it* attend to in a sentence where *it* must be resolved?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f90cf947",
   "metadata": {},
   "outputs": [],
   "source": [
    "sentence = \"The animal did not cross the street because it was too tired.\"\n",
    "enc = tok(sentence, return_tensors=\"pt\")\n",
    "with torch.no_grad():\n",
    "    out = bert(**enc)\n",
    "toks = tok.convert_ids_to_tokens(enc[\"input_ids\"][0])\n",
    "att = torch.stack(out.attentions).squeeze(1).numpy()    # (layers, heads, T, T)\n",
    "print(\"attention tensor:\", att.shape, \"= (layers, heads, tokens, tokens)\")\n",
    "it = toks.index(\"it\")\n",
    "# which heads, in which layers, put the most weight on 'animal' when the query is 'it'?\n",
    "ai = toks.index(\"animal\")\n",
    "best = sorted(((att[l, h, it, ai], l, h) for l in range(12) for h in range(12)), reverse=True)[:5]\n",
    "for w, l, h in best: print(f\"layer {l:2d} head {h:2d}: weight on 'animal' = {w:.2f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e55b8fcf",
   "metadata": {},
   "outputs": [],
   "source": [
    "w, l, h = best[0]\n",
    "heat(att[l, h], toks, toks, f\"BERT layer {l} head {h}\")\n",
    "print(\"Row for 'it':\", {t: round(float(a), 2) for t, a in zip(toks, att[l, h, it])})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5f6af801",
   "metadata": {},
   "source": [
    "An honest caveat: attention weights are a useful window into the model, but they are not a complete explanation of its behaviour."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2a77a91f",
   "metadata": {},
   "source": [
    "## Part 5. Masked language modelling (BERT's pretraining task)\n",
    "BERT is trained to predict masked tokens using context from **both** sides.\n",
    "Exact scores can differ slightly across library versions. Watch the first prompt: the model may rank a famous city above the true capital, a useful reminder that it completes patterns and is not a fact database."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2facba89",
   "metadata": {},
   "outputs": [],
   "source": [
    "fill = pipeline(\"fill-mask\", model=\"bert-base-uncased\")\n",
    "for s in [\"The capital of India is [MASK].\",\n",
    "          \"Faculty members attended a workshop on [MASK] learning.\",\n",
    "          \"She opened the [MASK] and started typing the report.\"]:\n",
    "    print(s)\n",
    "    for r in fill(s, top_k=3): print(f\"   {r['token_str']:12s} {r['score']:.3f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e09a9578",
   "metadata": {},
   "source": [
    "## Part 6. A fine-tuned transformer for sentiment, and an exercise\n",
    "A pretrained BERT-family model fine-tuned on a labelled task. We use DistilBERT fine-tuned on SST-2."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f06a0d89",
   "metadata": {},
   "outputs": [],
   "source": [
    "clf = pipeline(\"sentiment-analysis\", model=\"distilbert-base-uncased-finetuned-sst-2-english\")\n",
    "tests = [\"The lectures were clear and the examples were excellent.\",\n",
    "         \"The session ran over time and the audio was terrible.\",\n",
    "         \"The workshop was not bad at all.\",\n",
    "         \"I expected more, but it was fine.\"]\n",
    "for t in tests: print(f\"{clf(t)[0]['label']:9s} {clf(t)[0]['score']:.3f} | {t}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7a672619",
   "metadata": {},
   "source": [
    "### Exercises\n",
    "1. Write three sentences where negation flips the sentiment and check whether the model gets them right.\n",
    "2. Replace `[MASK]` prompts in Part 5 with your own subject area. Which domains does BERT handle well, and which badly?\n",
    "3. Change the sentence in Part 4. Do any heads still link a pronoun to its noun?\n",
    "\n",
    "### Takeaways\n",
    "- Static embeddings: one vector per word. Contextual embeddings: one vector per occurrence.\n",
    "- Attention is a learned, differentiable lookup: queries match keys, values are mixed by the weights.\n",
    "- Transformers replace recurrence with attention plus positional information, so training parallelises across tokens.\n",
    "- BERT is an encoder pretrained with masked language modelling and then fine-tuned for downstream tasks."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
