{ "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", "\n", "1. The code for chunk splitting\n", "2. The illustrative examples of how retrived chunks differ depending on the chunking strategy.\n", "3. The analysis of pros and cons of each strategy\n" ] }, { "cell_type": "code", "execution_count": null, "id": "f7bad8c8", "metadata": {}, "outputs": [], "source": [ "# chunk splitting" ] }, { "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", "Your task is to vectorize and ingest chunked documents into the database. 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 model 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 see all 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_scrips/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\n", "2. The analysis of how the embedding time differs between models\n" ] }, { "cell_type": "code", "execution_count": null, "id": "f7db282e-e03c-41de-9c03-54abf455481f", "metadata": {}, "outputs": [], "source": [ "# Embed documents and ingest into the database " ] }, { "cell_type": "markdown", "id": "c929fe99-7f3f-49cf-af9f-07bac9668c2f", "metadata": {}, "source": [ "### Step 3: DB retrieval\n", "\n", "To augment an LLM with a knowledge base the context provided in a prompt is enriched with relevant pieces from a DB. An incoming query is vectorized with an embedding model and top-k relevant pieces are retrieved based on similarity to a query vector. Your task is to implement database retrieval and adjust the prompt to include the documents from the DB.\n", "\n", "The deliverables are:\n", "\n", "1. The new code that enables RAG. Paste the code added and some surrounding context; indicate which file it comes from.\n", "2. A new prompt template\n", "3. Examples of how the output changes\n" ] }, { "cell_type": "code", "execution_count": null, "id": "5bc1399d-1c3b-48b7-a9fb-ed48a0dfaa6a", "metadata": {}, "outputs": [], "source": [ "# DB retrieval implementation" ] }, { "cell_type": "markdown", "id": "7d818b4f-ba5a-4c81-b6d7-f3474c398d9c", "metadata": {}, "source": [ "### Step 4: 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]). 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", "2. A comparison of how the prompt and the model output change after adding a reranker\n", "3. 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" ] }, { "cell_type": "markdown", "id": "f5816c54-a290-4cb0-b7db-3b8901998cb0", "metadata": {}, "source": [ "### Step 5: Try a different LLM\n", "\n", "The suggested Mistral-7b 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. \n", "\n", "A good option for a large model is gpt-4 but the inference time comparison will not be representative due to the hosting infrastructure differences. Try a larger model hosted by HF if you have access.\n", "\n", "The task here is to try out a large LLM and describe the differencies.\n", "\n", "The deliverables are:\n", "\n", "1. The comparison between outputs with Mistral-7b and a larger model\n", "2. The difference in response times\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 6 (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": null, "id": "39c18ba0-e54a-478f-9e60-0ea65c29238a", "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 }