{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "78ff4d5a",
   "metadata": {},
   "source": [
    "# Week 4: In-Context Learning and Training Data Generation\n",
    "\n",
    "In this practical, we will explore:\n",
    "\n",
    "1. **Chat Templates**: Understanding how LLMs format conversations\n",
    "   - Exploring `apply_chat_template` and its parameters\n",
    "   - Introduction to thinking models (DeepSeek-R1, Qwen3)\n",
    "1. **In-Context Learning (ICL)**: Learning from examples in the prompt\n",
    "   - Chain-of-Thought (CoT) prompting for step-by-step reasoning\n",
    "   - Self-Consistency for improved reliability\n",
    "1. **Dataset Exploration**: Working with the LoTTE IR benchmark\n",
    "1. **Training Data Generation**: Creating synthetic queries for IR training\n",
    "   - Validating generated queries using ROUGE and BERTScore\n",
    "1. **Introduction to RAG**: Simple RAG with BM25 retrieval\n",
    "\n",
    "We use the LoTTE (Long-Tail Topic-stratified Evaluation) dataset,\n",
    "which contains StackExchange Q&A pairs with search queries."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "816a9cbc",
   "metadata": {},
   "source": [
    "## Setup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ca036925",
   "metadata": {
    "tags": [
     "colab",
     "pip",
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "# Installing required packages\n",
    "\n",
    "%pip install setuptools==80.9.0\n",
    "\n",
    "# Installing main packages\n",
    "\n",
    "%pip install evaluate==0.4.6\n",
    "%pip install pyterrier==1.0.1\n",
    "%pip install su-master-mind==2026.1.25.4\n",
    "%pip install torch==2.9.1\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f9b74c93",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "import pandas as pd\n",
    "import pyterrier as pt\n",
    "import getpass\n",
    "import os\n",
    "import tarfile\n",
    "import urllib.request\n",
    "from collections import Counter\n",
    "from pathlib import Path\n",
    "from typing import Dict, List, Tuple\n",
    "from master_mind.teaching.hf import load_hf_model, load_hf_tokenizer\n",
    "from evaluate import load as load_metric\n",
    "from rouge_score import rouge_scorer\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "459dfdb9",
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_best_device():\n",
    "    \"\"\"Returns the best device on this computer\"\"\"\n",
    "\n",
    "    if torch.cuda.is_available():\n",
    "        device = torch.device(\"cuda\")\n",
    "        total_memory = torch.cuda.get_device_properties(device).total_memory\n",
    "        print(f\"GPU Memory: {total_memory / 1e9:.1f} GB\")\n",
    "        print(f\"GPU Name: {torch.cuda.get_device_name(device)}\")\n",
    "    elif torch.backends.mps.is_available():\n",
    "        device = torch.device(\"mps\")\n",
    "    else:\n",
    "        device = torch.device(\"cpu\")\n",
    "    print(f\"Found device: {device}\")\n",
    "    return device\n",
    "\n",
    "\n",
    "device = get_best_device()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1c58ff22",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"Cache utilities for downloading and caching files.\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "889b2bb9",
   "metadata": {
    "tags": [
     "hidden"
    ]
   },
   "outputs": [],
   "source": [
    "def get_from_cache(url: str, name: str) -> Path:\n",
    "    \"\"\"Get a file from cache, downloading it if necessary.\n",
    "\n",
    "    Args:\n",
    "        url: URL to download the file from if not cached.\n",
    "        name: Name of the cached file.\n",
    "\n",
    "    Returns:\n",
    "        Path to the cached file.\n",
    "    \"\"\"\n",
    "    cache_dir_env = os.environ.get(\"MASTER_MIND_CACHE\")\n",
    "\n",
    "    if cache_dir_env:\n",
    "        # Check if file exists in the cache directory\n",
    "        cache_path = Path(cache_dir_env) / name\n",
    "        if cache_path.exists():\n",
    "            print(f\"Found {cache_path}\")\n",
    "            return cache_path\n",
    "\n",
    "        # File doesn't exist, create temp directory and download\n",
    "        username = getpass.getuser()\n",
    "        temp_dir = Path(f\"/tmp/{username}/master-mind\")\n",
    "        print(f\"Did not find {name} in ${cache_dir_env}, downloading to {temp_dir}...\")\n",
    "        temp_dir.mkdir(parents=True, exist_ok=True)\n",
    "        cache_path = temp_dir / name\n",
    "    else:\n",
    "        # No cache env variable, use outputs/cache\n",
    "        cache_dir = Path(\"outputs/cache\")\n",
    "        cache_dir.mkdir(parents=True, exist_ok=True)\n",
    "        cache_path = cache_dir / name\n",
    "\n",
    "    # Download if file doesn't exist\n",
    "    if not cache_path.exists():\n",
    "        print(f\"Loading {url} to cache {cache_path}...\")\n",
    "        cache_path.parent.mkdir(parents=True, exist_ok=True)\n",
    "        if url.endswith(\".tar.gz\"):\n",
    "            # Download to temp file and extract\n",
    "            archive_path = cache_path.with_suffix(\".tar.gz\")\n",
    "            urllib.request.urlretrieve(url, archive_path)\n",
    "            with tarfile.open(archive_path, \"r:gz\") as tar:\n",
    "                tar.extractall(path=cache_path)\n",
    "            archive_path.unlink()\n",
    "        else:\n",
    "            urllib.request.urlretrieve(url, cache_path)\n",
    "\n",
    "    return cache_path"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1425b90a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load a model for generation\n",
    "#\n",
    "# Options (uncomment ONE model_name):\n",
    "#\n",
    "# 1. SmolLM2-1.7B float16 (~3.4GB) - default, works on all platforms\n",
    "model_name = \"HuggingFaceTB/SmolLM2-1.7B-Instruct\"\n",
    "#\n",
    "# 2. Pre-quantized models (GPTQ/AWQ) - Linux only, requires:\n",
    "#    uv pip install auto-gptq autoawq  (or: uv sync --extra quantized)\n",
    "# FIXME: update to Qwen3 and test\n",
    "# model_name = \"Qwen/Qwen2.5-3B-Instruct-AWQ\"  # 3B AWQ, ~2GB\n",
    "# model_name = \"Qwen/Qwen2.5-7B-Instruct-AWQ\"  # 7B AWQ, ~4GB\n",
    "\n",
    "tokenizer = load_hf_tokenizer(model_name)\n",
    "\n",
    "# Detect if model is pre-quantized (AWQ/GPTQ) by name\n",
    "is_quantized = \"AWQ\" in model_name or \"GPTQ\" in model_name\n",
    "\n",
    "if is_quantized:\n",
    "    # Pre-quantized models need autoawq/auto-gptq (Linux only)\n",
    "    model = load_hf_model(\n",
    "        model_name,\n",
    "        AutoModelForCausalLM,\n",
    "        device_map=\"auto\",\n",
    "    )\n",
    "    print(f\"Model loaded: {model_name} (pre-quantized)\")\n",
    "else:\n",
    "    model = load_hf_model(\n",
    "        model_name,\n",
    "        AutoModelForCausalLM,\n",
    "        dtype=torch.float16,\n",
    "    )\n",
    "    model = model.to(device)\n",
    "    print(f\"Model loaded: {model_name} on {device}\")\n",
    "\n",
    "model.eval()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "81fc9cc0",
   "metadata": {},
   "outputs": [],
   "source": [
    "def build_prompt(user: str, system: str = \"You are a helpful assistant.\") -> str:\n",
    "    \"\"\"Build a chat-format prompt using the tokenizer's chat template.\"\"\"\n",
    "    messages = [\n",
    "        {\"role\": \"system\", \"content\": system},\n",
    "        {\"role\": \"user\", \"content\": user},\n",
    "    ]\n",
    "    return tokenizer.apply_chat_template(\n",
    "        messages, tokenize=False, add_generation_prompt=True\n",
    "    )\n",
    "\n",
    "\n",
    "@torch.no_grad()\n",
    "def generate_text(\n",
    "    prompt: str,\n",
    "    max_new_tokens: int = 100,\n",
    "    temperature: float = 0.7,\n",
    "    do_sample: bool = True,\n",
    "    num_return_sequences: int = 1,\n",
    ") -> list[str]:\n",
    "    \"\"\"Generate text from a prompt.\"\"\"\n",
    "    inputs = tokenizer(prompt, return_tensors=\"pt\").to(device)\n",
    "\n",
    "    outputs = model.generate(\n",
    "        **inputs,\n",
    "        max_new_tokens=max_new_tokens,\n",
    "        temperature=temperature,\n",
    "        do_sample=do_sample,\n",
    "        num_return_sequences=num_return_sequences,\n",
    "        pad_token_id=tokenizer.eos_token_id,\n",
    "    )\n",
    "\n",
    "    # Decode and extract only the response\n",
    "    generated = []\n",
    "    for output in outputs:\n",
    "        text = tokenizer.decode(output, skip_special_tokens=True)\n",
    "        # Extract the part after the last \"assistant\"\n",
    "        if \"assistant\" in text.lower():\n",
    "            text = text.split(\"assistant\")[-1].strip()\n",
    "        generated.append(text)\n",
    "\n",
    "    return generated"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7b43eb6a",
   "metadata": {},
   "source": [
    "## Part 0: Understanding Chat Templates\n",
    "\n",
    "Modern instruction-tuned LLMs are trained with specific **chat formats**\n",
    "that structure conversations between users and assistants. The\n",
    "`apply_chat_template` method from HuggingFace tokenizers handles this\n",
    "formatting automatically.\n",
    "\n",
    "### Why chat templates matter:\n",
    "- Different models use different formats (ChatML, Llama, etc.)\n",
    "- Incorrect formatting leads to poor model performance\n",
    "- Templates handle special tokens automatically\n",
    "\n",
    "### Components of a chat:\n",
    "- **system**: Instructions that define the assistant's behavior\n",
    "- **user**: Messages from the user\n",
    "- **assistant**: Responses from the model"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e71ac254",
   "metadata": {},
   "source": [
    "### 0.1 Examining the Chat Template\n",
    "\n",
    "Let's see what the chat template for our model looks like."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4ae8e8b8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# The chat template is a Jinja2 template stored in the tokenizer\n",
    "print(f\"Chat template for {model_name}:\")\n",
    "print(\"-\" * 60)\n",
    "print(tokenizer.chat_template)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f38cb5db",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Let's see how a simple conversation gets formatted\n",
    "simple_messages = [\n",
    "    {\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n",
    "    {\"role\": \"user\", \"content\": \"What is 2+2?\"},\n",
    "]\n",
    "\n",
    "# Without add_generation_prompt\n",
    "formatted = tokenizer.apply_chat_template(simple_messages, tokenize=False)\n",
    "print(\"Formatted (without generation prompt):\")\n",
    "print(repr(formatted))\n",
    "print()\n",
    "\n",
    "# With add_generation_prompt - adds the assistant's turn start\n",
    "formatted_gen = tokenizer.apply_chat_template(\n",
    "    simple_messages, tokenize=False, add_generation_prompt=True\n",
    ")\n",
    "print(\"Formatted (with generation prompt):\")\n",
    "print(repr(formatted_gen))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a7fce26e",
   "metadata": {},
   "source": [
    "The `add_generation_prompt=True` option adds tokens that signal to the model\n",
    "it should start generating a response. This is crucial for inference!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f93e7606",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Multi-turn conversation example\n",
    "multi_turn = [\n",
    "    {\"role\": \"system\", \"content\": \"You are a math tutor.\"},\n",
    "    {\"role\": \"user\", \"content\": \"What is 5 + 3?\"},\n",
    "    {\"role\": \"assistant\", \"content\": \"5 + 3 = 8\"},\n",
    "    {\"role\": \"user\", \"content\": \"And what is 8 × 2?\"},\n",
    "]\n",
    "\n",
    "formatted_multi = tokenizer.apply_chat_template(\n",
    "    multi_turn, tokenize=False, add_generation_prompt=True\n",
    ")\n",
    "print(\"Multi-turn conversation:\")\n",
    "print(formatted_multi)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "917a1359",
   "metadata": {},
   "source": [
    "### 0.2 Thinking Models\n",
    "\n",
    "Some recent models support explicit **thinking/reasoning tokens**:\n",
    "- **DeepSeek-R1**: Uses `<think>...</think>` for chain-of-thought reasoning\n",
    "- **Qwen3**: Supports `enable_thinking=True` in `apply_chat_template`\n",
    "\n",
    "These models can show their reasoning process explicitly, which is useful\n",
    "for debugging and understanding model behavior.\n",
    "\n",
    "Let's load a Qwen3 tokenizer to explore this feature (we only need the\n",
    "tokenizer, not the full model)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f7511ab8",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Load a Qwen3 tokenizer to explore thinking mode\n",
    "# (Qwen3 is a \"thinking\" model with enable_thinking support)\n",
    "thinking_model_name = \"Qwen/Qwen3-0.6B\"\n",
    "thinking_tokenizer = load_hf_tokenizer(thinking_model_name)\n",
    "\n",
    "print(f\"Loaded tokenizer for: {thinking_model_name}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "56e85c9e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Compare prompts with and without thinking enabled\n",
    "test_messages = [\n",
    "    {\"role\": \"user\", \"content\": \"What is the capital of France?\"},\n",
    "]\n",
    "\n",
    "# Without thinking (standard mode)\n",
    "prompt_no_think = thinking_tokenizer.apply_chat_template(\n",
    "    test_messages,\n",
    "    tokenize=False,\n",
    "    add_generation_prompt=True,\n",
    "    enable_thinking=False,\n",
    ")\n",
    "print(\"=== Without thinking (enable_thinking=False) ===\")\n",
    "print(prompt_no_think)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3fc87879",
   "metadata": {},
   "outputs": [],
   "source": [
    "# With thinking enabled - the model will generate <think>...</think> blocks\n",
    "prompt_with_think = thinking_tokenizer.apply_chat_template(\n",
    "    test_messages,\n",
    "    tokenize=False,\n",
    "    add_generation_prompt=True,\n",
    "    enable_thinking=True,\n",
    ")\n",
    "print(\"=== With thinking (enable_thinking=True) ===\")\n",
    "print(prompt_with_think)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fd1962c5",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "Notice how the prompt differs when thinking is enabled. The model is\n",
    "instructed to first reason in `<think>` tags before providing the answer.\n",
    "\n",
    "**Example of thinking model output:**\n",
    "```\n",
    "<think>\n",
    "The user is asking about the capital of France.\n",
    "France is a country in Western Europe.\n",
    "Its capital city is Paris, which is also its largest city.\n",
    "</think>\n",
    "\n",
    "The capital of France is Paris.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cef1171a",
   "metadata": {},
   "source": [
    "### Exercise 0: Explore different chat formats\n",
    "\n",
    "Try formatting the same message with different configurations and observe\n",
    "the differences. What special tokens does each model use?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6cc1d97e",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Explore the chat template\n",
    "\n",
    "# 1. Create a simple message and format it with both tokenizers\n",
    "# 2. Try with and without system message\n",
    "# 3. Try with add_generation_prompt=True or False\n",
    "# 4. Observe the special tokens used by each model\n",
    "messages = [{\"role\": \"user\", \"content\": \"Hello!\"}]\n",
    "formatted = tokenizer.apply_chat_template(messages, tokenize=False)\n",
    "print(formatted)\n",
    "assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "612105ca",
   "metadata": {},
   "source": [
    "## Part 1: Introduction to In-Context Learning (ICL)\n",
    "\n",
    "ICL allows adapting a model to a task simply by providing examples\n",
    "in the prompt, without modifying the model weights.\n",
    "\n",
    "### Advantages of ICL:\n",
    "- No training required\n",
    "- Flexible: change task by changing examples\n",
    "- Works with pre-trained models\n",
    "\n",
    "### Disadvantages:\n",
    "- Consumes context tokens\n",
    "- Performance depends on example quality\n",
    "- Variance in responses"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9281fc26",
   "metadata": {},
   "source": [
    "### 1.1 Zero-shot vs Few-shot\n",
    "\n",
    "Let's start with a sentiment classification task on tech-related text."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "785beda7",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Example tech support questions (simplified)\n",
    "test_questions = [\n",
    "    \"How do I fix the blue screen error on Windows?\",\n",
    "    \"Python is such a terrible language, nothing works!\",\n",
    "    \"Can someone explain how to set up a VPN?\",\n",
    "    \"This software is garbage, crashes every 5 minutes.\",\n",
    "]\n",
    "\n",
    "# Expected labels: question, complaint, question, complaint\n",
    "expected_labels = [\"question\", \"complaint\", \"question\", \"complaint\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a1659f6a",
   "metadata": {},
   "source": [
    "### ZERO-SHOT (no examples)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "04d85acf",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Zero-shot: classification without examples\n",
    "\n",
    "zero_shot_prompt = \"\"\"Classify the following text as \"question\" or \"complaint\".\n",
    "Reply with a single word only.\n",
    "\n",
    "Text: {text}\n",
    "Classification:\"\"\"\n",
    "\n",
    "for text, expected in zip(test_questions[:2], expected_labels[:2]):\n",
    "    prompt = build_prompt(zero_shot_prompt.format(text=text))\n",
    "    response = generate_text(prompt, max_new_tokens=10, temperature=0.1)[0]\n",
    "    print(f\"Text: {text[:60]}...\")\n",
    "    print(f\"Predicted: {response.strip()} | Expected: {expected}\")\n",
    "    print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6098fb33",
   "metadata": {},
   "source": [
    "### FEW-SHOT (with 2 examples)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1584431c",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Few-shot: classification with examples\n",
    "\n",
    "few_shot_examples = \"\"\"Example 1:\n",
    "Text: \"Where can I find the settings menu in this app?\"\n",
    "Classification: question\n",
    "\n",
    "Example 2:\n",
    "Text: \"This update broke everything and I lost all my data!\"\n",
    "Classification: complaint\n",
    "\n",
    "\"\"\"\n",
    "\n",
    "few_shot_prompt = (\n",
    "    few_shot_examples\n",
    "    + \"\"\"Now, classify this text:\n",
    "Text: \"{text}\"\n",
    "Classification:\"\"\"\n",
    ")\n",
    "\n",
    "for text, expected in zip(test_questions[:2], expected_labels[:2]):\n",
    "    prompt = build_prompt(few_shot_prompt.format(text=text))\n",
    "    response = generate_text(prompt, max_new_tokens=10, temperature=0.1)[0]\n",
    "    print(f\"Text: {text[:60]}...\")\n",
    "    print(f\"Predicted: {response.strip()} | Expected: {expected}\")\n",
    "    print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "de6d73c3",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "### Exercise 1: Implement a few-shot prompt builder\n",
    "\n",
    "Complete the following function to automatically build few-shot prompts."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "19953671",
   "metadata": {},
   "outputs": [],
   "source": [
    "def build_few_shot_prompt(\n",
    "    examples: List[Tuple[str, str]],\n",
    "    query: str,\n",
    "    task_description: str = \"Classify the following text.\",\n",
    "    input_label: str = \"Text\",\n",
    "    output_label: str = \"Classification\",\n",
    ") -> str:\n",
    "    \"\"\"\n",
    "    Build a few-shot prompt from examples.\n",
    "\n",
    "    Args:\n",
    "        examples: List of tuples (input, output) for examples\n",
    "        query: The text to classify\n",
    "        task_description: Description of the task\n",
    "        input_label: Label for input (e.g., \"Text\", \"Question\")\n",
    "        output_label: Label for output (e.g., \"Classification\", \"Answer\")\n",
    "\n",
    "    Returns:\n",
    "        Formatted prompt for the model\n",
    "    \"\"\"\n",
    "    prompt_parts = [task_description, \"\"]\n",
    "\n",
    "    for i, (inp, out) in enumerate(examples, 1):\n",
    "        prompt_parts.append(f\"Example {i}:\")\n",
    "        prompt_parts.append(f'{input_label}: \"{inp}\"')\n",
    "        prompt_parts.append(f\"{output_label}: {out}\")\n",
    "        prompt_parts.append(\"\")\n",
    "\n",
    "    prompt_parts.append(\"Now:\")\n",
    "    prompt_parts.append(f'{input_label}: \"{query}\"')\n",
    "    prompt_parts.append(f\"{output_label}:\")\n",
    "\n",
    "    return \"\\n\".join(prompt_parts)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3939be9d",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Test the function\n",
    "examples = [\n",
    "    (\"How do I update my graphics drivers?\", \"question\"),\n",
    "    (\"The app is so slow it's unusable.\", \"complaint\"),\n",
    "    (\"What's the difference between RAM and ROM?\", \"question\"),\n",
    "]\n",
    "\n",
    "test_query = \"This product is a complete waste of money.\"\n",
    "prompt = build_few_shot_prompt(\n",
    "    examples,\n",
    "    test_query,\n",
    "    task_description=\"Classify the text as 'question' or 'complaint'.\",\n",
    ")\n",
    "print(\"Generated prompt:\")\n",
    "print(prompt)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "36b97151",
   "metadata": {},
   "source": [
    "## Part 1b: Chain-of-Thought (CoT) Prompting\n",
    "\n",
    "Chain-of-Thought prompting encourages the model to **reason step by step**\n",
    "before giving a final answer. This improves performance on tasks requiring\n",
    "multi-step reasoning.\n",
    "\n",
    "### Key insight:\n",
    "Instead of asking for a direct answer, we ask the model to \"think aloud\".\n",
    "The reasoning process helps the model arrive at better answers.\n",
    "\n",
    "### Two approaches:\n",
    "1. **Zero-shot CoT**: Add \"Let's think step by step\" to the prompt\n",
    "2. **Few-shot CoT**: Provide examples with explicit reasoning steps"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "80004943",
   "metadata": {},
   "source": [
    "### 1b.1 Zero-shot Chain-of-Thought\n",
    "\n",
    "Simply adding \"Let's think step by step\" can improve reasoning."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0fb03417",
   "metadata": {},
   "outputs": [],
   "source": [
    "# A task that benefits from reasoning\n",
    "reasoning_questions = [\n",
    "    # Query 1\n",
    "    \"A store has 45 apples. \"\n",
    "    \"They sell 12 in the morning and receive 20 more. \"\n",
    "    \"How many apples do they have?\",\n",
    "    # Query 2\n",
    "    \"If a train travels at 60 km/h for 2.5 hours, how far does it travel?\",\n",
    "    # Query 3\n",
    "    \"Marie has 3 times as many books as Paul. \"\n",
    "    \"Paul has 8 books. How many books does Marie have?\",\n",
    "]\n",
    "\n",
    "expected_answers = [\"53\", \"150\", \"24\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d032cc91",
   "metadata": {},
   "source": [
    "### DIRECT PROMPTING (no reasoning)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "13ab1b12",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Direct prompting (no CoT)\n",
    "\n",
    "direct_prompt = \"\"\"Answer the following question with just the number.\n",
    "\n",
    "Question: {question}\n",
    "Answer:\"\"\"\n",
    "\n",
    "for question, expected in zip(reasoning_questions[:2], expected_answers[:2]):\n",
    "    prompt = build_prompt(direct_prompt.format(question=question))\n",
    "    response = generate_text(prompt, max_new_tokens=20, temperature=0.1)[0]\n",
    "    print(\"=\" * 80)\n",
    "    print(f\"Q: {question}\")\n",
    "    print(f\"A: {response.strip()} (expected: {expected})\")\n",
    "    print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f65d4ad1",
   "metadata": {},
   "source": [
    "### ZERO-SHOT CoT ('Let's think step by step')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "437ed639",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Zero-shot CoT\n",
    "\n",
    "cot_prompt = \"\"\"Answer the following question. Let's think step by step.\n",
    "\n",
    "Question: {question}\n",
    "\n",
    "Step-by-step reasoning:\"\"\"\n",
    "\n",
    "for question, expected in zip(reasoning_questions[:2], expected_answers[:2]):\n",
    "    prompt = build_prompt(cot_prompt.format(question=question))\n",
    "    response = generate_text(prompt, max_new_tokens=150, temperature=0.1)[0]\n",
    "    print(\"=\" * 80)\n",
    "    print(f\"Q: {question}\")\n",
    "    print(f\"Reasoning: {response.strip()}\")\n",
    "    print(f\"(Expected answer: {expected})\")\n",
    "    print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "63cf32e0",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "### 1b.2 Few-shot Chain-of-Thought\n",
    "\n",
    "Providing examples with explicit reasoning steps teaches the model\n",
    "how to reason about similar problems."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "278adc08",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def build_cot_prompt(\n",
    "    examples: List[Tuple[str, str, str]],\n",
    "    query: str,\n",
    "    task_description: str = \"Solve the following problem step by step.\",\n",
    ") -> str:\n",
    "    \"\"\"\n",
    "    Build a few-shot CoT prompt with reasoning examples.\n",
    "\n",
    "    Args:\n",
    "        examples: List of (question, reasoning, answer) tuples\n",
    "        query: The question to solve\n",
    "        task_description: Description of the task\n",
    "\n",
    "    Returns:\n",
    "        Formatted CoT prompt\n",
    "    \"\"\"\n",
    "    # Implement few-shot CoT prompt builder\n",
    "\n",
    "    # 1. Start with task_description\n",
    "    # 2. Add each example with Question, Reasoning, and Answer\n",
    "    # 3. End with the query (without answer)\n",
    "    prompt_parts = [task_description, \"\"]\n",
    "    for i, (question, reasoning, answer) in enumerate(examples, 1):\n",
    "    assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e7cdc563",
   "metadata": {},
   "source": [
    "### FEW-SHOT CoT (with reasoning examples)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "07ed95b7",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Few-shot CoT examples with reasoning\n",
    "\n",
    "cot_examples = [\n",
    "    (\n",
    "        # Query\n",
    "        \"A baker makes 24 cookies. He gives away 8 and bakes 15 more. \"\n",
    "        \"How many cookies does he have?\",\n",
    "        # Think\n",
    "        \"Start with 24 cookies. Give away 8: 24 - 8 = 16. Bake 15 more: 16 + 15 = 31.\",\n",
    "        # Answer\n",
    "        \"31\",\n",
    "    ),\n",
    "    (\n",
    "        \"A car travels at 80 km/h for 3 hours. How far does it go?\",\n",
    "        \"Distance = speed × time. Distance = 80 × 3 = 240 km.\",\n",
    "        \"240\",\n",
    "    ),\n",
    "]\n",
    "\n",
    "for question, expected in zip(reasoning_questions, expected_answers):\n",
    "    prompt = build_cot_prompt(cot_examples, question)\n",
    "    full_prompt = build_prompt(prompt)\n",
    "    response = generate_text(full_prompt, max_new_tokens=100, temperature=0.1)[0]\n",
    "    print(\"=\" * 80)\n",
    "    print(f\"Q: {question}\")\n",
    "    print(f\"Response: {response.strip()}\")\n",
    "    print(f\"(Expected: {expected})\")\n",
    "    print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "acc0817f",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "### Extract final answer from CoT response\n",
    "\n",
    "CoT responses contain reasoning followed by the answer. We need to extract\n",
    "the final answer for evaluation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a6200954",
   "metadata": {},
   "outputs": [],
   "source": [
    "def extract_answer_from_cot(response: str) -> str:\n",
    "    \"\"\"\n",
    "    Extract the final numerical answer from a CoT response.\n",
    "\n",
    "    Args:\n",
    "        response: The model's response with reasoning\n",
    "\n",
    "    Returns:\n",
    "        The extracted answer (number as string)\n",
    "    \"\"\"\n",
    "    import re\n",
    "\n",
    "    # Try to find \"Answer: X\" pattern\n",
    "    answer_match = re.search(r\"Answer:\\s*(\\d+)\", response, re.IGNORECASE)\n",
    "    if answer_match:\n",
    "        return answer_match.group(1)\n",
    "\n",
    "    # Try to find \"= X\" at the end of reasoning\n",
    "    equals_match = re.search(r\"=\\s*(\\d+)\", response)\n",
    "    if equals_match:\n",
    "        return equals_match.group(1)\n",
    "\n",
    "    # Fall back to last number in response\n",
    "    numbers = re.findall(r\"\\d+\", response)\n",
    "    if numbers:\n",
    "        return numbers[-1]\n",
    "\n",
    "    return \"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ae879b54",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Test answer extraction\n",
    "test_responses = [\n",
    "    \"Start with 45. Subtract 12: 45 - 12 = 33. Add 20: 33 + 20 = 53. Answer: 53\",\n",
    "    \"Speed is 60 km/h, time is 2.5 hours. Distance = 60 × 2.5 = 150 km.\",\n",
    "    \"Paul has 8 books. Marie has 3 times more: 3 × 8 = 24 books.\",\n",
    "]\n",
    "\n",
    "print(\"Testing answer extraction:\")\n",
    "for resp in test_responses:\n",
    "    answer = extract_answer_from_cot(resp)\n",
    "    print(f\"  Response: {resp[:50]}...\")\n",
    "    print(f\"  Extracted: {answer}\")\n",
    "    print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7014d3de",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Part 1c: Self-Consistency Decoding\n",
    "\n",
    "Self-consistency combines well with CoT: instead of generating one reasoning\n",
    "path, we generate **multiple paths** and take the **majority answer**.\n",
    "\n",
    "The idea: different reasoning paths may lead to different answers,\n",
    "but the correct answer is more likely to appear consistently.\n",
    "\n",
    "This reduces variance and improves reliability."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7523fd6c",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def self_consistency_classify(\n",
    "    prompt: str,\n",
    "    num_samples: int = 5,\n",
    "    temperature: float = 0.7,\n",
    "    valid_labels: List[str] = None,\n",
    ") -> Tuple[str, dict]:\n",
    "    \"\"\"\n",
    "    Classification with self-consistency.\n",
    "\n",
    "    Args:\n",
    "        prompt: The classification prompt\n",
    "        num_samples: Number of samples to generate\n",
    "        temperature: Temperature for sampling\n",
    "        valid_labels: List of valid labels (for filtering)\n",
    "\n",
    "    Returns:\n",
    "        Tuple (majority_label, counts)\n",
    "    \"\"\"\n",
    "    # Implement self-consistency\n",
    "\n",
    "    # 1. Generate num_samples responses with temperature > 0\n",
    "    # 2. Extract the label from each response\n",
    "    # 3. Vote for the majority label\n",
    "    responses = generate_text(prompt, ..., num_return_sequences=num_samples)\n",
    "    labels = []\n",
    "    for response in responses:\n",
    "    assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "50098dae",
   "metadata": {},
   "source": [
    "### SELF-CONSISTENCY (5 samples)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "612104bf",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "for text, expected in zip(test_questions, expected_labels):\n",
    "    prompt = build_prompt(few_shot_prompt.format(text=text))\n",
    "    label, counts = self_consistency_classify(\n",
    "        prompt, num_samples=5, valid_labels=[\"question\", \"complaint\"]\n",
    "    )\n",
    "    print(f\"Text: {text[:50]}...\")\n",
    "    print(f\"Votes: {counts}\")\n",
    "    print(f\"Result: {label} | Expected: {expected}\")\n",
    "    print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "38a8a781",
   "metadata": {},
   "source": [
    "### Exercise 2: Compare single-shot vs self-consistency\n",
    "\n",
    "Measure the accuracy of both approaches on a small test set."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "08e31a86",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create a test dataset\n",
    "test_data = [\n",
    "    (\"How do I install Python on Mac?\", \"question\"),\n",
    "    (\"This keyboard is absolutely terrible.\", \"complaint\"),\n",
    "    (\"What programming language should I learn first?\", \"question\"),\n",
    "    (\"The customer service is useless.\", \"complaint\"),\n",
    "    (\"Can you explain how databases work?\", \"question\"),\n",
    "    (\"I wasted hours on this broken software.\", \"complaint\"),\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "daa8bd94",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Configuration\n",
    "num_consistency_samples = 5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f6f9914d",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Compare the two approaches\n",
    "\n",
    "# 1. For each example, compute single-shot and self-consistency predictions\n",
    "# 2. Calculate accuracy for each method\n",
    "single_correct = 0\n",
    "consistency_correct = 0\n",
    "for text, expected in test_data:\n",
    "assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "97fde58e",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "### Exercise 3: CoT + Self-Consistency for Reasoning\n",
    "\n",
    "The most powerful combination: use CoT prompts with self-consistency.\n",
    "Generate multiple reasoning paths and take the majority answer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b247060f",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def self_consistency_cot(\n",
    "    question: str,\n",
    "    cot_examples: List[Tuple[str, str, str]],\n",
    "    num_samples: int = 5,\n",
    "    temperature: float = 0.7,\n",
    ") -> Tuple[str, dict]:\n",
    "    \"\"\"\n",
    "    Self-consistency with Chain-of-Thought for reasoning tasks.\n",
    "\n",
    "    Args:\n",
    "        question: The question to solve\n",
    "        cot_examples: CoT examples (question, reasoning, answer)\n",
    "        num_samples: Number of reasoning paths to generate\n",
    "        temperature: Temperature for sampling\n",
    "\n",
    "    Returns:\n",
    "        Tuple of (majority_answer, vote_counts)\n",
    "    \"\"\"\n",
    "    # Implement CoT + Self-Consistency\n",
    "\n",
    "    # 1. Build a CoT prompt\n",
    "    # 2. Generate multiple responses with temperature > 0\n",
    "    # 3. Extract answers from each response\n",
    "    # 4. Vote for the majority answer\n",
    "    prompt = build_cot_prompt(cot_examples, question)\n",
    "    full_prompt = build_prompt(prompt)\n",
    "    responses = generate_text(full_prompt, ..., num_return_sequences=num_samples)\n",
    "    answers = [extract_answer_from_cot(r) for r in responses]\n",
    "    assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ecfe119f",
   "metadata": {},
   "source": [
    "### CoT + SELF-CONSISTENCY"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "de1a45ff",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Test CoT + Self-Consistency\n",
    "\n",
    "for question, expected in zip(reasoning_questions, expected_answers):\n",
    "    answer, votes = self_consistency_cot(\n",
    "        question,\n",
    "        cot_examples,\n",
    "        num_samples=num_consistency_samples,\n",
    "    )\n",
    "    print(\"=\" * 80)\n",
    "    print(f\"Q: {question}\")\n",
    "    print(f\"Votes: {votes}\")\n",
    "    print(f\"Answer: {answer} (expected: {expected})\")\n",
    "    correct = \"✓\" if answer == expected else \"✗\"\n",
    "    print(f\"Result: {correct}\")\n",
    "    print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a68f8987",
   "metadata": {},
   "source": [
    "## Part 2: Exploring the LoTTE Dataset\n",
    "\n",
    "LoTTE (Long-Tail Topic-stratified Evaluation) is an IR benchmark based on\n",
    "StackExchange Q&A. We use the technology domain with search queries.\n",
    "\n",
    "Dataset: https://ir-datasets.com/lotte.html\n",
    "\n",
    "We use PyTerrier's integration with ir-datasets for easy access:\n",
    "https://ir-datasets.com/pyterrier.html"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "147d2586",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load the LoTTE technology dataset via PyTerrier's ir-datasets integration\n",
    "dataset = pt.get_dataset(\"irds:lotte/technology/dev/search\")\n",
    "print(\"Dataset loaded: lotte/technology/dev/search\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "809ecd08",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Explore the structure using PyTerrier's dataset methods\n",
    "print(\"\\nDataset info:\")\n",
    "# Get counts from the underlying ir-datasets object\n",
    "irds = dataset.irds_ref()\n",
    "print(f\"  - Documents: {irds.docs_count()}\")\n",
    "print(f\"  - Queries: {irds.queries_count()}\")\n",
    "print(f\"  - Relevance judgments (qrels): {irds.qrels_count()}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6e1400ff",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Display some documents using PyTerrier's corpus iterator\n",
    "print(\"\\nExample documents (StackExchange answers):\")\n",
    "for i, doc in enumerate(dataset.get_corpus_iter()):\n",
    "    if i >= 3:\n",
    "        break\n",
    "    print(f\"\\n[{i + 1}] ID: {doc['docno']}\")\n",
    "    print(f\"    Text: {doc['text'][:200]}...\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5aaa1def",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Display some queries using PyTerrier's topics method\n",
    "topics_df = dataset.get_topics()\n",
    "print(\"\\nExample queries:\")\n",
    "print(topics_df.head())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "85265d09",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Display some relevance judgments using PyTerrier's qrels method\n",
    "qrels_df_all = dataset.get_qrels()\n",
    "print(\"\\nExample qrels (query-document relevance):\")\n",
    "print(qrels_df_all.head())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2d0054ab",
   "metadata": {},
   "source": [
    "### Exercise 4: Index the dataset with PyTerrier\n",
    "\n",
    "Using PyTerrier's integration, we can access the data via:\n",
    "- `dataset.get_corpus_iter()` for documents\n",
    "- `dataset.get_topics()` for queries\n",
    "- `dataset.get_qrels()` for relevance judgments\n",
    "\n",
    "We'll index the entire corpus with PyTerrier for efficient retrieval.\n",
    "The document text is stored in the index metadata for later lookup."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f63a9438",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Get queries and qrels\n",
    "queries_df = dataset.get_topics()\n",
    "qrels_df = dataset.get_qrels()\n",
    "\n",
    "print(\"Loaded:\")\n",
    "print(f\"  - Queries: {len(queries_df)}\")\n",
    "print(f\"  - Qrels: {len(qrels_df)}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7d09eaee",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Download the PyTerrier index of LoTTE (technology subset) from cache\n",
    "# The index includes document text in metadata for retrieval during RAG\n",
    "\n",
    "# Use either the full index or a smaller subset for testing\n",
    "# index_name = \"index_lotte\"\n",
    "index_name = \"index_lotte-100000\"\n",
    "\n",
    "index_path = get_from_cache(\n",
    "    f\"https://master-mind.isir.upmc.fr/llm/data/{index_name}\", f\"llm/{index_name}\"\n",
    ")\n",
    "\n",
    "# Initialize PyTerrier with the index\n",
    "index = pt.terrier.TerrierIndex(str(index_path))\n",
    "print(f\"Index has {index.getCollectionStatistics().getNumberOfDocuments()} documents\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0b96133e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Helper functions to get document text from index\n",
    "def get_text_from_index(\n",
    "    index: pt.terrier.TerrierIndex, doc_ids: list[str]\n",
    ") -> dict[str, str]:\n",
    "    \"\"\"\n",
    "    Retrieve document text from the index metadata.\n",
    "\n",
    "    Args:\n",
    "        index: PyTerrier index reference\n",
    "        doc_ids: List of document IDs\n",
    "\n",
    "    Returns:\n",
    "        Dict mapping doc_id -> text\n",
    "    \"\"\"\n",
    "    meta_index = index.meta_index()\n",
    "\n",
    "    result = {}\n",
    "    for doc_id in doc_ids:\n",
    "        try:\n",
    "            # Get internal docid from docno\n",
    "            docid = meta_index.getDocument(\"docno\", doc_id)\n",
    "            if docid >= 0:\n",
    "                text = meta_index.getItem(\"text\", docid)\n",
    "                result[doc_id] = text\n",
    "        except Exception:\n",
    "            pass  # Document not found\n",
    "\n",
    "    return result\n",
    "\n",
    "\n",
    "# Helper for single document lookup\n",
    "def get_doc_text(index, doc_id: str) -> str:\n",
    "    \"\"\"Get text for a single document from the index.\"\"\"\n",
    "    texts = get_text_from_index(index, [doc_id])\n",
    "    return texts.get(doc_id, \"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "177434aa",
   "metadata": {},
   "source": [
    "## Part 3: Generating Training Data for IR\n",
    "\n",
    "To train a neural retrieval model like SPLADE, we need query-document pairs.\n",
    "While LoTTE provides some qrels, we can **generate additional queries** using\n",
    "the LLM to create more training data.\n",
    "\n",
    "### Why generate synthetic queries?\n",
    "- More training data improves model quality\n",
    "- Covers diverse query formulations for the same document\n",
    "- Cost-effective compared to human annotation\n",
    "\n",
    "### Strategy:\n",
    "1. Sample documents from the corpus\n",
    "2. Use the LLM to generate questions that the document answers\n",
    "3. Filter generated queries for quality\n",
    "4. Save for training in the next practical"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "47886569",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Configuration for query generation\n",
    "num_docs_to_augment = 50  # Number of documents to generate queries for\n",
    "queries_per_doc = 2  # Number of queries to generate per document"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9c650d16",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def generate_queries_for_document(\n",
    "    document: str,\n",
    "    num_queries: int = 2,\n",
    "    max_doc_length: int = 500,\n",
    ") -> List[str]:\n",
    "    \"\"\"\n",
    "    Generate search queries that the document would answer.\n",
    "\n",
    "    Args:\n",
    "        document: The document text\n",
    "        num_queries: Number of queries to generate\n",
    "        max_doc_length: Maximum document length to use\n",
    "\n",
    "    Returns:\n",
    "        List of generated queries\n",
    "    \"\"\"\n",
    "    # Implement query generation\n",
    "\n",
    "    # 1. Build a prompt asking the LLM to generate queries\n",
    "    # 2. The queries should be questions that the document answers\n",
    "    # 3. Parse the response to extract individual queries\n",
    "    doc_excerpt = document[:max_doc_length]\n",
    "    prompt = f\"Given this document, generate {num_queries} search queries...\"\n",
    "    response = generate_text(build_prompt(prompt), ...)\n",
    "    assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "de2af236",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Test query generation on a sample document\n",
    "# Get a sample document ID from qrels (guaranteed to exist in index)\n",
    "sample_doc_id = qrels_df[\"docno\"].iloc[0]\n",
    "sample_doc = get_doc_text(index, sample_doc_id)\n",
    "\n",
    "print(f\"Document ({sample_doc_id}):\")\n",
    "print(f\"{sample_doc[:300]}...\")\n",
    "print()\n",
    "\n",
    "generated = generate_queries_for_document(sample_doc, num_queries=3)\n",
    "print(\"Generated queries:\")\n",
    "for i, q in enumerate(generated, 1):\n",
    "    print(f\"  {i}. {q}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "161291b7",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "### Exercise: Generate queries for multiple documents\n",
    "\n",
    "Generate synthetic training data by creating queries for documents in the corpus."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8e4a6ee3",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def generate_training_pairs(\n",
    "    qrels_df: pd.DataFrame,\n",
    "    num_docs: int = 50,\n",
    "    queries_per_doc: int = 2,\n",
    ") -> List[Dict]:\n",
    "    \"\"\"\n",
    "    Generate query-document training pairs.\n",
    "\n",
    "    Uses the global `index` variable for document text retrieval.\n",
    "\n",
    "    Args:\n",
    "        qrels_df: DataFrame with qrels (to get document IDs)\n",
    "        num_docs: Number of documents to process\n",
    "        queries_per_doc: Queries to generate per document\n",
    "\n",
    "    Returns:\n",
    "        List of {\"query\": str, \"doc_id\": str, \"document\": str}\n",
    "    \"\"\"\n",
    "    # Generate training pairs\n",
    "\n",
    "    # 1. Sample documents from the corpus (use qrels to get doc IDs)\n",
    "    # 2. Generate queries for each document\n",
    "    # 3. Create training pairs\n",
    "    import random\n",
    "    doc_ids = qrels_df[\"docno\"].unique().tolist()\n",
    "    sampled_ids = random.sample(doc_ids, min(num_docs, len(doc_ids)))\n",
    "    training_pairs = []\n",
    "    for doc_id in tqdm(sampled_ids):\n",
    "    assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6a575172",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Generate synthetic training pairs\n",
    "print(f\"Generating queries for {num_docs_to_augment} documents...\")\n",
    "synthetic_pairs = generate_training_pairs(\n",
    "    qrels_df,\n",
    "    num_docs=num_docs_to_augment,\n",
    "    queries_per_doc=queries_per_doc,\n",
    ")\n",
    "\n",
    "print(f\"\\nGenerated {len(synthetic_pairs)} synthetic query-document pairs\")\n",
    "\n",
    "# Show examples\n",
    "print(\"\\nExample synthetic pairs:\")\n",
    "for pair in synthetic_pairs[:3]:\n",
    "    print(f\"  Query: {pair['query']}\")\n",
    "    print(f\"  Doc: {pair['document'][:100]}...\")\n",
    "    print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "480e2944",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "### Filtering synthetic queries\n",
    "\n",
    "Not all generated queries are good. We can filter by:\n",
    "- Query length (too short or too long queries are often bad)\n",
    "- Diversity (avoid duplicate queries)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3eb0f7bd",
   "metadata": {},
   "outputs": [],
   "source": [
    "def filter_synthetic_pairs(\n",
    "    pairs: List[Dict],\n",
    "    min_query_words: int = 3,\n",
    "    max_query_words: int = 20,\n",
    ") -> List[Dict]:\n",
    "    \"\"\"\n",
    "    Filter synthetic query-document pairs for quality.\n",
    "\n",
    "    Args:\n",
    "        pairs: List of training pairs\n",
    "        min_query_words: Minimum query length\n",
    "        max_query_words: Maximum query length\n",
    "\n",
    "    Returns:\n",
    "        Filtered list of pairs\n",
    "    \"\"\"\n",
    "    filtered = []\n",
    "    seen_queries = set()\n",
    "\n",
    "    for pair in pairs:\n",
    "        query = pair[\"query\"]\n",
    "\n",
    "        # Length filter\n",
    "        query_words = len(query.split())\n",
    "        if query_words < min_query_words or query_words > max_query_words:\n",
    "            continue\n",
    "\n",
    "        # Duplicate filter\n",
    "        query_lower = query.lower()\n",
    "        if query_lower in seen_queries:\n",
    "            continue\n",
    "        seen_queries.add(query_lower)\n",
    "\n",
    "        filtered.append(pair)\n",
    "\n",
    "    return filtered"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a19da0f7",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Filter the synthetic pairs\n",
    "filtered_pairs = filter_synthetic_pairs(synthetic_pairs)\n",
    "\n",
    "print(f\"Filtered: {len(synthetic_pairs)} -> {len(filtered_pairs)} pairs\")\n",
    "print(f\"Kept: {100 * len(filtered_pairs) / max(1, len(synthetic_pairs)):.1f}%\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1894576c",
   "metadata": {},
   "source": [
    "### Part 3b: Validating Generated Queries with Evaluation Metrics\n",
    "\n",
    "How do we know if our generated queries are good? We can compare them to\n",
    "**real user queries** from the LoTTE dataset using evaluation metrics.\n",
    "\n",
    "### Evaluation Metrics\n",
    "\n",
    "- **ROUGE**: Measures n-gram overlap between texts (recall-oriented)\n",
    "- **BERTScore**: Measures semantic similarity using BERT embeddings\n",
    "\n",
    "### Validation strategy:\n",
    "1. Select documents that have real queries (from qrels)\n",
    "2. Generate multiple synthetic queries for each document\n",
    "3. Compare generated queries to the real query for that document\n",
    "4. Take the **max score** over generations (best of N)\n",
    "\n",
    "This approach directly compares against ground truth without needing\n",
    "embedding models to find similar queries."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f37a3764",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize evaluation metrics\n",
    "rouge = rouge_scorer.RougeScorer([\"rouge1\", \"rouge2\", \"rougeL\"], use_stemmer=True)\n",
    "bertscore = load_metric(\"bertscore\", force_download=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5e2e4adb",
   "metadata": {},
   "outputs": [],
   "source": [
    "def compute_rouge(prediction: str, reference: str) -> dict:\n",
    "    \"\"\"Compute ROUGE scores between two texts.\"\"\"\n",
    "    scores = rouge.score(reference, prediction)\n",
    "    return {\n",
    "        \"rouge1\": scores[\"rouge1\"].fmeasure,\n",
    "        \"rouge2\": scores[\"rouge2\"].fmeasure,\n",
    "        \"rougeL\": scores[\"rougeL\"].fmeasure,\n",
    "    }\n",
    "\n",
    "\n",
    "def compute_bertscore(predictions: List[str], references: List[str]) -> dict:\n",
    "    \"\"\"Compute BERTScore for a batch of predictions.\"\"\"\n",
    "    results = bertscore.compute(\n",
    "        predictions=predictions,\n",
    "        references=references,\n",
    "        lang=\"en\",\n",
    "        model_type=\"microsoft/deberta-xlarge-mnli\",\n",
    "    )\n",
    "    return {\n",
    "        \"precision\": sum(results[\"precision\"]) / len(results[\"precision\"]),\n",
    "        \"recall\": sum(results[\"recall\"]) / len(results[\"recall\"]),\n",
    "        \"f1\": sum(results[\"f1\"]) / len(results[\"f1\"]),\n",
    "    }"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1d7762f8",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def validate_query_generation(\n",
    "    queries_df: pd.DataFrame,\n",
    "    qrels_df: pd.DataFrame,\n",
    "    num_samples: int = 10,\n",
    "    queries_per_doc: int = 3,\n",
    ") -> Dict:\n",
    "    \"\"\"\n",
    "    Validate query generation by comparing to real queries for the same document.\n",
    "\n",
    "    For documents with known queries, generate synthetic queries and compare\n",
    "    to the ground truth. Takes the max score over multiple generations.\n",
    "\n",
    "    Uses the global `index` variable for document text retrieval.\n",
    "\n",
    "    Args:\n",
    "        queries_df: DataFrame with real queries\n",
    "        qrels_df: DataFrame with relevance judgments\n",
    "        num_samples: Number of documents to evaluate\n",
    "        queries_per_doc: Number of queries to generate per document\n",
    "\n",
    "    Returns:\n",
    "        Dictionary with validation metrics and examples\n",
    "    \"\"\"\n",
    "    # Implement query validation\n",
    "\n",
    "    # 1. Find documents that have real queries (via qrels)\n",
    "    # 2. Generate synthetic queries for those documents\n",
    "    # 3. Compute ROUGE between each generated query and the real query\n",
    "    # 4. Take max score over generations\n",
    "    doc_to_queries = {}  # Map doc_id -> list of real queries\n",
    "    for _, row in qrels_df.iterrows():\n",
    "    assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6afa4d21",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Validate query generation quality\n",
    "print(\"Evaluating query generation quality...\")\n",
    "print(\"(Generating queries for documents with known real queries)\\n\")\n",
    "\n",
    "num_validation_samples = 10\n",
    "\n",
    "\n",
    "validation_results = validate_query_generation(\n",
    "    queries_df,\n",
    "    qrels_df,\n",
    "    num_samples=num_validation_samples,\n",
    "    queries_per_doc=3,\n",
    ")\n",
    "\n",
    "if \"error\" not in validation_results:\n",
    "    print(\"=== Query Generation Validation ===\")\n",
    "    print(f\"Max ROUGE-1 (avg): {validation_results['avg_max_rouge1']:.3f}\")\n",
    "    print(f\"Max ROUGE-L (avg): {validation_results['avg_max_rougeL']:.3f}\")\n",
    "    print(f\"BERTScore (best): {validation_results['avg_bertscore']:.3f}\")\n",
    "\n",
    "    # Show examples\n",
    "    examples = validation_results[\"examples\"]\n",
    "    examples_sorted = sorted(examples, key=lambda x: x[\"max_rouge1\"], reverse=True)\n",
    "\n",
    "    print(\"\\n--- Best Examples (highest max ROUGE-1) ---\")\n",
    "    for ex in examples_sorted[:2]:\n",
    "        print(f\"  Real query: {ex['real_query']}\")\n",
    "        print(f\"  Best generated: {ex['best_generated']}\")\n",
    "        print(f\"  Max ROUGE-1: {ex['max_rouge1']:.3f}\")\n",
    "        print(f\"  All generated: {ex['generated_queries']}\")\n",
    "        print()\n",
    "\n",
    "    print(\"--- Challenging Examples (lower ROUGE) ---\")\n",
    "    for ex in examples_sorted[-2:]:\n",
    "        print(f\"  Real query: {ex['real_query']}\")\n",
    "        print(f\"  Best generated: {ex['best_generated']}\")\n",
    "        print(f\"  Max ROUGE-1: {ex['max_rouge1']:.3f}\")\n",
    "        print()\n",
    "else:\n",
    "    print(f\"Validation skipped: {validation_results['error']}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b4c93d70",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "### Interpretation of Validation Results\n",
    "\n",
    "We use **max over generations** because:\n",
    "- Query generation is inherently variable\n",
    "- Any of the generated queries could be good\n",
    "- This measures \"can the model generate at least one good query?\"\n",
    "\n",
    "**Metrics interpretation**:\n",
    "- **Max ROUGE-1/L**: N-gram overlap with real query (best of N generations)\n",
    "- **BERTScore**: Semantic similarity of best generation to real query\n",
    "\n",
    "**Quality indicators**:\n",
    "- Max ROUGE-1 > 0.4: Good lexical overlap\n",
    "- Max ROUGE-1 > 0.6: Excellent - very similar phrasing\n",
    "- BERTScore > 0.7: Strong semantic similarity\n",
    "\n",
    "Low ROUGE but high BERTScore means the generated query captures\n",
    "the intent but uses different words (which is fine for diversity)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2e4abacf",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "### Combining real and synthetic data\n",
    "\n",
    "We combine the original qrels with our synthetic pairs for training."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7dc9aaab",
   "metadata": {},
   "outputs": [],
   "source": [
    "def create_combined_training_data(\n",
    "    qrels_df: pd.DataFrame,\n",
    "    queries_df: pd.DataFrame,\n",
    "    synthetic_pairs: List[Dict],\n",
    ") -> List[Dict]:\n",
    "    \"\"\"\n",
    "    Combine real qrels with synthetic pairs.\n",
    "\n",
    "    Uses the global `index` variable for document text retrieval.\n",
    "\n",
    "    Args:\n",
    "        qrels_df: Original relevance judgments\n",
    "        queries_df: Original queries\n",
    "        synthetic_pairs: Synthetically generated pairs\n",
    "\n",
    "    Returns:\n",
    "        Combined list of training pairs\n",
    "    \"\"\"\n",
    "    training_data = []\n",
    "\n",
    "    # Add real pairs from qrels\n",
    "    for _, row in qrels_df.iterrows():\n",
    "        qid = row[\"qid\"]\n",
    "        doc_id = row[\"docno\"]\n",
    "\n",
    "        query_rows = queries_df[queries_df[\"qid\"] == qid][\"query\"].values\n",
    "        if len(query_rows) == 0:\n",
    "            continue\n",
    "\n",
    "        doc_text = get_doc_text(index, doc_id)\n",
    "        if not doc_text:\n",
    "            continue\n",
    "\n",
    "        training_data.append(\n",
    "            {\n",
    "                \"query\": query_rows[0],\n",
    "                \"doc_id\": doc_id,\n",
    "                \"document\": doc_text,\n",
    "                \"source\": \"qrels\",  # From original dataset\n",
    "            }\n",
    "        )\n",
    "\n",
    "    # Add synthetic pairs\n",
    "    training_data.extend(synthetic_pairs)\n",
    "\n",
    "    return training_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "468acfd6",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Create combined training data\n",
    "combined_training = create_combined_training_data(qrels_df, queries_df, filtered_pairs)\n",
    "\n",
    "print(f\"Combined training data: {len(combined_training)} pairs\")\n",
    "print(f\"  - From qrels: {sum(1 for p in combined_training if p['source'] == 'qrels')}\")\n",
    "print(\n",
    "    f\"  - Synthetic: {sum(1 for p in combined_training if p['source'] == 'synthetic')}\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ee2859cd",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "### Save training data for practical 5\n",
    "\n",
    "Save the combined training data for SPLADE training."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4c938e9a",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "import json\n",
    "\n",
    "# Prepare data for saving (don't include full document text to save space)\n",
    "training_export = []\n",
    "for pair in combined_training:\n",
    "    training_export.append(\n",
    "        {\n",
    "            \"query\": pair[\"query\"],\n",
    "            \"doc_id\": pair[\"doc_id\"],\n",
    "            \"source\": pair[\"source\"],\n",
    "        }\n",
    "    )\n",
    "\n",
    "output_dir = Path(\"./outputs/practical-04\")\n",
    "output_dir.mkdir(parents=True, exist_ok=True)\n",
    "output_path = output_dir / \"training_data_for_splade.json\"\n",
    "with open(output_path, \"w\", encoding=\"utf-8\") as f:\n",
    "    json.dump(training_export, f, indent=2)\n",
    "\n",
    "print(f\"Saved {len(training_export)} training pairs to {output_path}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "81c38681",
   "metadata": {},
   "source": [
    "## Part 4: Introduction to RAG with BM25\n",
    "\n",
    "Before implementing SPLADE in the next practical, let's see how RAG\n",
    "(Retrieval-Augmented Generation) works with a simple BM25 retriever.\n",
    "\n",
    "RAG combines:\n",
    "1. **Retrieval**: Find relevant documents for a question\n",
    "2. **Generation**: Use the documents as context to generate an answer\n",
    "\n",
    "We already indexed the documents in Part 2, so we just need to create\n",
    "the BM25 retriever."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3c9730ac",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create BM25 retriever using the index\n",
    "bm25 = index.retriever(\"BM25\")\n",
    "print(\"BM25 retriever ready\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d0a02b18",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def simple_rag(\n",
    "    question: str,\n",
    "    retriever,\n",
    "    pt_index,\n",
    "    model,\n",
    "    tokenizer,\n",
    "    top_k: int = 3,\n",
    ") -> dict:\n",
    "    \"\"\"\n",
    "    Simple RAG pipeline with BM25.\n",
    "\n",
    "    Args:\n",
    "        question: User question\n",
    "        retriever: PyTerrier retriever (BM25)\n",
    "        pt_index: PyTerrier index reference (for text retrieval)\n",
    "        model: Generation model\n",
    "        tokenizer: Model tokenizer\n",
    "        top_k: Number of documents to retrieve\n",
    "\n",
    "    Returns:\n",
    "        Dict with retrieved docs and generated answer\n",
    "    \"\"\"\n",
    "    # Implement simple RAG with BM25\n",
    "\n",
    "    # 1. Retrieve top-k documents using BM25\n",
    "    # 2. Build context from retrieved documents\n",
    "    # 3. Generate answer using the LLM\n",
    "    results = retriever.search(question)\n",
    "    top_docs = results.head(top_k)\n",
    "    doc_ids = top_docs[\"docno\"].tolist()\n",
    "    doc_texts = get_text_from_index(pt_index, doc_ids)\n",
    "    context_parts = [doc_texts.get(doc_id, \"\")[:300] for doc_id in doc_ids]\n",
    "    assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9b370c77",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Test RAG with BM25\n",
    "test_questions_rag = [\n",
    "    \"How do I install Python packages?\",\n",
    "    \"What is the difference between a list and a tuple?\",\n",
    "]\n",
    "\n",
    "print(\"=== RAG with BM25 ===\\n\")\n",
    "for question in test_questions_rag[:1]:  # Just one for the practical\n",
    "    result = simple_rag(question, bm25, index, model, tokenizer, top_k=3)\n",
    "\n",
    "    print(f\"Question: {result['question']}\")\n",
    "    print(f\"\\nRetrieved documents ({len(result['retrieved_docs'])}):\")\n",
    "    for doc_info in result[\"retrieved_docs\"]:\n",
    "        print(f\"  - {doc_info['doc_id'][:20]}... (score: {doc_info['score']:.2f})\")\n",
    "    print(f\"\\nGenerated answer:\\n{result['answer'][:500]}\")\n",
    "    print(\"\\n\" + \"=\" * 80)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "20849e34",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "### Exercise 5: Compare retrieval without vs with generation\n",
    "\n",
    "Let's see if retrieval helps the model answer questions better."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b7b9c941",
   "metadata": {},
   "outputs": [],
   "source": [
    "def answer_without_retrieval(question: str, model, tokenizer) -> str:\n",
    "    \"\"\"Generate an answer without retrieval (direct generation).\"\"\"\n",
    "    messages = [\n",
    "        {\"role\": \"system\", \"content\": \"You are a helpful technical assistant.\"},\n",
    "        {\"role\": \"user\", \"content\": question},\n",
    "    ]\n",
    "    prompt = tokenizer.apply_chat_template(\n",
    "        messages, tokenize=False, add_generation_prompt=True\n",
    "    )\n",
    "    inputs = tokenizer(prompt, return_tensors=\"pt\").to(device)\n",
    "\n",
    "    with torch.no_grad():\n",
    "        outputs = model.generate(\n",
    "            **inputs,\n",
    "            max_new_tokens=150,\n",
    "            temperature=0.7,\n",
    "            do_sample=True,\n",
    "            pad_token_id=tokenizer.eos_token_id,\n",
    "        )\n",
    "\n",
    "    answer = tokenizer.decode(outputs[0], skip_special_tokens=True)\n",
    "    if \"assistant\" in answer.lower():\n",
    "        answer = answer.split(\"assistant\")[-1].strip()\n",
    "    return answer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1e9048c1",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Compare approaches\n",
    "comparison_question = \"How do I debug a Python program?\"\n",
    "\n",
    "print(f\"Question: {comparison_question}\\n\")\n",
    "\n",
    "# Without retrieval\n",
    "print(\"=== WITHOUT RETRIEVAL ===\")\n",
    "direct_answer = answer_without_retrieval(comparison_question, model, tokenizer)\n",
    "print(direct_answer[:400])\n",
    "\n",
    "print(\"\\n\" + \"=\" * 80)\n",
    "\n",
    "# With RAG\n",
    "print(\"\\n=== WITH RAG (BM25) ===\")\n",
    "rag_result = simple_rag(comparison_question, bm25, index, model, tokenizer)\n",
    "print(rag_result[\"answer\"][:400])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "974d38a8",
   "metadata": {},
   "source": [
    "### Discussion: When is RAG useful?\n",
    "\n",
    "RAG is particularly useful when:\n",
    "- The knowledge is specific or recent (not in the model's training data)\n",
    "- We need citations or sources for the answers\n",
    "- The corpus is specialized (like StackExchange technical Q&A)\n",
    "\n",
    "In the next practical, we will replace BM25 with SPLADE for better retrieval."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
