{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c395a434",
   "metadata": {},
   "source": [
    "# Week 5: RAG and Information Retrieval with SPLADE\n",
    "\n",
    "In this practical, we will build a complete RAG (Retrieval-Augmented Generation)\n",
    "system using the LoTTE dataset from ir-datasets.\n",
    "\n",
    "We use PyTerrier's integration with ir-datasets for easy access:\n",
    "https://ir-datasets.com/pyterrier.html\n",
    "\n",
    "**Note**: This practical can optionally use synthetic training data generated\n",
    "in Practical 04 (`training_data_for_splade.json`). Run Practical 04 first\n",
    "to generate more training data for better SPLADE performance.\n",
    "\n",
    "Outline:\n",
    "1. **IR Fundamentals**: Indexing and BM25 with PyTerrier\n",
    "1b. **Hard Negative Mining**: Creating effective training data\n",
    "2. **Introduction to SPLADE**: Learned sparse representations\n",
    "3. **SPLADE Implementation**: Architecture from scratch\n",
    "4. **SPLADE Training**: Contrastive learning with hard negatives\n",
    "5. **Distillation**: Cross-encoder to bi-encoder\n",
    "6. **RAG Pipeline**: Retrieval + Generation\n",
    "7. **Evaluation**: MRR, Recall@k"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5ee50d58",
   "metadata": {},
   "source": [
    "## Setup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "20ffb62e",
   "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 pyterrier==1.0.1\n",
    "%pip install su-master-mind==2026.1.25.4\n",
    "%pip install torch==2.9.1\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d603ade1",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "source": [
    "## Load the Dataset\n",
    "\n",
    "We load the LoTTE dataset directly using PyTerrier's ir-datasets integration.\n",
    "This gives us access to documents, queries, and relevance judgments.\n",
    "\n",
    "See: https://ir-datasets.com/pyterrier.html"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7685276c",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import pyterrier as pt\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "import ir_measures\n",
    "import getpass\n",
    "import os\n",
    "import tarfile\n",
    "import urllib.request\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 ir_measures import RR, Recall\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "38d64908",
   "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": "c812fdd3",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"Cache utilities for downloading and caching files.\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b7bfbc61",
   "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": "fabb07f0",
   "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": "c6fc3db1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Configuration\n",
    "num_docs = 5000  # Limit documents for practical\n",
    "num_queries = 100  # Limit queries"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "94f3cb3d",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Get queries and qrels first to know which documents are relevant\n",
    "queries_df = dataset.get_topics().head(num_queries)\n",
    "qrels_df = dataset.get_qrels()\n",
    "\n",
    "# Filter qrels for our queries first\n",
    "query_ids = set(queries_df[\"qid\"].tolist())\n",
    "qrels_df = qrels_df[qrels_df[\"qid\"].isin(query_ids)].copy()\n",
    "\n",
    "# Get the set of relevant document IDs we need\n",
    "relevant_doc_ids = set(qrels_df[\"docno\"].tolist())\n",
    "\n",
    "print(\"Queries and Qrels loaded:\")\n",
    "print(f\"  - Queries: {len(queries_df)}\")\n",
    "print(f\"  - Qrels: {len(qrels_df)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c1a78169",
   "metadata": {},
   "source": [
    "## Part 1: Information Retrieval Fundamentals"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "391ef983",
   "metadata": {},
   "source": [
    "### Indexing with PyTerrier\n",
    "\n",
    "`IterDictIndexer` accepts any iterable of `{\"docno\": ..., \"text\": ...}` dicts.\n",
    "We configure `meta` to store document text in the index for later retrieval.\n",
    "This allows scaling to larger collections without keeping all text in memory."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d99cd2e5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Download the PyTerrier index of Lotte (technology subset)\n",
    "index_path = get_from_cache(\n",
    "    \"https://master-mind.isir.upmc.fr/llm/data/index_lotte.tar.gz\", \"llm/index_lotte\"\n",
    ")\n",
    "\n",
    "# Initialize PyTerrier with the index\n",
    "index = pt.terrier.TerrierIndex(str(index_path))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "56db92a5",
   "metadata": {},
   "outputs": [],
   "source": [
    "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, \"\")\n",
    "\n",
    "\n",
    "def doc_exists_in_index(index, doc_id: str) -> bool:\n",
    "    \"\"\"Check if a document exists in the index (without fetching text).\"\"\"\n",
    "    meta_index = index.meta_index()\n",
    "    try:\n",
    "        return meta_index.getDocument(\"docno\", doc_id) >= 0\n",
    "    except Exception:\n",
    "        return False"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a9d3fd30",
   "metadata": {},
   "source": [
    "### BM25 Baseline Retriever"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5d1b7640",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create a BM25 retriever\n",
    "bm25 = index.retriever(\"BM25\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "523f16ae",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Test search\n",
    "test_query = \"How do I install Python packages?\"\n",
    "results = bm25.search(test_query)\n",
    "print(f\"Top 3 results for: '{test_query}'\")\n",
    "for i, row in results.head(3).iterrows():\n",
    "    doc_text = get_doc_text(index, row[\"docno\"])\n",
    "    print(f\"\\n[{i + 1}] Score: {row['score']:.2f}\")\n",
    "    print(f\"    Doc: {doc_text[:150]}...\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "774335ac",
   "metadata": {},
   "source": [
    "### Evaluation with MRR and Recall@k\n",
    "\n",
    "We use `ir-measures` to compute standard IR metrics."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "290a41b7",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Convert PyTerrier dataframes to ir-measures format\n",
    "def to_ir_measures_qrels(qrels_df):\n",
    "    \"\"\"Convert PyTerrier qrels to ir-measures format.\"\"\"\n",
    "    return qrels_df.rename(\n",
    "        columns={\"qid\": \"query_id\", \"docno\": \"doc_id\", \"label\": \"relevance\"}\n",
    "    )\n",
    "\n",
    "\n",
    "def to_ir_measures_run(run_df):\n",
    "    \"\"\"Convert PyTerrier run to ir-measures format.\"\"\"\n",
    "    return run_df.rename(columns={\"qid\": \"query_id\", \"docno\": \"doc_id\"})\n",
    "\n",
    "\n",
    "qrels_ir = to_ir_measures_qrels(qrels_df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1604dd44",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Evaluate BM25\n",
    "results = bm25.transform(queries_df[[\"qid\", \"query\"]])\n",
    "\n",
    "# Compute metrics using ir-measures\n",
    "metrics = [RR, Recall @ 1, Recall @ 5, Recall @ 10]\n",
    "eval_results = ir_measures.calc_aggregate(\n",
    "    metrics, qrels_ir, to_ir_measures_run(results)\n",
    ")\n",
    "\n",
    "print(\"BM25 Baseline:\")\n",
    "for metric, value in eval_results.items():\n",
    "    print(f\"  {metric}: {value:.4f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b68d094f",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Part 1b: Hard Negative Mining\n",
    "\n",
    "To train a good retrieval model, we need more than just positive examples.\n",
    "**Hard negatives** are documents that seem relevant but are not the ground truth.\n",
    "\n",
    "Why hard negatives matter:\n",
    "- **Random negatives** are too easy to distinguish → model doesn't learn much\n",
    "- **Hard negatives** force the model to learn subtle differences\n",
    "- BM25 provides good hard negatives: similar in lexical terms, but different in meaning\n",
    "\n",
    "### Hard Negative Mining"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4437765d",
   "metadata": {},
   "outputs": [],
   "source": [
    "def find_hard_negatives_bm25(\n",
    "    query: str,\n",
    "    positive_doc_ids: set,\n",
    "    retriever,\n",
    "    num_negatives: int = 5,\n",
    ") -> List[str]:\n",
    "    \"\"\"\n",
    "    Find hard negatives using BM25.\n",
    "\n",
    "    Hard negatives are documents that are lexically similar to the query\n",
    "    but are NOT the ground truth positive document.\n",
    "\n",
    "    Args:\n",
    "        query: The query text\n",
    "        positive_doc_ids: Set of positive document IDs (to exclude)\n",
    "        retriever: BM25 retriever\n",
    "        num_negatives: Number of hard negatives to return\n",
    "\n",
    "    Returns:\n",
    "        List of document IDs for hard negatives\n",
    "    \"\"\"\n",
    "    # Implement hard negative mining with BM25\n",
    "\n",
    "    # 1. Retrieve top documents with BM25\n",
    "    # 2. Filter out the positive documents\n",
    "    # 3. Return the top-k remaining as hard negatives\n",
    "    results = retriever.search(query)\n",
    "    hard_negatives = []\n",
    "    for _, row in results.iterrows():\n",
    "    assert False, 'Not implemented yet'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eb0418af",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Test hard negative mining\n",
    "test_qid = qrels_df[\"qid\"].iloc[0]\n",
    "test_query_row = queries_df[queries_df[\"qid\"] == test_qid].iloc[0]\n",
    "test_query_text = test_query_row[\"query\"]\n",
    "test_positives = set(qrels_df[qrels_df[\"qid\"] == test_qid][\"docno\"].tolist())\n",
    "\n",
    "hard_negs = find_hard_negatives_bm25(\n",
    "    test_query_text, test_positives, bm25, num_negatives=3\n",
    ")\n",
    "\n",
    "print(f\"Query: {test_query_text}\")\n",
    "print(f\"\\nPositive documents ({len(test_positives)}):\")\n",
    "pos_texts = get_text_from_index(index, list(test_positives)[:2])\n",
    "for pos_id, pos_text in pos_texts.items():\n",
    "    print(f\"  {pos_text[:100]}...\")\n",
    "print(f\"\\nHard negatives ({len(hard_negs)}):\")\n",
    "neg_texts = get_text_from_index(index, hard_negs)\n",
    "for neg_id in hard_negs:\n",
    "    print(f\"  {neg_texts.get(neg_id, '')[:100]}...\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f25b04d8",
   "metadata": {},
   "outputs": [],
   "source": [
    "def create_training_triplets(\n",
    "    queries_df: pd.DataFrame,\n",
    "    qrels_df: pd.DataFrame,\n",
    "    index,\n",
    "    retriever,\n",
    "    num_hard_negatives: int = 3,\n",
    "    max_queries: int = None,\n",
    ") -> List[Dict]:\n",
    "    \"\"\"\n",
    "    Create training triplets with hard negatives.\n",
    "\n",
    "    Each triplet contains:\n",
    "    - query: The question\n",
    "    - positive: A relevant document\n",
    "    - negatives: List of hard negative documents\n",
    "\n",
    "    Args:\n",
    "        queries_df: DataFrame with queries\n",
    "        qrels_df: DataFrame with relevance judgments\n",
    "        index: PyTerrier index reference (for text retrieval)\n",
    "        retriever: BM25 retriever for hard negative mining\n",
    "        num_hard_negatives: Number of hard negatives per query\n",
    "        max_queries: Maximum number of queries to process\n",
    "\n",
    "    Returns:\n",
    "        List of training triplets\n",
    "    \"\"\"\n",
    "    triplets = []\n",
    "\n",
    "    queries_to_process = queries_df.head(max_queries) if max_queries else queries_df\n",
    "\n",
    "    for _, query_row in tqdm(\n",
    "        queries_to_process.iterrows(),\n",
    "        desc=\"Creating training triplets\",\n",
    "        total=len(queries_to_process),\n",
    "    ):\n",
    "        qid = query_row[\"qid\"]\n",
    "        query_text = query_row[\"query\"]\n",
    "\n",
    "        # Get positive documents for this query\n",
    "        positive_doc_ids = set(qrels_df[qrels_df[\"qid\"] == qid][\"docno\"].tolist())\n",
    "\n",
    "        if not positive_doc_ids:\n",
    "            continue\n",
    "\n",
    "        # Get the first positive document\n",
    "        positive_id = list(positive_doc_ids)[0]\n",
    "        positive_text = get_doc_text(index, positive_id)\n",
    "\n",
    "        if not positive_text:\n",
    "            continue\n",
    "\n",
    "        # Find hard negatives\n",
    "        hard_neg_ids = find_hard_negatives_bm25(\n",
    "            query_text, positive_doc_ids, retriever, num_hard_negatives\n",
    "        )\n",
    "        hard_neg_texts = get_text_from_index(index, hard_neg_ids)\n",
    "        hard_neg_list = [\n",
    "            hard_neg_texts[nid] for nid in hard_neg_ids if nid in hard_neg_texts\n",
    "        ]\n",
    "\n",
    "        if hard_neg_list:\n",
    "            triplets.append(\n",
    "                {\n",
    "                    \"query\": query_text,\n",
    "                    \"positive\": positive_text,\n",
    "                    \"negatives\": hard_neg_list,\n",
    "                }\n",
    "            )\n",
    "\n",
    "    return triplets"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cc3e98c6",
   "metadata": {},
   "source": [
    "### Loading synthetic training data from Practical 04\n",
    "\n",
    "In the previous practical, we generated synthetic queries using an LLM.\n",
    "We can load and use this additional training data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "33004eec",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "import json\n",
    "\n",
    "synthetic_training_path = Path(\"./outputs/practical-04/training_data_for_splade.json\")\n",
    "synthetic_pairs = []\n",
    "\n",
    "if synthetic_training_path.exists():\n",
    "    with open(synthetic_training_path, \"r\", encoding=\"utf-8\") as f:\n",
    "        synthetic_data = json.load(f)\n",
    "\n",
    "    # Convert to query-positive pairs (filter to docs in our index)\n",
    "    for item in synthetic_data:\n",
    "        # Check if doc exists in index\n",
    "        if doc_exists_in_index(index, item[\"doc_id\"]):\n",
    "            synthetic_pairs.append(\n",
    "                {\n",
    "                    \"query\": item[\"query\"],\n",
    "                    \"doc_id\": item[\"doc_id\"],\n",
    "                    \"source\": item.get(\"source\", \"synthetic\"),\n",
    "                }\n",
    "            )\n",
    "\n",
    "    print(f\"Loaded {len(synthetic_pairs)} synthetic training pairs from Practical 04\")\n",
    "else:\n",
    "    print(f\"No synthetic training data found at {synthetic_training_path}\")\n",
    "    print(\n",
    "        \"Run Practical 04 first to generate synthetic queries, or continue with qrels only.\"\n",
    "    )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "69d02b8e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create training data with hard negatives\n",
    "num_train_queries = 50\n",
    "\n",
    "\n",
    "# Create triplets from qrels (original data)\n",
    "training_triplets = create_training_triplets(\n",
    "    queries_df,\n",
    "    qrels_df,\n",
    "    index,\n",
    "    bm25,\n",
    "    num_hard_negatives=3,\n",
    "    max_queries=num_train_queries,\n",
    ")\n",
    "\n",
    "print(f\"\\nTraining triplets from qrels: {len(training_triplets)}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d0ee7942",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Add triplets from synthetic pairs (if available)\n",
    "if synthetic_pairs:\n",
    "    print(f\"Adding triplets from {len(synthetic_pairs)} synthetic pairs...\")\n",
    "\n",
    "    for pair in tqdm(\n",
    "        synthetic_pairs[:num_train_queries], desc=\"Processing synthetic pairs\"\n",
    "    ):\n",
    "        query_text = pair[\"query\"]\n",
    "        positive_id = pair[\"doc_id\"]\n",
    "        positive_text = get_doc_text(index, positive_id)\n",
    "\n",
    "        if not positive_text:\n",
    "            continue\n",
    "\n",
    "        # Find hard negatives for synthetic queries too\n",
    "        hard_neg_ids = find_hard_negatives_bm25(\n",
    "            query_text, {positive_id}, bm25, num_negatives=3\n",
    "        )\n",
    "        hard_neg_texts = get_text_from_index(index, hard_neg_ids)\n",
    "        hard_neg_list = [\n",
    "            hard_neg_texts[nid] for nid in hard_neg_ids if nid in hard_neg_texts\n",
    "        ]\n",
    "\n",
    "        if hard_neg_list:\n",
    "            training_triplets.append(\n",
    "                {\n",
    "                    \"query\": query_text,\n",
    "                    \"positive\": positive_text,\n",
    "                    \"negatives\": hard_neg_list,\n",
    "                }\n",
    "            )\n",
    "\n",
    "    print(f\"Total training triplets (qrels + synthetic): {len(training_triplets)}\")\n",
    "if training_triplets:\n",
    "    print(\"Example triplet:\")\n",
    "    print(f\"  Query: {training_triplets[0]['query'][:60]}...\")\n",
    "    print(f\"  Positive: {training_triplets[0]['positive'][:60]}...\")\n",
    "    print(f\"  Num negatives: {len(training_triplets[0]['negatives'])}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b2bca219",
   "metadata": {},
   "source": [
    "## Part 2: Introduction to SPLADE\n",
    "\n",
    "SPLADE (SParse Lexical AnD Expansion) learns sparse representations\n",
    "using a masked language model (MLM).\n",
    "\n",
    "### Key idea:\n",
    "- Use MLM logits to \"expand\" terms\n",
    "- Example: \"car\" can activate \"automobile\", \"vehicle\", \"transport\"\n",
    "- Sparsify with ReLU + log for few active terms\n",
    "\n",
    "### Formula:\n",
    "For each token position, we compute:\n",
    "```\n",
    "w_j = max_i log(1 + ReLU(MLM_logits[i, j]))\n",
    "```\n",
    "Where j is the vocabulary index.\n",
    "\n",
    "### SPLADE Introduction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "563aaf9a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load an MLM model (DistilBERT for efficiency)\n",
    "\n",
    "# You can also use\n",
    "# splade_baseline_model=\"naver/splade_v2_distil\"\n",
    "\n",
    "splade_baseline_model = \"distilbert-base-uncased\"\n",
    "mlm_tokenizer = load_hf_tokenizer(splade_baseline_model)\n",
    "mlm_model = load_hf_model(splade_baseline_model, AutoModelForMaskedLM)\n",
    "mlm_model = mlm_model.to(device)\n",
    "mlm_model.eval()\n",
    "\n",
    "print(f\"MLM model loaded: {splade_baseline_model} on {device}\")\n",
    "print(f\"Vocabulary size: {mlm_tokenizer.vocab_size}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "034cd09f",
   "metadata": {},
   "outputs": [],
   "source": [
    "def compute_splade_representation(\n",
    "    text: str,\n",
    "    model: AutoModelForMaskedLM,\n",
    "    tokenizer: AutoTokenizer,\n",
    ") -> torch.Tensor:\n",
    "    \"\"\"\n",
    "    Compute the SPLADE representation of a text.\n",
    "\n",
    "    Args:\n",
    "        text: Text to encode\n",
    "        model: MLM model\n",
    "        tokenizer: Tokenizer\n",
    "\n",
    "    Returns:\n",
    "        Sparse vector of size vocab_size\n",
    "    \"\"\"\n",
    "    # Implement SPLADE representation\n",
    "\n",
    "    # 2. Get MLM logits\n",
    "    # 3. Apply ReLU then log(1 + x)\n",
    "    # 4. Max-pooling over positions\n",
    "    inputs = tokenizer(text, return_tensors=\"pt\", ...).to(device)\n",
    "    with torch.no_grad():\n",
    "    Implement compute_splade_representation\n",
    "\n",
    "    assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2e9b16ec",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Test SPLADE representation\n",
    "test_text = \"How do I install Python packages using pip?\"\n",
    "sparse_rep = compute_splade_representation(test_text, mlm_model, mlm_tokenizer)\n",
    "\n",
    "print(f\"Dimension: {sparse_rep.shape}\")\n",
    "print(f\"Non-zero terms: {(sparse_rep > 0).sum().item()}\")\n",
    "print(f\"Sparsity: {100 * (sparse_rep == 0).sum().item() / len(sparse_rep):.1f}%\")\n",
    "\n",
    "# Display most activated terms\n",
    "top_indices = torch.topk(sparse_rep, k=15).indices\n",
    "top_tokens = mlm_tokenizer.convert_ids_to_tokens(top_indices.tolist())\n",
    "top_values = sparse_rep[top_indices].tolist()\n",
    "\n",
    "print(\"\\nMost activated terms:\")\n",
    "for token, value in zip(top_tokens, top_values):\n",
    "    print(f\"  {token}: {value:.3f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9e321d53",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Part 3: SPLADE Architecture from Scratch\n",
    "\n",
    "We will implement a complete SPLADE encoder.\n",
    "\n",
    "### SPLADE Architecture"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0cb8ab5a",
   "metadata": {},
   "outputs": [],
   "source": [
    "class SPLADEEncoder(nn.Module):\n",
    "    \"\"\"\n",
    "    SPLADE encoder based on an MLM model.\n",
    "\n",
    "    Architecture:\n",
    "    - Backbone: Pre-trained MLM model (DistilBERT, etc.)\n",
    "    - Sparsification: ReLU + log(1 + x)\n",
    "    - Pooling: Max over positions\n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(\n",
    "        self,\n",
    "        model_name: str = \"distilbert-base-uncased\",\n",
    "        sparsity_weight: float = 0.0001,\n",
    "    ):\n",
    "        super().__init__()\n",
    "        self.tokenizer = load_hf_tokenizer(model_name)\n",
    "        self.model = load_hf_model(model_name, AutoModelForMaskedLM)\n",
    "        self.sparsity_weight = sparsity_weight\n",
    "        self.vocab_size = self.tokenizer.vocab_size\n",
    "\n",
    "    def encode(\n",
    "        self,\n",
    "        texts: List[str],\n",
    "        max_length: int = 256,\n",
    "    ) -> torch.Tensor:\n",
    "        \"\"\"\n",
    "        Encode a list of texts into SPLADE representations.\n",
    "\n",
    "        Args:\n",
    "            texts: List of texts\n",
    "            max_length: Maximum length\n",
    "\n",
    "        Returns:\n",
    "            Tensor of shape (batch_size, vocab_size)\n",
    "        \"\"\"\n",
    "        # Implement batch encoding\n",
    "\n",
    "        # 2. Forward pass through MLM model\n",
    "        # 3. Sparsification: ReLU + log(1 + x)\n",
    "        # 4. Max-pooling over positions (attention to mask!)\n",
    "        inputs = self.tokenizer(texts, return_tensors=\"pt\", ...)\n",
    "        outputs = self.model(**inputs)\n",
    "        ...\n",
    "        Implement the encode method\n",
    "\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "    def compute_flops_loss(self, sparse_rep: torch.Tensor) -> torch.Tensor:\n",
    "        \"\"\"\n",
    "        Compute FLOPS penalty to encourage sparsity.\n",
    "\n",
    "        FLOPS = sum_j (sum_i w_ij)^2\n",
    "\n",
    "        This penalty encourages sparse representations.\n",
    "        \"\"\"\n",
    "        # Sum over batch then square\n",
    "        flops = (sparse_rep.sum(dim=0) ** 2).sum()\n",
    "        return self.sparsity_weight * flops\n",
    "\n",
    "    def forward(\n",
    "        self,\n",
    "        query_texts: List[str],\n",
    "        doc_texts: List[str],\n",
    "    ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n",
    "        \"\"\"\n",
    "        Forward pass for training.\n",
    "\n",
    "        Returns:\n",
    "            query_rep: Query representations\n",
    "            doc_rep: Document representations\n",
    "            flops_loss: Sparsity penalty\n",
    "        \"\"\"\n",
    "        query_rep = self.encode(query_texts)\n",
    "        doc_rep = self.encode(doc_texts)\n",
    "\n",
    "        flops_loss = self.compute_flops_loss(query_rep) + self.compute_flops_loss(\n",
    "            doc_rep\n",
    "        )\n",
    "\n",
    "        return query_rep, doc_rep, flops_loss"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2f02a18c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Test the encoder\n",
    "splade_encoder = SPLADEEncoder(splade_baseline_model)\n",
    "splade_encoder = splade_encoder.to(device)\n",
    "print(f\"SPLADE encoder loaded on {device}\")\n",
    "\n",
    "test_queries = [\"How to install Python packages?\"]\n",
    "test_docs = [\"Use pip install to install Python packages from PyPI.\"]\n",
    "\n",
    "with torch.no_grad():\n",
    "    q_rep, d_rep, flops = splade_encoder(test_queries, test_docs)\n",
    "\n",
    "print(f\"Query rep shape: {q_rep.shape}\")\n",
    "print(f\"Doc rep shape: {d_rep.shape}\")\n",
    "print(f\"FLOPS loss: {flops.item():.4f}\")\n",
    "\n",
    "# Similarity score (dot product)\n",
    "score = (q_rep * d_rep).sum().item()\n",
    "print(f\"Query-doc score: {score:.4f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7375e784",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Visualize activated terms\n",
    "def visualize_splade_terms(\n",
    "    rep: torch.Tensor,\n",
    "    tokenizer: AutoTokenizer,\n",
    "    top_k: int = 20,\n",
    "):\n",
    "    \"\"\"Display most activated terms.\"\"\"\n",
    "    top_indices = torch.topk(rep, k=top_k).indices\n",
    "    top_tokens = tokenizer.convert_ids_to_tokens(top_indices.tolist())\n",
    "    top_values = rep[top_indices].tolist()\n",
    "\n",
    "    print(\"Activated terms:\")\n",
    "    for token, value in zip(top_tokens, top_values):\n",
    "        bar = \"█\" * int(value * 5)\n",
    "        print(f\"  {token:20s} {value:6.3f} {bar}\")\n",
    "\n",
    "\n",
    "print(\"=== Query ===\")\n",
    "visualize_splade_terms(q_rep[0], splade_encoder.tokenizer)\n",
    "print(\"\\n=== Document ===\")\n",
    "visualize_splade_terms(d_rep[0], splade_encoder.tokenizer)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "90bc7ca1",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Part 4: Training SPLADE\n",
    "\n",
    "We use a contrastive loss (InfoNCE) to train SPLADE.\n",
    "\n",
    "For each query q:\n",
    "- Positive: the associated document d+\n",
    "- Negatives: other documents from the batch (in-batch negatives)\n",
    "\n",
    "### Training SPLADE"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bf938e8e",
   "metadata": {},
   "outputs": [],
   "source": [
    "def contrastive_loss(\n",
    "    query_rep: torch.Tensor,\n",
    "    doc_rep: torch.Tensor,\n",
    "    temperature: float = 0.05,\n",
    ") -> torch.Tensor:\n",
    "    \"\"\"\n",
    "    Compute InfoNCE contrastive loss.\n",
    "\n",
    "    Args:\n",
    "        query_rep: (batch_size, vocab_size)\n",
    "        doc_rep: (batch_size, vocab_size)\n",
    "        temperature: Temperature for softmax\n",
    "\n",
    "    Returns:\n",
    "        Average loss\n",
    "    \"\"\"\n",
    "    # Implement contrastive loss\n",
    "\n",
    "    # 1. Compute query-doc scores (dot product)\n",
    "    # 2. Positives are on the diagonal\n",
    "    # 3. InfoNCE: -log(exp(score_pos) / sum(exp(scores)))\n",
    "    # Normalize for stability (optional but recommended)\n",
    "    assert False, 'Not implemented yet'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8cbaec3d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Test the loss\n",
    "batch_q = splade_encoder.encode([\"Question 1\", \"Question 2\"])\n",
    "batch_d = splade_encoder.encode([\"Answer 1\", \"Answer 2\"])\n",
    "\n",
    "loss = contrastive_loss(batch_q, batch_d)\n",
    "print(f\"Contrastive loss: {loss.item():.4f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cee0335e",
   "metadata": {},
   "outputs": [],
   "source": [
    "def train_splade(\n",
    "    encoder: SPLADEEncoder,\n",
    "    train_data: List[Dict],\n",
    "    num_epochs: int = 3,\n",
    "    batch_size: int = 8,\n",
    "    learning_rate: float = 2e-5,\n",
    "    temperature: float = 0.05,\n",
    "    use_hard_negatives: bool = False,\n",
    "):\n",
    "    \"\"\"\n",
    "    Train the SPLADE encoder.\n",
    "\n",
    "    Args:\n",
    "        encoder: SPLADE model\n",
    "        train_data: List of triplets {query, positive, negatives}\n",
    "        num_epochs: Number of epochs\n",
    "        batch_size: Batch size\n",
    "        learning_rate: Learning rate\n",
    "        temperature: Temperature for InfoNCE\n",
    "        use_hard_negatives: If True, expects triplets with 'negatives' field\n",
    "    \"\"\"\n",
    "    from torch.optim import AdamW\n",
    "\n",
    "    optimizer = AdamW(encoder.parameters(), lr=learning_rate)\n",
    "    encoder.train()\n",
    "\n",
    "    for epoch in range(num_epochs):\n",
    "        total_loss = 0\n",
    "        total_contrastive = 0\n",
    "        total_flops = 0\n",
    "        num_batches = 0\n",
    "\n",
    "        # Shuffle data\n",
    "        import random\n",
    "\n",
    "        shuffled = train_data.copy()\n",
    "        random.shuffle(shuffled)\n",
    "\n",
    "        # Create batches\n",
    "        for i in tqdm(range(0, len(shuffled), batch_size), desc=f\"Epoch {epoch + 1}\"):\n",
    "            batch = shuffled[i : i + batch_size]\n",
    "            if len(batch) < 2:  # Need at least 2 for contrastive\n",
    "                continue\n",
    "\n",
    "            if use_hard_negatives:\n",
    "                # Use triplets with hard negatives\n",
    "                queries = [ex[\"query\"] for ex in batch]\n",
    "                positives = [ex[\"positive\"][:500] for ex in batch]\n",
    "                # Collect hard negatives from all examples in batch\n",
    "                all_negatives = []\n",
    "                for ex in batch:\n",
    "                    all_negatives.extend([n[:500] for n in ex.get(\"negatives\", [])[:2]])\n",
    "\n",
    "                # Encode queries\n",
    "                query_rep = encoder.encode(queries)\n",
    "                # Encode positives + negatives together\n",
    "                all_docs = positives + all_negatives\n",
    "                doc_reps = encoder.encode(all_docs)\n",
    "                positive_rep = doc_reps[: len(positives)]\n",
    "                negative_rep = doc_reps[len(positives) :]\n",
    "\n",
    "                # Contrastive loss with in-batch + hard negatives\n",
    "                cont_loss = contrastive_loss(query_rep, positive_rep, temperature)\n",
    "\n",
    "                # Add hard negative loss if we have negatives\n",
    "                if len(negative_rep) > 0:\n",
    "                    # Compute scores with negatives and ensure they're lower\n",
    "                    neg_scores = torch.matmul(\n",
    "                        F.normalize(query_rep, p=2, dim=-1),\n",
    "                        F.normalize(negative_rep, p=2, dim=-1).T,\n",
    "                    )\n",
    "                    # Margin loss: positive scores should be higher than negative\n",
    "                    hard_neg_loss = F.relu(neg_scores.mean() + 0.2).mean()\n",
    "                    cont_loss = cont_loss + 0.3 * hard_neg_loss\n",
    "\n",
    "                flops_loss = encoder.compute_flops_loss(\n",
    "                    query_rep\n",
    "                ) + encoder.compute_flops_loss(doc_reps)\n",
    "            else:\n",
    "                # Standard in-batch negatives only\n",
    "                queries = [ex[\"query\"] for ex in batch]\n",
    "                docs = [ex[\"positive\"][:500] for ex in batch]\n",
    "\n",
    "                # Forward\n",
    "                query_rep, doc_rep, flops_loss = encoder(queries, docs)\n",
    "\n",
    "                # Contrastive loss\n",
    "                cont_loss = contrastive_loss(query_rep, doc_rep, temperature)\n",
    "\n",
    "            # Total loss\n",
    "            loss = cont_loss + flops_loss\n",
    "\n",
    "            # Backward\n",
    "            optimizer.zero_grad()\n",
    "            loss.backward()\n",
    "            optimizer.step()\n",
    "\n",
    "            total_loss += loss.item()\n",
    "            total_contrastive += cont_loss.item()\n",
    "            total_flops += flops_loss.item()\n",
    "            num_batches += 1\n",
    "\n",
    "        avg_loss = total_loss / num_batches\n",
    "        avg_cont = total_contrastive / num_batches\n",
    "        avg_flops = total_flops / num_batches\n",
    "\n",
    "        print(\n",
    "            f\"Epoch {epoch + 1}: Loss={avg_loss:.4f} (Contrastive={avg_cont:.4f}, FLOPS={avg_flops:.4f})\"\n",
    "        )\n",
    "\n",
    "    encoder.eval()\n",
    "    print(\"Training complete!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "867c83b0",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Train SPLADE with hard negatives (reduced version for the practical)\n",
    "num_epochs = 2\n",
    "\n",
    "\n",
    "# Use training triplets created in Part 1b (with hard negatives)\n",
    "if training_triplets:\n",
    "    print(f\"Training on {len(training_triplets)} triplets with hard negatives...\")\n",
    "    train_splade(\n",
    "        splade_encoder,\n",
    "        training_triplets,\n",
    "        num_epochs=num_epochs,\n",
    "        batch_size=8,\n",
    "        use_hard_negatives=True,\n",
    "    )\n",
    "else:\n",
    "    print(\"No training triplets available. Skipping SPLADE training.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4046ac64",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Part 4b: Distillation Cross-Encoder → SPLADE\n",
    "\n",
    "Cross-encoders are more accurate but don't allow pre-indexing.\n",
    "We can distill their knowledge to a bi-encoder (SPLADE).\n",
    "\n",
    "### Principle:\n",
    "1. Train/load a cross-encoder teacher\n",
    "2. The teacher scores (query, doc) pairs\n",
    "3. The student (SPLADE) learns to reproduce these scores\n",
    "\n",
    "### Distillation: Cross-Encoder to SPLADE"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e7fc7ea8",
   "metadata": {},
   "outputs": [],
   "source": [
    "class CrossEncoderTeacher(nn.Module):\n",
    "    \"\"\"\n",
    "    Cross-encoder for scoring query-document pairs.\n",
    "\n",
    "    Unlike the bi-encoder, the cross-encoder sees query and doc together,\n",
    "    allowing richer interactions but preventing pre-computation.\n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(self, model_name: str = \"distilbert-base-uncased\"):\n",
    "        super().__init__()\n",
    "        self.tokenizer = load_hf_tokenizer(model_name)\n",
    "        self.model = load_hf_model(model_name, AutoModel)\n",
    "        self.classifier = nn.Linear(self.model.config.hidden_size, 1)\n",
    "\n",
    "    def forward(\n",
    "        self,\n",
    "        queries: List[str],\n",
    "        documents: List[str],\n",
    "    ) -> torch.Tensor:\n",
    "        \"\"\"\n",
    "        Score query-document pairs.\n",
    "\n",
    "        Args:\n",
    "            queries: List of queries\n",
    "            documents: List of documents (same length as queries)\n",
    "\n",
    "        Returns:\n",
    "            Relevance scores (batch_size,)\n",
    "        \"\"\"\n",
    "        # Implement cross-encoder forward\n",
    "\n",
    "        # 1. Concatenate query and document with [SEP]\n",
    "        # 2. Tokenize\n",
    "        # 3. Get [CLS] embedding\n",
    "        # 4. Classify to get score\n",
    "        pairs = [q + \" [SEP] \" + d for q, d in zip(queries, documents)]\n",
    "        inputs = self.tokenizer(pairs, ...)\n",
    "        outputs = self.model(**inputs)\n",
    "        cls_output = outputs.last_hidden_state[:, 0, :]\n",
    "        scores = self.classifier(cls_output)\n",
    "        assert False, 'Not implemented yet'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "428aa3e3",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize cross-encoder\n",
    "# Using pre-trained cross-encoder from sentence-transformers\n",
    "# Lightweight options:\n",
    "# - cross-encoder/ms-marco-MiniLM-L6-v2 (22.7M params, recommended)\n",
    "# - cross-encoder/ms-marco-MiniLM-L12-v2 (33.4M params, more powerful)\n",
    "# - cross-encoder/ms-marco-TinyBERT-L2-v2 (4.39M params, ultra-light)\n",
    "cross_encoder = CrossEncoderTeacher(\"cross-encoder/ms-marco-MiniLM-L6-v2\")\n",
    "cross_encoder = cross_encoder.to(device)\n",
    "print(f\"Cross-encoder loaded on {device}\")\n",
    "\n",
    "# Test\n",
    "test_scores = cross_encoder(\n",
    "    [\"How to install packages?\"],\n",
    "    [\"Use pip install to install Python packages.\"],\n",
    ")\n",
    "print(f\"Cross-encoder score: {test_scores.item():.4f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "935da86f",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def distillation_loss(\n",
    "    student_scores: torch.Tensor,\n",
    "    teacher_scores: torch.Tensor,\n",
    "    temperature: float = 1.0,\n",
    ") -> torch.Tensor:\n",
    "    \"\"\"\n",
    "    Compute distillation loss (MSE or KL divergence).\n",
    "\n",
    "    Args:\n",
    "        student_scores: Student (SPLADE) scores\n",
    "        teacher_scores: Teacher (cross-encoder) scores\n",
    "        temperature: Temperature for softening distributions (KL only)\n",
    "\n",
    "    Returns:\n",
    "        Distillation loss\n",
    "    \"\"\"\n",
    "    # Simple MSE between scores\n",
    "    return F.mse_loss(student_scores, teacher_scores.detach())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9b127373",
   "metadata": {},
   "source": [
    "## Part 5: Complete RAG Pipeline\n",
    "\n",
    "Now let's combine the SPLADE retriever with a generator (SmolLM2).\n",
    "\n",
    "### RAG Pipeline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2459d769",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load generation model\n",
    "#\n",
    "# Options (uncomment ONE gen_model_name):\n",
    "#\n",
    "# 1. SmolLM2-1.7B float16 (~3.4GB) - default, works on all platforms\n",
    "gen_model_name = \"HuggingFaceTB/SmolLM2-1.7B-Instruct\"\n",
    "#\n",
    "# 2. Pre-quantized models (GPTQ/AWQ) - Linux only\n",
    "# gen_model_name = \"Qwen/Qwen2.5-3B-Instruct-AWQ\"  # 3B AWQ, ~2GB\n",
    "# gen_model_name = \"Qwen/Qwen2.5-7B-Instruct-AWQ\"  # 7B AWQ, ~4GB\n",
    "\n",
    "gen_tokenizer = load_hf_tokenizer(gen_model_name)\n",
    "\n",
    "# Detect if model is pre-quantized (AWQ/GPTQ) by name\n",
    "is_quantized = \"AWQ\" in gen_model_name or \"GPTQ\" in gen_model_name\n",
    "\n",
    "if is_quantized:\n",
    "    gen_model = load_hf_model(\n",
    "        gen_model_name,\n",
    "        AutoModelForCausalLM,\n",
    "        device_map=\"auto\",\n",
    "    )\n",
    "    print(f\"Generation model loaded: {gen_model_name} (pre-quantized)\")\n",
    "else:\n",
    "    gen_model = load_hf_model(\n",
    "        gen_model_name,\n",
    "        AutoModelForCausalLM,\n",
    "        dtype=torch.float16,\n",
    "    )\n",
    "    gen_model = gen_model.to(device)\n",
    "    print(f\"Generation model loaded: {gen_model_name} on {device}\")\n",
    "\n",
    "gen_model.eval()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b4759364",
   "metadata": {},
   "outputs": [],
   "source": [
    "class RAGPipeline:\n",
    "    \"\"\"\n",
    "    Complete RAG pipeline: Retrieval + Generation.\n",
    "\n",
    "    Uses PyTerrier index for document storage (scalable to large collections).\n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(\n",
    "        self,\n",
    "        retriever: SPLADEEncoder,\n",
    "        generator,\n",
    "        generator_tokenizer,\n",
    "        pt_index,\n",
    "        doc_ids: List[str],\n",
    "        top_k: int = 3,\n",
    "    ):\n",
    "        self.retriever = retriever\n",
    "        self.generator = generator\n",
    "        self.gen_tokenizer = generator_tokenizer\n",
    "        self.pt_index = pt_index\n",
    "        self.doc_ids = doc_ids\n",
    "        self.top_k = top_k\n",
    "\n",
    "        # Pre-compute document representations\n",
    "        self._index_documents()\n",
    "\n",
    "    def _get_doc_text(self, doc_id: str) -> str:\n",
    "        \"\"\"Get document text from PyTerrier index.\"\"\"\n",
    "        return get_doc_text(self.pt_index, doc_id)\n",
    "\n",
    "    def _get_texts(self, doc_ids: List[str]) -> Dict[str, str]:\n",
    "        \"\"\"Get multiple document texts from PyTerrier index.\"\"\"\n",
    "        return get_text_from_index(self.pt_index, doc_ids)\n",
    "\n",
    "    def _index_documents(self, batch_size: int = 16):\n",
    "        \"\"\"Index all documents with SPLADE.\"\"\"\n",
    "        print(\"Indexing documents with SPLADE...\")\n",
    "\n",
    "        # Get texts from PyTerrier index in batches\n",
    "        all_reps = []\n",
    "\n",
    "        with torch.no_grad():\n",
    "            for i in tqdm(range(0, len(self.doc_ids), batch_size)):\n",
    "                batch_ids = self.doc_ids[i : i + batch_size]\n",
    "                batch_texts = self._get_texts(batch_ids)\n",
    "                # Truncate texts and maintain order\n",
    "                texts = [batch_texts.get(doc_id, \"\")[:500] for doc_id in batch_ids]\n",
    "                reps = self.retriever.encode(texts)\n",
    "                all_reps.append(reps.cpu())\n",
    "\n",
    "        self.doc_reps = torch.cat(all_reps, dim=0)\n",
    "        print(f\"Documents indexed: {len(self.doc_ids)}\")\n",
    "\n",
    "    def retrieve(self, query: str, top_k: int = None) -> List[Tuple[str, float]]:\n",
    "        \"\"\"\n",
    "        Retrieve most relevant documents.\n",
    "\n",
    "        Args:\n",
    "            query: User question\n",
    "            top_k: Number of documents to retrieve\n",
    "\n",
    "        Returns:\n",
    "            List of (doc_id, score)\n",
    "        \"\"\"\n",
    "        if top_k is None:\n",
    "            top_k = self.top_k\n",
    "\n",
    "        # Encode query\n",
    "        with torch.no_grad():\n",
    "            query_rep = self.retriever.encode([query]).cpu()\n",
    "\n",
    "        # Compute scores\n",
    "        scores = torch.matmul(query_rep, self.doc_reps.T).squeeze(0)\n",
    "\n",
    "        # Top-k\n",
    "        top_indices = torch.topk(scores, k=min(top_k, len(scores))).indices\n",
    "\n",
    "        results = []\n",
    "        for idx in top_indices:\n",
    "            doc_id = self.doc_ids[idx]\n",
    "            score = scores[idx].item()\n",
    "            results.append((doc_id, score))\n",
    "\n",
    "        return results\n",
    "\n",
    "    def generate(\n",
    "        self,\n",
    "        query: str,\n",
    "        context: str,\n",
    "        max_new_tokens: int = 200,\n",
    "    ) -> str:\n",
    "        \"\"\"Generate a response based on context.\"\"\"\n",
    "        system_msg = \"You are a helpful assistant that answers technical questions using the provided context.\"\n",
    "        user_msg = f\"Context:\\n{context}\\n\\nQuestion: {query}\"\n",
    "\n",
    "        messages = [\n",
    "            {\"role\": \"system\", \"content\": system_msg},\n",
    "            {\"role\": \"user\", \"content\": user_msg},\n",
    "        ]\n",
    "        prompt = self.gen_tokenizer.apply_chat_template(\n",
    "            messages, tokenize=False, add_generation_prompt=True\n",
    "        )\n",
    "        inputs = self.gen_tokenizer(prompt, return_tensors=\"pt\").to(device)\n",
    "\n",
    "        with torch.no_grad():\n",
    "            outputs = self.generator.generate(\n",
    "                **inputs,\n",
    "                max_new_tokens=max_new_tokens,\n",
    "                temperature=0.7,\n",
    "                do_sample=True,\n",
    "                pad_token_id=self.gen_tokenizer.eos_token_id,\n",
    "            )\n",
    "\n",
    "        response = self.gen_tokenizer.decode(outputs[0], skip_special_tokens=True)\n",
    "        # Extract only the response\n",
    "        if \"assistant\" in response.lower():\n",
    "            response = response.split(\"assistant\")[-1].strip()\n",
    "\n",
    "        return response\n",
    "\n",
    "    def __call__(self, query: str) -> Dict:\n",
    "        \"\"\"\n",
    "        Complete pipeline: retrieval + generation.\n",
    "\n",
    "        Args:\n",
    "            query: User question\n",
    "\n",
    "        Returns:\n",
    "            Dict with retrieved_docs and generated_answer\n",
    "        \"\"\"\n",
    "        # Implement RAG pipeline\n",
    "\n",
    "        # 1. Retrieve top-k documents\n",
    "        # 2. Build context from documents\n",
    "        # 3. Generate response\n",
    "        retrieved = self.retrieve(query)\n",
    "        doc_texts = self._get_texts([doc_id for doc_id, _ in retrieved])\n",
    "        context = \"\\n\\n\".join([doc_texts[doc_id][:300] for doc_id, _ in retrieved])\n",
    "        answer = self.generate(query, context)\n",
    "        assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "035681b6",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create RAG pipeline\n",
    "# Use document IDs from qrels (relevant documents in the index)\n",
    "doc_id_list = list(relevant_doc_ids)\n",
    "\n",
    "rag = RAGPipeline(\n",
    "    retriever=splade_encoder,\n",
    "    generator=gen_model,\n",
    "    generator_tokenizer=gen_tokenizer,\n",
    "    pt_index=index,\n",
    "    doc_ids=doc_id_list,\n",
    "    top_k=3,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "65ae21b5",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Test the pipeline\n",
    "test_query = \"How do I debug a Python program?\"\n",
    "\n",
    "result = rag(test_query)\n",
    "\n",
    "print(f\"Question: {result['query']}\")\n",
    "print(f\"\\n{'=' * 80}\")\n",
    "print(\"Retrieved documents:\")\n",
    "retrieved_texts = get_text_from_index(\n",
    "    index, [doc_id for doc_id, _ in result[\"retrieved_docs\"]]\n",
    ")\n",
    "for doc_id, score in result[\"retrieved_docs\"]:\n",
    "    print(f\"  [{score:.2f}] {retrieved_texts.get(doc_id, '')[:100]}...\")\n",
    "print(f\"\\n{'=' * 80}\")\n",
    "print(f\"Generated answer:\\n{result['generated_answer']}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cb8d8735",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Part 6: Complete Evaluation\n",
    "\n",
    "Let's compare BM25 and SPLADE on our test dataset.\n",
    "\n",
    "### Complete Evaluation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "38eefc46",
   "metadata": {},
   "outputs": [],
   "source": [
    "def retriever_to_results(\n",
    "    retriever_fn,\n",
    "    queries_df: pd.DataFrame,\n",
    ") -> pd.DataFrame:\n",
    "    \"\"\"\n",
    "    Convert a retriever function to a results DataFrame for ir-measures.\n",
    "\n",
    "    Args:\n",
    "        retriever_fn: Function that takes a query and returns [(doc_id, score)]\n",
    "        queries_df: DataFrame with queries\n",
    "\n",
    "    Returns:\n",
    "        DataFrame with columns [qid, docno, score]\n",
    "    \"\"\"\n",
    "    all_results = []\n",
    "\n",
    "    for _, query_row in tqdm(\n",
    "        queries_df.iterrows(), desc=\"Retrieving\", total=len(queries_df)\n",
    "    ):\n",
    "        qid = query_row[\"qid\"]\n",
    "        query_text = query_row[\"query\"]\n",
    "\n",
    "        results = retriever_fn(query_text)\n",
    "        for doc_id, score in results:\n",
    "            all_results.append({\"qid\": qid, \"docno\": doc_id, \"score\": score})\n",
    "\n",
    "    return pd.DataFrame(all_results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "74fc3a9b",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Evaluate SPLADE\n",
    "test_queries = queries_df.tail(20)  # Use last queries as test\n",
    "\n",
    "\n",
    "\n",
    "def splade_retriever(query: str) -> List[Tuple[str, float]]:\n",
    "    return rag.retrieve(query, top_k=20)\n",
    "\n",
    "\n",
    "splade_results = retriever_to_results(splade_retriever, test_queries)\n",
    "splade_metrics = ir_measures.calc_aggregate(\n",
    "    metrics, qrels_ir, to_ir_measures_run(splade_results)\n",
    ")\n",
    "\n",
    "print(\"\\n=== SPLADE Results ===\")\n",
    "for metric, value in splade_metrics.items():\n",
    "    print(f\"  {metric}: {value:.4f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b4313286",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Compare with BM25\n",
    "bm25_results = bm25.transform(test_queries[[\"qid\", \"query\"]])\n",
    "bm25_metrics = ir_measures.calc_aggregate(\n",
    "    metrics, qrels_ir, to_ir_measures_run(bm25_results)\n",
    ")\n",
    "\n",
    "print(\"\\n=== BM25 Results ===\")\n",
    "for metric, value in bm25_metrics.items():\n",
    "    print(f\"  {metric}: {value:.4f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c23abea4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Comparison table\n",
    "print(\"\\n=== Comparison ===\")\n",
    "print(f\"{'Metric':<12} {'BM25':>10} {'SPLADE':>10} {'Diff':>10}\")\n",
    "print(\"-\" * 44)\n",
    "for metric in splade_metrics:\n",
    "    bm25_val = bm25_metrics[metric]\n",
    "    splade_val = splade_metrics[metric]\n",
    "    diff = splade_val - bm25_val\n",
    "    diff_str = f\"+{diff:.4f}\" if diff > 0 else f\"{diff:.4f}\"\n",
    "    print(f\"{metric!s:<12} {bm25_val:>10.4f} {splade_val:>10.4f} {diff_str:>10}\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
