{ "cells": [ { "cell_type": "markdown", "id": "1cc557a5-5a55-4bae-8555-a2b655abfa4a", "metadata": {}, "source": [ "SPDX-License-Identifier: Apache-2.0\n", "Copyright (c) 2023, Rahul Unnikrishnan Nair \n" ] }, { "cell_type": "markdown", "id": "2123be0f-586b-47c9-af17-9d667f28eb3d", "metadata": {}, "source": [ "---\n", "\n", "**Text to SQL Generation: Fine-Tuning LLMs with QLoRA on Intel**\n", "\n", "๐Ÿ‘‹ Hello and welcome! In this Jupyter Notebook, we will walkthrough the process of fine-tuning a large language model (LLM) to improve its capabilities in generating SQL queries from natural language input. The notebook is suitable for AI engineers and practitioners looking to tune LLMs for specialized tasks such as Text-to-SQL conversions.\n", "\n", "**What you will learn with this Notebook**\n", "\n", "- ๐Ÿ› ๏ธ Fine-tune a Language Model with either a pre-existing dataset or a custom dataset tailored to your needs on Intel Hw.\n", "- ๐Ÿ’ก Gain insights into the fine-tuning process, including how to manipulate various training parameters to optimize your model's performance.\n", "- ๐Ÿ“Š Test different configurations and observe the results in real-time.\n", "\n", "**Hardware Compatibility**\n", "\n", "- ๐Ÿ–ฅ๏ธ Designed for 4th Generation Intelยฎ Xeonยฎ Scalable Processors (CPU) and Intelยฎ Data Center GPU Max Series 1100 (XPU)." ] }, { "cell_type": "code", "execution_count": 1, "id": "67c0e67f-8473-44d6-8065-edfc63a6459d", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "List of Intel GPUs available on the system:\n", "+-----------+--------------------------------------------------------------------------------------+\n", "| Device ID | Device Information |\n", "+-----------+--------------------------------------------------------------------------------------+\n", "| 0 | Device Name: Intel(R) Data Center GPU Max 1100 |\n", "| | Vendor Name: Intel(R) Corporation |\n", "| | SOC UUID: 00000000-0000-0029-0000-002f0bda8086 |\n", "| | PCI BDF Address: 0000:29:00.0 |\n", "| | DRM Device: /dev/dri/card0 |\n", "| | Function Type: physical |\n", "+-----------+--------------------------------------------------------------------------------------+\n", "| 1 | Device Name: Intel(R) Data Center GPU Max 1100 |\n", "| | Vendor Name: Intel(R) Corporation |\n", "| | SOC UUID: 00000000-0000-003a-0000-002f0bda8086 |\n", "| | PCI BDF Address: 0000:3a:00.0 |\n", "| | DRM Device: /dev/dri/card2 |\n", "| | Function Type: physical |\n", "+-----------+--------------------------------------------------------------------------------------+\n", "| 2 | Device Name: Intel(R) Data Center GPU Max 1100 |\n", "| | Vendor Name: Intel(R) Corporation |\n", "| | SOC UUID: 00000000-0000-009a-0000-002f0bda8086 |\n", "| | PCI BDF Address: 0000:9a:00.0 |\n", "| | DRM Device: /dev/dri/card3 |\n", "| | Function Type: physical |\n", "+-----------+--------------------------------------------------------------------------------------+\n", "| 3 | Device Name: Intel(R) Data Center GPU Max 1100 |\n", "| | Vendor Name: Intel(R) Corporation |\n", "| | SOC UUID: 00000000-0000-00ca-0000-002f0bda8086 |\n", "| | PCI BDF Address: 0000:ca:00.0 |\n", "| | DRM Device: /dev/dri/card4 |\n", "| | Function Type: physical |\n", "+-----------+--------------------------------------------------------------------------------------+\n", "Intel Xeon CPU used by this notebook:\n", "Model name: Intel(R) Xeon(R) Platinum 8480+\n" ] } ], "source": [ "!echo \"List of Intel GPUs available on the system:\"\n", "!xpu-smi discovery 2> /dev/null\n", "!echo \"Intel Xeon CPU used by this notebook:\"\n", "!lscpu | grep \"Model name\"\n" ] }, { "cell_type": "markdown", "id": "76293a12-551e-421a-8eb3-06387931d307", "metadata": { "jp-MarkdownHeadingCollapsed": true }, "source": [ "---\n", "\n", "**Fine-Tuning with QLoRA: Balancing Memory Efficiency and Adaptability**\n", "\n", "We leverage the QLoRA methodology for fine-tuning, enabling the loading and refinement of LLMs within the constraints of available GPU memory. Quantized Low Rank Adaptation or QLoRA achieves this by applying a clever combination of weight quantization and adapter-based finetuning.\n", "\n", "**How Does QLoRA Work?**\n", "\n", "- QLoRA reduces memory footprint via weight quantization. It compresses the pre-trained model weights significantly.\n", "- During fine-tuning, it focuses on optimizing adapter parametersโ€”low-rank matrices added to the network, tailored for the specific task.\n", "- This selective training is computationally efficient, targeting a smaller set of trainable parameters.\n", "\n", "\n", "**What is the Big Picture?**\n", "\n", "- Think reparameterization: We inject LoRA weights, training only these, not the entire layer, for fine-tuning.\n", "- This technique is key for task-specific model adaptation.\n", "- Imagine a hub-and-spoke model for deployment: The hub is the foundational model, and the spokes are task-specific LoRA adapters.\n", "\n", "Below, on the left, is an overview of the reparameterization implemented with LoRA (with Quantization). This involves a set of low-rank matricesโ€”think of these as an essential subset of larger weight matricesโ€”trained specifically for the task. On the right, there's a high-level view of a hub-and-spoke model for LLM deployment, where the hub represents the foundational model, and the spokes are the LoRA adapters.\n", "\n", "
\n", " \"lora_adapters_reparameterization\"\n", "
" ] }, { "cell_type": "markdown", "id": "6362a562-f3ce-4dce-9678-ce317e554a04", "metadata": {}, "source": [ "## Initialization\n", "\n", "Let's first install and import all the necessary packages required for the fine-tuning process.\n" ] }, { "cell_type": "code", "execution_count": 2, "id": "9236e9d1-e75e-4089-9a4d-27421521cfd5", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Installation in progress, please wait...\n", "Defaulting to user installation because normal site-packages is not writeable\n", "\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n", "\u001b[0mLooking in links: https://developer.intel.com/ipex-whl-stable-xpu\n", "Requirement already satisfied: bigdl-llm==2.5.0b20240318 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bigdl-llm[xpu]==2.5.0b20240318) (2.5.0b20240318)\n", "Requirement already satisfied: py-cpuinfo in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bigdl-llm[xpu]==2.5.0b20240318) (9.0.0)\n", "Requirement already satisfied: protobuf in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bigdl-llm[xpu]==2.5.0b20240318) (4.25.3)\n", "Requirement already satisfied: mpmath==1.3.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bigdl-llm[xpu]==2.5.0b20240318) (1.3.0)\n", "Requirement already satisfied: numpy==1.26.4 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bigdl-llm[xpu]==2.5.0b20240318) (1.26.4)\n", "Requirement already satisfied: transformers==4.31.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bigdl-llm[xpu]==2.5.0b20240318) (4.31.0)\n", "Requirement already satisfied: sentencepiece in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bigdl-llm[xpu]==2.5.0b20240318) (0.2.0)\n", "Requirement already satisfied: tokenizers==0.13.3 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bigdl-llm[xpu]==2.5.0b20240318) (0.13.3)\n", "Collecting accelerate==0.21.0 (from bigdl-llm[xpu]==2.5.0b20240318)\n", " Downloading accelerate-0.21.0-py3-none-any.whl.metadata (17 kB)\n", "Requirement already satisfied: tabulate in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bigdl-llm[xpu]==2.5.0b20240318) (0.9.0)\n", "Requirement already satisfied: torch==2.1.0a0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bigdl-llm[xpu]==2.5.0b20240318) (2.1.0a0+cxx11.abi)\n", "Requirement already satisfied: torchvision==0.16.0a0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bigdl-llm[xpu]==2.5.0b20240318) (0.16.0a0+cxx11.abi)\n", "Requirement already satisfied: intel-extension-for-pytorch==2.1.10+xpu in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bigdl-llm[xpu]==2.5.0b20240318) (2.1.10+xpu)\n", "Requirement already satisfied: bigdl-core-xe-21==2.5.0b20240318 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bigdl-llm[xpu]==2.5.0b20240318) (2.5.0b20240318)\n", "Requirement already satisfied: intel-openmp in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bigdl-llm[xpu]==2.5.0b20240318) (2024.0.3)\n", "Requirement already satisfied: bigdl-core-xe-esimd-21==2.5.0b20240318 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bigdl-llm[xpu]==2.5.0b20240318) (2.5.0b20240318)\n", "Requirement already satisfied: packaging>=20.0 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from accelerate==0.21.0->bigdl-llm[xpu]==2.5.0b20240318) (23.2)\n", "Requirement already satisfied: psutil in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from accelerate==0.21.0->bigdl-llm[xpu]==2.5.0b20240318) (5.9.8)\n", "Requirement already satisfied: pyyaml in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from accelerate==0.21.0->bigdl-llm[xpu]==2.5.0b20240318) (6.0.1)\n", "Requirement already satisfied: pydantic in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from intel-extension-for-pytorch==2.1.10+xpu->bigdl-llm[xpu]==2.5.0b20240318) (2.6.4)\n", "Requirement already satisfied: filelock in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch==2.1.0a0->bigdl-llm[xpu]==2.5.0b20240318) (3.13.1)\n", "Requirement already satisfied: typing-extensions in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch==2.1.0a0->bigdl-llm[xpu]==2.5.0b20240318) (4.10.0)\n", "Requirement already satisfied: sympy in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch==2.1.0a0->bigdl-llm[xpu]==2.5.0b20240318) (1.12)\n", "Requirement already satisfied: networkx in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch==2.1.0a0->bigdl-llm[xpu]==2.5.0b20240318) (3.2.1)\n", "Requirement already satisfied: jinja2 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch==2.1.0a0->bigdl-llm[xpu]==2.5.0b20240318) (3.1.3)\n", "Requirement already satisfied: fsspec in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch==2.1.0a0->bigdl-llm[xpu]==2.5.0b20240318) (2023.10.0)\n", "Requirement already satisfied: requests in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torchvision==0.16.0a0->bigdl-llm[xpu]==2.5.0b20240318) (2.31.0)\n", "Requirement already satisfied: pillow!=8.3.*,>=5.3.0 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from torchvision==0.16.0a0->bigdl-llm[xpu]==2.5.0b20240318) (10.0.1)\n", "Requirement already satisfied: huggingface-hub<1.0,>=0.14.1 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from transformers==4.31.0->bigdl-llm[xpu]==2.5.0b20240318) (0.17.3)\n", "Requirement already satisfied: regex!=2019.12.17 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from transformers==4.31.0->bigdl-llm[xpu]==2.5.0b20240318) (2023.12.25)\n", "Requirement already satisfied: safetensors>=0.3.1 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from transformers==4.31.0->bigdl-llm[xpu]==2.5.0b20240318) (0.4.2)\n", "Requirement already satisfied: tqdm>=4.27 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from transformers==4.31.0->bigdl-llm[xpu]==2.5.0b20240318) (4.66.2)\n", "Requirement already satisfied: MarkupSafe>=2.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from jinja2->torch==2.1.0a0->bigdl-llm[xpu]==2.5.0b20240318) (2.1.5)\n", "Requirement already satisfied: annotated-types>=0.4.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from pydantic->intel-extension-for-pytorch==2.1.10+xpu->bigdl-llm[xpu]==2.5.0b20240318) (0.6.0)\n", "Requirement already satisfied: pydantic-core==2.16.3 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from pydantic->intel-extension-for-pytorch==2.1.10+xpu->bigdl-llm[xpu]==2.5.0b20240318) (2.16.3)\n", "Requirement already satisfied: charset-normalizer<4,>=2 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->torchvision==0.16.0a0->bigdl-llm[xpu]==2.5.0b20240318) (3.3.2)\n", "Requirement already satisfied: idna<4,>=2.5 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->torchvision==0.16.0a0->bigdl-llm[xpu]==2.5.0b20240318) (3.6)\n", "Requirement already satisfied: urllib3<3,>=1.21.1 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->torchvision==0.16.0a0->bigdl-llm[xpu]==2.5.0b20240318) (2.2.1)\n", "Requirement already satisfied: certifi>=2017.4.17 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->torchvision==0.16.0a0->bigdl-llm[xpu]==2.5.0b20240318) (2024.2.2)\n", "Downloading accelerate-0.21.0-py3-none-any.whl (244 kB)\n", "\u001b[2K \u001b[90mโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\u001b[0m \u001b[32m244.2/244.2 kB\u001b[0m \u001b[31m5.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0ma \u001b[36m0:00:01\u001b[0m\n", "\u001b[?25h\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n", "\u001b[0mInstalling collected packages: accelerate\n", " Attempting uninstall: accelerate\n", " Found existing installation: accelerate 0.23.0\n", " Uninstalling accelerate-0.23.0:\n", " Successfully uninstalled accelerate-0.23.0\n", "\u001b[33m WARNING: The scripts accelerate, accelerate-config and accelerate-launch are installed in '/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/bin' which is not on PATH.\n", " Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.\u001b[0m\u001b[33m\n", "\u001b[0mSuccessfully installed accelerate-0.21.0\n", "\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n", "\u001b[0m\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n", "\u001b[0mDefaulting to user installation because normal site-packages is not writeable\n", "\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n", "\u001b[0mRequirement already satisfied: peft==0.5.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (0.5.0)\n", "Requirement already satisfied: numpy>=1.17 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from peft==0.5.0) (1.26.4)\n", "Requirement already satisfied: packaging>=20.0 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from peft==0.5.0) (23.2)\n", "Requirement already satisfied: psutil in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from peft==0.5.0) (5.9.8)\n", "Requirement already satisfied: pyyaml in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from peft==0.5.0) (6.0.1)\n", "Requirement already satisfied: torch>=1.13.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from peft==0.5.0) (2.1.0a0+cxx11.abi)\n", "Requirement already satisfied: transformers in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from peft==0.5.0) (4.31.0)\n", "Requirement already satisfied: tqdm in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from peft==0.5.0) (4.66.2)\n", "Requirement already satisfied: accelerate in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from peft==0.5.0) (0.21.0)\n", "Requirement already satisfied: safetensors in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from peft==0.5.0) (0.4.2)\n", "Requirement already satisfied: filelock in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch>=1.13.0->peft==0.5.0) (3.13.1)\n", "Requirement already satisfied: typing-extensions in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch>=1.13.0->peft==0.5.0) (4.10.0)\n", "Requirement already satisfied: sympy in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch>=1.13.0->peft==0.5.0) (1.12)\n", "Requirement already satisfied: networkx in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch>=1.13.0->peft==0.5.0) (3.2.1)\n", "Requirement already satisfied: jinja2 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch>=1.13.0->peft==0.5.0) (3.1.3)\n", "Requirement already satisfied: fsspec in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch>=1.13.0->peft==0.5.0) (2023.10.0)\n", "Requirement already satisfied: huggingface-hub<1.0,>=0.14.1 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from transformers->peft==0.5.0) (0.17.3)\n", "Requirement already satisfied: regex!=2019.12.17 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from transformers->peft==0.5.0) (2023.12.25)\n", "Requirement already satisfied: requests in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from transformers->peft==0.5.0) (2.31.0)\n", "Requirement already satisfied: tokenizers!=0.11.3,<0.14,>=0.11.1 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from transformers->peft==0.5.0) (0.13.3)\n", "Requirement already satisfied: MarkupSafe>=2.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from jinja2->torch>=1.13.0->peft==0.5.0) (2.1.5)\n", "Requirement already satisfied: charset-normalizer<4,>=2 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->transformers->peft==0.5.0) (3.3.2)\n", "Requirement already satisfied: idna<4,>=2.5 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->transformers->peft==0.5.0) (3.6)\n", "Requirement already satisfied: urllib3<3,>=1.21.1 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->transformers->peft==0.5.0) (2.2.1)\n", "Requirement already satisfied: certifi>=2017.4.17 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->transformers->peft==0.5.0) (2024.2.2)\n", "Requirement already satisfied: mpmath>=0.19 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from sympy->torch>=1.13.0->peft==0.5.0) (1.3.0)\n", "\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n", "\u001b[0m\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n", "\u001b[0m\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n", "\u001b[0mDefaulting to user installation because normal site-packages is not writeable\n", "\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n", "\u001b[0mCollecting accelerate==0.23.0\n", " Downloading accelerate-0.23.0-py3-none-any.whl.metadata (18 kB)\n", "Requirement already satisfied: numpy>=1.17 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from accelerate==0.23.0) (1.26.4)\n", "Requirement already satisfied: packaging>=20.0 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from accelerate==0.23.0) (23.2)\n", "Requirement already satisfied: psutil in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from accelerate==0.23.0) (5.9.8)\n", "Requirement already satisfied: pyyaml in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from accelerate==0.23.0) (6.0.1)\n", "Requirement already satisfied: torch>=1.10.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from accelerate==0.23.0) (2.1.0a0+cxx11.abi)\n", "Requirement already satisfied: huggingface-hub in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from accelerate==0.23.0) (0.17.3)\n", "Requirement already satisfied: filelock in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch>=1.10.0->accelerate==0.23.0) (3.13.1)\n", "Requirement already satisfied: typing-extensions in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch>=1.10.0->accelerate==0.23.0) (4.10.0)\n", "Requirement already satisfied: sympy in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch>=1.10.0->accelerate==0.23.0) (1.12)\n", "Requirement already satisfied: networkx in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch>=1.10.0->accelerate==0.23.0) (3.2.1)\n", "Requirement already satisfied: jinja2 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch>=1.10.0->accelerate==0.23.0) (3.1.3)\n", "Requirement already satisfied: fsspec in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch>=1.10.0->accelerate==0.23.0) (2023.10.0)\n", "Requirement already satisfied: requests in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from huggingface-hub->accelerate==0.23.0) (2.31.0)\n", "Requirement already satisfied: tqdm>=4.42.1 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from huggingface-hub->accelerate==0.23.0) (4.66.2)\n", "Requirement already satisfied: MarkupSafe>=2.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from jinja2->torch>=1.10.0->accelerate==0.23.0) (2.1.5)\n", "Requirement already satisfied: charset-normalizer<4,>=2 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->huggingface-hub->accelerate==0.23.0) (3.3.2)\n", "Requirement already satisfied: idna<4,>=2.5 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->huggingface-hub->accelerate==0.23.0) (3.6)\n", "Requirement already satisfied: urllib3<3,>=1.21.1 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->huggingface-hub->accelerate==0.23.0) (2.2.1)\n", "Requirement already satisfied: certifi>=2017.4.17 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->huggingface-hub->accelerate==0.23.0) (2024.2.2)\n", "Requirement already satisfied: mpmath>=0.19 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from sympy->torch>=1.10.0->accelerate==0.23.0) (1.3.0)\n", "Downloading accelerate-0.23.0-py3-none-any.whl (258 kB)\n", "\u001b[2K \u001b[90mโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\u001b[0m \u001b[32m258.1/258.1 kB\u001b[0m \u001b[31m3.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m00:01\u001b[0m0:01\u001b[0m\n", "\u001b[?25h\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n", "\u001b[0mInstalling collected packages: accelerate\n", " Attempting uninstall: accelerate\n", " Found existing installation: accelerate 0.21.0\n", " Uninstalling accelerate-0.21.0:\n", " Successfully uninstalled accelerate-0.21.0\n", "Successfully installed accelerate-0.23.0\n", "\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n", "\u001b[0m\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n", "\u001b[0mDefaulting to user installation because normal site-packages is not writeable\n", "\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n", "\u001b[0mCollecting transformers==4.34.0\n", " Downloading transformers-4.34.0-py3-none-any.whl.metadata (121 kB)\n", "\u001b[2K \u001b[90mโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\u001b[0m \u001b[32m121.5/121.5 kB\u001b[0m \u001b[31m2.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0ma \u001b[36m0:00:01\u001b[0m\n", "\u001b[?25hRequirement already satisfied: filelock in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from transformers==4.34.0) (3.13.1)\n", "Requirement already satisfied: huggingface-hub<1.0,>=0.16.4 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from transformers==4.34.0) (0.17.3)\n", "Requirement already satisfied: numpy>=1.17 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from transformers==4.34.0) (1.26.4)\n", "Requirement already satisfied: packaging>=20.0 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from transformers==4.34.0) (23.2)\n", "Requirement already satisfied: pyyaml>=5.1 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from transformers==4.34.0) (6.0.1)\n", "Requirement already satisfied: regex!=2019.12.17 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from transformers==4.34.0) (2023.12.25)\n", "Requirement already satisfied: requests in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from transformers==4.34.0) (2.31.0)\n", "Collecting tokenizers<0.15,>=0.14 (from transformers==4.34.0)\n", " Downloading tokenizers-0.14.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (6.7 kB)\n", "Requirement already satisfied: safetensors>=0.3.1 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from transformers==4.34.0) (0.4.2)\n", "Requirement already satisfied: tqdm>=4.27 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from transformers==4.34.0) (4.66.2)\n", "Requirement already satisfied: fsspec in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from huggingface-hub<1.0,>=0.16.4->transformers==4.34.0) (2023.10.0)\n", "Requirement already satisfied: typing-extensions>=3.7.4.3 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from huggingface-hub<1.0,>=0.16.4->transformers==4.34.0) (4.10.0)\n", "Requirement already satisfied: charset-normalizer<4,>=2 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->transformers==4.34.0) (3.3.2)\n", "Requirement already satisfied: idna<4,>=2.5 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->transformers==4.34.0) (3.6)\n", "Requirement already satisfied: urllib3<3,>=1.21.1 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->transformers==4.34.0) (2.2.1)\n", "Requirement already satisfied: certifi>=2017.4.17 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->transformers==4.34.0) (2024.2.2)\n", "Downloading transformers-4.34.0-py3-none-any.whl (7.7 MB)\n", "\u001b[2K \u001b[90mโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\u001b[0m \u001b[32m7.7/7.7 MB\u001b[0m \u001b[31m68.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m00:01\u001b[0m00:01\u001b[0m\n", "\u001b[?25hDownloading tokenizers-0.14.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (3.8 MB)\n", "\u001b[2K \u001b[90mโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\u001b[0m \u001b[32m3.8/3.8 MB\u001b[0m \u001b[31m97.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m:00:01\u001b[0m\n", "\u001b[?25h\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n", "\u001b[0mInstalling collected packages: tokenizers, transformers\n", " Attempting uninstall: tokenizers\n", " Found existing installation: tokenizers 0.13.3\n", " Uninstalling tokenizers-0.13.3:\n", " Successfully uninstalled tokenizers-0.13.3\n", " Attempting uninstall: transformers\n", " Found existing installation: transformers 4.31.0\n", " Uninstalling transformers-4.31.0:\n", " Successfully uninstalled transformers-4.31.0\n", "Successfully installed tokenizers-0.14.1 transformers-4.34.0\n", "\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n", "\u001b[0m\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n", "\u001b[0mDefaulting to user installation because normal site-packages is not writeable\n", "\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n", "\u001b[0mRequirement already satisfied: datasets==2.14.6 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (2.14.6)\n", "Requirement already satisfied: numpy>=1.17 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from datasets==2.14.6) (1.26.4)\n", "Requirement already satisfied: pyarrow>=8.0.0 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from datasets==2.14.6) (15.0.0)\n", "Requirement already satisfied: dill<0.3.8,>=0.3.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from datasets==2.14.6) (0.3.7)\n", "Requirement already satisfied: pandas in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from datasets==2.14.6) (2.2.1)\n", "Requirement already satisfied: requests>=2.19.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from datasets==2.14.6) (2.31.0)\n", "Requirement already satisfied: tqdm>=4.62.1 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from datasets==2.14.6) (4.66.2)\n", "Requirement already satisfied: xxhash in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from datasets==2.14.6) (3.4.1)\n", "Requirement already satisfied: multiprocess in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from datasets==2.14.6) (0.70.15)\n", "Requirement already satisfied: fsspec<=2023.10.0,>=2023.1.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from fsspec[http]<=2023.10.0,>=2023.1.0->datasets==2.14.6) (2023.10.0)\n", "Requirement already satisfied: aiohttp in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from datasets==2.14.6) (3.9.3)\n", "Requirement already satisfied: huggingface-hub<1.0.0,>=0.14.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from datasets==2.14.6) (0.17.3)\n", "Requirement already satisfied: packaging in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from datasets==2.14.6) (23.2)\n", "Requirement already satisfied: pyyaml>=5.1 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from datasets==2.14.6) (6.0.1)\n", "Requirement already satisfied: aiosignal>=1.1.2 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from aiohttp->datasets==2.14.6) (1.3.1)\n", "Requirement already satisfied: attrs>=17.3.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from aiohttp->datasets==2.14.6) (23.2.0)\n", "Requirement already satisfied: frozenlist>=1.1.1 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from aiohttp->datasets==2.14.6) (1.4.1)\n", "Requirement already satisfied: multidict<7.0,>=4.5 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from aiohttp->datasets==2.14.6) (6.0.5)\n", "Requirement already satisfied: yarl<2.0,>=1.0 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from aiohttp->datasets==2.14.6) (1.9.4)\n", "Requirement already satisfied: async-timeout<5.0,>=4.0 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from aiohttp->datasets==2.14.6) (4.0.3)\n", "Requirement already satisfied: filelock in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from huggingface-hub<1.0.0,>=0.14.0->datasets==2.14.6) (3.13.1)\n", "Requirement already satisfied: typing-extensions>=3.7.4.3 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from huggingface-hub<1.0.0,>=0.14.0->datasets==2.14.6) (4.10.0)\n", "Requirement already satisfied: charset-normalizer<4,>=2 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests>=2.19.0->datasets==2.14.6) (3.3.2)\n", "Requirement already satisfied: idna<4,>=2.5 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests>=2.19.0->datasets==2.14.6) (3.6)\n", "Requirement already satisfied: urllib3<3,>=1.21.1 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests>=2.19.0->datasets==2.14.6) (2.2.1)\n", "Requirement already satisfied: certifi>=2017.4.17 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests>=2.19.0->datasets==2.14.6) (2024.2.2)\n", "Requirement already satisfied: python-dateutil>=2.8.2 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from pandas->datasets==2.14.6) (2.8.2)\n", "Requirement already satisfied: pytz>=2020.1 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from pandas->datasets==2.14.6) (2023.3.post1)\n", "Requirement already satisfied: tzdata>=2022.7 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from pandas->datasets==2.14.6) (2023.3)\n", "Requirement already satisfied: six>=1.5 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from python-dateutil>=2.8.2->pandas->datasets==2.14.6) (1.16.0)\n", "\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n", "\u001b[0m\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n", "\u001b[0m\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n", "\u001b[0mDefaulting to user installation because normal site-packages is not writeable\n", "\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n", "\u001b[0mRequirement already satisfied: bitsandbytes==0.43.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (0.43.0)\n", "Requirement already satisfied: scipy==1.12.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (1.12.0)\n", "Requirement already satisfied: torch in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bitsandbytes==0.43.0) (2.1.0a0+cxx11.abi)\n", "Requirement already satisfied: numpy in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bitsandbytes==0.43.0) (1.26.4)\n", "Requirement already satisfied: filelock in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch->bitsandbytes==0.43.0) (3.13.1)\n", "Requirement already satisfied: typing-extensions in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch->bitsandbytes==0.43.0) (4.10.0)\n", "Requirement already satisfied: sympy in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch->bitsandbytes==0.43.0) (1.12)\n", "Requirement already satisfied: networkx in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch->bitsandbytes==0.43.0) (3.2.1)\n", "Requirement already satisfied: jinja2 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch->bitsandbytes==0.43.0) (3.1.3)\n", "Requirement already satisfied: fsspec in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch->bitsandbytes==0.43.0) (2023.10.0)\n", "Requirement already satisfied: MarkupSafe>=2.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from jinja2->torch->bitsandbytes==0.43.0) (2.1.5)\n", "Requirement already satisfied: mpmath>=0.19 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from sympy->torch->bitsandbytes==0.43.0) (1.3.0)\n", "\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n", "\u001b[0m\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n", "\u001b[0m\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n", "\u001b[0mInstallation completed.\n" ] } ], "source": [ "import sys\n", "import site\n", "from pathlib import Path\n", "\n", "!echo \"Installation in progress, please wait...\"\n", "!{sys.executable} -m pip cache purge > /dev/null\n", "!{sys.executable} -m pip install --pre --upgrade \"bigdl-llm[xpu]==2.5.0b20240318\" -f https://developer.intel.com/ipex-whl-stable-xpu\n", "!{sys.executable} -m pip install \"peft==0.5.0\" #> /dev/null\n", "!{sys.executable} -m pip install \"accelerate==0.23.0\" --no-warn-script-location #> /dev/null\n", "!{sys.executable} -m pip install \"transformers==4.34.0\" --no-warn-script-location #> /dev/null \n", "!{sys.executable} -m pip install \"datasets==2.14.6\" --no-warn-script-location #> /dev/null 2>&1 \n", "!{sys.executable} -m pip install \"bitsandbytes==0.43.0\" \"scipy==1.12.0\" #> /dev/null 2>&1\n", "!echo \"Installation completed.\"\n", "\n", "def get_python_version():\n", " return \"python\" + \".\".join(map(str, sys.version_info[:2]))\n", "\n", "def set_local_bin_path():\n", " local_bin = str(Path.home() / \".local\" / \"bin\") \n", " local_site_packages = str(\n", " Path.home() / \".local\" / \"lib\" / get_python_version() / \"site-packages\"\n", " )\n", " sys.path.append(local_bin)\n", " sys.path.insert(0, site.getusersitepackages())\n", " sys.path.insert(0, sys.path.pop(sys.path.index(local_site_packages)))\n", "\n", "set_local_bin_path()" ] }, { "cell_type": "code", "execution_count": 3, "id": "31eb9cf2-abcf-48f8-918b-37a18f85ac7c", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "2024-03-24 01:29:30,660 - root - INFO - intel_extension_for_pytorch auto imported\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/bitsandbytes/libbitsandbytes_cpu.so: undefined symbol: cadam32bit_grad_fp32\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "2024-03-24 01:29:32.212342: I tensorflow/core/util/port.cc:111] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`.\n", "2024-03-24 01:29:32.219815: I tensorflow/tsl/cuda/cudart_stub.cc:28] Could not find cuda drivers on your machine, GPU will not be used.\n", "2024-03-24 01:29:32.245983: E tensorflow/compiler/xla/stream_executor/cuda/cuda_dnn.cc:9342] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\n", "2024-03-24 01:29:32.246003: E tensorflow/compiler/xla/stream_executor/cuda/cuda_fft.cc:609] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered\n", "2024-03-24 01:29:32.246022: E tensorflow/compiler/xla/stream_executor/cuda/cuda_blas.cc:1518] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered\n", "2024-03-24 01:29:32.251166: I tensorflow/tsl/cuda/cudart_stub.cc:28] Could not find cuda drivers on your machine, GPU will not be used.\n", "2024-03-24 01:29:32.251625: I tensorflow/core/platform/cpu_feature_guard.cc:182] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.\n", "To enable the following instructions: AVX2 AVX512F AVX512_VNNI AVX512_BF16 AVX_VNNI AMX_TILE AMX_INT8 AMX_BF16 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.\n", "2024-03-24 01:29:34.718987: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT\n", "2024-03-24 01:29:36.469335: I itex/core/wrapper/itex_cpu_wrapper.cc:60] Intel Extension for Tensorflow* AVX512 CPU backend is loaded.\n", "2024-03-24 01:29:36.877562: I itex/core/wrapper/itex_gpu_wrapper.cc:35] Intel Extension for Tensorflow* GPU backend is loaded.\n", "2024-03-24 01:29:36.959003: I itex/core/devices/gpu/itex_gpu_runtime.cc:129] Selected platform: Intel(R) Level-Zero\n", "2024-03-24 01:29:36.959284: I itex/core/devices/gpu/itex_gpu_runtime.cc:154] number of sub-devices is zero, expose root device.\n" ] } ], "source": [ "import logging\n", "import os\n", "import warnings\n", "import predictionguard as pg\n", "\n", "warnings.filterwarnings(\n", " \"ignore\", category=UserWarning, module=\"intel_extension_for_pytorch\"\n", ")\n", "warnings.filterwarnings(\n", " \"ignore\", category=UserWarning, module=\"torchvision.io.image\", lineno=13\n", ")\n", "warnings.filterwarnings(\n", " \"ignore\",\n", " message=\"The installed version of bitsandbytes was compiled without GPU support.*\",\n", " category=UserWarning,\n", " module='bitsandbytes.cextension'\n", ")\n", "warnings.filterwarnings(\"ignore\")\n", "warnings.filterwarnings(\n", " \"ignore\",\n", " category=FutureWarning,\n", " message=\"This implementation of AdamW is deprecated\",\n", ")\n", "os.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n", "os.environ[\"NUMEXPR_MAX_THREADS\"] = \"28\"\n", "os.environ[\"ENABLE_SDP_FUSION\"] = \"true\"\n", "os.environ[\"SYCL_PI_LEVEL_ZERO_USE_IMMEDIATE_COMMANDLISTS\"]=\"1\"\n", "\n", "os.environ[\"PREDICTIONGUARD_TOKEN\"] = \"q1VuOjnffJ3NO2oFN8Q9m8vghYc84ld13jaqdF7E\"\n", "\n", "logging.getLogger(\"transformers\").setLevel(logging.ERROR)\n", "logging.getLogger(\"bigdl\").setLevel(logging.ERROR)\n", "\n", "\n", "import torch\n", "import intel_extension_for_pytorch as ipex\n", "from datasets import load_dataset\n", "from datasets import Dataset\n", "from bigdl.llm.transformers import AutoModelForCausalLM\n", "from bigdl.llm.transformers.qlora import (\n", " get_peft_model,\n", " prepare_model_for_kbit_training as prepare_model,\n", ")\n", "from peft import LoraConfig\n", "from bigdl.llm.transformers.qlora import PeftModel\n", "import transformers\n", "from transformers import (\n", " BitsAndBytesConfig,\n", " DataCollatorForSeq2Seq,\n", " LlamaTokenizer,\n", " AutoTokenizer,\n", " Trainer,\n", " TrainingArguments,\n", ")\n", "\n", "transformers.logging.set_verbosity_error()" ] }, { "cell_type": "markdown", "id": "02b08285", "metadata": {}, "source": [ "---\n", "\n", "**Note on Model Storage Management**\n", "\n", "A set of LLM foundation models are supported out-of-the-box as stated below `BASE_MDOELS` dictionary. However, if you're interested in experimenting with additional models, consider the following guidelines:\n", "\n", "- **Storage Quota:** Be mindful of your free storage quota and space requirements for additional models.\n", "- **PEFT Library Support:** For models supported by `peft`, refer to the [PEFT repository](https://github.com/huggingface/peft/blob/main/src/peft/utils/other.py#L434) for predefined LoRA target modules.\n", "- **Custom Models:** For non-`peft` models, manually configure LoRA target modules in `LoraConfig`. Example for llama models: `[\"q_proj\", \"k_proj\", \"v_proj\", \"o_proj\"]`.\n", "- **Disk Space Management:** Check disk space with the provided Python function. Delete cache to free space, but this requires re-downloading models later.\n", "- **Reset Model Cache Path:** Update `MODEL_CACHE_PATH = \"~/\"` in the **Model Configuration** cell.\n", "\n", "---\n", "\n", "**Python Function to Check Disk Space**\n", "\n", "```python\n", "# Function to check available disk space in the Hugging Face cache directory\n", "import os\n", "import shutil\n", "\n", "def check_disk_space(path=\"~/.cache/huggingface/\"):\n", " abs_path = os.path.expanduser(path)\n", " total, used, free = shutil.disk_usage(abs_path)\n", " print(f\"Total: {total // (2**30)} GiB\")\n", " print(f\"Used: {used // (2**30)} GiB\")\n", " print(f\"Free: {free // (2**30)} GiB\")\n", "\n", "# Example usage\n", "check_disk_space()\n", "```\n" ] }, { "cell_type": "markdown", "id": "131864cb-ce5d-405b-8886-5d0f1f487c30", "metadata": {}, "source": [ "---\n", "\n", "**Tailoring Your Model Configuration**\n", "\n", "Dive into the customization core of LLM fine-tuning, equipped with a diverse range of base models to suit unique goals.\n", "\n", "- **Model Choices in `BASE_MODELS`**: \n", " - From the `open_llama_3b_v2` to the broader `Llama-2-13b-hf`.\n", " - Specialized options like `CodeLlama-7b-hf`.\n", " - Experiment to find the best fit for your objectives.\n", "\n", "- **Dataset**:\n", " - Using `b-mc2/sql-create-context` from Huggingface datasets, a set of 78,577 examples (natural language queries, SQL statements).\n", " - Ideal for text-to-SQL models. Dataset details [here](https://huggingface.co/datasets/b-mc2/sql-create-context).\n", "\n", "- **Your Model Options**: Within the `BASE_MODELS`, youโ€™ll find options ranging from the nimble\n", " `open_llama_7b_v2` to the more expansive `Llama-2-13b-hf`, and specialized variants like `CodeLlama-7b-hf`.\n", " Feel free to switch between these models to discover which one aligns best with your objectives.\n", "\n", "- **LoRA Parameters - Your Knobs to Turn**:\n", " - `r` (Rank): This is a key factor in how finely your model can adapt. A higher rank can grasp more\n", " complex nuances, while a lower rank ensures a leaner memory footprint.\n", " - `lora_alpha` (Scaling Factor): Adjusts LoRA adapters' impact.\n", " the integrity of the pre-trained weights.\n", " - `target_modules`: You decide which parts of the transformer model to enhance with LoRA adapters,\n", " directly impacting how your model interprets and generates language.\n", " - `lora_dropout`: Controls overfitting; experiment for optimal generalization.\n", " - `bias`: Modify to observe learning dynamic changes.\n", "\n", "This notebook is set to start with `CodeLlama-7b-hf` as the default model, as our task is to generate code. To use models like Llama 2, you will have to accept the usage policy as stipulated [here](https://ai.meta.com/llama/use-policy/)\n" ] }, { "cell_type": "code", "execution_count": 4, "id": "88077cc2-8fcf-4128-ac44-9fb2bb327398", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "================================================================================\n", "Using Device: xpu\n", "Final model will be saved to: ./final_model\n", "LoRA adapters will be saved to: ./lora_adapters\n", "Finetuning Model: NousResearch/CodeLlama-7b-hf\n", "Using dataset from: b-mc2/sql-create-context\n", "Model cache: /home/common/data/Big_Data/GenAI/llm_models\n", "================================================================================\n" ] } ], "source": [ "BASE_MODELS = {\n", " \"0\": \"NousResearch/Nous-Hermes-Llama-2-7b\", # https://huggingface.co/NousResearch/Nous-Hermes-llama-2-7b\n", " \"1\": \"NousResearch/Llama-2-7b-chat-hf\", # https://huggingface.co/NousResearch/Llama-2-7b-chat-hf\n", " \"2\": \"NousResearch/Llama-2-13b-hf\", # https://huggingface.co/NousResearch/Llama-2-13b-hf\n", " \"3\": \"NousResearch/CodeLlama-7b-hf\", # https://huggingface.co/NousResearch/CodeLlama-7b-hf\n", " \"4\": \"Phind/Phind-CodeLlama-34B-v2\", # https://huggingface.co/Phind/Phind-CodeLlama-34B-v2\n", " \"5\": \"openlm-research/open_llama_3b_v2\", # https://huggingface.co/openlm-research/open_llama_3b_v2\n", " \"6\": \"openlm-research/open_llama_13b\", # https://huggingface.co/openlm-research/open_llama_13b\n", " \"7\": \"HuggingFaceH4/zephyr-7b-beta\", # https://huggingface.co/HuggingFaceH4/zephyr-7b-beta\n", "}\n", "BASE_MODEL = BASE_MODELS[\"3\"]\n", "DATA_PATH = \"b-mc2/sql-create-context\"\n", "MODEL_PATH = \"./final_model\"\n", "ADAPTER_PATH = \"./lora_adapters\"\n", "DEVICE = torch.device(\"xpu\" if torch.xpu.is_available() else \"cpu\")\n", "LORA_CONFIG = LoraConfig(\n", " r=16, # rank\n", " lora_alpha=32, # scaling factor\n", " target_modules=[\"q_proj\", \"k_proj\", \"v_proj\"], \n", " lora_dropout=0.05,\n", " bias=\"none\",\n", " task_type=\"CAUSAL_LM\",\n", ")\n", "MODEL_CACHE_PATH = \"/home/common/data/Big_Data/GenAI/llm_models\"\n", "\n", "print(\"=\" * 80)\n", "print(f\"Using Device: {DEVICE}\")\n", "print(f\"Final model will be saved to: {MODEL_PATH}\")\n", "print(f\"LoRA adapters will be saved to: {ADAPTER_PATH}\")\n", "print(f\"Finetuning Model: {BASE_MODEL}\")\n", "print(f\"Using dataset from: {DATA_PATH}\")\n", "print(f\"Model cache: {MODEL_CACHE_PATH}\")\n", "print(\"=\" * 80)" ] }, { "cell_type": "markdown", "id": "d797b621-fd06-4ae9-a883-d7d15f16d6c4", "metadata": {}, "source": [ "---\n", "\n", "**Prompt Engineering for Text-to-SQL Conversion**\n", "\n", "In the realm of fine-tuning language models for specialized tasks, the design of the prompt is pivotal. The function `generate_prompt_sql` encapsulates the input question, the relevant database context, and the expected output in a structured and concise manner.\n" ] }, { "cell_type": "code", "execution_count": 5, "id": "d8ecd7df-b7ce-48b0-ba9f-04b7ec0c1cf4", "metadata": {}, "outputs": [], "source": [ "def generate_prompt_sql(input_question, context, output=\"\"):\n", " \"\"\"\n", " Generates a prompt for fine-tuning the LLM model for text-to-SQL tasks.\n", "\n", " Parameters:\n", " input_question (str): The input text or question to be converted to SQL.\n", " context (str): The schema or context in which the SQL query operates.\n", " output (str, optional): The expected SQL query as the output.\n", "\n", " Returns:\n", " str: A formatted string serving as the prompt for the fine-tuning task.\n", " \"\"\"\n", " return f\"\"\"You are a powerful text-to-SQL model. Your job is to answer questions about a database. You are given a question and context regarding one or more tables.\"\"\" \n", "\n", "### Input:\n", "input_question = str(\"How many employees live in california\")\n", "\n", "### Context:\n", "context = str(\"the number of approximate employees worldwide, country, and state they are in a single company\")\n", "\n", "### Response:\n", "response = f\"Knowing {context}, can you answer {input_question}?\"\n", "\n", "output = \"Select from table employees with california home\" #approximately" ] }, { "cell_type": "markdown", "id": "9dd863cc", "metadata": {}, "source": [ "---\n", "\n", "**Model Loading and Configuration**\n", "\n", "Initializing the `FineTuner`, we load the base model using `base_model_id`. Key to this setup is the ` bnb_4bit_quant_type=\"nf4\"` option, using bitsandbytes library, checkout [BigDL library](https://bigdl.readthedocs.io/en/latest/) for more information on this. This approach significantly cuts down on memory. Additionally, we configure the LoRA adapters for mixed-precision training with `torch.float16`.\n" ] }, { "cell_type": "code", "execution_count": 6, "id": "aeab82dc", "metadata": {}, "outputs": [], "source": [ "def setup_model_and_tokenizer(base_model_id: str):\n", " \"\"\"Downloads / Loads the pre-trained model and tokenizer based on the given base model ID for training, \n", " with fallbacks for permission errors to use default cache.\"\"\"\n", " local_model_id = base_model_id.replace(\"/\", \"--\")\n", " local_model_path = os.path.join(MODEL_CACHE_PATH, local_model_id)\n", "\n", " bnb_config = BitsAndBytesConfig(\n", " load_in_8bit=True,\n", " bnb_4bit_use_double_quant=False,\n", " bnb_4bit_quant_type=\"nf4\",\n", " bnb_4bit_compute_dtype=torch.bfloat16,\n", " accelerator='onnxruntime',\n", " )\n", " try:\n", " print(f\"Attempting to load model and tokenizer from: {local_model_path}\")\n", " model = AutoModelForCausalLM.from_pretrained(\n", " local_model_path,\n", " quantization_config=bnb_config,\n", " )\n", " tokenizer_class = LlamaTokenizer if \"llama\" in base_model_id.lower() else AutoTokenizer\n", " tokenizer = tokenizer_class.from_pretrained(local_model_path)\n", " except (OSError, PermissionError) as e:\n", " print(f\"Failed to load from {local_model_path} due to {e}. Attempting to download...\")\n", " model = AutoModelForCausalLM.from_pretrained(\n", " base_model_id, \n", " quantization_config=bnb_config,\n", " )\n", " tokenizer_class = LlamaTokenizer if \"llama\" in base_model_id.lower() else AutoTokenizer\n", " tokenizer = tokenizer_class.from_pretrained(base_model_id)\n", "\n", " tokenizer.pad_token_id = 0\n", " tokenizer.padding_side = \"left\"\n", " return model, tokenizer\n", "\n" ] }, { "cell_type": "markdown", "id": "3777656b-74f4-4ebc-b741-a5d50bc6e79a", "metadata": {}, "source": [ "---\n", "\n", "**FineTuner**\n", "\n", "The `FineTuner` class encapsulates the entire process of fine-tuning llms for tasks such as text-to-SQL conversion.\n", "\n", "\n", "**Tokenization Strategy**\n", "\n", "The tokenization process is tailored to the type of model being fine-tuned. For instance, if we are working with a Llama model, we utilize a `LlamaTokenizer` to ensure compatibility with the model's expected input format. For other models, a generic `AutoTokenizer` is used. We configure the tokenizer to pad from the left side (`padding_side=\"left\"`) and set the pad token ID to 0.\n", "\n", "**Data Tokenization and Preparation**\n", "\n", "The `tokenize_data` method is where the fine-tuner ingests raw text data and converts it into a format suitable for training the model. This method handles the addition of end-of-sequence tokens, truncation to a specified `cutoff_len`, and conditioning on the input for training.\n", "\n", "**Dataset Handling**\n", "\n", "`prepare_data` manages the splitting of data into training and validation sets, applying the `tokenize_data` transformation to each entry. This ensures that our datasets are ready for input into the model, with all necessary tokenization applied.\n", "\n", "**Training Process**\n", "\n", "Finally, the `train_model` method orchestrates the training process, setting up the `Trainer` with the correct datasets, training arguments, and data collator. The fine-tuning process is encapsulated within the `finetune` method, which strings together all the previous steps into a coherent pipeline, from model setup to training execution.\n", "\n", "**Using QLoRA for Efficient Fine-Tuning**\n", "1. Load a pretrained model (e.g., LLaMA2) in low precision with ` bnb_4bit_quant_type=\"nf4\"` for 4-bit quantized weights.\n", "2. Prepare the quantized model with `prepare_model(model)`, handling weight quantization.\n", "3. Add LoRA adapters via `get_peft_model(model, config)` for setting adapter parameters.\n", "4. Fine-tune with `Trainer`, focusing gradients on adapters while keeping base model weights fixed.\n", "\n", "**Code Implementation**\n", "- Model loading with BigDL's `AutoModelForCausalLM`, initializing in 4-bit using `load_in_low_bit=\"nf4\"`.\n", "- `prepare_model()` quantizes the model weights.\n", "- `get_peft_model()` adds LoRA adapters.\n", "- Trainer handles fine-tuning, optimizing only adapter weights.\n", "\n", "\n", "So in summary, we leverage QLoRA in BigDL to load the base LLM in low precision, inject adapters with `peft`, and efficiently finetune by optimizing just the adapters end-to-end while keeping the base model fixed. This unlocks huge memory savings, allowing us to adapt giant models." ] }, { "cell_type": "code", "execution_count": 7, "id": "4d8f4cb8-0da5-4572-bd07-bdae1db897a3", "metadata": {}, "outputs": [], "source": [ "class FineTuner:\n", " \"\"\"A class to handle the fine-tuning of LLM models.\"\"\"\n", "\n", " def __init__(self, base_model_id: str, model_path: str, device: torch.device):\n", " \"\"\"\n", " Initialize the FineTuner with base model, model path, and device.\n", "\n", " Parameters:\n", " base_model_id (str): Id of pre-trained model to use for fine-tuning.\n", " model_path (str): Path to save the fine-tuned model.\n", " device (torch.device): Device to run the model on.\n", " \"\"\"\n", " self.base_model_id = base_model_id\n", " self.model_path = model_path\n", " self.device = device\n", " self.model, self.tokenizer = setup_model_and_tokenizer(base_model_id)\n", "\n", "\n", " def tokenize_data(\n", " self, data_points, add_eos_token=True, train_on_inputs=False, cutoff_len=512\n", " ) -> dict:\n", " \"\"\"\n", " Tokenizes dataset of SQL related data points consisting of questions, context, and answers.\n", "\n", " Parameters:\n", " data_points (dict): A batch from the dataset containing 'question', 'context', and 'answer'.\n", " add_eos_token (bool): Whether to add an EOS token at the end of each tokenized sequence.\n", " cutoff_len (int): The maximum length for each tokenized sequence.\n", "\n", " Returns:\n", " dict: A dictionary containing tokenized 'input_ids', 'attention_mask', and 'labels'.\n", " \"\"\"\n", " try:\n", " question = data_points[\"question\"]\n", " context = data_points[\"context\"]\n", " answer = data_points[\"answer\"]\n", " if train_on_inputs:\n", " user_prompt = generate_prompt_sql(question, context)\n", " tokenized_user_prompt = self.tokenizer(\n", " user_prompt,\n", " truncation=True,\n", " max_length=cutoff_len,\n", " padding=False,\n", " return_tensors=None,\n", " )\n", " user_prompt_len = len(tokenized_user_prompt[\"input_ids\"])\n", " if add_eos_token:\n", " user_prompt_len -= 1\n", "\n", " combined_text = generate_prompt_sql(question, context, answer)\n", " tokenized = self.tokenizer(\n", " combined_text,\n", " truncation=True,\n", " max_length=cutoff_len,\n", " padding=False,\n", " return_tensors=None,\n", " )\n", " if (\n", " tokenized[\"input_ids\"][-1] != self.tokenizer.eos_token_id\n", " and add_eos_token\n", " and len(tokenized[\"input_ids\"]) < cutoff_len\n", " ):\n", " tokenized[\"input_ids\"].append(self.tokenizer.eos_token_id)\n", " tokenized[\"attention_mask\"].append(1)\n", " tokenized[\"labels\"] = tokenized[\"input_ids\"].copy()\n", " if train_on_inputs:\n", " tokenized[\"labels\"] = [-100] * user_prompt_len + tokenized[\"labels\"][\n", " user_prompt_len:\n", " ]\n", " return tokenized\n", " except Exception as e:\n", " logging.error(\n", " f\"Error in batch tokenization: {e}\"\n", " )\n", " raise e\n", "\n", " def prepare_data(self, data, val_set_size=100) -> Dataset:\n", " \"\"\"Prepare training and validation datasets.\"\"\"\n", " try:\n", " train_val_split = data[\"train\"].train_test_split(\n", " test_size=val_set_size, shuffle=True, seed=42\n", " )\n", " train_data = train_val_split[\"train\"].shuffle().map(self.tokenize_data)\n", " val_data = train_val_split[\"test\"].shuffle().map(self.tokenize_data)\n", " return train_data, val_data\n", " except Exception as e:\n", " logging.error(\n", " f\"Error in preparing data: {e}\"\n", " )\n", " raise e\n", "\n", " def train_model(self, train_data, val_data, training_args):\n", " \"\"\"\n", " Fine-tune the model with the given training and validation data.\n", "\n", " Parameters:\n", " train_data (Dataset): Training data.\n", " val_data (Optional[Dataset]): Validation data.\n", " training_args (TrainingArguments): Training configuration.\n", " \"\"\"\n", " try:\n", " self.model = self.model.to(self.device)\n", " self.model.gradient_checkpointing_enable()\n", " self.model = prepare_model(self.model)\n", " self.model = get_peft_model(self.model, LORA_CONFIG)\n", " trainer = Trainer(\n", " model=self.model,\n", " train_dataset=train_data,\n", " eval_dataset=val_data,\n", " args=training_args,\n", " data_collator=DataCollatorForSeq2Seq(\n", " self.tokenizer,\n", " pad_to_multiple_of=8,\n", " return_tensors=\"pt\",\n", " padding=True,\n", " ),\n", " )\n", " self.model.config.use_cache = False\n", " results = trainer.train()\n", " #print(results)\n", " self.model.save_pretrained(self.model_path)\n", " except Exception as e:\n", " logging.error(f\"Error in model training: {e}\")\n", "\n", " def finetune(self, data_path, training_args):\n", " \"\"\"\n", " Execute the fine-tuning pipeline.\n", "\n", " Parameters:\n", " data_path (str): Path to the data for fine-tuning.\n", " training_args (TrainingArguments): Training configuration.\n", " \"\"\"\n", " try:\n", " data = load_dataset(data_path)\n", " train_data, val_data = self.prepare_data(data)\n", " self.train_model(train_data, val_data, training_args)\n", " except KeyboardInterrupt:\n", " print(\"Interrupt received, saving model...\")\n", " self.model.save_pretrained(f\"{self.model_path}_interrupted\")\n", " print(f\"Model saved to {self.model_path}_interrupted\")\n", " except Exception as e:\n", " logging.error(f\"Error in fintuning: {e}\")" ] }, { "cell_type": "markdown", "id": "34af4187-d362-49b8-bdbc-e8d2a7ae0ac0", "metadata": {}, "source": [ "---\n", "**Fine-Tuning the Model**\n", "\n", "The `lets_finetune` function orchestrates the fine-tuning process, offering a customizable interface for training. It enables specification of device, model, batch size, warm-up steps, learning rate, and maximum training steps.\n", "\n", "\n", "**Some of the key Training Parameters:**\n", "- `per_device_batch_size`: Number of batches on each XPU.\n", "- `gradient_accumulation_steps`: Enables larger effective batch sizes.\n", "- `warmup_steps`: Stabilizes training dynamics at the start.\n", "- `save_steps`: Determines checkpoint frequency.\n", "- `max_steps`: Limits training iterations, start with a high number like 1000 or 2000 (default here is `200`).\n", "- `learning_rate`: Balances convergence speed and training stability.\n", "- `max_grad_norm`: Clips gradients to avoid excessively large values.\n", "\n", "**Monitoring and Interruption**\n", "- Monitor training/validation loss to identify optimal stopping point.\n", "- Interrupt training in Jupyter via `Kernel -> Interrupt Kernel` if performance is satisfactory before `max_steps`.\n", "- Latest checkpoint is saved in `./final_model_interrupted`; last saved adapter checkpoint in `./lora_adapters`.\n", "\n", "This setup allows for efficient and flexible model fine-tuning, adaptable to varying project needs and computational constraints.\n", "\n", "---\n" ] }, { "cell_type": "code", "execution_count": 8, "id": "67a39122-eafc-483c-ad81-9c55de15e936", "metadata": {}, "outputs": [], "source": [ "ENABLE_WANDB = True\n", "\n", "def lets_finetune(\n", " device=DEVICE,\n", " model=BASE_MODEL,\n", " per_device_batch_size=4,\n", " warmup_steps=20,\n", " learning_rate=2e-5,\n", " max_steps=200,\n", " gradient_accum_steps=4,\n", "):\n", " try:\n", " # Training parameters\n", " save_steps = 20\n", " eval_steps = 20\n", " max_grad_norm = 0.3\n", " save_total_limit = 3\n", " logging_steps = 20\n", "\n", " print(\"\\n\" + \"\\033[1;34m\" + \"=\" * 60 + \"\\033[0m\")\n", " print(\"\\033[1;34mTraining Parameters:\\033[0m\")\n", " param_format = \"\\033[1;34m{:<25} {}\\033[0m\"\n", " print(param_format.format(\"Foundation model:\", BASE_MODEL))\n", " print(param_format.format(\"Model save path:\", MODEL_PATH))\n", " print(param_format.format(\"Device used:\", DEVICE))\n", " if DEVICE.type.startswith(\"xpu\"):\n", " print(param_format.format(\"Intel GPU:\", torch.xpu.get_device_name()))\n", " print(param_format.format(\"Batch size per device:\", per_device_batch_size))\n", " print(param_format.format(\"Gradient accum. steps:\", gradient_accum_steps))\n", " print(param_format.format(\"Warmup steps:\", warmup_steps))\n", " print(param_format.format(\"Save steps:\", save_steps))\n", " print(param_format.format(\"Evaluation steps:\", eval_steps))\n", " print(param_format.format(\"Max steps:\", max_steps))\n", " print(param_format.format(\"Learning rate:\", learning_rate))\n", " print(param_format.format(\"Max gradient norm:\", max_grad_norm))\n", " print(param_format.format(\"Save total limit:\", save_total_limit))\n", " print(param_format.format(\"Logging steps:\", logging_steps))\n", " print(\"\\033[1;34m\" + \"=\" * 60 + \"\\033[0m\\n\")\n", "\n", " # Initialize the finetuner with the model and device information\n", " finetuner = FineTuner(\n", " base_model_id=model, model_path=MODEL_PATH, device=device\n", " )\n", "\n", " training_args = TrainingArguments(\n", " per_device_train_batch_size=per_device_batch_size,\n", " gradient_accumulation_steps=gradient_accum_steps,\n", " warmup_steps=warmup_steps,\n", " save_steps=save_steps,\n", " save_strategy=\"steps\",\n", " eval_steps=eval_steps,\n", " evaluation_strategy=\"steps\",\n", " max_steps=max_steps,\n", " learning_rate=learning_rate,\n", " #max_grad_norm=max_grad_norm,\n", " bf16=True,\n", " use_ipex=True,\n", " #lr_scheduler_type=\"cosine\",\n", " load_best_model_at_end=True,\n", " ddp_find_unused_parameters=False,\n", " group_by_length=True,\n", " save_total_limit=save_total_limit,\n", " logging_steps=logging_steps,\n", " optim=\"adamw_hf\",\n", " output_dir=\"./lora_adapters\",\n", " logging_dir=\"./logs\",\n", " report_to=\"wandb\" if ENABLE_WANDB else [],\n", " )\n", " # Start fine-tuning\n", " finetuner.finetune(DATA_PATH, training_args)\n", " except Exception as e:\n", " logging.error(f\"Error occurred: {e}\")" ] }, { "cell_type": "markdown", "id": "5ddc5dee-498b-498a-9ad8-d03f569e9e9a", "metadata": {}, "source": [ "We can optionally use Weights & Biases to track our training metrics, uncomment the below cell to enable `wandb`. You will need to pass in your API key when prompted. You can ofcourse skip this step if you'd like to.\n" ] }, { "cell_type": "code", "execution_count": 9, "id": "f1a31697-8bf5-4ec9-9e13-bb7095218fcd", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "installing wandb...\n", "installation complete...\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "2024-03-24 01:30:49,246 - wandb.jupyter - ERROR - Failed to detect the name of this notebook, you can set it manually with the WANDB_NOTEBOOK_NAME environment variable to enable code saving.\n", "2024-03-24 01:30:54,065 - wandb.sdk.lib.retry - INFO - Retry attempt failed:\n", "Traceback (most recent call last):\n", " File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/connectionpool.py\", line 793, in urlopen\n", " response = self._make_request(\n", " File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/connectionpool.py\", line 491, in _make_request\n", " raise new_e\n", " File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/connectionpool.py\", line 467, in _make_request\n", " self._validate_conn(conn)\n", " File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/connectionpool.py\", line 1099, in _validate_conn\n", " conn.connect()\n", " File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/connection.py\", line 653, in connect\n", " sock_and_verified = _ssl_wrap_socket_and_match_hostname(\n", " File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/connection.py\", line 806, in _ssl_wrap_socket_and_match_hostname\n", " ssl_sock = ssl_wrap_socket(\n", " File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/util/ssl_.py\", line 465, in ssl_wrap_socket\n", " ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls, server_hostname)\n", " File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/util/ssl_.py\", line 509, in _ssl_wrap_socket_impl\n", " return ssl_context.wrap_socket(sock, server_hostname=server_hostname)\n", " File \"/opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/ssl.py\", line 501, in wrap_socket\n", " return self.sslsocket_class._create(\n", " File \"/opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/ssl.py\", line 1074, in _create\n", " self.do_handshake()\n", " File \"/opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/ssl.py\", line 1343, in do_handshake\n", " self._sslobj.do_handshake()\n", "ConnectionResetError: [Errno 104] Connection reset by peer\n", "\n", "During handling of the above exception, another exception occurred:\n", "\n", "Traceback (most recent call last):\n", " File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/requests/adapters.py\", line 486, in send\n", " resp = conn.urlopen(\n", " File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/connectionpool.py\", line 847, in urlopen\n", " retries = retries.increment(\n", " File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/util/retry.py\", line 470, in increment\n", " raise reraise(type(error), error, _stacktrace)\n", " File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/util/util.py\", line 38, in reraise\n", " raise value.with_traceback(tb)\n", " File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/connectionpool.py\", line 793, in urlopen\n", " response = self._make_request(\n", " File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/connectionpool.py\", line 491, in _make_request\n", " raise new_e\n", " File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/connectionpool.py\", line 467, in _make_request\n", " self._validate_conn(conn)\n", " File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/connectionpool.py\", line 1099, in _validate_conn\n", " conn.connect()\n", " File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/connection.py\", line 653, in connect\n", " sock_and_verified = _ssl_wrap_socket_and_match_hostname(\n", " File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/connection.py\", line 806, in _ssl_wrap_socket_and_match_hostname\n", " ssl_sock = ssl_wrap_socket(\n", " File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/util/ssl_.py\", line 465, in ssl_wrap_socket\n", " ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls, server_hostname)\n", " File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/util/ssl_.py\", line 509, in _ssl_wrap_socket_impl\n", " return ssl_context.wrap_socket(sock, server_hostname=server_hostname)\n", " File \"/opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/ssl.py\", line 501, in wrap_socket\n", " return self.sslsocket_class._create(\n", " File \"/opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/ssl.py\", line 1074, in _create\n", " self.do_handshake()\n", " File \"/opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/ssl.py\", line 1343, in do_handshake\n", " self._sslobj.do_handshake()\n", "urllib3.exceptions.ProtocolError: ('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))\n", "\n", "During handling of the above exception, another exception occurred:\n", "\n", "Traceback (most recent call last):\n", " File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/wandb/sdk/lib/retry.py\", line 131, in __call__\n", " result = self._call_fn(*args, **kwargs)\n", " File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/wandb/sdk/internal/internal_api.py\", line 366, in execute\n", " return self.client.execute(*args, **kwargs) # type: ignore\n", " File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/wandb/vendor/gql-0.2.0/wandb_gql/client.py\", line 52, in execute\n", " result = self._get_result(document, *args, **kwargs)\n", " File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/wandb/vendor/gql-0.2.0/wandb_gql/client.py\", line 60, in _get_result\n", " return self.transport.execute(document, *args, **kwargs)\n", " File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/wandb/sdk/lib/gql_request.py\", line 58, in execute\n", " request = self.session.post(self.url, **post_args)\n", " File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/requests/sessions.py\", line 637, in post\n", " return self.request(\"POST\", url, data=data, json=json, **kwargs)\n", " File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/requests/sessions.py\", line 589, in request\n", " resp = self.send(prep, **send_kwargs)\n", " File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/requests/sessions.py\", line 703, in send\n", " r = adapter.send(request, **kwargs)\n", " File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/requests/adapters.py\", line 501, in send\n", " raise ConnectionError(err, request=request)\n", "requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))\n", "\u001b[34m\u001b[1mwandb\u001b[0m: Network error (ConnectionError), entering retry loop.\n", "\u001b[34m\u001b[1mwandb\u001b[0m: W&B API key is configured. Use \u001b[1m`wandb login --relogin`\u001b[0m to force relogin\n" ] } ], "source": [ "if ENABLE_WANDB:\n", " print(\"installing wandb...\")\n", " !{sys.executable} -m pip install -U --force \"wandb==0.15.12\" > /dev/null 2>&1\n", " print(\"installation complete...\")\n", "\n", " import wandb\n", " os.environ[\"WANDB_PROJECT\"] = f\"text-to-sql-finetune-model-name_{BASE_MODEL.replace('/', '_')}\"\n", " os.environ[\"WANDB_LOG_MODEL\"] = \"checkpoint\"\n", " wandb.login()" ] }, { "cell_type": "markdown", "id": "c497cbaf-994b-474b-92f1-fb33fca6b81f", "metadata": {}, "source": [ "\n", "---\n", "\n", "**Let's Finetune!**\n", "\n", "Now it's time to actually fine-tune the model. The `lets_finetune` function below takes care of this. It initializes a FineTuner object with the configurations you've set or left as default." ] }, { "cell_type": "code", "execution_count": 10, "id": "1fa45c6d-fac1-4331-8dd5-3ebf9cceed6d", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\u001b[1;34m============================================================\u001b[0m\n", "\u001b[1;34mTraining Parameters:\u001b[0m\n", "\u001b[1;34mFoundation model: NousResearch/CodeLlama-7b-hf\u001b[0m\n", "\u001b[1;34mModel save path: ./final_model\u001b[0m\n", "\u001b[1;34mDevice used: xpu\u001b[0m\n", "\u001b[1;34mIntel GPU: Intel(R) Data Center GPU Max 1100\u001b[0m\n", "\u001b[1;34mBatch size per device: 4\u001b[0m\n", "\u001b[1;34mGradient accum. steps: 4\u001b[0m\n", "\u001b[1;34mWarmup steps: 20\u001b[0m\n", "\u001b[1;34mSave steps: 20\u001b[0m\n", "\u001b[1;34mEvaluation steps: 20\u001b[0m\n", "\u001b[1;34mMax steps: 200\u001b[0m\n", "\u001b[1;34mLearning rate: 2e-05\u001b[0m\n", "\u001b[1;34mMax gradient norm: 0.3\u001b[0m\n", "\u001b[1;34mSave total limit: 3\u001b[0m\n", "\u001b[1;34mLogging steps: 20\u001b[0m\n", "\u001b[1;34m============================================================\u001b[0m\n", "\n", "Attempting to load model and tokenizer from: /home/common/data/Big_Data/GenAI/llm_models/NousResearch--CodeLlama-7b-hf\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "118e0ed053b744399bd7b4509b2269c4", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Loading checkpoint shards: 0%| | 0/3 [00:00 705\u001b[0m config_dict \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mcls\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_dict_from_json_file\u001b[49m\u001b[43m(\u001b[49m\u001b[43mresolved_config_file\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 706\u001b[0m config_dict[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m_commit_hash\u001b[39m\u001b[38;5;124m\"\u001b[39m] \u001b[38;5;241m=\u001b[39m commit_hash\n", "File \u001b[0;32m~/.local/lib/python3.9/site-packages/transformers/configuration_utils.py:801\u001b[0m, in \u001b[0;36mPretrainedConfig._dict_from_json_file\u001b[0;34m(cls, json_file)\u001b[0m\n\u001b[1;32m 800\u001b[0m text \u001b[38;5;241m=\u001b[39m reader\u001b[38;5;241m.\u001b[39mread()\n\u001b[0;32m--> 801\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mjson\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mloads\u001b[49m\u001b[43m(\u001b[49m\u001b[43mtext\u001b[49m\u001b[43m)\u001b[49m\n", "File \u001b[0;32m/opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/json/__init__.py:346\u001b[0m, in \u001b[0;36mloads\u001b[0;34m(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)\u001b[0m\n\u001b[1;32m 343\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m (\u001b[38;5;28mcls\u001b[39m \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m object_hook \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m\n\u001b[1;32m 344\u001b[0m parse_int \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m parse_float \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m\n\u001b[1;32m 345\u001b[0m parse_constant \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m object_pairs_hook \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m kw):\n\u001b[0;32m--> 346\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43m_default_decoder\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mdecode\u001b[49m\u001b[43m(\u001b[49m\u001b[43ms\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 347\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mcls\u001b[39m \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n", "File \u001b[0;32m/opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/json/decoder.py:337\u001b[0m, in \u001b[0;36mJSONDecoder.decode\u001b[0;34m(self, s, _w)\u001b[0m\n\u001b[1;32m 333\u001b[0m \u001b[38;5;250m\u001b[39m\u001b[38;5;124;03m\"\"\"Return the Python representation of ``s`` (a ``str`` instance\u001b[39;00m\n\u001b[1;32m 334\u001b[0m \u001b[38;5;124;03mcontaining a JSON document).\u001b[39;00m\n\u001b[1;32m 335\u001b[0m \n\u001b[1;32m 336\u001b[0m \u001b[38;5;124;03m\"\"\"\u001b[39;00m\n\u001b[0;32m--> 337\u001b[0m obj, end \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mraw_decode\u001b[49m\u001b[43m(\u001b[49m\u001b[43ms\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43midx\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43m_w\u001b[49m\u001b[43m(\u001b[49m\u001b[43ms\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m0\u001b[39;49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mend\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 338\u001b[0m end \u001b[38;5;241m=\u001b[39m _w(s, end)\u001b[38;5;241m.\u001b[39mend()\n", "File \u001b[0;32m/opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/json/decoder.py:355\u001b[0m, in \u001b[0;36mJSONDecoder.raw_decode\u001b[0;34m(self, s, idx)\u001b[0m\n\u001b[1;32m 354\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mStopIteration\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m err:\n\u001b[0;32m--> 355\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m JSONDecodeError(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mExpecting value\u001b[39m\u001b[38;5;124m\"\u001b[39m, s, err\u001b[38;5;241m.\u001b[39mvalue) \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m\n\u001b[1;32m 356\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m obj, end\n", "\u001b[0;31mJSONDecodeError\u001b[0m: Expecting value: line 1 column 1 (char 0)", "\nDuring handling of the above exception, another exception occurred:\n", "\u001b[0;31mOSError\u001b[0m Traceback (most recent call last)", "Cell \u001b[0;32mIn[11], line 14\u001b[0m\n\u001b[1;32m 11\u001b[0m checkpoint_path \u001b[38;5;241m=\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mFredswqa1/DysfunctEcosenseLLM\u001b[39m\u001b[38;5;124m\"\u001b[39m \u001b[38;5;66;03m# Replace with your checkpoint folder\u001b[39;00m\n\u001b[1;32m 13\u001b[0m \u001b[38;5;66;03m# Load the model\u001b[39;00m\n\u001b[0;32m---> 14\u001b[0m model \u001b[38;5;241m=\u001b[39m \u001b[43mAutoModelForSequenceClassification\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mfrom_pretrained\u001b[49m\u001b[43m(\u001b[49m\u001b[43mcheckpoint_path\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 16\u001b[0m \u001b[38;5;66;03m# Load the tokenizer\u001b[39;00m\n\u001b[1;32m 17\u001b[0m tokenizer \u001b[38;5;241m=\u001b[39m AutoTokenizer\u001b[38;5;241m.\u001b[39mfrom_pretrained(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mLlamaTokenizer\u001b[39m\u001b[38;5;124m\"\u001b[39m) \u001b[38;5;66;03m#add name of your model's tokenizer on Hugging Face OR custom tokenizer\u001b[39;00m\n", "File \u001b[0;32m~/.local/lib/python3.9/site-packages/transformers/models/auto/auto_factory.py:525\u001b[0m, in \u001b[0;36m_BaseAutoModelClass.from_pretrained\u001b[0;34m(cls, pretrained_model_name_or_path, *model_args, **kwargs)\u001b[0m\n\u001b[1;32m 522\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m kwargs\u001b[38;5;241m.\u001b[39mget(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mquantization_config\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;28;01mNone\u001b[39;00m) \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[1;32m 523\u001b[0m _ \u001b[38;5;241m=\u001b[39m kwargs\u001b[38;5;241m.\u001b[39mpop(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mquantization_config\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m--> 525\u001b[0m config, kwargs \u001b[38;5;241m=\u001b[39m \u001b[43mAutoConfig\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mfrom_pretrained\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 526\u001b[0m \u001b[43m \u001b[49m\u001b[43mpretrained_model_name_or_path\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 527\u001b[0m \u001b[43m \u001b[49m\u001b[43mreturn_unused_kwargs\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;28;43;01mTrue\u001b[39;49;00m\u001b[43m,\u001b[49m\n\u001b[1;32m 528\u001b[0m \u001b[43m \u001b[49m\u001b[43mtrust_remote_code\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mtrust_remote_code\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 529\u001b[0m \u001b[43m \u001b[49m\u001b[43mcode_revision\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mcode_revision\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 530\u001b[0m \u001b[43m \u001b[49m\u001b[43m_commit_hash\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mcommit_hash\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 531\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mhub_kwargs\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 532\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 533\u001b[0m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 535\u001b[0m \u001b[38;5;66;03m# if torch_dtype=auto was passed here, ensure to pass it on\u001b[39;00m\n\u001b[1;32m 536\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m kwargs_orig\u001b[38;5;241m.\u001b[39mget(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mtorch_dtype\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;28;01mNone\u001b[39;00m) \u001b[38;5;241m==\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mauto\u001b[39m\u001b[38;5;124m\"\u001b[39m:\n", "File \u001b[0;32m~/.local/lib/python3.9/site-packages/transformers/models/auto/configuration_auto.py:1034\u001b[0m, in \u001b[0;36mAutoConfig.from_pretrained\u001b[0;34m(cls, pretrained_model_name_or_path, **kwargs)\u001b[0m\n\u001b[1;32m 1031\u001b[0m trust_remote_code \u001b[38;5;241m=\u001b[39m kwargs\u001b[38;5;241m.\u001b[39mpop(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mtrust_remote_code\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;28;01mNone\u001b[39;00m)\n\u001b[1;32m 1032\u001b[0m code_revision \u001b[38;5;241m=\u001b[39m kwargs\u001b[38;5;241m.\u001b[39mpop(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mcode_revision\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;28;01mNone\u001b[39;00m)\n\u001b[0;32m-> 1034\u001b[0m config_dict, unused_kwargs \u001b[38;5;241m=\u001b[39m \u001b[43mPretrainedConfig\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mget_config_dict\u001b[49m\u001b[43m(\u001b[49m\u001b[43mpretrained_model_name_or_path\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 1035\u001b[0m has_remote_code \u001b[38;5;241m=\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mauto_map\u001b[39m\u001b[38;5;124m\"\u001b[39m \u001b[38;5;129;01min\u001b[39;00m config_dict \u001b[38;5;129;01mand\u001b[39;00m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mAutoConfig\u001b[39m\u001b[38;5;124m\"\u001b[39m \u001b[38;5;129;01min\u001b[39;00m config_dict[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mauto_map\u001b[39m\u001b[38;5;124m\"\u001b[39m]\n\u001b[1;32m 1036\u001b[0m has_local_code \u001b[38;5;241m=\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mmodel_type\u001b[39m\u001b[38;5;124m\"\u001b[39m \u001b[38;5;129;01min\u001b[39;00m config_dict \u001b[38;5;129;01mand\u001b[39;00m config_dict[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mmodel_type\u001b[39m\u001b[38;5;124m\"\u001b[39m] \u001b[38;5;129;01min\u001b[39;00m CONFIG_MAPPING\n", "File \u001b[0;32m~/.local/lib/python3.9/site-packages/transformers/configuration_utils.py:620\u001b[0m, in \u001b[0;36mPretrainedConfig.get_config_dict\u001b[0;34m(cls, pretrained_model_name_or_path, **kwargs)\u001b[0m\n\u001b[1;32m 618\u001b[0m original_kwargs \u001b[38;5;241m=\u001b[39m copy\u001b[38;5;241m.\u001b[39mdeepcopy(kwargs)\n\u001b[1;32m 619\u001b[0m \u001b[38;5;66;03m# Get config dict associated with the base config file\u001b[39;00m\n\u001b[0;32m--> 620\u001b[0m config_dict, kwargs \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mcls\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_get_config_dict\u001b[49m\u001b[43m(\u001b[49m\u001b[43mpretrained_model_name_or_path\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 621\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m_commit_hash\u001b[39m\u001b[38;5;124m\"\u001b[39m \u001b[38;5;129;01min\u001b[39;00m config_dict:\n\u001b[1;32m 622\u001b[0m original_kwargs[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m_commit_hash\u001b[39m\u001b[38;5;124m\"\u001b[39m] \u001b[38;5;241m=\u001b[39m config_dict[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m_commit_hash\u001b[39m\u001b[38;5;124m\"\u001b[39m]\n", "File \u001b[0;32m~/.local/lib/python3.9/site-packages/transformers/configuration_utils.py:708\u001b[0m, in \u001b[0;36mPretrainedConfig._get_config_dict\u001b[0;34m(cls, pretrained_model_name_or_path, **kwargs)\u001b[0m\n\u001b[1;32m 706\u001b[0m config_dict[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m_commit_hash\u001b[39m\u001b[38;5;124m\"\u001b[39m] \u001b[38;5;241m=\u001b[39m commit_hash\n\u001b[1;32m 707\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m (json\u001b[38;5;241m.\u001b[39mJSONDecodeError, \u001b[38;5;167;01mUnicodeDecodeError\u001b[39;00m):\n\u001b[0;32m--> 708\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mEnvironmentError\u001b[39;00m(\n\u001b[1;32m 709\u001b[0m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mIt looks like the config file at \u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mresolved_config_file\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124m is not a valid JSON file.\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 710\u001b[0m )\n\u001b[1;32m 712\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m is_local:\n\u001b[1;32m 713\u001b[0m logger\u001b[38;5;241m.\u001b[39minfo(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mloading configuration file \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mresolved_config_file\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n", "\u001b[0;31mOSError\u001b[0m: It looks like the config file at '/home/uafcb7f73a7c1b7b8895a40af90eab07/.cache/huggingface/hub/models--Fredswqa1--DysfunctEcosenseLLM/snapshots/c8a9df5a77a07883e4ee3e59c9ca2683c4189c6b/config.json' is not a valid JSON file." ] } ], "source": [ "# Logging in to Hugging Face\n", "from huggingface_hub import notebook_login, Repository\n", "\n", "# Login to Hugging Face\n", "notebook_login()\n", "\n", "# Model and Tokenize Loading\n", "from transformers import AutoModelForSequenceClassification, AutoTokenizer\n", "\n", "# Define the path to the checkpoint\n", "checkpoint_path = \"Fredswqa1/DysfunctEcosenseLLM\" # Replace with your checkpoint folder\n", "\n", "# Load the model\n", "model = AutoModelForSequenceClassification.from_pretrained(checkpoint_path)\n", "\n", "# Load the tokenizer\n", "tokenizer = AutoTokenizer.from_pretrained(\"LlamaTokenizer\") #add name of your model's tokenizer on Hugging Face OR custom tokenizer\n", "\n", "# Save the model and tokenizer\n", "model_name_on_hub = \"EcoSense-LLMChat\"\n", "model.save_pretrained(model_name_on_hub)\n", "tokenizer.save_pretrained(model_name_on_hub)\n", "\n", "# Push to the hub\n", "model.push_to_hub(model_name_on_hub)\n", "tokenizer.push_to_hub(model_name_on_hub)\n", "\n", "# Congratulations! Your fine-tuned model is now uploaded to the Hugging Face Model Hub. \n", "# You can view and share your model using its URL: https://huggingface.co//" ] }, { "cell_type": "markdown", "id": "39613af7-3408-4412-8ded-aa6116759f06", "metadata": {}, "source": [ "\n", "**Testing our Fine-Tuned LLM**\n", "\n", "Congratulations on successfully fine-tuning your Language Model for Text-to-SQL tasks! It's now time to put the model to the test.\n", "\n", "___" ] }, { "cell_type": "markdown", "id": "00cb638e-1464-4596-8809-186834b3f277", "metadata": {}, "source": [ "**TextToSQLGenerator: Generating SQL Queries from Text Prompts**\n", "\n", "**Important Note**: Remember to re-import necessary packages and re-define `BASE_MODELS` by rerunning relevant cells if the Jupyter kernel is restarted.\n", "\n", "**Overview of `TextToSQLGenerator`**\n", "- Designed for generating SQL queries from natural language prompts.\n", "- Allows model selection at initialization.\n", "\n", "**Initialization and Configuration:**\n", "- Set `use_adapter` to `True` for using the fine-tuned LoRA model; defaults to the base model otherwise.\n", "- Automatic tokenizer selection based on the model ID, with special handling for 'llama' models.\n", "- Optimized loading for CPU / XPUs (`low_cpu_mem_usage`, `load_in_4bit`).\n", "- For LoRA models, loads fine-tuned checkpoints for inference.\n", "\n", "**Generating SQL Queries:**\n", "\n", "The `generate` method is where the actual translation occurs. Given a text prompt, the method encodes the prompt using the tokenizer, ensuring that it fits within the model's maximum length constraints. It then performs inference to generate the SQL query.\n", "\n", "The method parameters like `temperature` and `repetition_penalty` which we can tweak to control the creativity and quality of the generated queries!" ] }, { "cell_type": "code", "execution_count": null, "id": "10a0e504-46b7-4c6e-8d80-b28798607ed6", "metadata": {}, "outputs": [], "source": [ "os.environ[\"WANDB_DISABLED\"] = \"true\"\n", "INFERENCE_DEVICE = torch.device(\"xpu\") # change this to `xpu` to use Intel GPU for inference \n", "\n", "def generate_prompt_sql(input_question, context, output=\"\"):\n", " \"\"\"\n", " Generates a prompt for fine-tuning the LLM model for text-to-SQL tasks.\n", "\n", " Parameters:\n", " input_question (str): The input text or question to be converted to SQL.\n", " context (str): The schema or context in which the SQL query operates.\n", " output (str, optional): The expected SQL query as the output.\n", "\n", " Returns:\n", " str: A formatted string serving as the prompt for the fine-tuning task.\n", " \"\"\"\n", " return f\"\"\"You are a powerful text-to-SQL model. Your job is to answer questions about a database. You are given a question and context regarding one or more tables. \n", "\n", "You must output the SQL query that answers the question.\n", "\n", "### Input:\n", "{input_question}\n", "\n", "### Context:\n", "{context}\n", "\n", "### Response:\n", "{output}\"\"\"\n", "\n", "\n", "def setup_model_and_tokenizer(base_model_id: str):\n", " \"\"\"Downloads / Loads the pre-trained model and tokenizer in nf4 based on the given base model ID for training, \n", " with fallbacks for permission errors to use default cache.\"\"\"\n", " local_model_id = base_model_id.replace(\"/\", \"--\")\n", " local_model_path = os.path.join(MODEL_CACHE_PATH, local_model_id)\n", "\n", " bnb_config = BitsAndBytesConfig(\n", " load_in_4bit=True,\n", " bnb_4bit_use_double_quant=False,\n", " bnb_4bit_quant_type=\"nf4\",\n", " bnb_4bit_compute_dtype=torch.bfloat16\n", " )\n", " try:\n", " print(f\"Attempting to load model and tokenizer from: {local_model_path}\")\n", " model = AutoModelForCausalLM.from_pretrained(\n", " local_model_path,\n", " quantization_config=bnb_config\n", " )\n", " tokenizer_class = LlamaTokenizer if \"llama\" in base_model_id.lower() else AutoTokenizer\n", " tokenizer = tokenizer_class.from_pretrained(local_model_path)\n", " except (OSError, PermissionError) as e:\n", " print(f\"Failed to load from {local_model_path} due to {e}. Attempting to download...\")\n", " model = AutoModelForCausalLM.from_pretrained(\n", " base_model_id, \n", " quantization_config=bnb_config\n", " )\n", " tokenizer_class = LlamaTokenizer if \"llama\" in base_model_id.lower() else AutoTokenizer\n", " tokenizer = tokenizer_class.from_pretrained(base_model_id)\n", "\n", " tokenizer.pad_token_id = 0\n", " tokenizer.padding_side = \"left\"\n", " return model.to(INFERENCE_DEVICE), tokenizer\n", "\n", "class TextToSQLGenerator:\n", " \"\"\"Handles SQL query generation for a given text prompt.\"\"\"\n", "\n", " def __init__(\n", " self, base_model_id=BASE_MODEL, use_adapter=False, lora_checkpoint=None, loaded_base_model=None\n", " ):\n", " \"\"\"\n", " Initialize the InferenceModel class.\n", " Parameters:\n", " use_adapter (bool, optional): Whether to use LoRA model. Defaults to False.\n", " \"\"\"\n", " try:\n", " if loaded_base_model:\n", " self.model = loaded_base_model.model\n", " self.tokenizer = loaded_base_model.tokenizer\n", " else:\n", " self.model, self.tokenizer = setup_model_and_tokenizer(base_model_id)\n", " if use_adapter:\n", " self.model = PeftModel.from_pretrained(self.model, lora_checkpoint)\n", " except Exception as e:\n", " logging.error(f\"Exception occurred during model initialization: {e}\")\n", " raise\n", "\n", " self.model.to(INFERENCE_DEVICE)\n", " self.max_length = 512\n", "\n", "\n", " def generate(self, prompt, **kwargs):\n", " \"\"\"Generates an SQL query based on the given prompt.\n", " Parameters:\n", " prompt (str): The SQL prompt.\n", " Returns:\n", " str: The generated SQL query.\n", " \"\"\"\n", " try:\n", " encoded_prompt = self.tokenizer(\n", " prompt,\n", " truncation=True,\n", " max_length=self.max_length,\n", " padding=False,\n", " return_tensors=\"pt\",\n", " ).input_ids.to(INFERENCE_DEVICE)\n", " with torch.no_grad():\n", " with torch.xpu.amp.autocast():\n", " outputs = self.model.generate(\n", " input_ids=encoded_prompt,\n", " do_sample=True,\n", " max_length=self.max_length,\n", " temperature=0.3,\n", " repetition_penalty=1.2,\n", " )\n", " generated = self.tokenizer.decode(outputs[0], skip_special_tokens=True)\n", " return generated\n", " except Exception as e:\n", " logging.error(f\"Exception occurred during query generation: {e}\")\n", " raise" ] }, { "cell_type": "markdown", "id": "dfb1c247-f6e2-4ccd-bdc6-26f41ea63c55", "metadata": {}, "source": [ "---\n", "**Generate SQL from Natural Language!** ๐Ÿš€ \n", "\n", "**With `TextToSQLGenerator`:**\n", "- Compare base model ๐Ÿ†š LoRA model.\n", "- Instantiate with different `use_adapter` settings for side-by-side comparison.\n", "\n", "**Things to try out:**\n", "\n", "1. **Select a Natural Language Question** ๐Ÿ—ฃ๏ธ: Use a prompt or sample data (see samples dict below) for SQL translation.\n", "2. **Base Model SQL Generation** ๐Ÿ—๏ธ: Generate SQL from the prompt using the base model.\n", "3. **Fine-Tuned Model SQL Generation** โœจ: Generate SQL with the fine-tuned model; note improvements.\n", "4. **Compare Outputs** ๐Ÿ”: Evaluate both SQL queries for accuracy to compare both models.\n", "5. **Iterate and Refine** ๐Ÿ”: Adjust training parameters or dataset and finetune again if required.\n", "6. **Integrate with ๐Ÿ—‚๏ธ LlamaIndex ๐Ÿฆ™**: Use frameworks like [LlamaIndex](https://github.com/run-llama/llama_index) to integrated your finetuned model for querying a database using natural language.\n" ] }, { "cell_type": "markdown", "id": "94c63bc1-9e86-4760-ac9b-c915969ee5fb", "metadata": {}, "source": [ "**Now let's see how our model performance, Let's generate some SQL queries:**" ] }, { "cell_type": "code", "execution_count": null, "id": "dd2c6f25-5c45-4061-9b62-91233149b7a2", "metadata": {}, "outputs": [], "source": [ "# lets load base model for a baseline comparison\n", "base_model = TextToSQLGenerator(\n", " use_adapter=False,\n", " lora_checkpoint=\"\",\n", ") # setting use_adapter=False to use the base model\n", "finetuned_model = None" ] }, { "cell_type": "code", "execution_count": null, "id": "b8417146-0c28-4996-81a4-c4b0857d81e7", "metadata": {}, "outputs": [], "source": [ "import json\n", "\n", "from IPython.display import display, HTML\n", "\n", "\n", "# let's use some fake sample data\n", "samples = \"\"\"\n", "[\n", " {\n", " \"question\": \"What is the capacity of the stadium where the team 'Mountain Eagles' plays?\",\n", " \"context\": \"CREATE TABLE stadium_info (team_name VARCHAR, stadium_name VARCHAR, capacity INT)\"\n", " },\n", " {\n", " \"question\": \"How many goals did player John Smith score last season?\",\n", " \"context\": \"CREATE TABLE player_stats (player_name VARCHAR, goals_scored INT, season VARCHAR)\"\n", " },\n", " {\n", " \"question\": \"What are the operating hours for the Central Library on weekends?\",\n", " \"context\": \"CREATE TABLE library_hours (library_name VARCHAR, day_of_week VARCHAR, open_time TIME, close_time TIME)\"\n", " }\n", "]\n", "\"\"\"\n", "\n", "def _extract_sections(output):\n", " input_section = output.split(\"### Input:\")[1].split(\"### Context:\")[0]\n", " context_section = output.split(\"### Context:\")[1].split(\"### Response:\")[0]\n", " response_section = output.split(\"### Response:\")[1]\n", " return input_section, context_section, response_section\n", "\n", "def run_inference(sample_data, model, finetuned=False):\n", " if INFERENCE_DEVICE.type.startswith(\"xpu\"):\n", " torch.xpu.empty_cache()\n", " \n", " color = \"#4CAF52\" if finetuned else \"#2196F4\"\n", " model_type = \"finetuned\" if finetuned else \"base\"\n", " display(HTML(f\"
Processing queries on {INFERENCE_DEVICE} please wait...
\"))\n", " \n", " for index, row in enumerate(sample_data):\n", " try:\n", " prompt = generate_prompt_sql(row[\"question\"], context=row[\"context\"])\n", " output = model.generate(prompt) \n", " input_section, context_section, response_section = _extract_sections(output)\n", " \n", " tabbed_output = f\"\"\"\n", "
\n", " {model_type} model - Sample {index+1} (Click to expand)\n", "
\n", "

Expected input ๐Ÿ“:
{input_section}

\n", "

Expected context ๐Ÿ“š:
{context_section}

\n", "

Generated response ๐Ÿ’ก:
{response_section}

\n", "
\n", "
\n", "
\"\"\" # Subtle separator\n", " display(HTML(tabbed_output))\n", " except Exception as e:\n", " logging.error(f\"Exception occurred during sample processing: {e}\")\n", "\n", "# checkpoints are saved to `./lora_adapters`.\n", "# Update the USING_CHECKPOINT to the one you want to use.\n", "USING_CHECKPOINT=200\n", "# if the kernel is interrupted the latest adapter (LORA_CHECKPOINT) is `./final_model_interrupted/`\n", "# or else, the final model LORA_CHECKPOINT is `./final_model`\n", "LORA_CHECKPOINT = f\"./lora_adapters/checkpoint-{USING_CHECKPOINT}/\"\n", "\n", "if os.path.exists(LORA_CHECKPOINT):\n", " sample_data = json.loads(samples)\n", " run_inference(sample_data, model=base_model)\n", " if not finetuned_model:\n", " finetuned_model = TextToSQLGenerator(\n", " use_adapter=True,\n", " lora_checkpoint=LORA_CHECKPOINT,\n", " loaded_base_model=base_model\n", " )\n", " run_inference(sample_data, model=finetuned_model, finetuned=True)\n", "\n", " # To conserve memory we can delete the model\n", " #del finetuned_model\n", " #del base_model" ] }, { "cell_type": "markdown", "id": "11c2506c", "metadata": {}, "source": [ "---\n", "**Conclusion** ๐Ÿ‘\n", "\n", "We've successfully navigated the process of selecting and fine-tuning a foundational LLM model on Intel GPUs, showcasing its SQL generation capabilities. I hope that I have been able to highlight the potential of customizing language models for specific tasks and on how to efficiently finetune LLMs on Intel XPUs. As a suggestion for your continued journey, consider experimenting with different models, adjusting inference settings, and exploring various LoRA configurations to refine your results. Keep exploring!\n", "\n", "---\n" ] }, { "cell_type": "markdown", "id": "c458cac4", "metadata": { "jp-MarkdownHeadingCollapsed": true }, "source": [ "\n", "**Disclaimer for Using Large Language Models**\n", "\n", "Please be aware that while Large Language Models are powerful tools for text generation, they may sometimes produce results that are unexpected, biased, or inconsistent with the given prompt. It's advisable to carefully review the generated text and consider the context and application in which you are using these models.\n", "\n", "For detailed information on each model's capabilities, licensing, and attribution, please refer to the respective model cards:\n", "\n", "1. **Open LLaMA 3B v2**\n", " - Model Card: [openlm-research/open_llama_3b_v2](https://huggingface.co/openlm-research/open_llama_3b_v2)\n", "\n", "2. **Open LLaMA 13B**\n", " - Model Card: [openlm-research/open_llama_13b](https://huggingface.co/openlm-research/open_llama_13b)\n", "\n", "3. **Nous-Hermes LLaMA 2-7B**\n", " - Model Card: [NousResearch/Nous-Hermes-llama-2-7b](https://huggingface.co/NousResearch/Nous-Hermes-llama-2-7b)\n", "\n", "4. **LLaMA 2-7B Chat HF**\n", " - Model Card: [NousResearch/Llama-2-7b-chat-hf](https://huggingface.co/NousResearch/Llama-2-7b-chat-hf)\n", "\n", "5. **LLaMA 2-13B HF**\n", " - Model Card: [NousResearch/Llama-2-13b-hf](https://huggingface.co/NousResearch/Llama-2-13b-hf)\n", "\n", "6. **CodeLlama 7B HF**\n", " - Model Card: [NousResearch/CodeLlama-7b-hf](https://huggingface.co/NousResearch/CodeLlama-7b-hf)\n", "\n", "7. **Phind-CodeLlama 34B v2**\n", " - Model Card: [Phind/Phind-CodeLlama-34B-v2](https://huggingface.co/Phind/Phind-CodeLlama-34B-v2)\n", "\n", "8. **Zephyr-7b-beta**\n", " - Model Card: [HuggingFaceH4/zephyr-7b-beta](https://huggingface.co/HuggingFaceH4/zephyr-7b-beta)\n", "\n", "\n", "Usage of these models must also adhere to the licensing agreements and be in accordance with ethical guidelines and best practices for AI. If you have any concerns or encounter issues with the models, please refer to the respective model cards and documentation provided in the links above.\n", "To the extent that any public or non-Intel datasets or models are referenced by or accessed using these materials those datasets or models are provided by the third party indicated as the content source. Intel does not create the content and does not warrant its accuracy or quality. By accessing the public content, or using materials trained on or with such content, you agree to the terms associated with that content and that your use complies with the applicable license.\n", "\n", " \n", "Intel expressly disclaims the accuracy, adequacy, or completeness of any such public content, and is not liable for any errors, omissions, or defects in the content, or for any reliance on the content. Intel is not liable for any liability or damages relating to your use of public content.\n", "\n", "Intelโ€™s provision of these resources does not expand or otherwise alter Intelโ€™s applicable published warranties or warranty disclaimers for Intel products or solutions, and no additional obligations, indemnifications, or liabilities arise from Intel providing such resources. Intel reserves the right, without notice, to make corrections, enhancements, improvements, and other changes to its materials.\n", "\n", "---\n" ] } ], "metadata": { "kernelspec": { "display_name": "pytorch-gpu", "language": "python", "name": "pytorch-gpu" }, "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.18" } }, "nbformat": 4, "nbformat_minor": 5 }