{ "nbformat": 4, "nbformat_minor": 5, "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": {"name": "ipython", "version": 3}, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "version": "3.10.0" } }, "cells": [ { "cell_type": "markdown", "id": "md-title", "metadata": {}, "source": [ "# RAGBench Knowledge Base Builder — v2\n", "\n", "Builds **FAISS + BM25 + chunk/doc artefacts** for every\n", "`(dataset × embedding_model × chunk_config)` combination and uploads each\n", "to a Hugging Face dataset repo so the Gradio app can download on demand.\n", "\n", "## Design decisions\n", "\n", "| Decision | Choice | Rationale |\n", "|---|---|---|\n", "| Corpus scope (v1) | `test` split only | 12 datasets × models × chunk configs is significant compute; test split is sufficient for comparative evaluation |\n", "| Evaluation setting | **Closed retrieval** | Every test question's relevant document is guaranteed in the index; metrics measure *relative quality* across configs, not open-corpus absolute recall |\n", "| Future expansion | `all_splits` rebuild | Change `corpus_scope` → new `index_id` automatically; old indices untouched |\n", "| Existing indices | Deleted + rebuilt | Prior indices had an incomplete cache key and silent truncation (chunk_size > model max_seq_length) |\n", "\n", "## Key improvements over v1\n", "\n", "1. **Parameterised corpus scope** — `corpus_scope` field drives the loader; upgrading to `all_splits` later needs only one field change.\n", "2. **Pre-build validation** — chunk sizes are checked against every model's effective `max_seq_length` before any encoding starts.\n", "3. **Query / passage prefixes** — BGE and other asymmetric models require different text formats for passages vs queries; both are stored in every combo and in `meta.json`.\n", "4. **Chunking strategy dispatch** — `chunking_strategy` now selects a real implementation (`passthrough`, `recursive`); unknown strategies raise immediately.\n", "5. **Complete cache key** — includes schema version, corpus scope, model revision, prefixes, and strategy; two different indices can never share an `index_id`.\n", "6. **Improved BM25 tokenisation** — regex word splitting separates punctuation from legal terms (e.g. `clause,` → `clause`).\n", "7. **Richer `meta.json`** — stores every field needed to reproduce or audit the index.\n", "\n", "## Colab workflow\n", "\n", "1. Set `HF_TOKEN` in the Colab secrets panel (🔑 left sidebar).\n", "2. Edit `HF_REPO` in **Cell 2**.\n", "3. Run **Cells 1–5** once per session (install + auth + helpers).\n", "4. Run **Cell 6** (validation) — confirms all combos are safe before any compute.\n", "5. Run **Cell 7** to see which combos are done vs pending.\n", "6. Set `COMBO_IDX` in **Cell 8** and run **Cells 8–12** to build and upload one combo.\n", "7. Repeat step 6 in a fresh session for the next pending combo.\n", "\n", "Or run **Cell 13** to build all pending combos automatically in one session." ] }, { "cell_type": "markdown", "id": "md-install", "metadata": {}, "source": [ "## Cell 1 — Install dependencies" ] }, { "cell_type": "code", "execution_count": null, "id": "cd-install", "metadata": {}, "outputs": [], "source": [ "!pip install -q datasets transformers sentence-transformers faiss-cpu rank_bm25 langchain-text-splitters huggingface_hub pyarrow pandas numpy" ] }, { "cell_type": "markdown", "id": "md-config", "metadata": {}, "source": [ "## Cell 2 — Configuration\n", "\n", "### Corpus scope\n", "\n", "RAGBench provides train / validation / test splits of *question–answer–context triples*,\n", "not of a separate document corpus. In a production RAG system all documents are indexed;\n", "queries are evaluated against that one index regardless of which split they came from.\n", "\n", "For this first build (`corpus_scope = \"test\"`) we index only the documents attached to\n", "test-split examples. This creates a **closed retrieval** setting: every test question's\n", "relevant document is guaranteed to be in the index. Retrieval metrics (Hit@k, nDCG@k)\n", "therefore measure *relative quality* across configurations, not open-corpus absolute recall.\n", "This is documented explicitly in every `meta.json` artifact.\n", "\n", "**Upgrade path:** change `corpus_scope` to `\"all_splits\"` in any combo. The updated\n", "`make_cache_key()` will produce a different `index_id`; old test-scope indices stay\n", "untouched in the HF repo and both are listed in `index_config.json`.\n", "\n", "### Combo schema\n", "\n", "| Field | Purpose |\n", "|---|---|\n", "| `corpus_scope` | Which splits to load for the document corpus (`test` / `train` / `all_splits`) |\n", "| `embedding_model` | HuggingFace model ID |\n", "| `model_revision` | Git ref — pins the model checkpoint for reproducibility |\n", "| `query_prefix` | Instruction prepended to queries **at runtime** by the retriever |\n", "| `passage_prefix` | Instruction prepended to passages **during indexing** |\n", "| `chunking_strategy` | `passthrough`, `recursive`, or `parent_child` |\n", "| `chunk_size` | Target chunk size in tokens (0 = not applicable for passthrough) |\n", "| `chunk_overlap` | Overlap between adjacent chunks in tokens |\n", "\n", "### Asymmetric model prefixes\n", "\n", "Some embedding models use asymmetric formatting:\n", "- **BGE v1.5** — short instruction on retrieval queries; no prefix on passages.\n", "- **E5** — `query: ` on queries, `passage: ` on passages.\n", "- **GTE-ModernBERT / MiniLM / MPNet** — symmetric raw-text embedding (empty prefixes).\n", "\n", "The `passage_prefix` is applied during index construction (this notebook).\n", "The `query_prefix` must be applied in the app's `HybridRetriever.dense_search()`\n", "and read from `meta.json` — **both must change together**.\n", "\n", "### Chunking strategies\n", "\n", "- **`passthrough`** — each source passage becomes one chunk. Best for short retrieved\n", " passages (e.g. CovidQA ~100 words) that already fit within any model's limit.\n", "- **`recursive`** — tokenizer-aware `RecursiveCharacterTextSplitter`. `chunk_size` is in\n", " the model's own token space and validated against `model.max_seq_length` before building.\n", "- **`parent_child`** — small retrieval children with a larger parent stored for generation.\n", " Not yet implemented; requires retrieval + generation pipeline changes." ] }, { "cell_type": "code", "execution_count": null, "id": "cd-config", "metadata": {}, "outputs": [], "source": [ "# ── Schema version ─────────────────────────────────────────────────────────────\n", "# Increment when any build-logic change would produce a different index from the\n", "# same combo settings. Forces all affected combos to a new index_id.\n", "SCHEMA_VERSION = 2\n", "\n", "HF_REPO = \"your-username/rag-capstone-indices\" # <── change to your HF repo\n", "\n", "SPLIT_MAP = {\n", " \"test\": [\"test\"],\n", " \"train\": [\"train\"],\n", " \"all_splits\": [\"train\", \"validation\", \"test\"],\n", "}\n", "\n", "ARTIFACT_FILES = [\n", " \"faiss.index\", \"embeddings.npy\", \"bm25.pkl\",\n", " \"chunks.parquet\", \"docs.parquet\", \"meta.json\",\n", "]\n", "\n", "# ── CovidQA combos — biomedical domain ────────────────────────────────────────\n", "# Source passages are already short (~100 words from CORD-19 retrieval).\n", "# Strategy: passthrough — each passage becomes exactly one chunk.\n", "# chunk_size=0 / chunk_overlap=0 are sentinels meaning \"not applicable\".\n", "COVIDQA_COMBOS = [\n", " {\n", " \"dataset\": \"covidqa\", \"domain\": \"biomedical\",\n", " \"display_name\": \"CovidQA (Biomedical)\",\n", " \"corpus_scope\": \"test\",\n", " \"embedding_model\": \"sentence-transformers/all-MiniLM-L6-v2\",\n", " \"embedding_display_name\": \"MiniLM L6 v2\",\n", " \"model_revision\": \"main\",\n", " \"query_prefix\": \"\",\n", " \"passage_prefix\": \"\",\n", " \"chunking_strategy\": \"passthrough\",\n", " \"chunk_size\": 0, \"chunk_overlap\": 0,\n", " },\n", " {\n", " \"dataset\": \"covidqa\", \"domain\": \"biomedical\",\n", " \"display_name\": \"CovidQA (Biomedical)\",\n", " \"corpus_scope\": \"test\",\n", " \"embedding_model\": \"BAAI/bge-base-en-v1.5\",\n", " \"embedding_display_name\": \"BGE base en v1.5\",\n", " \"model_revision\": \"main\",\n", " \"query_prefix\": \"Represent this sentence for searching relevant passages: \",\n", " \"passage_prefix\": \"\",\n", " \"chunking_strategy\": \"passthrough\",\n", " \"chunk_size\": 0, \"chunk_overlap\": 0,\n", " },\n", " {\n", " \"dataset\": \"covidqa\", \"domain\": \"biomedical\",\n", " \"display_name\": \"CovidQA (Biomedical)\",\n", " \"corpus_scope\": \"test\",\n", " \"embedding_model\": \"Alibaba-NLP/gte-modernbert-base\",\n", " \"embedding_display_name\": \"GTE ModernBERT base\",\n", " \"model_revision\": \"main\",\n", " \"query_prefix\": \"\",\n", " \"passage_prefix\": \"\",\n", " \"chunking_strategy\": \"passthrough\",\n", " \"chunk_size\": 0, \"chunk_overlap\": 0,\n", " },\n", " {\n", " \"dataset\": \"covidqa\", \"domain\": \"biomedical\",\n", " \"display_name\": \"CovidQA (Biomedical)\",\n", " \"corpus_scope\": \"test\",\n", " \"embedding_model\": \"sentence-transformers/all-mpnet-base-v2\",\n", " \"embedding_display_name\": \"MPNet base v2\",\n", " \"model_revision\": \"main\",\n", " \"query_prefix\": \"\",\n", " \"passage_prefix\": \"\",\n", " \"chunking_strategy\": \"passthrough\",\n", " \"chunk_size\": 0, \"chunk_overlap\": 0,\n", " },\n", "]\n", "\n", "# ── CUAD combos — legal domain ─────────────────────────────────────────────────\n", "# Full commercial contracts (1–100 pages). Recursive chunking required.\n", "# All chunk sizes stay within each model's max_seq_length (validated in Cell 6).\n", "CUAD_COMBOS = [\n", " # Tier 1: fast baseline — MiniLM (max_seq_length=256)\n", " {\n", " \"dataset\": \"cuad\", \"domain\": \"legal\",\n", " \"display_name\": \"CUAD (Legal Contracts)\",\n", " \"corpus_scope\": \"test\",\n", " \"embedding_model\": \"sentence-transformers/all-MiniLM-L6-v2\",\n", " \"embedding_display_name\": \"MiniLM L6 v2\",\n", " \"model_revision\": \"main\",\n", " \"query_prefix\": \"\",\n", " \"passage_prefix\": \"\",\n", " \"chunking_strategy\": \"recursive\",\n", " \"chunk_size\": 256, \"chunk_overlap\": 32,\n", " },\n", " # Tier 2: cross-domain baseline — MPNet (max_seq_length=384)\n", " {\n", " \"dataset\": \"cuad\", \"domain\": \"legal\",\n", " \"display_name\": \"CUAD (Legal Contracts)\",\n", " \"corpus_scope\": \"test\",\n", " \"embedding_model\": \"sentence-transformers/all-mpnet-base-v2\",\n", " \"embedding_display_name\": \"MPNet base v2\",\n", " \"model_revision\": \"main\",\n", " \"query_prefix\": \"\",\n", " \"passage_prefix\": \"\",\n", " \"chunking_strategy\": \"recursive\",\n", " \"chunk_size\": 384, \"chunk_overlap\": 64,\n", " },\n", " # Tier 3: strong dense retrieval — BGE-large (max_seq_length=512, asymmetric)\n", " {\n", " \"dataset\": \"cuad\", \"domain\": \"legal\",\n", " \"display_name\": \"CUAD (Legal Contracts)\",\n", " \"corpus_scope\": \"test\",\n", " \"embedding_model\": \"BAAI/bge-large-en-v1.5\",\n", " \"embedding_display_name\": \"BGE large en v1.5\",\n", " \"model_revision\": \"main\",\n", " \"query_prefix\": \"Represent this sentence for searching relevant passages: \",\n", " \"passage_prefix\": \"\",\n", " \"chunking_strategy\": \"recursive\",\n", " \"chunk_size\": 512, \"chunk_overlap\": 96,\n", " },\n", " # Tier 4: modern long-context — GTE-ModernBERT (max_seq_length=8192), 512 tokens\n", " {\n", " \"dataset\": \"cuad\", \"domain\": \"legal\",\n", " \"display_name\": \"CUAD (Legal Contracts)\",\n", " \"corpus_scope\": \"test\",\n", " \"embedding_model\": \"Alibaba-NLP/gte-modernbert-base\",\n", " \"embedding_display_name\": \"GTE ModernBERT base\",\n", " \"model_revision\": \"main\",\n", " \"query_prefix\": \"\",\n", " \"passage_prefix\": \"\",\n", " \"chunking_strategy\": \"recursive\",\n", " \"chunk_size\": 512, \"chunk_overlap\": 96,\n", " },\n", " # Tier 4b: long-clause experiment — GTE-ModernBERT, 1024 tokens\n", " {\n", " \"dataset\": \"cuad\", \"domain\": \"legal\",\n", " \"display_name\": \"CUAD (Legal Contracts)\",\n", " \"corpus_scope\": \"test\",\n", " \"embedding_model\": \"Alibaba-NLP/gte-modernbert-base\",\n", " \"embedding_display_name\": \"GTE ModernBERT base (long clause)\",\n", " \"model_revision\": \"main\",\n", " \"query_prefix\": \"\",\n", " \"passage_prefix\": \"\",\n", " \"chunking_strategy\": \"recursive\",\n", " \"chunk_size\": 1024, \"chunk_overlap\": 128,\n", " },\n", "]\n", "\n", "# ── Other RAGBench datasets ────────────────────────────────────────────────────\n", "# Add combos here for the remaining RAGBench datasets.\n", "# First verify the HF config name:\n", "# load_dataset(\"rungalileo/ragbench\", \"\", split=\"test\")\n", "#\n", "# Most RAGBench datasets are short retrieved passages → use passthrough.\n", "# Switch to recursive only if source passages exceed the model's max_seq_length.\n", "#\n", "# Minimum baseline per dataset: MiniLM (floor) + one stronger model.\n", "#\n", "# Example for FiQA:\n", "# {\n", "# \"dataset\": \"fiqa\", \"domain\": \"financial\",\n", "# \"display_name\": \"FiQA (Financial)\",\n", "# \"corpus_scope\": \"test\",\n", "# \"embedding_model\": \"sentence-transformers/all-MiniLM-L6-v2\",\n", "# \"embedding_display_name\": \"MiniLM L6 v2\",\n", "# \"model_revision\": \"main\",\n", "# \"query_prefix\": \"\", \"passage_prefix\": \"\",\n", "# \"chunking_strategy\": \"passthrough\",\n", "# \"chunk_size\": 0, \"chunk_overlap\": 0,\n", "# },\n", "OTHER_COMBOS = [] # <── extend with other RAGBench dataset combos\n", "\n", "COMBOS = COVIDQA_COMBOS + CUAD_COMBOS + OTHER_COMBOS\n", "\n", "print(f\"Repo : {HF_REPO}\")\n", "print(f\"CovidQA : {len(COVIDQA_COMBOS)} combos\")\n", "print(f\"CUAD : {len(CUAD_COMBOS)} combos\")\n", "print(f\"Other : {len(OTHER_COMBOS)} combos\")\n", "print(f\"Total : {len(COMBOS)} combos\")" ] }, { "cell_type": "markdown", "id": "md-auth", "metadata": {}, "source": [ "## Cell 3 — Authenticate with Hugging Face\n", "\n", "Store your token via the 🔑 Colab secrets panel (key name `HF_TOKEN`).\n", "Never paste a token directly in a cell you might share or commit." ] }, { "cell_type": "code", "execution_count": null, "id": "cd-auth", "metadata": {}, "outputs": [], "source": [ "from huggingface_hub import HfApi, login\n", "\n", "try:\n", " from google.colab import userdata\n", " HF_TOKEN = userdata.get(\"HF_TOKEN\")\n", "except Exception:\n", " HF_TOKEN = \"\" # <── paste token here ONLY for quick local tests, never commit\n", "\n", "login(token=HF_TOKEN, add_to_git_credential=False)\n", "api = HfApi()\n", "\n", "api.create_repo(repo_id=HF_REPO, repo_type=\"dataset\", exist_ok=True)\n", "print(f\"Repo ready: https://huggingface.co/datasets/{HF_REPO}\")" ] }, { "cell_type": "markdown", "id": "md-helpers", "metadata": {}, "source": [ "## Cell 4 — Helper functions\n", "\n", "### Cache key design\n", "\n", "`make_cache_key()` hashes **every field that materially changes the index**:\n", "`schema_version`, `dataset`, `corpus_scope`, `embedding_model`, `model_revision`,\n", "`query_prefix`, `passage_prefix`, `chunking_strategy`, `chunk_size`, `chunk_overlap`.\n", "\n", "Any change to any of these fields produces a new `index_id`. This means:\n", "- Fixing a bug → increment `SCHEMA_VERSION` → all combos get new IDs automatically.\n", "- Expanding corpus → change `corpus_scope` → new ID, old index untouched.\n", "- Adding a prefix → new ID, no silent overwrites.\n", "\n", "### Corpus loading\n", "\n", "`load_ragbench()` accepts a `corpus_scope` string and loads the appropriate splits\n", "from `SPLIT_MAP`. Multiple splits are concatenated before deduplication so the\n", "knowledge base contains only unique documents.\n", "\n", "### Chunking dispatch\n", "\n", "`chunk_documents()` is a dispatcher: it reads `combo['chunking_strategy']` and calls\n", "the matching private function. An unknown strategy raises `ValueError` immediately\n", "so no compute is wasted. Currently implemented:\n", "\n", "- `passthrough` — each source document becomes exactly one chunk (no splitting).\n", "- `recursive` — tokenizer-aware `RecursiveCharacterTextSplitter`. Uses the embedding\n", " model's own tokenizer so `chunk_size` is in the same token space as `max_seq_length`.\n", "\n", "### Dense index with passage prefix\n", "\n", "`build_dense_index()` prepends `passage_prefix` to every chunk before encoding.\n", "Embeddings are L2-normalised so inner-product search is equivalent to cosine similarity.\n", "The matching `query_prefix` must be applied in the app's retriever at query time.\n", "\n", "### BM25 tokenisation\n", "\n", "`build_bm25()` uses `re.findall(r\"\\w+\", text.lower())` instead of `str.split()`.\n", "This separates punctuation from tokens — important for legal text where terms like\n", "`clause,` or `§3.1` would otherwise not match their clean forms.\n", "\n", "### Artifact schema (meta.json)\n", "\n", "Every uploaded artefact folder includes a `meta.json` with the full provenance:\n", "schema version, corpus scope, model revision, effective sequence limit, both prefixes,\n", "chunking parameters, normalisation, similarity metric, counts, and build timestamp." ] }, { "cell_type": "code", "execution_count": null, "id": "cd-helpers", "metadata": {}, "outputs": [], "source": [ "import hashlib\n", "import io\n", "import json\n", "import pickle\n", "import re\n", "import shutil\n", "from datetime import datetime, timezone\n", "from pathlib import Path\n", "\n", "import faiss\n", "import numpy as np\n", "import pandas as pd\n", "from datasets import load_dataset\n", "from rank_bm25 import BM25Okapi\n", "from sentence_transformers import SentenceTransformer\n", "from langchain_text_splitters import RecursiveCharacterTextSplitter\n", "\n", "\n", "# ── Cache key ──────────────────────────────────────────────────────────────────\n", "def make_cache_key(combo: dict) -> str:\n", " \"\"\"Deterministic 12-char hash covering every field that defines index content.\"\"\"\n", " parts = [\n", " str(SCHEMA_VERSION),\n", " combo[\"dataset\"],\n", " combo[\"corpus_scope\"],\n", " combo[\"embedding_model\"],\n", " combo.get(\"model_revision\", \"main\"),\n", " combo.get(\"query_prefix\", \"\"),\n", " combo.get(\"passage_prefix\", \"\"),\n", " combo[\"chunking_strategy\"],\n", " str(combo[\"chunk_size\"]),\n", " str(combo[\"chunk_overlap\"]),\n", " ]\n", " raw = \"|\".join(parts)\n", " return hashlib.md5(raw.encode(\"utf-8\")).hexdigest()[:12]\n", "\n", "\n", "# ── RAGBench loader ────────────────────────────────────────────────────────────\n", "def load_ragbench(dataset_name: str, corpus_scope: str) -> pd.DataFrame:\n", " \"\"\"Load RAGBench rows from the splits specified by corpus_scope.\"\"\"\n", " splits = SPLIT_MAP[corpus_scope]\n", " frames = []\n", " for s in splits:\n", " print(f\" Loading rungalileo/ragbench [{dataset_name}] split={s} ...\")\n", " ds = load_dataset(\"rungalileo/ragbench\", dataset_name, split=s)\n", " frames.append(ds.to_pandas())\n", " df = pd.concat(frames, ignore_index=True)\n", " print(f\" {len(df):,} rows, columns: {list(df.columns)}\")\n", " return df\n", "\n", "\n", "# ── Document deduplication ─────────────────────────────────────────────────────\n", "def build_knowledge_base(df: pd.DataFrame) -> pd.DataFrame:\n", " \"\"\"Flatten list-of-contexts columns into one row per unique document.\"\"\"\n", " ctx_col = next(\n", " (c for c in [\"documents\", \"context\", \"contexts\"] if c in df.columns), None\n", " )\n", " if ctx_col is None:\n", " raise ValueError(f\"No context column found. Available: {list(df.columns)}\")\n", " seen, rows = set(), []\n", " for cell in df[ctx_col]:\n", " if isinstance(cell, (list, np.ndarray)):\n", " docs = list(cell)\n", " elif isinstance(cell, str):\n", " docs = [cell]\n", " else:\n", " docs = list(cell) if hasattr(cell, \"__iter__\") else [cell]\n", " for doc in docs:\n", " text = doc.strip() if isinstance(doc, str) else str(doc).strip()\n", " if not text:\n", " continue\n", " h = hashlib.md5(text.encode()).hexdigest()\n", " if h not in seen:\n", " seen.add(h)\n", " rows.append({\"doc_id\": h[:12], \"text\": text})\n", " docs_df = pd.DataFrame(rows)\n", " print(f\" {len(docs_df):,} unique documents\")\n", " return docs_df\n", "\n", "\n", "# ── Chunking strategies ────────────────────────────────────────────────────────\n", "def _chunk_passthrough(docs_df: pd.DataFrame) -> pd.DataFrame:\n", " \"\"\"Keep each source passage as exactly one chunk (no splitting).\"\"\"\n", " rows = [\n", " {\n", " \"chunk_id\": f\"{row['doc_id']}_0\",\n", " \"doc_id\": row[\"doc_id\"],\n", " \"chunk_idx\": i,\n", " \"text\": row[\"text\"],\n", " }\n", " for i, (_, row) in enumerate(docs_df.iterrows())\n", " ]\n", " return pd.DataFrame(rows).reset_index(drop=True)\n", "\n", "\n", "def _chunk_recursive(\n", " docs_df: pd.DataFrame,\n", " model: SentenceTransformer,\n", " chunk_size: int,\n", " chunk_overlap: int,\n", ") -> pd.DataFrame:\n", " \"\"\"Tokenizer-aware recursive splitting. chunk_size is in model token space.\"\"\"\n", " splitter = RecursiveCharacterTextSplitter.from_huggingface_tokenizer(\n", " model.tokenizer,\n", " chunk_size=chunk_size,\n", " chunk_overlap=chunk_overlap,\n", " )\n", " rows = []\n", " for _, row in docs_df.iterrows():\n", " for i, chunk in enumerate(splitter.split_text(row[\"text\"])):\n", " rows.append({\n", " \"chunk_id\": f\"{row['doc_id']}_{i}\",\n", " \"doc_id\": row[\"doc_id\"],\n", " \"chunk_idx\": len(rows),\n", " \"text\": chunk,\n", " })\n", " return pd.DataFrame(rows).reset_index(drop=True)\n", "\n", "\n", "def chunk_documents(\n", " docs_df: pd.DataFrame,\n", " model: SentenceTransformer,\n", " combo: dict,\n", ") -> pd.DataFrame:\n", " \"\"\"Dispatch to the chunking strategy named in combo['chunking_strategy'].\"\"\"\n", " strategy = combo[\"chunking_strategy\"]\n", " if strategy == \"passthrough\":\n", " chunks_df = _chunk_passthrough(docs_df)\n", " elif strategy == \"recursive\":\n", " chunks_df = _chunk_recursive(\n", " docs_df, model, combo[\"chunk_size\"], combo[\"chunk_overlap\"]\n", " )\n", " elif strategy == \"parent_child\":\n", " raise NotImplementedError(\n", " \"parent_child requires retrieval + generation pipeline changes. \"\n", " \"Implement after the dense/BM25 baseline is stable.\"\n", " )\n", " else:\n", " raise ValueError(\n", " f\"Unknown chunking_strategy: {strategy!r}. \"\n", " \"Valid options: passthrough, recursive, parent_child\"\n", " )\n", " print(\n", " f\" {len(chunks_df):,} chunks from {len(docs_df):,} docs \"\n", " f\"(strategy={strategy}, chunk_size={combo['chunk_size']}, \"\n", " f\"overlap={combo['chunk_overlap']})\"\n", " )\n", " return chunks_df\n", "\n", "\n", "# ── Pre-build validation ───────────────────────────────────────────────────────\n", "def validate_combo(combo: dict, model: SentenceTransformer) -> None:\n", " \"\"\"Raise before encoding if chunk_size would cause silent text truncation.\n", "\n", " SentenceTransformer.encode() silently drops tokens beyond max_seq_length.\n", " This guard surfaces the problem before any compute is spent.\n", " \"\"\"\n", " if combo[\"chunking_strategy\"] == \"passthrough\":\n", " return # no fixed chunk size; individual long passages are a data concern\n", " if combo[\"chunk_size\"] > model.max_seq_length:\n", " raise ValueError(\n", " f\"chunk_size={combo['chunk_size']} exceeds \"\n", " f\"{combo['embedding_model']} max_seq_length={model.max_seq_length}. \"\n", " \"Reduce chunk_size or use a model with a larger limit.\"\n", " )\n", "\n", "\n", "# ── Dense index ────────────────────────────────────────────────────────────────\n", "def build_dense_index(\n", " chunks_df: pd.DataFrame,\n", " model: SentenceTransformer,\n", " passage_prefix: str = \"\",\n", "):\n", " \"\"\"Encode chunks with optional passage_prefix; build FAISS inner-product index.\n", "\n", " Embeddings are L2-normalised: inner-product == cosine similarity.\n", " The passage_prefix is required for asymmetric models (e.g. BGE v1.5).\n", " The matching query_prefix must be applied in the app retriever at query time.\n", " \"\"\"\n", " texts = [passage_prefix + t for t in chunks_df[\"text\"].tolist()]\n", " print(f\" Encoding {len(texts):,} chunks ...\")\n", " embeddings = model.encode(\n", " texts,\n", " batch_size=64,\n", " show_progress_bar=True,\n", " convert_to_numpy=True,\n", " normalize_embeddings=True,\n", " ).astype(\"float32\")\n", " index = faiss.IndexFlatIP(embeddings.shape[1])\n", " index.add(embeddings)\n", " print(f\" FAISS index: {index.ntotal:,} vectors, dim={embeddings.shape[1]}\")\n", " return embeddings, index\n", "\n", "\n", "# ── BM25 index ─────────────────────────────────────────────────────────────────\n", "def build_bm25(chunks_df: pd.DataFrame) -> BM25Okapi:\n", " \"\"\"Build BM25 index with regex word tokenisation.\n", "\n", " re.findall(r'\\\\w+') separates punctuation from tokens — important for legal\n", " text where terms like 'clause,' or '§3.1' must match their clean forms.\n", " \"\"\"\n", " tokenized = [re.findall(r\"\\w+\", t.lower()) for t in chunks_df[\"text\"]]\n", " return BM25Okapi(tokenized)\n", "\n", "\n", "# ── Artifact serialisation ─────────────────────────────────────────────────────\n", "def save_artifacts(\n", " out_dir: Path,\n", " chunks_df: pd.DataFrame,\n", " docs_df: pd.DataFrame,\n", " embeddings: np.ndarray,\n", " faiss_index,\n", " bm25: BM25Okapi,\n", " combo: dict,\n", " index_id: str,\n", " model: SentenceTransformer,\n", ") -> dict:\n", " \"\"\"Write all artefacts to out_dir and return the meta dict.\"\"\"\n", " out_dir.mkdir(parents=True, exist_ok=True)\n", " faiss.write_index(faiss_index, str(out_dir / \"faiss.index\"))\n", " np.save(str(out_dir / \"embeddings.npy\"), embeddings)\n", " with open(out_dir / \"bm25.pkl\", \"wb\") as f:\n", " pickle.dump(bm25, f)\n", " chunks_df.to_parquet(out_dir / \"chunks.parquet\", index=False)\n", " docs_df.to_parquet(out_dir / \"docs.parquet\", index=False)\n", "\n", " meta = {\n", " \"schema_version\": SCHEMA_VERSION,\n", " \"index_id\": index_id,\n", " \"dataset_repo\": \"rungalileo/ragbench\",\n", " \"dataset_config\": combo[\"dataset\"],\n", " \"corpus_scope\": combo[\"corpus_scope\"],\n", " \"evaluation_note\": (\n", " \"Closed retrieval: documents from the selected corpus_scope only. \"\n", " \"Metrics measure relative quality across configs, \"\n", " \"not open-corpus absolute recall.\"\n", " ),\n", " \"model_name\": combo[\"embedding_model\"],\n", " \"model_revision\": combo.get(\"model_revision\", \"main\"),\n", " \"effective_max_seq_length\": model.max_seq_length,\n", " \"query_prefix\": combo.get(\"query_prefix\", \"\"),\n", " \"passage_prefix\": combo.get(\"passage_prefix\", \"\"),\n", " \"chunking_strategy\": combo[\"chunking_strategy\"],\n", " \"chunk_size\": combo[\"chunk_size\"],\n", " \"chunk_overlap\": combo[\"chunk_overlap\"],\n", " \"normalization\": \"l2\",\n", " \"similarity\": \"inner_product\",\n", " \"domain\": combo[\"domain\"],\n", " \"n_chunks\": len(chunks_df),\n", " \"n_docs\": len(docs_df),\n", " \"build_date\": datetime.now(timezone.utc).isoformat(),\n", " }\n", " with open(out_dir / \"meta.json\", \"w\") as f:\n", " json.dump(meta, f, indent=2)\n", " print(f\" Saved to {out_dir}/\")\n", " return meta\n", "\n", "\n", "print(\"Helper functions loaded.\")" ] }, { "cell_type": "markdown", "id": "md-index-config", "metadata": {}, "source": [ "## Cell 5 — `index_config.json` helpers\n", "\n", "`index_config.json` is the registry file in the HF dataset repo that the Gradio app\n", "reads to populate its dropdowns. It stores the full tree of\n", "`dataset → embedding_model → chunk_config → index_id` mappings.\n", "\n", "After every successful build the notebook:\n", "1. Downloads the current config from HF.\n", "2. Upserts the new `chunk_config` entry (replacing any existing entry with the same\n", " `chunk_size / chunk_overlap / chunking_strategy / corpus_scope` tuple).\n", "3. Re-uploads the updated config.\n", "\n", "The `register_combo()` function now includes `corpus_scope`, `query_prefix`,\n", "`passage_prefix`, and `build_date` in the registered entry so the app can\n", "read them from the config without loading `meta.json`." ] }, { "cell_type": "code", "execution_count": null, "id": "cd-index-config", "metadata": {}, "outputs": [], "source": [ "import copy\n", "\n", "INDEX_CONFIG_FILENAME = \"index_config.json\"\n", "\n", "_EMPTY_CONFIG = {\n", " \"schema_version\": 1,\n", " \"hub_repo\": HF_REPO,\n", " \"datasets\": {},\n", " \"runtime_options\": {\n", " \"retrieval_strategies\": [\n", " {\"id\": \"dense\", \"display_name\": \"Dense only\"},\n", " {\"id\": \"bm25\", \"display_name\": \"BM25 only\"},\n", " {\"id\": \"hybrid\", \"display_name\": \"Hybrid (Dense + BM25, RRF)\"},\n", " ],\n", " \"query_rewrite_strategies\": [\n", " {\"id\": \"none\", \"display_name\": \"None (raw question)\"},\n", " {\"id\": \"rewrite\", \"display_name\": \"Query rewrite\"},\n", " {\"id\": \"multiquery\", \"display_name\": \"Multi-query expansion\"},\n", " {\"id\": \"hyde\", \"display_name\": \"HyDE (dense)\"},\n", " {\"id\": \"hyde_hybrid\", \"display_name\": \"HyDE + BM25 (hybrid)\"},\n", " ],\n", " \"rerankers\": [\n", " {\"id\": \"off\", \"display_name\": \"Off\"},\n", " {\"id\": \"cross-encoder/ms-marco-MiniLM-L-6-v2\", \"display_name\": \"MiniLM-L-6-v2 cross-encoder\"},\n", " ],\n", " \"llm_models\": [\n", " {\"id\": \"llama-3.1-8b-instant\", \"display_name\": \"Llama 3.1 8B Instant\"},\n", " {\"id\": \"llama-3.3-70b-versatile\", \"display_name\": \"Llama 3.3 70B Versatile\"},\n", " ],\n", " },\n", "}\n", "\n", "\n", "def download_index_config() -> dict:\n", " \"\"\"Download index_config.json from HF repo, or return a fresh empty config.\"\"\"\n", " try:\n", " from huggingface_hub import hf_hub_download\n", " path = hf_hub_download(\n", " repo_id=HF_REPO, repo_type=\"dataset\",\n", " filename=INDEX_CONFIG_FILENAME, token=HF_TOKEN,\n", " )\n", " with open(path) as f:\n", " cfg = json.load(f)\n", " print(\" Downloaded existing index_config.json\")\n", " return cfg\n", " except Exception:\n", " print(\" index_config.json not found — starting fresh.\")\n", " cfg = copy.deepcopy(_EMPTY_CONFIG)\n", " cfg[\"hub_repo\"] = HF_REPO\n", " return cfg\n", "\n", "\n", "def register_combo(cfg: dict, combo: dict, meta: dict) -> dict:\n", " \"\"\"Upsert a chunk_config entry into the in-memory config dict.\"\"\"\n", " cfg = copy.deepcopy(cfg)\n", " cfg[\"hub_repo\"] = HF_REPO\n", "\n", " ds_key = combo[\"dataset\"]\n", " em_key = combo[\"embedding_model\"]\n", " index_id = meta[\"index_id\"]\n", "\n", " ds_entry = cfg.setdefault(\"datasets\", {}).setdefault(ds_key, {\n", " \"display_name\": combo[\"display_name\"],\n", " \"domain\": combo[\"domain\"],\n", " \"embedding_models\": {},\n", " })\n", " ds_entry[\"display_name\"] = combo[\"display_name\"]\n", " ds_entry[\"domain\"] = combo[\"domain\"]\n", "\n", " em_entry = ds_entry.setdefault(\"embedding_models\", {}).setdefault(em_key, {\n", " \"display_name\": combo[\"embedding_display_name\"],\n", " \"chunk_configs\": [],\n", " })\n", " em_entry[\"display_name\"] = combo[\"embedding_display_name\"]\n", "\n", " new_entry = {\n", " \"chunk_size\": combo[\"chunk_size\"],\n", " \"chunk_overlap\": combo[\"chunk_overlap\"],\n", " \"chunking_strategy\": combo[\"chunking_strategy\"],\n", " \"corpus_scope\": combo[\"corpus_scope\"],\n", " \"query_prefix\": combo.get(\"query_prefix\", \"\"),\n", " \"passage_prefix\": combo.get(\"passage_prefix\", \"\"),\n", " \"index_id\": index_id,\n", " \"subfolder\": index_id,\n", " \"files\": ARTIFACT_FILES,\n", " \"n_chunks\": meta[\"n_chunks\"],\n", " \"n_docs\": meta[\"n_docs\"],\n", " \"build_date\": meta[\"build_date\"],\n", " }\n", "\n", " # Replace any existing entry with the same (size, overlap, strategy, scope).\n", " cfgs = em_entry[\"chunk_configs\"]\n", " cfgs[:] = [\n", " c for c in cfgs\n", " if not (\n", " c[\"chunk_size\"] == combo[\"chunk_size\"]\n", " and c[\"chunk_overlap\"] == combo[\"chunk_overlap\"]\n", " and c[\"chunking_strategy\"] == combo[\"chunking_strategy\"]\n", " and c.get(\"corpus_scope\", \"train\") == combo[\"corpus_scope\"]\n", " )\n", " ]\n", " cfgs.append(new_entry)\n", " return cfg\n", "\n", "\n", "def upload_index_config(cfg: dict) -> None:\n", " buf = json.dumps(cfg, indent=2).encode(\"utf-8\")\n", " api.upload_file(\n", " path_or_fileobj=io.BytesIO(buf),\n", " path_in_repo=INDEX_CONFIG_FILENAME,\n", " repo_id=HF_REPO,\n", " repo_type=\"dataset\",\n", " token=HF_TOKEN,\n", " commit_message=\"chore: update index_config.json\",\n", " )\n", " print(f\" Uploaded {INDEX_CONFIG_FILENAME} to {HF_REPO}\")\n", "\n", "\n", "print(\"index_config.json helpers loaded.\")" ] }, { "cell_type": "markdown", "id": "md-validate", "metadata": {}, "source": [ "## Cell 6 — Validation: check all combos before any compute\n", "\n", "### Why validate first?\n", "\n", "`SentenceTransformer.encode()` silently truncates tokens beyond `model.max_seq_length`.\n", "For `all-MiniLM-L6-v2` (limit = 256) with `chunk_size = 512`, the index builds without\n", "error but encodes only the first 256 tokens of every chunk — the rest is silently dropped.\n", "The resulting metrics look fine but the comparison across models is meaningless.\n", "\n", "There are three separate limits in every HuggingFace embedding model:\n", "\n", "| Property | Description |\n", "|---|---|\n", "| `config.max_position_embeddings` | Architectural capacity of the transformer |\n", "| `tokenizer.model_max_length` | Tokenizer-level limit (may be 512 even for 256-limit models) |\n", "| `model.max_seq_length` | **Operative limit** — what `SentenceTransformer.encode()` actually uses |\n", "\n", "This cell uses known `max_seq_length` values to validate all combos without loading any model.\n", "The runtime `validate_combo()` call (Cell 9) performs the definitive check against the\n", "actually-loaded model.\n", "\n", "**Run this cell before running any build. Fix any `EXCEEDS LIMIT` rows in the COMBOS config.**" ] }, { "cell_type": "code", "execution_count": null, "id": "cd-validate", "metadata": {}, "outputs": [], "source": [ "# Known effective max_seq_length values (SentenceTransformer.max_seq_length).\n", "# These are the operative limits for encode() — NOT tokenizer.model_max_length.\n", "KNOWN_MAX_SEQ_LENGTHS = {\n", " \"sentence-transformers/all-MiniLM-L6-v2\": 256,\n", " \"sentence-transformers/all-mpnet-base-v2\": 384,\n", " \"BAAI/bge-base-en-v1.5\": 512,\n", " \"BAAI/bge-large-en-v1.5\": 512,\n", " \"thenlper/gte-large\": 512,\n", " \"Alibaba-NLP/gte-modernbert-base\": 8192,\n", "}\n", "\n", "print(f\"{'IDX':>3} {'STATUS':<18} {'MODEL':<38} {'LIMIT':>6} {'CHUNK':>6}\")\n", "print(\"-\" * 82)\n", "issues = []\n", "for i, c in enumerate(COMBOS):\n", " strategy = c[\"chunking_strategy\"]\n", " chunk_size = c[\"chunk_size\"]\n", " model_id = c[\"embedding_model\"]\n", " limit = KNOWN_MAX_SEQ_LENGTHS.get(model_id, \"?\")\n", "\n", " if strategy == \"passthrough\":\n", " status = \"OK (passthrough)\"\n", " elif limit == \"?\":\n", " status = \"? limit unknown\"\n", " elif chunk_size > limit:\n", " status = \"EXCEEDS LIMIT\"\n", " issues.append(i)\n", " else:\n", " status = \"valid\"\n", "\n", " short = model_id.split(\"/\")[-1]\n", " print(f\"{i:>3} {status:<18} {short:<38} {str(limit):>6} {chunk_size:>6}\")\n", "\n", "print()\n", "if issues:\n", " print(f\"FAIL: {len(issues)} combo(s) have invalid chunk sizes: indices {issues}\")\n", " print(\"Fix chunk_size in COMBOS (Cell 2) before running any build.\")\n", "else:\n", " print(\"All combos valid. Safe to build.\")" ] }, { "cell_type": "markdown", "id": "md-status", "metadata": {}, "source": [ "## Cell 7 — Status: which combos are done / pending\n", "\n", "Queries the HF repo for already-uploaded subfolders and matches them against\n", "the current COMBOS list. Run this at the start of every session to choose\n", "which `COMBO_IDX` to build next." ] }, { "cell_type": "code", "execution_count": null, "id": "cd-status", "metadata": {}, "outputs": [], "source": [ "from huggingface_hub import list_repo_files\n", "\n", "\n", "def _uploaded_index_ids() -> set:\n", " \"\"\"Return subfolder names already present in the HF dataset repo.\"\"\"\n", " try:\n", " files = list(list_repo_files(repo_id=HF_REPO, repo_type=\"dataset\", token=HF_TOKEN))\n", " return {f.split(\"/\")[0] for f in files if \"/\" in f}\n", " except Exception:\n", " return set()\n", "\n", "\n", "done_ids = _uploaded_index_ids()\n", "\n", "print(f\"{'IDX':>3} {'STATUS':<10} {'INDEX_ID':<14} COMBO\")\n", "print(\"-\" * 80)\n", "for i, c in enumerate(COMBOS):\n", " idx_id = make_cache_key(c)\n", " status = \"done\" if idx_id in done_ids else \"pending\"\n", " short = c[\"embedding_model\"].split(\"/\")[-1]\n", " label = (\n", " f\"{c['dataset']} / {short} / \"\n", " f\"{c['chunking_strategy']}:{c['chunk_size']}-{c['chunk_overlap']} / \"\n", " f\"scope={c['corpus_scope']}\"\n", " )\n", " print(f\"{i:>3} {status:<10} {idx_id:<14} {label}\")\n", "\n", "n_done = sum(1 for c in COMBOS if make_cache_key(c) in done_ids)\n", "n_pending = len(COMBOS) - n_done\n", "print(f\"\\n{n_done} done / {n_pending} pending / {len(COMBOS)} total\")" ] }, { "cell_type": "markdown", "id": "md-pick", "metadata": {}, "source": [ "## Cell 8 — Pick the combo to build\n", "\n", "Set `COMBO_IDX` to the row number shown in Cell 7 that you want to build,\n", "then run **Cells 8–12** in sequence." ] }, { "cell_type": "code", "execution_count": null, "id": "cd-pick", "metadata": {}, "outputs": [], "source": [ "COMBO_IDX = 0 # <── CHANGE THIS\n", "\n", "combo = COMBOS[COMBO_IDX]\n", "INDEX_ID = make_cache_key(combo)\n", "\n", "print(f\"Selected combo {COMBO_IDX}:\")\n", "print(f\" dataset : {combo['dataset']} ({combo['domain']})\")\n", "print(f\" corpus_scope : {combo['corpus_scope']}\")\n", "print(f\" embedding_model : {combo['embedding_model']}\")\n", "print(f\" model_revision : {combo.get('model_revision', 'main')}\")\n", "print(f\" query_prefix : {combo.get('query_prefix', '')!r}\")\n", "print(f\" passage_prefix : {combo.get('passage_prefix', '')!r}\")\n", "print(f\" chunking_strategy : {combo['chunking_strategy']}\")\n", "print(f\" chunk_size : {combo['chunk_size']}\")\n", "print(f\" chunk_overlap : {combo['chunk_overlap']}\")\n", "print(f\" index_id (key) : {INDEX_ID}\")\n", "\n", "if INDEX_ID in done_ids:\n", " print(\"\\nWARNING: This combo is already uploaded.\")\n", " print(\"Continue to re-build and overwrite, or change COMBO_IDX.\")" ] }, { "cell_type": "markdown", "id": "md-build-kb", "metadata": {}, "source": [ "## Cell 9 — Load dataset, build knowledge base, chunk\n", "\n", "Steps:\n", "1. Load RAGBench rows from the splits defined by `corpus_scope`.\n", "2. Flatten the per-row context lists into a deduplicated document table.\n", "3. Load the embedding model (needed for the tokenizer in recursive chunking).\n", "4. Run the pre-build validation guard — raises immediately if `chunk_size` exceeds\n", " the model's effective sequence limit.\n", "5. Chunk documents using the strategy declared in the combo." ] }, { "cell_type": "code", "execution_count": null, "id": "cd-build-kb", "metadata": {}, "outputs": [], "source": [ "print(f\"Loading {combo['dataset']} [{combo['corpus_scope']}] ...\")\n", "full_df = load_ragbench(combo[\"dataset\"], combo[\"corpus_scope\"])\n", "\n", "print(\"\\nDeduplicating documents ...\")\n", "docs_df = build_knowledge_base(full_df)\n", "\n", "print(f\"\\nLoading embedding model: {combo['embedding_model']} ...\")\n", "embed_model = SentenceTransformer(\n", " combo[\"embedding_model\"],\n", " revision=combo.get(\"model_revision\", \"main\"),\n", ")\n", "print(f\" max_seq_length : {embed_model.max_seq_length}\")\n", "print(f\" embedding_dim : {embed_model.get_sentence_embedding_dimension()}\")\n", "\n", "print(\"\\nValidating combo against model limits ...\")\n", "validate_combo(combo, embed_model)\n", "print(\" Validation passed\")\n", "\n", "print(\"\\nChunking documents ...\")\n", "chunks_df = chunk_documents(docs_df, embed_model, combo)" ] }, { "cell_type": "markdown", "id": "md-build-idx", "metadata": {}, "source": [ "## Cell 10 — Build dense and BM25 indices\n", "\n", "**Dense index:** each chunk is encoded with the embedding model. If the combo\n", "specifies a `passage_prefix`, it is prepended to every chunk before encoding.\n", "Vectors are L2-normalised so FAISS inner-product search is equivalent to cosine\n", "similarity. `IndexFlatIP` performs exact search — no approximation.\n", "\n", "**BM25 index:** built with improved regex tokenisation. BM25 has no incremental\n", "update API; if the corpus scope is expanded later the BM25 index must be rebuilt\n", "from scratch (which is why the full pipeline is re-run for each combo)." ] }, { "cell_type": "code", "execution_count": null, "id": "cd-build-idx", "metadata": {}, "outputs": [], "source": [ "print(\"Building dense index ...\")\n", "embeddings, faiss_index = build_dense_index(\n", " chunks_df,\n", " embed_model,\n", " passage_prefix=combo.get(\"passage_prefix\", \"\"),\n", ")\n", "\n", "print(\"\\nBuilding BM25 index ...\")\n", "bm25 = build_bm25(chunks_df)\n", "print(f\" BM25 done ({len(chunks_df):,} tokenized chunks)\")" ] }, { "cell_type": "markdown", "id": "md-save", "metadata": {}, "source": [ "## Cell 11 — Save artifacts locally and upload to HF Hub\n", "\n", "Artifacts saved per combo:\n", "\n", "| File | Contents |\n", "|---|---|\n", "| `faiss.index` | FAISS `IndexFlatIP` — serialised binary |\n", "| `embeddings.npy` | Float32 numpy array of L2-normalised vectors |\n", "| `bm25.pkl` | Pickled `BM25Okapi` object |\n", "| `chunks.parquet` | Chunk table: `chunk_id`, `doc_id`, `chunk_idx`, `text` |\n", "| `docs.parquet` | Document table: `doc_id`, `text` |\n", "| `meta.json` | Full provenance record (see Cell 4 for schema) |\n", "\n", "All six files are uploaded to `{HF_REPO}/{index_id}/` in one `upload_folder` call." ] }, { "cell_type": "code", "execution_count": null, "id": "cd-save", "metadata": {}, "outputs": [], "source": [ "OUT_DIR = Path(f\"/tmp/rag_indices/{INDEX_ID}\")\n", "\n", "print(f\"Saving artifacts to {OUT_DIR} ...\")\n", "meta = save_artifacts(\n", " OUT_DIR, chunks_df, docs_df,\n", " embeddings, faiss_index, bm25,\n", " combo, INDEX_ID, embed_model,\n", ")\n", "\n", "print(f\"\\nUploading {OUT_DIR} → {HF_REPO}/{INDEX_ID} ...\")\n", "api.upload_folder(\n", " folder_path=str(OUT_DIR),\n", " path_in_repo=INDEX_ID,\n", " repo_id=HF_REPO,\n", " repo_type=\"dataset\",\n", " token=HF_TOKEN,\n", " commit_message=(\n", " f\"add {INDEX_ID} \"\n", " f\"({combo['dataset']} / {combo['embedding_model']} / \"\n", " f\"{combo['chunking_strategy']}:{combo['chunk_size']}-{combo['chunk_overlap']} / \"\n", " f\"scope={combo['corpus_scope']})\"\n", " ),\n", ")\n", "print(\" Upload complete.\")" ] }, { "cell_type": "markdown", "id": "md-update-config", "metadata": {}, "source": [ "## Cell 12 — Update `index_config.json`\n", "\n", "Downloads the current registry, upserts the new combo entry, and re-uploads.\n", "The Gradio app reads this file to build its dataset / model / chunk dropdowns." ] }, { "cell_type": "code", "execution_count": null, "id": "cd-update-config", "metadata": {}, "outputs": [], "source": [ "print(\"Updating index_config.json ...\")\n", "current_cfg = download_index_config()\n", "updated_cfg = register_combo(current_cfg, combo, meta)\n", "upload_index_config(updated_cfg)\n", "\n", "# Refresh done_ids so Cell 7 is accurate if re-run in the same session.\n", "done_ids = _uploaded_index_ids()\n", "\n", "print(\"\\n── Registered chunk_config entry ──\")\n", "ds_cfg = updated_cfg[\"datasets\"].get(combo[\"dataset\"], {})\n", "em_cfg = ds_cfg.get(\"embedding_models\", {}).get(combo[\"embedding_model\"], {})\n", "for cc in em_cfg.get(\"chunk_configs\", []):\n", " if cc[\"index_id\"] == INDEX_ID:\n", " print(json.dumps(cc, indent=2))\n", " break\n", "\n", "print(f\"\\nCombo {COMBO_IDX} complete. Run Cell 7 to see remaining combos.\")" ] }, { "cell_type": "markdown", "id": "md-batch", "metadata": {}, "source": [ "## Cell 13 — Batch: build all pending combos automatically\n", "\n", "Alternative to running Cells 8–12 one combo at a time. Discovers every pending\n", "combo from the HF repo, then builds and uploads them in sequence.\n", "\n", "**Optimisation:** combos are sorted by `(dataset, corpus_scope, embedding_model)` so\n", "each dataset is loaded once and each model is loaded once across all its chunk-size\n", "variants. This avoids redundant downloads on free-tier Colab.\n", "\n", "Set `DRY_RUN = True` to preview what would be built without running any compute.\n", "\n", "Each combo's result is uploaded immediately on completion so progress is never lost\n", "if the session is interrupted." ] }, { "cell_type": "code", "execution_count": null, "id": "cd-batch", "metadata": {}, "outputs": [], "source": [ "import gc\n", "from itertools import groupby\n", "\n", "DRY_RUN = False # set True to preview without building\n", "\n", "# ── Gather pending combos ──────────────────────────────────────────────────────\n", "done_ids = _uploaded_index_ids()\n", "pending = [\n", " (i, make_cache_key(c), c)\n", " for i, c in enumerate(COMBOS)\n", " if make_cache_key(c) not in done_ids\n", "]\n", "\n", "print(f\"{len(pending)} pending / {len(COMBOS)} total\")\n", "for i, idx_id, c in pending:\n", " short = c[\"embedding_model\"].split(\"/\")[-1]\n", " print(\n", " f\" [{i}] {idx_id} {c['dataset']} / {short} / \"\n", " f\"{c['chunking_strategy']}:{c['chunk_size']}-{c['chunk_overlap']} / \"\n", " f\"scope={c['corpus_scope']}\"\n", " )\n", "\n", "if DRY_RUN:\n", " print(\"\\nDRY_RUN=True — nothing built.\")\n", "else:\n", " # Sort so dataset+scope and model are each loaded once.\n", " keyfn = lambda t: (t[2][\"dataset\"], t[2][\"corpus_scope\"], t[2][\"embedding_model\"])\n", " pending_sorted = sorted(pending, key=keyfn)\n", "\n", " _ds_cache = {} # \"dataset::scope\" -> docs_df\n", " _model_key = None\n", " _model = None\n", "\n", " for (ds_name, scope, em_name), group in groupby(pending_sorted, key=keyfn):\n", " group = list(group)\n", " ds_scope_key = f\"{ds_name}::{scope}\"\n", "\n", " if ds_scope_key not in _ds_cache:\n", " print(f\"\\n── Loading dataset: {ds_name} [{scope}] ──\")\n", " raw_df = load_ragbench(ds_name, scope)\n", " _ds_cache[ds_scope_key] = build_knowledge_base(raw_df)\n", "\n", " if _model_key != em_name:\n", " print(f\"\\n── Loading model: {em_name} ──\")\n", " _model = SentenceTransformer(em_name)\n", " _model_key = em_name\n", "\n", " docs_df = _ds_cache[ds_scope_key]\n", " embed_model = _model\n", "\n", " for combo_idx, index_id, combo in group:\n", " print(f\"\\n{'='*60}\")\n", " print(f\"Building [{combo_idx}] {index_id}\")\n", " print(f\" {combo['chunking_strategy']}:{combo['chunk_size']}-{combo['chunk_overlap']}\")\n", " print(f\"{'='*60}\")\n", " try:\n", " validate_combo(combo, embed_model)\n", " chunks_df = chunk_documents(docs_df, embed_model, combo)\n", " embeddings, faiss_index = build_dense_index(\n", " chunks_df, embed_model,\n", " passage_prefix=combo.get(\"passage_prefix\", \"\"),\n", " )\n", " bm25 = build_bm25(chunks_df)\n", " out_dir = Path(f\"/tmp/rag_indices/{index_id}\")\n", " meta = save_artifacts(\n", " out_dir, chunks_df, docs_df,\n", " embeddings, faiss_index, bm25,\n", " combo, index_id, embed_model,\n", " )\n", " api.upload_folder(\n", " folder_path=str(out_dir),\n", " path_in_repo=index_id,\n", " repo_id=HF_REPO,\n", " repo_type=\"dataset\",\n", " token=HF_TOKEN,\n", " commit_message=(\n", " f\"add {index_id} \"\n", " f\"({combo['dataset']}/{combo['embedding_model']}/\"\n", " f\"{combo['chunking_strategy']}:{combo['chunk_size']}-{combo['chunk_overlap']})\"\n", " ),\n", " )\n", " current_cfg = download_index_config()\n", " updated_cfg = register_combo(current_cfg, combo, meta)\n", " upload_index_config(updated_cfg)\n", " done_ids = _uploaded_index_ids()\n", " del embeddings, faiss_index, bm25, chunks_df\n", " shutil.rmtree(out_dir, ignore_errors=True)\n", " gc.collect()\n", " print(f\"[{combo_idx}] done\")\n", " except Exception as exc:\n", " print(f\"[{combo_idx}] FAILED: {exc}\")\n", " print(\" Skipping to next combo ...\")\n", "\n", " print(\"\\nAll pending combos processed.\")" ] }, { "cell_type": "markdown", "id": "md-final", "metadata": {}, "source": [ "## Cell 14 — Final status\n", "\n", "Re-fetches the uploaded subfolder list from HF and shows the full progress table.\n", "Run after each session to confirm what has been uploaded." ] }, { "cell_type": "code", "execution_count": null, "id": "cd-final", "metadata": {}, "outputs": [], "source": [ "done_ids = _uploaded_index_ids()\n", "n_done = sum(1 for c in COMBOS if make_cache_key(c) in done_ids)\n", "\n", "print(f\"Progress: {n_done}/{len(COMBOS)} combos uploaded\\n\")\n", "print(f\"{'IDX':>3} {'STATUS':<10} {'INDEX_ID':<14} COMBO\")\n", "print(\"-\" * 80)\n", "for i, c in enumerate(COMBOS):\n", " idx_id = make_cache_key(c)\n", " status = \"done\" if idx_id in done_ids else \"pending\"\n", " short = c[\"embedding_model\"].split(\"/\")[-1]\n", " label = (\n", " f\"{c['dataset']} / {short} / \"\n", " f\"{c['chunking_strategy']}:{c['chunk_size']}-{c['chunk_overlap']} / \"\n", " f\"scope={c['corpus_scope']}\"\n", " )\n", " print(f\"{i:>3} {status:<10} {idx_id:<14} {label}\")" ] } ] }