diff --git a/.github/workflows/build_documentation.yml b/.github/workflows/build_documentation.yml index 3aed3267..7870ecc5 100644 --- a/.github/workflows/build_documentation.yml +++ b/.github/workflows/build_documentation.yml @@ -17,7 +17,7 @@ jobs: package_name: cookbook path_to_docs: cookbook/notebooks/ additional_args: --not_python_module - languages: en zh-CN + languages: en zh-CN ca convert_notebooks: true secrets: hf_token: ${{ secrets.HF_DOC_BUILD_PUSH }} \ No newline at end of file diff --git a/.github/workflows/build_pr_documentation.yml b/.github/workflows/build_pr_documentation.yml index 64aaf9fe..1c482cd8 100644 --- a/.github/workflows/build_pr_documentation.yml +++ b/.github/workflows/build_pr_documentation.yml @@ -20,5 +20,5 @@ jobs: package_name: cookbook path_to_docs: cookbook/notebooks/ additional_args: --not_python_module - languages: en zh-CN + languages: en zh-CN ca convert_notebooks: true \ No newline at end of file diff --git a/notebooks/ca/_toctree.yml b/notebooks/ca/_toctree.yml new file mode 100644 index 00000000..e7a7bcb7 --- /dev/null +++ b/notebooks/ca/_toctree.yml @@ -0,0 +1,9 @@ +- title: Open-Source AI Cookbook + sections: + - local: index + title: Open-Source AI Cookbook + +- title: Receptes de LLM i RAG amb altres Llibreries + sections: + - local: rag_zephyr_langchain + title: Simple RAG utilitzant Hugging Face Zephyr i LangChain diff --git a/notebooks/ca/index.md b/notebooks/ca/index.md new file mode 100644 index 00000000..89ba51a1 --- /dev/null +++ b/notebooks/ca/index.md @@ -0,0 +1,17 @@ +# Open-Source AI Cookbook + +El Codi-Obert IA Cookbook es una colecció de llibretes que ensenyen com construir aplicacions de IA i resoldre diferents problemes de *machine learning* utilitzant models i eines de codi-obert. + +## Ultimes llibretes + +Revisa les llibretes afeguides recentment en català: + + +- [Simple RAG per GitHub issues utilitzant Hugging Face Zephyr i LangChain](rag_zephyr_langchain) + +També pots mirar les llibretes de cookbook a [GitHub repo](https://github.com/huggingface/cookbook). + +## Contributing + +El Codi-Obert AI Cookbook es un esforç de la comunitat i es benvinguda la col·laboració de tothom! +Mira el Cookbook aqui [Contribution guide](https://github.com/huggingface/cookbook/blob/main/README.md) per apendre com pots afeguir "receptes". diff --git a/notebooks/ca/rag_zephyr_langchain.ipynb b/notebooks/ca/rag_zephyr_langchain.ipynb new file mode 100644 index 00000000..f55f5eef --- /dev/null +++ b/notebooks/ca/rag_zephyr_langchain.ipynb @@ -0,0 +1,526 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "id": "Kih21u1tyr-I" + }, + "source": [ + "# Simple RAG for GitHub issues using Hugging Face Zephyr and LangChain\n", + "\n", + "_Autora: [Maria Khalusova](https://github.com/MKhalusova)_\n", + "_Traductor: [Jan Leyva](https://github.com/JanLeyva)_\n", + "\n", + "Aquesta llibreta ensenya com pots construir rapidament un RAG *(Retrieval Augmented Generation)* per a un projecte de *GitHub issues* utilitzant el model[`HuggingFaceH4/zephyr-7b-beta`](https://huggingface.co/HuggingFaceH4/zephyr-7b-beta), i LangChain.\n", + "\n", + "\n", + "\n", + "**Que es un *RAG*?**\n", + "\n", + "Un *RAG* es una técnica popular per corretgir el problema quan un *LLM* no te l'informació necessaries o bé perquè aquestes no estava en el seu conjunt de dades d'entrenament o bé per evitar al·lucinacions tot i haver-les vist abans. Aquestes dades poden ser de propietat privada, sensibles o com en l'exemple actualitzades sovint.\n", + "\n", + "Si les teves dades son estatiques i no canvien sivint, hauries de considerar *fine-tune* un model de llenguatge. En moltes casos, encara que *fine-tune* pot ser costos i quan es fa repetidament pot comportar problemes (e.g. evitar que el model es desvi). Això passa quan el model te un comportament no desitjable.\n", + "\n", + "\n", + "**RAG (Retrieval Augmented Generation)** no requereix *fine-tine* (ajustar) el model. En comptes, el que fa el *RAG* es proporcionar mes context de dades rellevants al model i així pot generar millor respostes informades.\n", + "\n", + "\n", + "Aqui tenim una il·lustració d'un RAG:\n", + "\n", + "![RAG diagram](https://huggingface.co/datasets/huggingface/cookbook-images/resolve/main/rag-diagram.png)\n", + "\n", + "* Les dades externes es converteixen en vectors *embedding* (representacions vecgtoritzada del text) amb un model que crea aquests *embeddings* diferent. Embeddings models son tipicament petits, així actualitzar els vectors creats es més ràpid, barat i fàcil que *fine-tune* el model.\n", + "\n", + "* A la vegada, el fet de que el *fine-tune* no sigui necessari et dona mes llivertat a l'hora de canviar el *LLM* per un més potent quan estigui disponible. O canviar-lo per una versió mes petita i optima quan necessitis que la generació sigui mes ràpida.\n", + "\n", + "Ilustrem com construir un *RAG* utilitzant un model lliure *LLM*, *embeddings* del model i LangChain.\n", + "\n", + "Primer, instala les dependencies requerides:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "lC9frDOlyi38" + }, + "outputs": [], + "source": [ + "!pip install -q torch transformers accelerate bitsandbytes transformers sentence-transformers faiss-gpu" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "id": "-aYENQwZ-p_c" + }, + "outputs": [], + "source": [ + "# If running in Google Colab, you may need to run this cell to make sure you're using UTF-8 locale to install LangChain\n", + "import locale\n", + "locale.getpreferredencoding = lambda: \"UTF-8\"" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "W5HhMZ2c-NfU" + }, + "outputs": [], + "source": [ + "!pip install -q langchain" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "R8po01vMWzXL" + }, + "source": [ + "## Prepara les dades" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "3cCmQywC04x6" + }, + "source": [ + "En aquest example, carreguem totes les incidencies (ambdues obertes i tancades) desde [PEFT library's repo](https://github.com/huggingface/peft).\n", + "\n", + "Primer, necessitem aconseguir [GitHub personal access token](https://github.com/settings/tokens?type=beta) to access the GitHub API." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "8MoD7NbsNjlM" + }, + "outputs": [], + "source": [ + "from getpass import getpass\n", + "ACCESS_TOKEN = getpass(\"YOUR_GITHUB_PERSONAL_TOKEN\")" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "fccecm3a10N6" + }, + "source": [ + "Després, carreguem totes les incidencies de [huggingface/peft](https://github.com/huggingface/peft) repositori:\n", + "\n", + "- Per defecte, les *pull requests* son considerades incidencies també, per això escollim excloir-les de les dades editant la configuració `include_prs=False`\n", + "- Possa `state=\"all\"` vol dir que carregarem ambdos tancats i oberts." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "id": "8EKMit4WNDY8" + }, + "outputs": [], + "source": [ + "from langchain.document_loaders import GitHubIssuesLoader\n", + "\n", + "loader = GitHubIssuesLoader(\n", + " repo=\"huggingface/peft\",\n", + " access_token=ACCESS_TOKEN,\n", + " include_prs=False,\n", + " state=\"all\"\n", + ")\n", + "\n", + "docs = loader.load()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "CChTrY-k2qO5" + }, + "source": [ + "La llargada d'una incidencia de GitHub pot ser mes llarga de la capacitat màxima que pot admetre el *embedding*. Per això, si volem aplicar el *embbeding* a tot el contingut, hem de separar en troços del tamany adecuat les incidencies.\n", + "\n", + "La manera més directe de fer això es separar el contingut en una mesura definida i marcar una sobreposició d'aquest. D'aquesta manera, mantenint una sobreposició entre la separació del text, mantenim el context semantic entre les diferents divisions del text. Per separar el text es recomana utilitzar [RecursiveCharacterTextSplitter](https://python.langchain.com/docs/modules/data_connection/document_transformers/recursive_text_splitter), i per això es el que utilitzarem." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "OmsXOf59Pmm-" + }, + "outputs": [], + "source": [ + "from langchain.text_splitter import RecursiveCharacterTextSplitter\n", + "\n", + "splitter = RecursiveCharacterTextSplitter(chunk_size=512, chunk_overlap=30)\n", + "\n", + "chunked_docs = splitter.split_documents(docs)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "DAt_zPVlXOn7" + }, + "source": [ + "## Crear els embeddings + retriever" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "-mvat6JQl4yp" + }, + "source": [ + "Una vegada totes els documents tenen la llargada apropiada, podem crear una base de dades amb aquests *embbedings*.\n", + "\n", + "Per crear els troços dels documents i fer els embeddings utilitzarem `HuggingFaceEmbeddings` and the [`BAAI/bge-base-en-v1.5`](https://huggingface.co/BAAI/bge-base-en-v1.5). Hi ha moltes mes models de embbeding disponibles en la plataforma, pots fer-hi una ullada als que millor funcionen a [Massive Text Embedding Benchmark (MTEB) Leaderboard](https://huggingface.co/spaces/mteb/leaderboard).\n", + "\n", + "Per crear la base de dades vectoritzada, utilitzarem `FAISS`, una llibreria desenvolupada per Facebook AI. Aquesta llibreria ofereix similars resultats per busqueda i agrupament que una base de dades convencional. FAISS es actualmentr una de les llibreries mes utilitzades per busqueda de NN en base de dades gegants.\n", + "\n", + "Utilitarem LangChain API per accedir ambdues llibreries FAISS i el model de *embedding*." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "ixmCdRzBQ5gu" + }, + "outputs": [], + "source": [ + "from langchain.vectorstores import FAISS\n", + "from langchain.embeddings import HuggingFaceEmbeddings\n", + "\n", + "db = FAISS.from_documents(chunked_docs,\n", + " HuggingFaceEmbeddings(model_name='BAAI/bge-base-en-v1.5'))" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "2iCgEPi0nnN6" + }, + "source": [ + "Necessitem una manera de retornar els documents necessaris amb una demanda no estructurada (query unstructured). Per això, utilitzarem el métode `as_retriever` utilitzant la `db` com a suport:\n", + "- `search_type=\"similarity\"` vol dir que volem fer una busqueda amb resultats similars entre la demanda/*query* i els documents.\n", + "- `search_kwargs={'k': 4}` ens retornara nomes els 4 resultats principals." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "id": "mBTreCQ9noHK" + }, + "outputs": [], + "source": [ + "retriever = db.as_retriever(\n", + " search_type=\"similarity\",\n", + " search_kwargs={'k': 4}\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "WgEhlISJpTgj" + }, + "source": [ + "Tant la base de dades vectoritzada com el retornador de documents estan iniciats i configuratrs, el següent pas serà configurar la cadena del model." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "tzQxx0HkXVFU" + }, + "source": [ + "## Carrega el model quantitzat\n", + "\n", + "(un model quantitzat es un model que en comptes de expressar-lo en la seva màxima precisió els valors o fem una precisió menor (e.g. int8, in4))" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "9jy1cC65p_GD" + }, + "source": [ + "Per aquest exemple, hem escollit [`HuggingFaceH4/zephyr-7b-beta`](https://huggingface.co/HuggingFaceH4/zephyr-7b-beta), un model petit però potent.\n", + "\n", + "Amb tant models que surten cada setmana, potser voldras canviar a un model més nou i més gran. La millor manera d'estar alerta dels ultims models de llicencia lliure es mirant [Open-source LLM leaderboard](https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard).\n", + "\n", + "Per tal de fer més ràpida la generació de text carregarem el model quantitzat:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "L-ggaa763VRo" + }, + "outputs": [], + "source": [ + "import torch\n", + "from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig\n", + "\n", + "model_name = 'HuggingFaceH4/zephyr-7b-beta'\n", + "\n", + "bnb_config = BitsAndBytesConfig(\n", + " load_in_4bit=True,\n", + " bnb_4bit_use_double_quant=True,\n", + " bnb_4bit_quant_type=\"nf4\",\n", + " bnb_4bit_compute_dtype=torch.bfloat16\n", + ")\n", + "\n", + "model = AutoModelForCausalLM.from_pretrained(model_name, quantization_config=bnb_config)\n", + "tokenizer = AutoTokenizer.from_pretrained(model_name)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "hVNRJALyXYHG" + }, + "source": [ + "## Configura la cadena del LLM" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "RUUNneJ1smhl" + }, + "source": [ + "Finalment, tenim totes les peces que necessitavem per configurar la cedena del LLM.\n", + "\n", + "Primer de tot, creem un generador de text `text_generation`utilitzant el model carregat i el seu *tokenitzador*.\n", + "\n", + "Despres, crearem una plantilla de *prompt* - això ha de seguir el format del model, això vol dir que si en algun moment canvies els *checkpoint* del model, assegura't de canviar la plantilla per una apropiada també." + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "id": "cR0k1cRWz8Pm" + }, + "outputs": [], + "source": [ + "from langchain.llms import HuggingFacePipeline\n", + "from langchain.prompts import PromptTemplate\n", + "from transformers import pipeline\n", + "from langchain_core.output_parsers import StrOutputParser\n", + "\n", + "text_generation_pipeline = pipeline(\n", + " model=model,\n", + " tokenizer=tokenizer,\n", + " task=\"text-generation\",\n", + " temperature=0.2,\n", + " do_sample=True,\n", + " repetition_penalty=1.1,\n", + " return_full_text=True,\n", + " max_new_tokens=400,\n", + ")\n", + "\n", + "llm = HuggingFacePipeline(pipeline=text_generation_pipeline)\n", + "\n", + "prompt_template = \"\"\"\n", + "<|system|>\n", + "Answer the question based on your knowledge. Use the following context to help:\n", + "\n", + "{context}\n", + "\n", + "\n", + "<|user|>\n", + "{question}\n", + "\n", + "<|assistant|>\n", + "\n", + " \"\"\"\n", + "\n", + "prompt = PromptTemplate(\n", + " input_variables=[\"context\", \"question\"],\n", + " template=prompt_template,\n", + ")\n", + "\n", + "llm_chain = prompt | llm | StrOutputParser()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "l19UKq5HXfSp" + }, + "source": [ + "Nota: _També pots utilitzar `tokenizer.apply_chat_template` per convertir la llista de missatges (com a diccionaris: `{'role': 'user', 'content': '(...)'}`) a str amb la plantilla apropiada._\n", + "\n", + "Finalment, necessitem convinar `llm_chain` amb el que ens torna la base de dades vectoritzada per tal de crear la cadena del RAG. Per això, necessitem passar la pregunta original a traves del generador de text (LLM) juntament amb els documents mes rellevants que ens torni dels que hem fet el *embbeding* abans:" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "id": "_rI3YNp9Xl4s" + }, + "outputs": [], + "source": [ + "from langchain_core.runnables import RunnablePassthrough\n", + "\n", + "retriever = db.as_retriever()\n", + "\n", + "rag_chain = (\n", + " {\"context\": retriever, \"question\": RunnablePassthrough()}\n", + " | llm_chain\n", + ")\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "UsCOhfDDXpaS" + }, + "source": [ + "## Comparem els resultats\n", + "\n", + "Mirem quina diferencia que hi ha generant les respostes amb el RAG a preguntes específiques." + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": { + "id": "W7F07fQLXusU" + }, + "outputs": [], + "source": [ + "question = \"How do you combine multiple adapters?\"" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "KC0rJYU1x1ir" + }, + "source": [ + "Primer de tot mirem quins resultats obtenim sense passar extra de context al model." + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 125 + }, + "id": "GYh-HG1l0De5", + "outputId": "277d8e89-ce9b-4e04-c11b-639ad2645759" + }, + "outputs": [ + { + "data": { + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + }, + "text/plain": [ + "\" To combine multiple adapters, you need to ensure that they are compatible with each other and the devices you want to connect. Here's how you can do it:\\n\\n1. Identify the adapters you need: Determine which adapters you require to connect the devices you want to use together. For example, if you want to connect a USB-C device to an HDMI monitor, you may need a USB-C to HDMI adapter and a USB-C to USB-A adapter (if your computer only has USB-A ports).\\n\\n2. Connect the first adapter: Plug in the first adapter into the device you want to connect. For instance, if you're connecting a USB-C laptop to an HDMI monitor, plug the USB-C to HDMI adapter into the laptop's USB-C port.\\n\\n3. Connect the second adapter: Next, connect the second adapter to the first one. In this case, connect the USB-C to USB-A adapter to the USB-C port of the USB-C to HDMI adapter.\\n\\n4. Connect the final device: Finally, connect the device you want to use to the second adapter. For example, connect the HDMI cable from the monitor to the HDMI port on the USB-C to HDMI adapter.\\n\\n5. Test the connection: Turn on both devices and check whether everything is working correctly. If necessary, adjust the settings on your devices to ensure optimal performance.\\n\\nBy combining multiple adapters, you can connect a variety of devices together, even if they don't have the same type of connector. Just be sure to choose adapters that are compatible with all the devices you want to connect and test the connection thoroughly before relying on it for critical tasks.\"" + ] + }, + "execution_count": 20, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "llm_chain.invoke({\"context\":\"\", \"question\": question})" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "i-TIWr3wx9w8" + }, + "source": [ + "Com pots veuere el model interpreta la pregunta com si parlessim de adaptadors fisics d'ordinador, mentres que amb el contexte del PEFT, \"adapters\" es refereix als adaptadors de LoRa.\n", + "\n", + "Anem a veure sia afeguint context de les incidencies de GitHub ajuda al model a donar una resposta més rellevant:" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 125 + }, + "id": "FZpNA3o10H10", + "outputId": "31f9aed3-3dd7-4ff8-d1a8-866794fefe80" + }, + "outputs": [ + { + "data": { + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + }, + "text/plain": [ + "\" Based on the provided context, it seems that combining multiple adapters is still an open question in the community. Here are some possibilities:\\n\\n 1. Save the output from the base model and pass it to each adapter separately, as described in the first context snippet. This allows you to run multiple adapters simultaneously and reuse the output from the base model. However, this approach requires loading and running each adapter separately.\\n\\n 2. Export everything into a single PyTorch model, as suggested in the second context snippet. This would involve saving all the adapters and their weights into a single model, potentially making it larger and more complex. The advantage of this approach is that it would allow you to run all the adapters simultaneously without having to load and run them separately.\\n\\n 3. Merge multiple Lora adapters, as mentioned in the third context snippet. This involves adding multiple distinct, independent behaviors to a base model by merging multiple Lora adapters. It's not clear from the context how this would be done, but it suggests that there might be a recommended way of doing it.\\n\\n 4. Combine adapters through a specific architecture, as proposed in the fourth context snippet. This involves merging multiple adapters into a single architecture, potentially creating a more complex model with multiple behaviors. Again, it's not clear from the context how this would be done.\\n\\n Overall, combining multiple adapters is still an active area of research, and there doesn't seem to be a widely accepted solution yet. If you're interested in exploring this further, it might be worth reaching out to the Hugging Face community or checking out their documentation for more information.\"" + ] + }, + "execution_count": 21, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "rag_chain.invoke(question)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "hZQedZKSyrwO" + }, + "source": [ + "Tal i com podem veure, afeguir context, realment ajuda al mateix model, i així retorna molt millor resposta i més relevant per el context que estavem preguntat.\n", + "\n", + "Hem de tenir en compte, que combinar diferents \"adapters\" per generar text s'ha afeguit a la llibreria recentment, aquesta informació es pot trobar a la documentació, i per això podría ser beneficios afeguir la documentació a la base de dades vectoritzada havent fet els *embedding* corresponents. Per la pròxima itereció podria ser beneficios incluir això al RAG." + ] + } + ], + "metadata": { + "accelerator": "GPU", + "colab": { + "gpuType": "T4", + "provenance": [] + }, + "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.9.7" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +}