{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "t6-instructions",
   "metadata": {},
   "source": [
    "**Run the following cell before doing anything else** and then click the blue bar to the left of the cell to hide it, if it isn't already. Do **not** edit it!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t6-setup",
   "metadata": {
    "deletable": false,
    "editable": false,
    "init_cell": true,
    "jupyter": {
     "source_hidden": true
    },
    "tags": [
     "hide-input",
     "init_cell",
     "tutorial-setup"
    ]
   },
   "outputs": [],
   "source": [
    "from IPython import get_ipython\n",
    "from IPython.display import HTML, Javascript, clear_output, display\n",
    "import hashlib\n",
    "import hmac\n",
    "import html\n",
    "import json\n",
    "\n",
    "_TUTORIAL_CHECK_ORDER = ['1.0.1',\n",
    " '2.1.1',\n",
    " '2.2.1',\n",
    " '3.1.1',\n",
    " '3.2.1',\n",
    " '3.3.1',\n",
    " '3.4.1',\n",
    " '4.1.1',\n",
    " '4.2.1',\n",
    " '4.3.1',\n",
    " '4.4.1',\n",
    " '5.1.1',\n",
    " '5.2.1',\n",
    " '5.3.1']\n",
    "_TUTORIAL_PROGRESS_IDS = {}\n",
    "_TUTORIAL_CHECK_BRANCHES = {}\n",
    "_TUTORIAL_TEXT_CHECKS = {'3.3.1', '5.1.1', '3.4.1', '5.2.1', '2.2.1', '5.3.1', '3.1.1', '1.0.1'}\n",
    "_TUTORIAL_OPTIONAL_NOTES = {'6.3.1', '6.2.1', '6.1.1'}\n",
    "_TUTORIAL_EXACT_CHECKS = {'2.1.1': ('d52b0ac499c65f394ce77d3e5a1e7bc63b4679a56f042861f338204dc3157d5d',\n",
    "           'Run check_environment.py using uv run from tutorial-6. Paste only its two print '\n",
    "           'lines.'),\n",
    " '3.2.1': ('28b93288ef93357f9cf22934ecf74696a85421fe8fa5b173d92258c80bc8016c',\n",
    "           'Select the first row, count its input tokens, then slice the output row starting '\n",
    "           'at that count.'),\n",
    " '4.1.1': ('c22774f1a04a52cb483f986b7bfb182e9295cd17314bfe140566609d0067be30',\n",
    "           'Append a new dictionary on each call using the supplied role and content. Run the '\n",
    "           'assertions, then paste the three printed lines.'),\n",
    " '4.2.1': ('b39823897e56d214ed8a28f189e969b0faeb556c0f262bc577ce7a65d6919612',\n",
    "           'Keep the original message for the history. Empty input and bye should stay out of '\n",
    "           'get_reply. Paste the three responses, without the greeting or You: lines.'),\n",
    " '4.3.1': ('6c62016b943e4d0357eef07a6dc87ef4d08e1b654ac321da61c82a781972ef35',\n",
    "           'Keep one list throughout the loop and append both sides of every ordinary '\n",
    "           'exchange. Paste only the four history lines printed after the farewell.'),\n",
    " '4.4.1': ('67463f45e82a1c8d13326387950ce2787d4a6e280680c83d8a47f1574bf01133',\n",
    "           'Reset must replace the history with an empty list and skip reply generation. '\n",
    "           'Paste four responses followed by Saved messages: 0.')}\n",
    "_TUTORIAL_STARTER_ANSWERS = {'1.0.1': 'WRITE NAMES HERE',\n",
    " '2.1.1': 'PASTE OUTPUT HERE',\n",
    " '2.2.1': 'WRITE NOTES HERE',\n",
    " '3.1.1': 'WRITE NOTES HERE',\n",
    " '3.2.1': 'PASTE OUTPUT HERE',\n",
    " '3.3.1': 'WRITE NOTES HERE',\n",
    " '3.4.1': 'WRITE NOTES HERE',\n",
    " '4.1.1': 'PASTE OUTPUT HERE',\n",
    " '4.2.1': 'PASTE OUTPUT HERE',\n",
    " '4.3.1': 'PASTE OUTPUT HERE',\n",
    " '4.4.1': 'PASTE OUTPUT HERE',\n",
    " '5.1.1': 'WRITE NOTES HERE',\n",
    " '5.2.1': 'WRITE NOTES HERE',\n",
    " '5.3.1': 'WRITE NOTES HERE',\n",
    " '6.1.1': 'WRITE NOTES HERE',\n",
    " '6.2.1': 'WRITE NOTES HERE',\n",
    " '6.3.1': 'WRITE NOTES HERE'}\n",
    "_TUTORIAL_SUCCESS_MESSAGES = {'1.0.1': ('Notes recorded.', 'Your investigation team is ready. Let us meet the suspect.'),\n",
    " '2.1.1': ('Correct!', 'Both libraries imported inside your project environment.'),\n",
    " '2.2.1': ('Notes recorded.',\n",
    "           'Keep the model card handy. Documentation is part of programming too.'),\n",
    " '3.1.1': ('Notes recorded.',\n",
    "           'You have run a language model locally. Now let us look at what we asked it to '\n",
    "           'do.'),\n",
    " '3.2.1': ('Correct!',\n",
    "           'The slice keeps only the new tokens. Our chatbot will not need to repeat the '\n",
    "           'whole conversation.'),\n",
    " '3.3.1': ('Notes recorded.',\n",
    "           'Keep the settings with your observations, so someone else can repeat your '\n",
    "           'experiment.'),\n",
    " '3.4.1': ('Notes recorded.',\n",
    "           'You have tested some claims instead of relying on how convincing the replies '\n",
    "           'sounded.'),\n",
    " '4.1.1': ('Correct!', 'Your list keeps separate messages in conversation order.'),\n",
    " '4.2.1': ('Correct!', 'The loop handles ordinary input, empty input, and a farewell.'),\n",
    " '4.3.1': ('Correct!',\n",
    "           'Both sides of the conversation are stored, and the command is left out.'),\n",
    " '4.4.1': ('Correct!',\n",
    "           'Your conversation code is ready. Time to give it a less predictable voice.'),\n",
    " '5.1.1': ('Notes recorded.',\n",
    "           'Your turn-based chatbot now uses the model to generate its replies.'),\n",
    " '5.2.1': ('Notes recorded.',\n",
    "           'You have distinguished the conversation stored by your program from the model '\n",
    "           'that reads it.'),\n",
    " '5.3.1': ('Notes recorded.',\n",
    "           'You have completed the core tutorial, and the course capstone! Choose any bonus '\n",
    "           'task if there is time.'),\n",
    " '6.1.1': ('Notes recorded.', 'You can continue with any bonus task.'),\n",
    " '6.2.1': ('Notes recorded.', 'You can continue with any bonus task.'),\n",
    " '6.3.1': ('Notes recorded.', 'You can continue with any bonus task.')}\n",
    "\n",
    "# Only inherit progress when this setup belongs to the same tutorial.\n",
    "# A different notebook may have used this kernel before us.\n",
    "_tutorial_same_identity = (\n",
    "    globals().get(\"_TUTORIAL_IDENTITY\") == \"tutorial-6-the-worst-language-model\"\n",
    "    and getattr(globals().get(\"_tutorial_check\"), \"_tutorial_identity\", None) == \"tutorial-6-the-worst-language-model\"\n",
    ")\n",
    "_previous_completed = set(globals().get(\"_TUTORIAL_COMPLETED\", set())) if _tutorial_same_identity else set()\n",
    "_TUTORIAL_IDENTITY = \"tutorial-6-the-worst-language-model\"\n",
    "_TUTORIAL_COMPLETED = set()\n",
    "for _check_id in _TUTORIAL_CHECK_ORDER:\n",
    "    if _check_id not in _previous_completed:\n",
    "        break\n",
    "    _TUTORIAL_COMPLETED.add(_check_id)\n",
    "_TUTORIAL_COMPLETED.update(_previous_completed & _TUTORIAL_OPTIONAL_NOTES)\n",
    "_TUTORIAL_SELECTIONS = {}\n",
    "\n",
    "\n",
    "def _tutorial_progress_id(check_id):\n",
    "    return _TUTORIAL_PROGRESS_IDS.get(check_id, check_id)\n",
    "\n",
    "\n",
    "def _tutorial_reset_progress(expected_identity=\"tutorial-6-the-worst-language-model\"):\n",
    "    if expected_identity != _TUTORIAL_IDENTITY:\n",
    "        return False\n",
    "    _TUTORIAL_COMPLETED.clear()\n",
    "    _TUTORIAL_SELECTIONS.clear()\n",
    "    return True\n",
    "\n",
    "\n",
    "def _tutorial_normalize(value):\n",
    "    return \"\\n\".join(line.rstrip() for line in value.strip().splitlines())\n",
    "\n",
    "\n",
    "def _tutorial_digest(value):\n",
    "    return hashlib.sha256(value.encode(\"utf-8\")).hexdigest()\n",
    "\n",
    "\n",
    "def _tutorial_message(kind, title, message):\n",
    "    colours = {\n",
    "        \"correct\": (\"#166534\", \"#dcfce7\", \"#86efac\"),\n",
    "        \"incorrect\": (\"#991b1b\", \"#fef2f2\", \"#fca5a5\"),\n",
    "    }\n",
    "    text, background, border = colours[kind]\n",
    "    display(HTML(\n",
    "        f'<div style=\"margin:8px 0;padding:10px 12px;border-left:4px solid {border};'\n",
    "        f'background:{background};color:{text}\">'\n",
    "        f'<strong>{html.escape(title)}</strong> {html.escape(message)}</div>'\n",
    "    ))\n",
    "\n",
    "\n",
    "def _tutorial_check(line, cell, _identity=\"tutorial-6-the-worst-language-model\"):\n",
    "    clear_output(wait=True)\n",
    "    if _identity != _TUTORIAL_IDENTITY:\n",
    "        _tutorial_message(\"incorrect\", \"Run this tutorial's setup first.\", \"This kernel is currently checking a different tutorial.\")\n",
    "        return\n",
    "    check_id = line.strip()\n",
    "    progress_id = _tutorial_progress_id(check_id)\n",
    "    answer = _tutorial_normalize(cell)\n",
    "    known_checks = set(_TUTORIAL_CHECK_ORDER) | _TUTORIAL_OPTIONAL_NOTES\n",
    "\n",
    "    if check_id not in known_checks:\n",
    "        _tutorial_message(\"incorrect\", \"This check could not run.\", \"Please ask your tutor for help.\")\n",
    "        return\n",
    "\n",
    "    placeholders = tuple(value.upper() for value in _TUTORIAL_STARTER_ANSWERS.values())\n",
    "    if not answer or any(placeholder in answer.upper() for placeholder in placeholders):\n",
    "        _tutorial_message(\"incorrect\", \"No answer yet.\", \"Replace the placeholder, then run the cell again.\")\n",
    "        return\n",
    "\n",
    "    if progress_id in _TUTORIAL_CHECK_ORDER:\n",
    "        position = _TUTORIAL_CHECK_ORDER.index(progress_id)\n",
    "        missing = [\n",
    "            earlier for earlier in _TUTORIAL_CHECK_ORDER[:position]\n",
    "            if earlier not in _TUTORIAL_COMPLETED\n",
    "        ]\n",
    "        if missing:\n",
    "            _tutorial_message(\"incorrect\", \"Complete the previous step first.\", \"Return to the last visible check above.\")\n",
    "            return\n",
    "\n",
    "    correct = False\n",
    "    hint = \"Check your answer carefully and try again.\"\n",
    "    completion_details = {}\n",
    "\n",
    "    if check_id in _TUTORIAL_EXACT_CHECKS:\n",
    "        expected_digest, hint = _TUTORIAL_EXACT_CHECKS[check_id]\n",
    "        correct = hmac.compare_digest(_tutorial_digest(answer), expected_digest)\n",
    "    elif check_id in _TUTORIAL_TEXT_CHECKS or check_id in _TUTORIAL_OPTIONAL_NOTES:\n",
    "        correct = bool(answer)\n",
    "        hint = \"Write something before running the cell.\"\n",
    "\n",
    "    if not correct:\n",
    "        _tutorial_message(\"incorrect\", \"Not quite.\", hint)\n",
    "        return\n",
    "\n",
    "    already_completed = progress_id in _TUTORIAL_COMPLETED\n",
    "    if progress_id in _TUTORIAL_CHECK_ORDER and not already_completed:\n",
    "        position = _TUTORIAL_CHECK_ORDER.index(progress_id)\n",
    "        for later_id in _TUTORIAL_CHECK_ORDER[position + 1:]:\n",
    "            _TUTORIAL_COMPLETED.discard(later_id)\n",
    "        completion_details[\"resetFollowing\"] = True\n",
    "\n",
    "    _TUTORIAL_COMPLETED.add(progress_id)\n",
    "\n",
    "    if check_id in _TUTORIAL_OPTIONAL_NOTES:\n",
    "        _tutorial_message(\"correct\", \"Notes recorded.\", \"You can continue with any bonus task.\")\n",
    "        return\n",
    "\n",
    "    title, message = _TUTORIAL_SUCCESS_MESSAGES.get(check_id, (\"Correct!\", \"\"))\n",
    "    _tutorial_message(\"correct\", title, message)\n",
    "    display(Javascript(\n",
    "        \"window.__tutorialProgress && window.__tutorialProgress.complete(\"\n",
    "        + json.dumps(check_id)\n",
    "        + \", \"\n",
    "        + json.dumps(completion_details)\n",
    "        + \");\"\n",
    "    ))\n",
    "\n",
    "\n",
    "_tutorial_check._tutorial_identity = _TUTORIAL_IDENTITY\n",
    "_tutorial_shell = get_ipython()\n",
    "if _tutorial_shell is None:\n",
    "    raise RuntimeError(\"Run this cell with a Python Jupyter kernel.\")\n",
    "_tutorial_shell.register_magic_function(_tutorial_check, \"cell\", \"check\")\n",
    "_tutorial_message(\"correct\", \"Setup complete.\", \"Your language model tutorial checks are ready.\")\n",
    "\n",
    "\n",
    "_tutorial_progress_javascript = r\"\"\"\n",
    "(() => {\n",
    "  const tutorialIdentity = \"tutorial-6-the-worst-language-model\";\n",
    "  const checkOrder = __CHECK_ORDER__;\n",
    "  const progressIds = __PROGRESS_IDS__;\n",
    "  const checkBranches = __CHECK_BRANCHES__;\n",
    "  const optionalNotes = __OPTIONAL_NOTES__;\n",
    "  const completedFromKernel = __COMPLETED__;\n",
    "  const selectionsFromKernel = __SELECTIONS__;\n",
    "  const hiddenClass = \"tutorial-progress-hidden\";\n",
    "  const styleId = \"tutorial-progress-style\";\n",
    "  const starterAnswers = __STARTER_ANSWERS__;\n",
    "\n",
    "  if (!document.getElementById(styleId)) {\n",
    "    const style = document.createElement(\"style\");\n",
    "    style.id = styleId;\n",
    "    style.textContent = `.${hiddenClass} { display: none !important; }`;\n",
    "    document.head.appendChild(style);\n",
    "  }\n",
    "\n",
    "  const previous = window.__tutorialProgress;\n",
    "  if (previous && previous.observer) previous.observer.disconnect();\n",
    "\n",
    "  const state = {\n",
    "    completed: new Set(completedFromKernel),\n",
    "    selections: { ...selectionsFromKernel },\n",
    "    observer: null,\n",
    "    scheduled: false,\n",
    "  };\n",
    "\n",
    "  function progressId(id) {\n",
    "    return progressIds[id] || id;\n",
    "  }\n",
    "\n",
    "  function visibleNotebook() {\n",
    "    const scriptNotebook = document.currentScript &&\n",
    "      document.currentScript.closest(\".jp-Notebook, #notebook-container\");\n",
    "    if (scriptNotebook) return scriptNotebook;\n",
    "    const candidates = [...document.querySelectorAll(\".jp-Notebook, #notebook-container\")];\n",
    "    return candidates.find((node) => node.offsetParent !== null) || candidates[0] || null;\n",
    "  }\n",
    "\n",
    "  function currentNotebookPanel() {\n",
    "    const apps = [\n",
    "      window.jupyterapp,\n",
    "      window.jupyterlab,\n",
    "      window.jupyterLab,\n",
    "      window.jupyterFrontEnd,\n",
    "      window.jupyterApp,\n",
    "    ];\n",
    "    for (const app of apps) {\n",
    "      const widget = app && app.shell && app.shell.currentWidget;\n",
    "      if (widget && widget.content && widget.content.model && widget.context) return widget;\n",
    "    }\n",
    "    return null;\n",
    "  }\n",
    "\n",
    "  state.notebook = visibleNotebook();\n",
    "\n",
    "  if (!state.notebook) {\n",
    "    const warning = document.createElement(\"div\");\n",
    "    warning.style.cssText = \"margin:8px 0;padding:10px 12px;border-left:4px solid #f59e0b;background:#fffbeb;color:#92400e;font-family:system-ui,sans-serif\";\n",
    "    warning.textContent = \"The checks are ready, but this notebook frontend does not allow automatic section reveal. The checks will still mark answers, but all sections may remain visible.\";\n",
    "    document.body.appendChild(warning);\n",
    "    return;\n",
    "  }\n",
    "\n",
    "  state.notebook.__tutorialProgress = state;\n",
    "\n",
    "  function cells() {\n",
    "    const selector = state.notebook.id === \"notebook-container\"\n",
    "      ? \":scope > .cell\"\n",
    "      : \".jp-Notebook-cell\";\n",
    "    return [...state.notebook.querySelectorAll(selector)].filter(\n",
    "      (cell) => !cell.closest(\".jp-Notebook\") || cell.closest(\".jp-Notebook\") === state.notebook\n",
    "    );\n",
    "  }\n",
    "\n",
    "  function source(cell) {\n",
    "    const classicEditor = cell.querySelector(\".CodeMirror\");\n",
    "    if (classicEditor && classicEditor.CodeMirror) return classicEditor.CodeMirror.getValue();\n",
    "    const modernEditor = cell.querySelector(\".cm-content\");\n",
    "    if (modernEditor) return modernEditor.innerText || modernEditor.textContent || \"\";\n",
    "    const input = cell.querySelector(\".input_area, .jp-InputArea-editor\");\n",
    "    return input ? (input.innerText || input.textContent || \"\") : \"\";\n",
    "  }\n",
    "\n",
    "  function checkId(cell) {\n",
    "    const match = source(cell).match(/^%%check\\s+([a-z0-9_.-]+)/m);\n",
    "    return match ? match[1] : null;\n",
    "  }\n",
    "\n",
    "  function renderedMarker(cell) {\n",
    "    return cell.querySelector(\"[data-tutorial-section]\");\n",
    "  }\n",
    "\n",
    "  function explicitSectionNumber(cell) {\n",
    "    const sectionMarker = renderedMarker(cell);\n",
    "    if (sectionMarker) return Number(sectionMarker.dataset.tutorialSection);\n",
    "    const markerMatch = source(cell).match(/data-tutorial-section=[\\\"'](\\d+)[\\\"']/);\n",
    "    if (markerMatch) return Number(markerMatch[1]);\n",
    "    const id = checkId(cell);\n",
    "    const progress = id ? progressId(id) : null;\n",
    "    const checkIndex = progress ? checkOrder.indexOf(progress) : -1;\n",
    "    if (checkIndex >= 0) return checkIndex;\n",
    "    if (id && optionalNotes.includes(id)) return checkOrder.length;\n",
    "    return null;\n",
    "  }\n",
    "\n",
    "  function sectionNumber(cell, notebookCells) {\n",
    "    const ownSection = explicitSectionNumber(cell);\n",
    "    if (ownSection !== null) return ownSection;\n",
    "    const index = notebookCells.indexOf(cell);\n",
    "    for (let cursor = index - 1; cursor >= 0; cursor -= 1) {\n",
    "      const inheritedSection = explicitSectionNumber(notebookCells[cursor]);\n",
    "      if (inheritedSection !== null) return inheritedSection;\n",
    "    }\n",
    "    return 0;\n",
    "  }\n",
    "\n",
    "  function branch(cell) {\n",
    "    const sectionMarker = renderedMarker(cell);\n",
    "    if (sectionMarker && sectionMarker.dataset.tutorialOs) {\n",
    "      return {\n",
    "        software: sectionMarker.dataset.tutorialSoftware,\n",
    "        os: sectionMarker.dataset.tutorialOs,\n",
    "      };\n",
    "    }\n",
    "    const id = checkId(cell);\n",
    "    if (id && checkBranches[id]) return checkBranches[id];\n",
    "    const cellSource = source(cell);\n",
    "    const software = cellSource.match(/data-tutorial-software=[\\\"']([^\\\"']+)[\\\"']/);\n",
    "    const os = cellSource.match(/data-tutorial-os=[\\\"']([^\\\"']+)[\\\"']/);\n",
    "    return software && os ? { software: software[1], os: os[1] } : null;\n",
    "  }\n",
    "\n",
    "  function refresh() {\n",
    "    state.scheduled = false;\n",
    "    let unlockedSection = 0;\n",
    "    for (const id of checkOrder) {\n",
    "      if (!state.completed.has(id)) break;\n",
    "      unlockedSection += 1;\n",
    "    }\n",
    "    const notebookCells = cells();\n",
    "    for (const cell of notebookCells) {\n",
    "      const requiredBranch = branch(cell);\n",
    "      const wrongBranch = requiredBranch &&\n",
    "        state.selections[requiredBranch.software] !== requiredBranch.os;\n",
    "      const locked = sectionNumber(cell, notebookCells) > unlockedSection;\n",
    "      cell.classList.toggle(hiddenClass, Boolean(locked || wrongBranch));\n",
    "    }\n",
    "    bindResetButtons();\n",
    "    window.dispatchEvent(new Event(\"resize\"));\n",
    "  }\n",
    "\n",
    "  function scheduleRefresh() {\n",
    "    if (state.scheduled) return;\n",
    "    state.scheduled = true;\n",
    "    requestAnimationFrame(refresh);\n",
    "  }\n",
    "\n",
    "  state.complete = (id, details = {}) => {\n",
    "    const progress = progressId(id);\n",
    "    if (!checkOrder.includes(progress)) return;\n",
    "    const position = checkOrder.indexOf(progress);\n",
    "    if (details.resetFollowing) {\n",
    "      for (const laterId of checkOrder.slice(position + 1)) state.completed.delete(laterId);\n",
    "    }\n",
    "    state.completed.add(progress);\n",
    "    if (details.software && details.os) state.selections[details.software] = details.os;\n",
    "    refresh();\n",
    "  };\n",
    "\n",
    "\n",
    "  function starterSource(id) {\n",
    "    return `%%check ${id}\\n${starterAnswers[id]}`;\n",
    "  }\n",
    "\n",
    "  function modelSource(cell) {\n",
    "    if (cell.sharedModel && cell.sharedModel.getSource) return cell.sharedModel.getSource();\n",
    "    if (cell.value && typeof cell.value.text === \"string\") return cell.value.text;\n",
    "    return \"\";\n",
    "  }\n",
    "\n",
    "  function clearDomOutput(cellNode) {\n",
    "    for (const output of cellNode.querySelectorAll(\".output, .output_wrapper, .jp-OutputArea, .jp-Cell-outputArea\")) {\n",
    "      output.replaceChildren();\n",
    "    }\n",
    "  }\n",
    "\n",
    "  function resetDomCheckCells() {\n",
    "    let resetCount = 0;\n",
    "    for (const cellNode of cells()) {\n",
    "      const id = checkId(cellNode);\n",
    "      if (!id || !starterAnswers[id]) continue;\n",
    "      const sourceText = starterSource(id);\n",
    "      const classicEditor = cellNode.querySelector(\".CodeMirror\");\n",
    "      if (classicEditor && classicEditor.CodeMirror) {\n",
    "        classicEditor.CodeMirror.setValue(sourceText);\n",
    "        clearDomOutput(cellNode);\n",
    "        resetCount += 1;\n",
    "      }\n",
    "    }\n",
    "    return resetCount;\n",
    "  }\n",
    "\n",
    "  async function resetNotebookCells() {\n",
    "    const classicNotebook = window.Jupyter && window.Jupyter.notebook;\n",
    "    if (classicNotebook && classicNotebook.get_cells) {\n",
    "      for (const cell of classicNotebook.get_cells()) {\n",
    "        const match = cell.get_text().match(/^%%check\\s+([a-z0-9_.-]+)/m);\n",
    "        if (!match || !starterAnswers[match[1]]) continue;\n",
    "        cell.set_text(starterSource(match[1]));\n",
    "        if (cell.clear_output) cell.clear_output();\n",
    "        if (cell.set_input_prompt) cell.set_input_prompt(null);\n",
    "      }\n",
    "      classicNotebook.set_dirty(true);\n",
    "      await classicNotebook.save_notebook();\n",
    "      return;\n",
    "    }\n",
    "\n",
    "    const panel = currentNotebookPanel();\n",
    "    const notebookModel = panel && panel.content && panel.content.model;\n",
    "    if (notebookModel && notebookModel.cells) {\n",
    "      for (let index = 0; index < notebookModel.cells.length; index += 1) {\n",
    "        const cell = notebookModel.cells.get(index);\n",
    "        const match = modelSource(cell).match(/^%%check\\s+([a-z0-9_.-]+)/m);\n",
    "        if (!match || !starterAnswers[match[1]]) continue;\n",
    "        if (cell.sharedModel && cell.sharedModel.setSource) {\n",
    "          cell.sharedModel.setSource(starterSource(match[1]));\n",
    "        } else if (cell.value && typeof cell.value.text === \"string\") {\n",
    "          cell.value.text = starterSource(match[1]);\n",
    "        }\n",
    "        if (cell.outputs && cell.outputs.clear) cell.outputs.clear();\n",
    "        if (\"executionCount\" in cell) cell.executionCount = null;\n",
    "      }\n",
    "      await panel.context.save();\n",
    "      return;\n",
    "    }\n",
    "\n",
    "    if (resetDomCheckCells() > 0) return;\n",
    "\n",
    "    throw new Error(\"This notebook frontend does not expose a writable notebook model.\");\n",
    "  }\n",
    "\n",
    "  async function resetKernelProgress() {\n",
    "    const code = \"_tutorial_reset_progress(\\\"\" + tutorialIdentity + \"\\\")\";\n",
    "    try {\n",
    "      const classicKernel = window.Jupyter && window.Jupyter.notebook && window.Jupyter.notebook.kernel;\n",
    "      if (classicKernel && classicKernel.execute) {\n",
    "        classicKernel.execute(code, {}, { silent: true, store_history: false });\n",
    "        return true;\n",
    "      }\n",
    "\n",
    "      const panel = currentNotebookPanel();\n",
    "      const kernel = panel && panel.sessionContext && panel.sessionContext.session &&\n",
    "        panel.sessionContext.session.kernel;\n",
    "      if (kernel && kernel.requestExecute) {\n",
    "        const future = kernel.requestExecute({ code, silent: true, store_history: false });\n",
    "        await future.done;\n",
    "        return true;\n",
    "      }\n",
    "    } catch (error) {\n",
    "      console.error(\"Could not reset tutorial kernel state\", error);\n",
    "    }\n",
    "    return false;\n",
    "  }\n",
    "\n",
    "  async function resetProgress(button) {\n",
    "    const confirmed = window.confirm(\n",
    "      \"Reset all tutorial progress? Every answer and check result will be cleared.\"\n",
    "    );\n",
    "    if (!confirmed) return;\n",
    "\n",
    "    button.disabled = true;\n",
    "    button.textContent = \"Resetting…\";\n",
    "    try {\n",
    "      await resetNotebookCells();\n",
    "      const kernelWasReset = await resetKernelProgress();\n",
    "      state.completed.clear();\n",
    "      state.selections = {};\n",
    "      refresh();\n",
    "      state.notebook.scrollIntoView({ behavior: \"smooth\", block: \"start\" });\n",
    "      button.disabled = false;\n",
    "      button.textContent = \"Reset all tutorial progress\";\n",
    "      if (kernelWasReset) {\n",
    "        window.alert(\"Tutorial progress has been reset.\");\n",
    "      } else {\n",
    "        window.alert(\n",
    "          \"Answers were reset. Restart the kernel before beginning again to clear its saved progress too.\"\n",
    "        );\n",
    "      }\n",
    "    } catch (error) {\n",
    "      console.error(\"Could not reset tutorial progress\", error);\n",
    "      window.alert(`The tutorial could not be reset: ${error.message}`);\n",
    "      button.disabled = false;\n",
    "      button.textContent = \"Reset all tutorial progress\";\n",
    "    }\n",
    "  }\n",
    "\n",
    "  function bindResetButtons() {\n",
    "    for (const button of state.notebook.querySelectorAll(\"[data-tutorial-reset]\")) {\n",
    "      if (button.dataset.tutorialResetBound) continue;\n",
    "      button.dataset.tutorialResetBound = \"true\";\n",
    "      button.addEventListener(\"click\", () => state.notebook.__tutorialProgress.reset(button));\n",
    "    }\n",
    "  }\n",
    "\n",
    "  state.reset = resetProgress;\n",
    "  state.observer = new MutationObserver(scheduleRefresh);\n",
    "  state.observer.observe(state.notebook, { childList: true, subtree: true });\n",
    "  window.__tutorialProgress = state;\n",
    "  refresh();\n",
    "  setTimeout(refresh, 100);\n",
    "  setTimeout(refresh, 500);\n",
    "  setTimeout(refresh, 1500);\n",
    "})();\n",
    "\"\"\".replace(\"__STARTER_ANSWERS__\", json.dumps(_TUTORIAL_STARTER_ANSWERS)).replace(\"__CHECK_ORDER__\", json.dumps(_TUTORIAL_CHECK_ORDER)).replace(\n",
    "    \"__PROGRESS_IDS__\", json.dumps(_TUTORIAL_PROGRESS_IDS)\n",
    ").replace(\n",
    "    \"__CHECK_BRANCHES__\", json.dumps(_TUTORIAL_CHECK_BRANCHES)\n",
    ").replace(\n",
    "    \"__OPTIONAL_NOTES__\", json.dumps(sorted(_TUTORIAL_OPTIONAL_NOTES))\n",
    ").replace(\n",
    "    \"__COMPLETED__\", json.dumps(sorted(_TUTORIAL_COMPLETED))\n",
    ").replace(\n",
    "    \"__SELECTIONS__\", json.dumps(_TUTORIAL_SELECTIONS)\n",
    ")\n",
    "\n",
    "display(Javascript(_tutorial_progress_javascript))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t6-step-1-0-1",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"0\" hidden></span>\n",
    "\n",
    "# Tutorial 6: The Worst Language Model\n",
    "\n",
    "<div class=\"alert alert-info\">\n",
    "Week 9 | Author: Rayo Verweij (<code>rayo.verweij@ed.ac.uk</code>)<br>\n",
    "</div>\n",
    "\n",
    "Welcome back, for the final time already!\n",
    "\n",
    "Throughout this course, we have touched on different types of AI: symbolic AI with EDIZA in Tutorial 2, and an intro to generative AI in Lecture 8. Today, we are finishing this exploration with a deeper dive into **language models** and what it takes to run them yourself.\n",
    "\n",
    "Running language models yourself has several advantages over using commercial models: the environmental impact of using them is no greater than your computer's electricity usage, and you can be certain that your data is not being collected by anyone. However, running large language models requires powerful hardware. To ensure that everyone can participate, we'll therefore be running one of the *smallest* language models that exists, the appropriately named *SmolLM*.\n",
    "\n",
    "As to whether it'll actually be *useful*... well, let's put a pin in that for now.\n",
    "\n",
    "---\n",
    "\n",
    "## 1 Introductions\n",
    "\n",
    "Find yourself a partner at about the **same skill level**. Both of you should write and run the code on your own laptops, although you only need to fill out one copy of this tutorial sheet. Take turns predicting what will happen and explaining what actually happened. Write both your names below.\n",
    "\n",
    "<div class=\"alert alert-info\">\n",
    "<b>ℹ️ Checking your work</b>\n",
    "\n",
    "As before, replace the placeholder in each checker cell and run it using the ▶️ button or Ctrl+Enter. Leave its <code>%%check</code> line in place. Paste only the output requested, without commands or terminal prompts.\n",
    "\n",
    "Some checks expect an exact answer whereas others simply record your observations for discussion with your partner and tutor. <b>Large language model outputs are almost always somewhat random by nature</b>, so cells that ask for their output will never need any specific wording.\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t6-check-1-0-1",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 1.0.1\n",
    "WRITE NAMES HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t6-step-2-1-1",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"1\" hidden></span>\n",
    "\n",
    "## 2 Installing all necessities\n",
    "\n",
    "### 2.1 Set up the environment\n",
    "\n",
    "Open your `Intro to Programming` folder in VS Code and open a terminal. Leave any active environment using `deactivate`. On Windows, use the **Command Prompt**, as in Tutorial 3.\n",
    "\n",
    "Run these commands **one line at a time**:\n",
    "\n",
    "```text\n",
    "mkdir tutorial-6\n",
    "cd tutorial-6\n",
    "uv init --bare --python 3.12\n",
    "```\n",
    "\n",
    "If the `uv` command is not recognised, revisit Tutorial 3's installation instructions. \n",
    "\n",
    "We use `uv init` with two flags: `--bare` sets up a minimal project, and `--python 3.12` uses that specific version of Python as we need it for the libraries we will rely on today. uv will automatically download it if necessary.\n",
    "\n",
    "If the project was initialised successfully, install those libraries as follows:\n",
    "\n",
    "```text\n",
    "uv add torch --index pytorch=https://download.pytorch.org/whl/cpu\n",
    "uv add transformers\n",
    "```\n",
    "\n",
    "These packages are quite large so downloading them might take a second. They each have different jobs:\n",
    "\n",
    "| Package | Job |\n",
    "| --- | --- |\n",
    "| **PyTorch**, installed as `torch` | Performs the numerical calculations that run the language model. |\n",
    "| **Transformers** | Provides the Python interface for loading models, preparing their input, and generating text. |\n",
    "\n",
    "The `--index` argument indicates which *version* of PyTorch we are using. We will use its CPU packages, which means it will run on your machine regardless of whether or not you have a dedicated graphics card.\n",
    "\n",
    "As in Tutorial 3, uv creates `.venv`, records dependencies in `pyproject.toml`, and records their versions in `uv.lock`. Leave both `.venv` and `uv.lock` alone throughout this tutorial.\n",
    "\n",
    "Now open `tutorial-6` using **File > Open Folder...** and open a terminal there.\n",
    "\n",
    "Create a file named `check_environment.py` in the project's root folder (alongside `pyproject.toml` and `uv.lock`), containing:\n",
    "\n",
    "```python\n",
    "import sys\n",
    "import torch\n",
    "import transformers\n",
    "\n",
    "print(\"Libraries ready.\")\n",
    "print(sys.prefix != sys.base_prefix)\n",
    "```\n",
    "\n",
    "Now run `uv run check_environment.py`. If the libraries were installed correctly, it should run the `import` statements without any errors and print both statements.\n",
    "\n",
    "What does the second print statement do? Remember, `uv run` automatically uses the virtual environment for us. The `prefix` attribute of the `sys` (system) library allows us to check where the Python installation that we are running is installed. By checking `sys.prefix != sys.base_prefix`, we are checking that the Python installation that the file is using is *different* from our default Python installation. This is what we want, because that means Python is running inside a virtual envirionment!\n",
    "\n",
    "Paste the two printed lines below. If you'd like, yo can inspect the installed versions of the libraries with `uv pip show torch transformers`.\n",
    "\n",
    "<div class=\"alert alert-info\">\n",
    "<b>ℹ️ Troubleshooting installation errors</b>\n",
    "\n",
    "If installation of the libraries fails, read the error with your tutor and have a look together. Older computers, particularly Intel Macs or Macs running macOS versions before 14, may need a different PyTorch setup. If you aren't able to figure it out in about 15 minutes, feel free to start working together with someone else on their laptop so you can still go through the entire tutorial.\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t6-check-2-1-1",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 2.1.1\n",
    "PASTE OUTPUT HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t6-step-2-2-1",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"2\" hidden></span>\n",
    "\n",
    "### 2.2 Read the label\n",
    "\n",
    "The model we will use today is called **SmolLM2-135M-Instruct**. SmolLM is its name, 2 its version number, and 135M the number of parameters in the model - 135 million of them. Each parameter is one of the numbers adjusted during training of the model. There's a lot of them, but this is actually one of the tiniest models available. Others can have up to 1,000 times the number of parameters!\n",
    "\n",
    "We can download the model from Hugging Face, a platform where developers and researchers share the language models they've created. First open the model's [Hugging Face page for SmolLM2-135M](https://huggingface.co/HuggingFaceTB/SmolLM2-135M) and then its [SmolLM2-135M-Instruct page](https://huggingface.co/HuggingFaceTB/SmolLM2-135M-Instruct). The description on each page is called a **model card**. Like documentation for a package, it tells us what we are downloading and how to use it.\n",
    "\n",
    "SmolLM2-135M is the **base** model, which is simply trained to continue text. The **Instruct** version, which we will be using today, has additional training for following instructions and conversations. Many language models, small and large, follow this pattern of having a base and instruct version.\n",
    "\n",
    "On the Instruct card, read the **Model Summary** and **Limitations** sections. Discuss:\n",
    "\n",
    "- Who published this model?\n",
    "- What kinds of tasks do they say it can do?\n",
    "- What limitations does its publisher acknowledge?\n",
    "\n",
    "Record your answers below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t6-check-2-2-1",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 2.2.1\n",
    "WRITE NOTES HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t6-step-3-1-1",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"3\" hidden></span>\n",
    "\n",
    "## 3 First words\n",
    "\n",
    "### 3.1 Follow the model card\n",
    "\n",
    "Create a file named `one_reply.py` in `tutorial-6` and paste in the following code, adapted from the **How to use** section on the model card:\n",
    "\n",
    "```python\n",
    "from transformers import AutoModelForCausalLM, AutoTokenizer\n",
    "\n",
    "model_name = \"HuggingFaceTB/SmolLM2-135M-Instruct\"\n",
    "tokenizer = AutoTokenizer.from_pretrained(model_name)\n",
    "model = AutoModelForCausalLM.from_pretrained(model_name, dtype=\"float32\").to(\"cpu\")\n",
    "\n",
    "messages = [{\"role\": \"user\", \"content\": \"What is the capital of Scotland?\"}]\n",
    "\n",
    "prompt = tokenizer.apply_chat_template(\n",
    "    messages, tokenize=False, add_generation_prompt=True\n",
    ")\n",
    "inputs = tokenizer(prompt, return_tensors=\"pt\", add_special_tokens=False)\n",
    "outputs = model.generate(\n",
    "    input_ids=inputs[\"input_ids\"],\n",
    "    attention_mask=inputs[\"attention_mask\"],\n",
    "    max_new_tokens=80,\n",
    "    do_sample=False,\n",
    "    pad_token_id=tokenizer.eos_token_id,\n",
    ")\n",
    "prompt_length = len(inputs[\"input_ids\"][0])\n",
    "new_tokens = outputs[0][prompt_length:]\n",
    "reply = tokenizer.decode(new_tokens, skip_special_tokens=True)\n",
    "print(reply)\n",
    "```\n",
    "\n",
    "Run it with `uv run one_reply.py`.\n",
    "\n",
    "**Note:** the first run has to download the tokeniser and model weights from Hugging Face, which again can take a bit of time. As these are public files, this example does not require an account or API key. The model then generates its reply **on your computer**. \n",
    "\n",
    "Some library warnings may appear in the terminal, but you're safe to ignore them. If VS Code highlights any errors, such as on the `generate` method on line 13, you can probably ignore those lines as well.\n",
    "\n",
    "While the model is loading, take a minute to familiarise yourself with the code above. The tokenizer and model are both **objects** supplied by the library. As with other objects we've used, we call their methods to ask them to do particular jobs. In short:\n",
    "\n",
    "- The tokeniser converts the input message into tokens;\n",
    "- This is fed into the model's `generate` method, along with some settings such as the answer's maximum length (80 in our code);\n",
    "- We calculate how many tokens long our input message was and save it to `prompt_length`;\n",
    "- We use this to remove the input prompt from the `outputs` list and save the remaining output to `new_tokens`; and finally\n",
    "- We send this back to the tokeniser which now converts the generated numbers back to text, which we print in the terminal.\n",
    "\n",
    "Paste the reply you got below (without loading progress or warning messages). Did it answer your question?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t6-check-3-1-1",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 3.1.1\n",
    "WRITE NOTES HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t6-step-3-2-1",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"4\" hidden></span>\n",
    "\n",
    "### 3.2 Where does the reply begin?\n",
    "\n",
    "Let's take a look at some of these mechanisms in a bit more detail.\n",
    "\n",
    "| Variable or function | Use |\n",
    "| --- | --- |\n",
    "| `messages` | A list of dictionaries, each containing a speaker's `role` and their text in `content`. |\n",
    "| `apply_chat_template(...)` | Formats those messages using the model's conversation markers. `add_generation_prompt=True` marks where the assistant's reply should begin. |\n",
    "| `tokenizer(...)` | Converts the formatted text into numerical **token IDs**. `add_special_tokens=False` avoids adding markers a second time. |\n",
    "| `model.generate(...)` | Continues the token sequence by predicting what comes next, producing up to `max_new_tokens` new tokens. |\n",
    "| `tokenizer.decode(...)` | Converts token IDs back into text. `skip_special_tokens=True` leaves out the conversation markers. |\n",
    "\n",
    "When building EDIZA, we split text into words ourselves, but this time we have a tokeniser to do it for us. Note that each tokeniser has its own learned vocabulary: a token might represent a word, part of a word, punctuation, or another piece of text. *80 tokens does not necessarily mean 80 words!*\n",
    "\n",
    "The returned sequence contains *both the prompt and the new reply*. We use indexing and slicing to keep just the new part. Let's try the same idea with ordinary lists in a temporary file called `slicing.py`:\n",
    "\n",
    "```python\n",
    "input_ids = [[11, 12, 13]]\n",
    "output_ids = [[11, 12, 13, 40, 41]]\n",
    "\n",
    "prompt_length = len(input_ids[0])\n",
    "print(prompt_length)\n",
    "print(output_ids[0][prompt_length:])\n",
    "```\n",
    "\n",
    "Predict what output you'll get and then run `uv run slicing.py` and paste them below. Why would decoding the whole output be inconvenient once we have several turns of conversation?\n",
    "\n",
    "If you don't remember slicing syntax, take a look at Lecture 12 again."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t6-check-3-2-1",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 3.2.1\n",
    "PASTE OUTPUT HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t6-step-3-3-1",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"5\" hidden></span>\n",
    "\n",
    "### 3.3 A little unpredictability\n",
    "\n",
    "Return to `one_reply.py`. Change the message to `Suggest a name for a very small dragon.`\n",
    "\n",
    "1. Run the unchanged generation settings twice.\n",
    "\n",
    "With `do_sample=False`, the model always chooses the highest-scoring next token at each step. This is called **greedy decoding**. Compare the two replies you get - what can you notice?\n",
    "\n",
    "2. Change `do_sample=False` to `do_sample=True` and add `temperature=0.8` as another argument to `generate`. Run it three times with the same message.\n",
    "\n",
    "Sampling introduces randomness into which tokens are chosen. Are the replies any different?\n",
    "\n",
    "3. Change **only** `temperature` to `1.2` and repeat.\n",
    "\n",
    "Higher temperatures make the choices less concentrated on the highest-scoring options. Do you notice any change?\n",
    "\n",
    "4. Try `max_new_tokens=20`. What happens if the model runs out of its token allowance in the middle of a sentence?\n",
    "\n",
    "For each setting, record the replies you received. Discuss with your partner: for what types of questions would you prefer a low temperature, and when would you prefer a higher one?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t6-check-3-3-1",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 3.3.1\n",
    "WRITE NOTES HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t6-step-3-4-1",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"6\" hidden></span>\n",
    "\n",
    "### 3.4 Put it to the test\n",
    "\n",
    "Restore `max_new_tokens` to a length of your choice and `do_sample=False`, and remove the `temperature` argument.\n",
    "\n",
    "Then, design three short prompts with your partner. Create:\n",
    "\n",
    "- A factual question that you can easily check the answer of.\n",
    "- A small calculation or programming problem that you can easily check in Python yourself.\n",
    "- An instruction with an clear rule, such as giving exactly three items of something or avoiding a particular word in an answer.\n",
    "\n",
    "For each of them, check whether the model is able to handle it. If all three work, make one a little more demanding. If none work, try simplifying one. How reliable are you finding this model?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t6-check-3-4-1",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 3.4.1\n",
    "WRITE NOTES HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t6-step-4-1-1",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"7\" hidden></span>\n",
    "\n",
    "## 4 Building a chatbot\n",
    "\n",
    "### 4.1 Who said what?\n",
    "\n",
    "EDIZA kept asking for input because we put it inside a `while` loop. To build our own language model-based chatbot, we can do something simliar, but this time we will also keep a **conversation history** for the model to draw upon.\n",
    "\n",
    "Create a file named `chat.py` and populate it with this function and small test program:\n",
    "\n",
    "```python\n",
    "def add_message(messages, role, content):\n",
    "    pass  # Build a new dictionary with keys \"role\" and \"content\", and append it to messages\n",
    "\n",
    "\n",
    "def main():\n",
    "    messages = []\n",
    "    add_message(messages, \"user\", \"My dragon is called Pip.\")\n",
    "    add_message(messages, \"assistant\", \"Hello, Pip!\")\n",
    "\n",
    "    assert len(messages) == 2\n",
    "    assert messages[0][\"role\"] == \"user\"\n",
    "    assert messages[0][\"content\"] == \"My dragon is called Pip.\"\n",
    "    assert messages[1][\"role\"] == \"assistant\"\n",
    "    assert messages[1][\"content\"] == \"Hello, Pip!\"\n",
    "    print(len(messages))\n",
    "    print(messages[0][\"role\"])\n",
    "    print(messages[1][\"content\"])\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()\n",
    "```\n",
    "\n",
    "Replace `pass` with the implementation of a function that adds a message with a certain `role` and `content` to `messages`. Look to the assertions for additional hints for how the function should work.\n",
    "\n",
    "Run `uv run chat.py` and paste the three printed lines below once the assertions pass."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t6-check-4-1-1",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 4.1.1\n",
    "PASTE OUTPUT HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t6-step-4-2-1",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"8\" hidden></span>\n",
    "\n",
    "### 4.2 Keep talking\n",
    "\n",
    "Let's test our conversation rules with something more predictable than a language model. Add this temporary function above `main()`:\n",
    "\n",
    "```python\n",
    "def get_reply(messages):\n",
    "    return \"I heard: \" + messages[-1][\"content\"]\n",
    "```\n",
    "\n",
    "It simply echoes the last message. We know exactly what it should return, which lets us investigate our own code without waiting for the model or guessing what it will say.\n",
    "\n",
    "Keep `add_message`, but replace `main()` with the following scaffold. Also keep the `if __name__ == \"__main__\":` block at the end of the file.\n",
    "\n",
    "```python\n",
    "def main():\n",
    "    messages = []\n",
    "    print(\"SMOL: Hello! Type bye to stop.\")\n",
    "\n",
    "    while True:\n",
    "        message = input(\"You: \").strip()\n",
    "        if message.lower() == \"bye\":\n",
    "            print(\"SMOL: Goodbye!\")\n",
    "            break\n",
    "        elif message == \"\":\n",
    "            print(\"SMOL: Please type a message.\")\n",
    "        else:\n",
    "            pass  # Add the user's message to the history\n",
    "            pass  # Call get_reply with the message history and store its return value\n",
    "            pass  # Add that reply to the history with role \"assistant\"\n",
    "            pass  # Print the reply, prefixed with \"SMOL:\"\n",
    "```\n",
    "\n",
    "We've copied over our structure from EDIZA: the greeting only appears once, empty input should not generate a reply, and `bye` ends the loop.\n",
    "\n",
    "Complete the four lines in the `else` statement. Then run the file, enter `HELLO, Edinburgh!`, an empty input, and finally `BYE`. Paste the **three responses after the greeting** (including the SMOL: prefix) below.\n",
    "\n",
    "If you get an endless stream of replies, you're in an infinite loop - stop with Ctrl+C and check the position of `input()` and the indentation!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t6-check-4-2-1",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 4.2.1\n",
    "PASTE OUTPUT HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t6-step-4-3-1",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"9\" hidden></span>\n",
    "\n",
    "### 4.3 Check the history\n",
    "\n",
    "The conversation loop is working, but are we actually saving everything in the conversation?\n",
    "\n",
    "At the end of `main()`, **after and outside the `while` loop**, temporarily add:\n",
    "\n",
    "```python\n",
    "for entry in messages:\n",
    "    print(entry[\"role\"] + \": \" + entry[\"content\"])\n",
    "```\n",
    "\n",
    "Run the program again. Enter `Tea`, then `Biscuits`, then `bye`. Paste only the **history lines printed after `SMOL: Goodbye!`** below.\n",
    "\n",
    "You should see the messages in conversation order, without the greeting or the farewell command. If you only see the final exchange, or both entries change together, fix your code accordingly.\n",
    "\n",
    "Not sure where you went wrong? Use the debugger to inspect `messages` just before `get_reply` is called. At that point, what should the last message's role be? Why do we append the user's message before asking for the reply, and the assistant's message afterwards?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t6-check-4-3-1",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 4.3.1\n",
    "PASTE OUTPUT HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t6-step-4-4-1",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"10\" hidden></span>\n",
    "\n",
    "### 4.4 A fresh start\n",
    "\n",
    "Add a `reset` command. It should discard the conversation history without ending the program or asking `get_reply` for a response.\n",
    "\n",
    "1. Add an `elif` branch **before** the final `else`, checking whether `message.lower() == \"reset\"`.\n",
    "2. In that branch, assign a new empty list to `messages` and print exactly `SMOL: New conversation.`\n",
    "3. Remove the temporary `for` loop from section 4.3.\n",
    "4. In its place, after the `while` loop, temporarily add `print(\"Saved messages:\", len(messages))`.\n",
    "\n",
    "Run the program and enter `Tea`, then `RESET`, then an empty input, then `BYE`.\n",
    "\n",
    "Paste the **four responses after the greeting as well as the saved-message count** below. This allows us to check that both commands and empty input stay out of the history.\n",
    "\n",
    "When you've done so, remove the temporary print statement."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t6-check-4-4-1",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 4.4.1\n",
    "PASTE OUTPUT HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t6-step-5-1-1",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"11\" hidden></span>\n",
    "\n",
    "## 5 The worst chatbot\n",
    "\n",
    "### 5.1 Connecting the model\n",
    "\n",
    "We'll keep `one_reply.py` as a record of our first experiments and create a new file, `model_tools.py`, to connect to `chat.py`.\n",
    "\n",
    "Copy the **import and three loading lines** from the top of `one_reply.py` into `model_tools.py`: the import from `transformers` as well as the assignments to `model_name`, `tokenizer`, and `model`.\n",
    "\n",
    "Next, write a function `get_reply` that takes in a `messages` parameter. Copy over the code from `one_reply.py` starting on line 9 (beginning with `prompt =`), paste it in the function body, and **edit the final two lines** so that:\n",
    "\n",
    "1. The model's reply is returned rather than printed; and\n",
    "2. Any excess whitespace is stripped off of the model's reply.\n",
    "\n",
    "Do not copy over the old fixed message list.\n",
    "\n",
    "In `chat.py`, **delete the temporary echo version of `get_reply`** and add this import at the top:\n",
    "\n",
    "```python\n",
    "from model_tools import get_reply\n",
    "```\n",
    "\n",
    "We can keep our history function, loop, commands, and main guard. The conversation code calls a function with the same name and input as before, but now gets its reply from a model. This is the benefit of decomposing our code into multiple functions!\n",
    "\n",
    "Run `uv run chat.py`. The model loads when the module is imported, so the greeting may take a moment to appear. Have at least **two ordinary turns in one run**, then use `bye`.\n",
    "\n",
    "Record the conversation below!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t6-check-5-1-1",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 5.1.1\n",
    "WRITE NOTES HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t6-step-5-2-1",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"12\" hidden></span>\n",
    "\n",
    "### 5.2 What does it actualy remember?\n",
    "\n",
    "Start a fresh run and say `My dragon is called Luigi.` Then ask `What is my dragon called?` Did the model get it correct?\n",
    "\n",
    "Next, enter `reset`, then ask that same question again. What about now?\n",
    "\n",
    "The model does not keep the conversation in some kind of memory; instead, each call to `get_reply` sends the **whole current list** as input. Appending to that list gives the model more context to use in its predictions, but **does not retrain it or change its learned parameters**. Resetting the list removes that context from subsequent calls, as does restarting the program.\n",
    "\n",
    "We can verify this using the debugger. Set a breakpoint on `get_reply(messages)` and send some input to the chatbot. When the line is highlighted, select `main` under CALL STACK, inspect the `messages` variable, and see how it updates as you step through the code. Caution: use **Step Over** for the model call - exploring the library's internals would take us rather beyond this tutorial!\n",
    "\n",
    "Can the model fail to recall the name even when the correct history was supplied? Can it invent a name after a reset? Describe your observations.\n",
    "\n",
    "<div class=\"alert alert-info\">\n",
    "<b>ℹ️ Models do not have unlimited memory</b>\n",
    "\n",
    "The model has a finite <b>context window</b>, how much input it can process at once, measured in tokens. In addition, the longer the message history, the slower generation becomes. Keep your experiments short and use <code>reset</code> between them to not spend too much time waiting.\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t6-check-5-2-1",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 5.2.1\n",
    "WRITE NOTES HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t6-step-5-3-1",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"13\" hidden></span>\n",
    "\n",
    "### 5.3 Small but useful?\n",
    "\n",
    "Well done, you now have a complete, somewhat-functioning chatbot! Language models are very complex systems but hopefully this has demystified them at least a little bit. While many of SmolLM's responses weren't particularly good, let's finish by having a bit of a think:\n",
    "\n",
    "**When might a small language model be a better choice than a larger one?**\n",
    "\n",
    "Discuss this with your partner, drawing on your experiments. Consider:\n",
    "\n",
    "- **Control and resource use.** What are the benefits of running a model on an ordinary laptop?\n",
    "- **Being good enough.** Can you think of tasks where this model's abilities would be sufficient, even if a larger model could do better?\n",
    "- **Trade-offs.** What might you gain or lose by choosing a larger model?\n",
    "\n",
    "Add your discussion notes below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t6-check-5-3-1",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 5.3.1\n",
    "WRITE NOTES HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t6-step-6-1-1",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"14\" hidden></span>\n",
    "\n",
    "## 6 Bonus Tasks\n",
    "\n",
    "Well done, you've finished the final tutorial of the course! From installing Python to using entire language models, you've come a *very* long way in just 10 short weeks. I hope that this tutorial has shown you that you now have the ability to use even very complicated pieces of software by just following the instructions and making some of your own changes.\n",
    "\n",
    "As always, if you still have time left over, here are some bonus tasks to work on.\n",
    "\n",
    "### 6.1 A slightly larger brain\n",
    "\n",
    "Download **another small model** and compare it with ours. A convenient starting point is [SmolLM2-360M-Instruct](https://huggingface.co/HuggingFaceTB/SmolLM2-360M-Instruct), a slightly larger sibling of our model that uses the same code. You could also choose a different small, text-only instruction model, but will need to read their model card carefully as you might have to make adjustments to the code.\n",
    "\n",
    "If you use SmolLM2-360M-Instruct, you simply have to change the `model_name` variable and the next time you run the code, the `transformers` library will automatically download it. Remember, the larger the model, the longer it will take to load!\n",
    "\n",
    "Can you spot any differences between answers? What do you think it would take to run a comprehensive test to see which one is better?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t6-check-6-1-1",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 6.1.1\n",
    "WRITE NOTES HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t6-step-6-2-1",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"14\" hidden></span>\n",
    "\n",
    "### 6.2 Who's hugging whose face?\n",
    "\n",
    "Today, we used **Hugging Face** to download our models. SmolLM too was created by people at Hugging Face for research purposes. But who are *they*, and who controls them? Let's find out!\n",
    "\n",
    "- Who founded Hugging Face, when, and what did it originally make?\n",
    "- What does the company do now, and how does it make money?\n",
    "- **Who owns it now?** Is it independent, publicly traded, or owned by another company? What evidence can you find about shareholders, investors, and who controls it?\n",
    "- How does ownership of the company relate to the licences of the transformers library and the model we downloaded? Does hosting a model mean Hugging Face owns it?\n",
    "\n",
    "Start with [Hugging Face's company page](https://huggingface.co/huggingface) and [blog](https://huggingface.co/blog), then see what else you can find online. Write a short answer with **source links and the date they were published**."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t6-check-6-2-1",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 6.2.1\n",
    "WRITE NOTES HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t6-step-6-3-1",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"14\" hidden></span>\n",
    "\n",
    "### 6.3 Read the fine print\n",
    "\n",
    "Here's one for the nerds. Most model releases on Hugging Face are accompanied with a research paper that describes the training procedures used. The paper for SmolLM2 was released on arXiv, a paper repository where people can upload their papers without needing to go through the process of peer-review.\n",
    "\n",
    "Find the SmolLM2 paper on arXiv: [*SmolLM2: When Smol Goes Big — Data-Centric Training of a Small Language Model*](https://arxiv.org/abs/2502.02737). You can read either the PDF or the [HTML version](https://arxiv.org/html/2502.02737v1). This is a research paper, so there will be a lot of unfamiliar terminology - take a look anyway, and see what you can figure out.\n",
    "\n",
    "Try to answer (some of) the following:\n",
    "\n",
    "1. **Training data:** Which datasets and kinds of text were used? What filtering or selection is described? Can you establish the origin and licence of every part, or would you need to follow more references?\n",
    "2. **Our model:** What does section 6 say about the **135M** model, and how does it differ from the headline **1.7B** model?\n",
    "3. **Environmental impact:** What information is reported about hardware, compute, training duration, electricity, water, or carbon emissions? Which of those are absent?\n",
    "\n",
    "Write down your notes and any other things that strike you as interesting or peculiar below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t6-check-6-3-1",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 6.3.1\n",
    "WRITE NOTES HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t6-summary",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"14\" hidden></span>\n",
    "\n",
    "## 7 Summary\n",
    "\n",
    "...and that's us done. If you're reading this, you've probably worked through most if not all of the tutorials for this course, so well done again. Please don't hesitate to give us feedback or let us know if you find any mistakes or points of unclarity - it would be much appreciated.\n",
    "\n",
    "Quite a journey from your first `print(\"Hello world\")`!\n",
    "\n",
    "As always, some key terms to take away:\n",
    "\n",
    "<dl>\n",
    "    <dt><b>Language model</b></dt>\n",
    "    <dd>A model trained to predict tokens, which can generate text by repeatedly selecting another token.</dd>\n",
    "    <dt><b>Parameters / weights</b></dt>\n",
    "    <dd>The numerical values learned during training and loaded when a language model is run.</dd>\n",
    "    <dt><b>Instruction tuning</b></dt>\n",
    "    <dd>Additional training that adapts a base language model to follow instructions and respond in conversations.</dd>\n",
    "    <dt><b>Tokeniser</b></dt>\n",
    "    <dd>The component that converts text into token IDs and converts token IDs back into text. Remember - tokens are not necessarily whole words!</dd>\n",
    "    <dt><b>Context window</b></dt>\n",
    "    <dd>The finite token capacity within which the model can use that input and generate a reply.</dd>\n",
    "    <dt><b>Inference</b></dt>\n",
    "    <dd>The process of running a language model and having it generate tokens.</dd>\n",
    "    <dt><b>Sampling</b></dt>\n",
    "    <dd>Introducing randomness during inference by selecting random tokens from its predictions.</dd>\n",
    "</dl>\n",
    "\n",
    "### Sources and further reading\n",
    "\n",
    "- [SmolLM2-135M model card](https://huggingface.co/HuggingFaceTB/SmolLM2-135M) and [SmolLM2-135M-Instruct model card](https://huggingface.co/HuggingFaceTB/SmolLM2-135M-Instruct)\n",
    "- [Transformers: installation](https://huggingface.co/docs/transformers/en/installation)\n",
    "- [uv: using PyTorch](https://docs.astral.sh/uv/guides/integration/pytorch/)\n",
    "- [SmolLM2 paper on arXiv](https://arxiv.org/abs/2502.02737)\n",
    "\n",
    "---\n",
    "\n",
    "### Start over\n",
    "\n",
    "Use this button to erase every answer in this notebook and begin the tutorial again!\n",
    "\n",
    "<button type=\"button\" data-tutorial-reset style=\"padding:8px 14px;border:1px solid #b91c1c;border-radius:6px;background:#dc2626;color:white;font-weight:600;cursor:pointer\">Reset all tutorial progress</button>"
   ]
  }
 ],
 "metadata": {
  "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"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
