{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "859589ce",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "# Lab\n",
    "\n",
    "**Agentic AI** · `L-Att`\n",
    "\n",
    "Programming exercises on the four parts of the lecture. Each exercise gives a complete implementation:\n",
    "run it, read it, and answer the questions on how it works. All three exercises are required."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ff5cf50a",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## Setup\n",
    "\n",
    "The code uses `numpy` and `tiktoken`: `pip install numpy tiktoken`.\n",
    "\n",
    "**Exercise 3 runs on the local Ollama server**, installed as described in the lab of → L-Intro. Start the server in each session and pull the model once:\n",
    "\n",
    "```bash\n",
    "ollama serve &\n",
    "ollama pull qwen2.5:3b\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "att-lab-e1",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## Exercise 1 — Explore a BPE Tokenizer *(code given, conceptual)*\n",
    "\n",
    "The code loads the GPT-4o tokenizer (`o200k_base`) of the `tiktoken` library, the tokenizer that the web\n",
    "tool Tiktokenizer shows, and defines `show(text)`. The function prints the number of tokens and of\n",
    "characters, and every token on its own with `·` for a space; it returns the token ids. Run the cell,\n",
    "then answer the questions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "att-lab-c1",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "import tiktoken\n",
    "enc = tiktoken.get_encoding(\"o200k_base\")     # the GPT-4o tokenizer\n",
    "print(\"vocabulary size:\", enc.n_vocab)\n",
    "\n",
    "def show(text):\n",
    "    ids = enc.encode(text)                                       # a list of integers, one per token\n",
    "    pieces = [enc.decode([i]).replace(\" \", \"·\") for i in ids]    # every token decoded on its own\n",
    "    print(f\"{len(ids):3d} tokens, {len(text):3d} characters: {' | '.join(pieces)}\")\n",
    "    assert enc.decode(ids) == text                               # decoding all ids restores the text\n",
    "    return ids\n",
    "\n",
    "for text in [\"The cat sat on the mat.\", \"antidisestablishmentarianism\",\n",
    "             \"def f(x): return x*x\", \"Straßenbahnhaltestelle\"]:\n",
    "    show(text)\n",
    "show(\"lower slow lows owl bowl only\")      # the corpus of the BPE exercise on the exercise sheet\n",
    "show(\"owls bow slowly wolf\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "att-lab-q1",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "**(a)** What does `enc.encode` return, and what does `len(ids)` count? Which of the two numbers\n",
    "that `show` prints decides what a request costs and how much of the context window it fills?\n",
    "\n",
    "**(b)** `show` decodes every id on its own with `enc.decode([i])`. What does that output show that\n",
    "`enc.decode(ids)` does not? What does the `assert` line check, and why must it hold for every string?\n",
    "\n",
    "**(c)** Read the vocabulary size from the output. With a model dimension of $d = 4{,}096$, how many\n",
    "parameters do the embedding table and the output layer hold together (lecture section *The\n",
    "Tokenization Dilemma*)?\n",
    "\n",
    "**(d)** Compare the segmentation of `Straßenbahnhaltestelle` with its morphemes\n",
    "*Straße · n · Bahn · halte · Stelle*. Do the token boundaries follow the morphemes? Explain the result\n",
    "with the rule by which BPE training builds its vocabulary.\n",
    "\n",
    "**(e)** In the corpus line every word is one token, with the space at its front. Why does `owls` at the\n",
    "start of the second line become two tokens, although ` owl` is one token?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "att-lab-e2",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## Exercise 2 — Implement Scaled Dot-Product Attention *(code given, conceptual)*\n",
    "\n",
    "**One attention head computes, for every position $i$ of a sequence of $n$ positions, a weighted\n",
    "average of the value vectors of the positions it may read; the weights come from comparing the query of\n",
    "$i$ with the keys of those positions** (lecture sections *Self-Attention at One Position* and\n",
    "*Causal Mask*). The code below implements the head for all positions at once. The queries, keys\n",
    "and values are stacked as the rows of three matrices, $Q, K \\in \\mathbb{R}^{n \\times d_k}$ and\n",
    "$V \\in \\mathbb{R}^{n \\times d_v}$; row $i$ of $Q$ is $\\mathbf q_i$. In a model they are\n",
    "$XW^Q$, $XW^K$, $XW^V$; here they are drawn at random. The head computes\n",
    "\n",
    "$$Z = \\operatorname{attn}(Q,K,V) = \\underbrace{\\operatorname{softmax}\\Big(\\frac{QK^\\top}{\\sqrt{d_k}} + M\\Big)}_{A} V .$$\n",
    "\n",
    "| Symbol | Shape | Meaning |\n",
    "|---|---|---|\n",
    "| $S = QK^\\top/\\sqrt{d_k}$ | $n \\times n$ | scaled scores: entry $(i,j)$ is $s_{ij} = \\mathbf q_i \\cdot \\mathbf k_j / \\sqrt{d_k}$ |\n",
    "| $M$ | $n \\times n$ | causal mask: $M_{ij} = 0$ for $j \\le i$ and $-\\infty$ for $j > i$; without the mask $M = 0$ |\n",
    "| $A$ | $n \\times n$ | attention weights: the softmax of $S + M$ applied to **each row**, so row $i$ is a distribution over positions |\n",
    "| $Z = AV$ | $n \\times d_v$ | output: row $i$ is $\\mathbf z_i = \\sum_j a_{ij}\\,\\mathbf v_j$ |\n",
    "\n",
    "The code tests the head on random input with $n = 4$ and $d_k = d_v = 8$. Run it, then answer the\n",
    "questions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "att-lab-c2",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "def softmax(z):\n",
    "    \"\"\"Softmax of each row of z.\"\"\"\n",
    "    z = z - z.max(axis=-1, keepdims=True)       # subtract the row maximum\n",
    "    e = np.exp(z)\n",
    "    return e / e.sum(axis=-1, keepdims=True)\n",
    "\n",
    "def attention(Q, K, V, causal=False):\n",
    "    \"\"\"One attention head in matrix form; returns the output Z and the weights A.\"\"\"\n",
    "    n, d_k = Q.shape\n",
    "    S = Q @ K.T / np.sqrt(d_k)                  # scaled scores s_ij, shape (n, n)\n",
    "    if causal:\n",
    "        S = S + np.triu(np.ones((n, n)), k=1) * -1e9   # the causal mask M\n",
    "    A = softmax(S)                              # attention weights a_ij\n",
    "    return A @ V, A                             # Z = AV\n",
    "\n",
    "print(softmax(np.array([[1000.0, 1001.0]])))\n",
    "\n",
    "rng = np.random.default_rng(0)\n",
    "n, d_k, d_v = 4, 8, 8\n",
    "Q, K, V = rng.normal(size=(n, d_k)), rng.normal(size=(n, d_k)), rng.normal(size=(n, d_v))\n",
    "Z, A = attention(Q, K, V, causal=True)\n",
    "print(np.round(A, 2))\n",
    "print(\"rows sum to 1:      \", np.allclose(A.sum(axis=1), 1))\n",
    "print(\"upper triangle is 0:\", np.allclose(np.triu(A, k=1), 0))\n",
    "Z_loop = np.array([sum(A[i, j] * V[j] for j in range(n)) for i in range(n)])\n",
    "print(\"z_i = sum_j a_ij v_j:\", np.allclose(Z, Z_loop))\n",
    "\n",
    "Z3, _ = attention(Q[:3], K[:3], V[:3], causal=True)\n",
    "print(\"causal, first 3 rows unchanged:   \", np.allclose(Z3, Z[:3]))\n",
    "Z3b, _ = attention(Q[:3], K[:3], V[:3])\n",
    "Zb, _ = attention(Q, K, V)\n",
    "print(\"bidirectional, first 3 unchanged: \", np.allclose(Z3b, Zb[:3]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "att-lab-q2",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "**(a)** `softmax` subtracts the maximum of each row before `np.exp`. Show that the result does not\n",
    "change. What would `np.exp` return for the row `[1000, 1001]` without the subtraction, and what would\n",
    "the division then give?\n",
    "\n",
    "**(b)** What is the shape of `z.max(axis=-1, keepdims=True)` for an $n \\times n$ matrix, and of\n",
    "`z.max(axis=-1)`? What would `z - z.max(axis=-1)` subtract from entry $(i, j)$ instead of the maximum of\n",
    "row $i$?\n",
    "\n",
    "**(c)** Which entries of `np.triu(np.ones((n, n)), k=1)` are 1, and which pairs $(i, j)$ do they mask?\n",
    "Suppose `k=0` were written instead. Which further entries would be masked, and what would happen to the\n",
    "first row of $A$ — with $-10^{9}$, and with $-\\infty$?\n",
    "\n",
    "**(d)** State the shapes of `S`, `A` and `Z` for the test input. Which of them changes if $d_v = 16$?\n",
    "\n",
    "**(e)** Why is the first row of the printed $A$ equal to $(1, 0, 0, 0)$, and why is $A$ lower-triangular?\n",
    "\n",
    "**(f)** The last two lines print `True` and `False`. Explain both, and state why the first result is the\n",
    "premise of the KV-cache (lecture section *Autoregressive Inference & the KV-Cache*)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "att-lab-e3",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## Exercise 3 — Measure Prompt Caching *(code given, conceptual)*\n",
    "\n",
    "**Prompt caching** reuses the keys and values of a prompt prefix that an earlier request already\n",
    "computed, so the **prefill**, the pass over the prompt that fills the KV-cache, runs only over what\n",
    "follows that prefix (lecture section *The Context Window and the KV-Cache*). The code sends five\n",
    "requests to the local Ollama server through its native `/api/chat` endpoint. The system prompt is a\n",
    "long block of about 7,400 tokens that starts with a random session id, so that no earlier run has cached\n",
    "it. For each request the code prints the wall time, the number of prompt tokens (`prompt_eval_count`)\n",
    "and the prefill time Ollama reports (`prompt_eval_duration`). Run the cell, then answer the questions;\n",
    "your times depend on the machine."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "att-lab-c3",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "import json, time, uuid, urllib.request\n",
    "\n",
    "URL, MODEL = \"http://localhost:11434/api/chat\", \"qwen2.5:3b\"\n",
    "\n",
    "def ask(system, question=\"Reply with the word OK.\"):\n",
    "    \"\"\"One chat call; returns the wall time, the prompt length and Ollama's prefill time.\"\"\"\n",
    "    body = {\"model\": MODEL, \"stream\": False, \"keep_alive\": \"10m\",\n",
    "            \"options\": {\"num_predict\": 5, \"temperature\": 0, \"num_ctx\": 16384},\n",
    "            \"messages\": [{\"role\": \"system\", \"content\": system},\n",
    "                         {\"role\": \"user\", \"content\": question}]}\n",
    "    req = urllib.request.Request(URL, data=json.dumps(body).encode(),\n",
    "                                 headers={\"Content-Type\": \"application/json\"})\n",
    "    t = time.perf_counter()\n",
    "    r = json.load(urllib.request.urlopen(req))\n",
    "    return {\"wall_s\": round(time.perf_counter() - t, 3),\n",
    "            \"prompt_tokens\": r[\"prompt_eval_count\"],\n",
    "            \"prefill_s\": round(r[\"prompt_eval_duration\"] / 1e9, 3)}\n",
    "\n",
    "facts = \" \".join(f\"Fact {i}: the value of item {i} is {i * 7 % 101}.\" for i in range(400))\n",
    "run = uuid.uuid4().hex[:8]                    # a new prompt start in every run: nothing is cached yet\n",
    "prefix = f\"Session {run}. Context:\\n{facts}\"\n",
    "edited = f\"Session {run}. CONTEXT:\\n{facts}\"   # one word changed near the start\n",
    "\n",
    "ask(\"warm-up\")                                 # loads the model, so that loading time is not measured\n",
    "print(\"1 new prefix         \", ask(prefix))\n",
    "print(\"2 same prompt        \", ask(prefix))\n",
    "print(\"3 same prefix, new question\", ask(prefix, \"Reply with the word YES.\"))\n",
    "print(\"4 edited near start  \", ask(edited))\n",
    "print(\"5 4 + appended text  \", ask(edited + \" Fact 400: the value of item 400 is 49.\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "att-lab-q3",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "**(a)** Why does the code send a warm-up request before it measures anything?\n",
    "\n",
    "**(b)** Requests 1 and 2 send the same prompt. By which factor does the prefill time fall? The number\n",
    "of prompt tokens is the same for both: what does `prompt_tokens` count, and what does it not count?\n",
    "\n",
    "**(c)** Request 3 keeps the system prompt and changes only the question at the end. Which tokens had to\n",
    "be computed?\n",
    "\n",
    "**(d)** Request 4 changes one word near the start and leaves the rest of the 7,400 tokens unchanged.\n",
    "Why is the prefill time back at the level of request 1? Use the causal mask: on which tokens do the key\n",
    "and the value of position $i$ depend?\n",
    "\n",
    "**(e)** Request 5 appends one sentence to the prompt of request 4. Why is it cheap again?\n",
    "\n",
    "**(f)** Derive a rule for building the prompt of an agent from (c)–(e): where do the system\n",
    "prompt and the tool descriptions go, and where the parts that change from turn to turn?"
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Slideshow",
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.3"
  },
  "rise": {
   "scroll": true,
   "theme": "simple",
   "transition": "none"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}