{ "cells": [ { "cell_type": "markdown", "id": "844fe3af-9cf1-4c66-aa78-b88a3429acc6", "metadata": {}, "source": [ "### 0. Setup\n", "- Clone https://github.com/plaggy/rag-gradio-sample-project and set up an environment with gradio_app/requirements.txt.\n", "\n", "A convenient way to work through the project is to test locally and keep committing the changes to the [HF Spaces](https://huggingface.co/spaces) repo. A space gets automatically rebuilt after each commit and you get a new version of your application up and running.\n", "\n", "- Create a new space with Gradio SDK. You'll get an almost empty repo, the only thing you'll need from it is README.md which has a config letting a space builder know that it's a Gradio app. Reset a remote upstream of your local rag-gradio-sample-project clone to be your freshly created Spaces repository.\n", "\n", "The easiest way to set your space up is to set up the gradio_app folder as a git repo, set remote origin to your space repo and checkout the remote README:\n", "\n", "```\n", "cd gradio_app\n", "git init\n", "git remote add origin \n", "git fetch\n", "git checkout origin/main README.md\n", "```\n", "\n", "The space is not working yet. You'll get the first working version after the Step 3.\n", "\n", "- Clone https://github.com/huggingface/transformers to a local machine and run prep_scripts/markdown_to_text.py script to extract raw text from transformers/docs/source/en/. This will be your knowledge base, you don't need it to be a part of your repository\n", "\n", "Run the command as follows (pass arguments that work for you)\n", "```\n", "python prep_scripts/markdown_to_text.py --input-dir transformers/docs/source/en/ --output-dir docs\n", "```\n" ] }, { "cell_type": "markdown", "id": "762e9fde-c1f4-464c-b12b-dca602fac5ba", "metadata": {}, "source": [ "**By design, you'll be running your experiments in a [Gradio space](https://huggingface.co/docs/hub/en/spaces-sdks-gradio). Apart from deliverables for each step you'll need to provide a link to a functioning RAG space in it final state!**" ] }, { "cell_type": "code", "execution_count": 1, "id": "6c813d03-33a7-4ce1-836f-11afc541f291", "metadata": {}, "outputs": [], "source": [ "# Add the link to the space you've just created here:" ] }, { "cell_type": "markdown", "id": "c970d0a4-fee8-48ac-9377-4a6def7712b2", "metadata": {}, "source": [ "### Step 1: Chunk Your Data\n", "\n", "To efficiently pull up documents relevant to a query from a knowledge base documents are embedded and stored as vectors. Documents in your knowledge base are not expected to fit into the context length of an embedding model (most have 512 token limit). Hence chunking your documents into smaller pieces is required. Take a deeper dive into why chunking is imoprtant and what are the options [here](https://www.pinecone.io/learn/chunking-strategies/).\n", "\n", "Your task is to implement and compare two chunking strategies: fixed-sized chunking and content-aware chunking. For content-aware you could split by sentences, paragraphs or in some other way that makes sence.\n", "\n", "The deliverables are:\n", "- The code for chunk splitting" ] }, { "cell_type": "code", "execution_count": 1, "id": "f7bad8c8", "metadata": {}, "outputs": [], "source": [ "# Chunk splitting deliverables" ] }, { "cell_type": "markdown", "id": "5e5ebaad-8d42-430c-b00b-18198cdb9ce8", "metadata": {}, "source": [ "### Step 2: Ingest chunks into a database and create an index\n", "\n", "Chunks need to be vectorized and made accessible to an LLM to enable semantic search with embedding models. A current industry standard is to use a vector database to store and retrieve texts both conveniently and efficiently. There are many products out there, we'll be using [LanceDB](https://lancedb.github.io/lancedb/). LanceDB is a young product, one way it stands out is that it's embedded - it's designed not to be a standalone service but rather a part of an application, more on this [here](https://lancedb.github.io/lancedb/basic/).\n", "\n", "Find more details on how different databases compare in [this](https://thedataquarry.com/tags/vector-db/) series of posts. \n", "\n", "Your task is to vectorize and ingest chunked documents into the database. \n", "**For each chunking strategy from the previous step create a separate table with one of the embedding models. Compare the chunking strategies and choose one. Perform vectorization+ingestion with the second model only with one chunking strategy of your choice**.\n", "Use prep_scrips/lancedb_setup.py to vectorize chunks and store vector representations along with raw text in a Lancedb instance. The script also creates an index for fast ANN retrieval (not really needed for this exercise but necessary at scale). Try different embedding models and see how results differ. The options are:\n", "\n", "- `sentence-transformers/all-MiniLM-L6-v2`: a light model, produces vectors of length 384\n", "- `BAAI/bge-large-en-v1.5`: a much heavier model, embedding vector length is 1024\n", "\n", "Feel free to explore other embedding models and justify your choice.\n", "For different embedding models and different chunking strategies create different tables in the database so you can easily switch between them and compare.\n", "\n", "Run the embedding+ingestion script as follows, make sure to look into the script and go over the arguments. Note that the number of sub-vectors for indexing must be a divisor of the model embedding size.\n", "\n", "```\n", "python prep_scripts/lancedb_setup.py --emb-model --table --input-dir --num-sub-vectors \n", "```\n", "\n", "Before committing to your space set up environment variables on the settings tab of your space, use `.env` as a ference list of all the things you can customize. Make sure to add HF_TOKEN and OPENAI_API_KEY as secrets.\n", "Not all the parameters are required to set via environment variables, most have default values.\n", "\n", "*The database is expected to be in the `gradio_app` folder under `.lancedb`, make sure to move it there if was initialized elsewhere.* It can be parametrized but it's unnecessary here.\n", "\n", "To commit large files to Github use `git lfs`:\n", "```\n", "git lfs install\n", "git lfs track \"*.lance\"\n", "git lfs track \"*.idx\"\n", "git add .gitattributes\n", "```\n", "Then proceed as usual.\n", "\n", "For experimenting you can easily switch between embedding models/tables by changing the values of the corresponding env variables in your space (`EMB_MODEL`, `TABLE_NAME`). Overall, every time you change the value of an environment variable a space gets automatically rebuilt.\n", "\n", "The deliverables are:\n", "1. The illustration of how retrieved documents differ depending on the embedding model and the chunking strategy. You should create at least 3 tables: model_1 + chunking_strategy_1, model_1 + chunking_strategy_2, model_2 + chunking_strategy_<1 or 2>\n", "2. The analysis of pros and cons of chunking strategies\n", "3. The analysis of how retrieved document differ between embedding models (is one better than the other?)\n", "4. The analysis of how the embedding time differs between models" ] }, { "cell_type": "code", "execution_count": null, "id": "f7db282e-e03c-41de-9c03-54abf455481f", "metadata": {}, "outputs": [], "source": [ "# Embed documents with different chunking strategies and ingest into the database " ] }, { "cell_type": "markdown", "id": "7d818b4f-ba5a-4c81-b6d7-f3474c398d9c", "metadata": {}, "source": [ "### Step 3: Add a reranker\n", "\n", "A reranker is a second-level model which produces similarity scores for pairs of (input query + retrieved document). Cross-encoders are conventionally used for reranking, their architecture is slightly different from retrieval models (more on it [here](https://www.pinecone.io/learn/series/rag/rerankers/) and [here](https://www.sbert.net/examples/applications/retrieve_rerank/README.html)). Cross-encoders are much more costly to run, therefore a retrieval model is used to get a few (dozens) highest-scoring items, and a reranker picks the best among these. The overall pipeline is similar to the recommender system indudustry standard: a light model retrieves top-n, a precise and heavy model reranks n to get top k, n is orders of magnitude larger than k.\n", "\n", "Cross-encoders are optional because of the overhead their usage implies. Your task is to implement a reranker using a cross-encoder and assess pros and cons of having it. Do not forget that the process of pulling the most relevant documents becomes two-staged: retrieve a larger number of items first, than rerank and keep the best top-k for context.\n", "\n", "The models fit for the task:\n", "1. BAAI/bge-reranker-large\n", "2. cross-encoder/ms-marco-MiniLM-L-6-v2\n", "\n", "As usual, feel free to pick another model and provide some description to it.\n", "\n", "The deliverables are:\n", "\n", "1. The code that enables a reranker.\n", "3. A comparison of how the prompt and the model output change after adding a reranker\n", "4. The analysis of pros and cons. The evaluation aspects should include the relevance of the top-k documents, the response time.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "ee1b0160-0ba0-4b5f-81c4-ef3ea76850e5", "metadata": {}, "outputs": [], "source": [ "# Implement code for selecting the final documents using a cross-encoder and compare with and without" ] }, { "cell_type": "markdown", "id": "f5816c54-a290-4cb0-b7db-3b8901998cb0", "metadata": {}, "source": [ "### Step 4: Try a different LLM\n", "\n", "The suggested `Mistral-7b-instruct` is a great but small model for an LLM. A larger model can be applied to a wider range of problems and do more complex reasoning. Within the scope of this project a larger model may not be beneficial but for more complex cases the difference would become apparent. Another dimension to explore is a base model which was not instruction fine-tuned - it won't respond to your queries the way you'd expect. It may be a great exercise to see the value of fine-tuning.\n", "\n", "The task here is to try out an alternative LLM to explore the differencies.\n", "\n", "The options are:\n", "1. mistralai/Mistral-7B-v0.1\n", "2. mistralai/Mixtral-8x7B-Instruct-v0.1\n", "\n", "Of couse, feel free to choose another one and give some details on how different it is from the initial model.\n", "\n", "The deliverables are:\n", "\n", "1. The comparison between outputs of the Mistral-7b-instuct and a different model of your choice.\n", "2. The difference in response times if a larger model was chosen. Make sure to make multiple queries to make the comparison meaningful.\n", "3. Analyse the differencies between outputs and share the conclusions.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "942f39d4-eb27-4f2d-ae47-a5d65f102faa", "metadata": {}, "outputs": [], "source": [ "# Analysis of the difference between LLMs" ] }, { "cell_type": "markdown", "id": "70c16440", "metadata": {}, "source": [ "### Step 5 (Bonus): Use an LLM to quantitatively compare outputs of different variants of the system (LLM as a Judge)\n", "\n", "Use a powerful LLM (e.g. GPT-4) to quantitatively evaluate outputs of two alternative setups (different embedding models, different LLMs, both etc.). For inspiration and for prompts refer to [1](https://arxiv.org/pdf/2306.05685.pdf), [2](https://arxiv.org/pdf/2401.10020.pdf), [3](https://www.airtrain.ai/blog/the-comprehensive-guide-to-llm-evaluation#high-level-approach)\n", "\n", "The deliverables:\n", "\n", "1. The code you put together\n", "2. The high-level description of the setup\n", "3. The results of the qualitative comparison\n" ] }, { "cell_type": "code", "execution_count": 2, "id": "39c18ba0-e54a-478f-9e60-0ea65c29238a", "metadata": {}, "outputs": [], "source": [ "# The code implementing LLM-as-a-Judge and the evaluation results" ] }, { "cell_type": "code", "execution_count": null, "id": "2ce78700-2578-4719-8b6b-d59fc669d1c1", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.11" } }, "nbformat": 4, "nbformat_minor": 5 }