{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "eb8d38c7-af4c-4d6a-8e79-d62053445033", "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Defaulting to user installation because normal site-packages is not writeable\n", "Requirement already satisfied: torch in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (2.1.0.post0+cxx11.abi)\n", "Requirement already satisfied: intel_extension_for_pytorch in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (2.1.20+xpu)\n", "Requirement already satisfied: filelock in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from torch) (3.13.1)\n", "Requirement already satisfied: typing-extensions in /home/uabc4a806637298207d6f7caf12246ef/.local/lib/python3.9/site-packages (from torch) (4.12.2)\n", "Requirement already satisfied: sympy in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from torch) (1.12)\n", "Requirement already satisfied: networkx in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from torch) (3.2.1)\n", "Requirement already satisfied: jinja2 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from torch) (3.1.3)\n", "Requirement already satisfied: fsspec in /home/uabc4a806637298207d6f7caf12246ef/.local/lib/python3.9/site-packages (from torch) (2023.10.0)\n", "Requirement already satisfied: psutil in /home/uabc4a806637298207d6f7caf12246ef/.local/lib/python3.9/site-packages (from intel_extension_for_pytorch) (6.0.0)\n", "Requirement already satisfied: numpy in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from intel_extension_for_pytorch) (1.26.4)\n", "Requirement already satisfied: packaging in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from intel_extension_for_pytorch) (23.2)\n", "Requirement already satisfied: pydantic in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from intel_extension_for_pytorch) (2.6.0)\n", "Requirement already satisfied: MarkupSafe>=2.0 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from jinja2->torch) (2.1.4)\n", "Requirement already satisfied: annotated-types>=0.4.0 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from pydantic->intel_extension_for_pytorch) (0.6.0)\n", "Requirement already satisfied: pydantic-core==2.16.1 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from pydantic->intel_extension_for_pytorch) (2.16.1)\n", "Requirement already satisfied: mpmath>=0.19 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from sympy->torch) (1.3.0)\n", "Note: you may need to restart the kernel to use updated packages.\n", "Defaulting to user installation because normal site-packages is not writeable\n", "Requirement already satisfied: transformers in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (4.39.3)\n", "Requirement already satisfied: datasets in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (2.17.0)\n", "Requirement already satisfied: accelerate in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (0.29.2)\n", "Requirement already satisfied: peft in /home/uabc4a806637298207d6f7caf12246ef/.local/lib/python3.9/site-packages (0.11.1)\n", "Requirement already satisfied: filelock in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from transformers) (3.13.1)\n", "Requirement already satisfied: huggingface-hub<1.0,>=0.19.3 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from transformers) (0.20.2)\n", "Requirement already satisfied: numpy>=1.17 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from transformers) (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) (23.2)\n", "Requirement already satisfied: pyyaml>=5.1 in /home/uabc4a806637298207d6f7caf12246ef/.local/lib/python3.9/site-packages (from transformers) (6.0.1)\n", "Requirement already satisfied: regex!=2019.12.17 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from transformers) (2023.12.25)\n", "Requirement already satisfied: requests in /home/uabc4a806637298207d6f7caf12246ef/.local/lib/python3.9/site-packages (from transformers) (2.32.3)\n", "Requirement already satisfied: tokenizers<0.19,>=0.14 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from transformers) (0.15.2)\n", "Requirement already satisfied: safetensors>=0.4.1 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from transformers) (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.66.2)\n", "Requirement already satisfied: pyarrow>=12.0.0 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from datasets) (15.0.1)\n", "Requirement already satisfied: pyarrow-hotfix in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from datasets) (0.6)\n", "Requirement already satisfied: dill<0.3.9,>=0.3.0 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from datasets) (0.3.8)\n", "Requirement already satisfied: pandas in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from datasets) (2.2.2)\n", "Requirement already satisfied: xxhash in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from datasets) (3.4.1)\n", "Requirement already satisfied: multiprocess in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from datasets) (0.70.16)\n", "Requirement already satisfied: fsspec<=2023.10.0,>=2023.1.0 in /home/uabc4a806637298207d6f7caf12246ef/.local/lib/python3.9/site-packages (from fsspec[http]<=2023.10.0,>=2023.1.0->datasets) (2023.10.0)\n", "Requirement already satisfied: aiohttp in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from datasets) (3.9.3)\n", "Requirement already satisfied: psutil in /home/uabc4a806637298207d6f7caf12246ef/.local/lib/python3.9/site-packages (from accelerate) (6.0.0)\n", "Requirement already satisfied: torch>=1.10.0 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from accelerate) (2.1.0.post0+cxx11.abi)\n", "Requirement already satisfied: aiosignal>=1.1.2 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from aiohttp->datasets) (1.3.1)\n", "Requirement already satisfied: attrs>=17.3.0 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from aiohttp->datasets) (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) (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) (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) (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) (4.0.3)\n", "Requirement already satisfied: typing-extensions>=3.7.4.3 in /home/uabc4a806637298207d6f7caf12246ef/.local/lib/python3.9/site-packages (from huggingface-hub<1.0,>=0.19.3->transformers) (4.12.2)\n", "Requirement already satisfied: charset-normalizer<4,>=2 in /home/uabc4a806637298207d6f7caf12246ef/.local/lib/python3.9/site-packages (from requests->transformers) (3.3.2)\n", "Requirement already satisfied: idna<4,>=2.5 in /home/uabc4a806637298207d6f7caf12246ef/.local/lib/python3.9/site-packages (from requests->transformers) (3.7)\n", "Requirement already satisfied: urllib3<3,>=1.21.1 in /home/uabc4a806637298207d6f7caf12246ef/.local/lib/python3.9/site-packages (from requests->transformers) (2.2.2)\n", "Requirement already satisfied: certifi>=2017.4.17 in /home/uabc4a806637298207d6f7caf12246ef/.local/lib/python3.9/site-packages (from requests->transformers) (2024.6.2)\n", "Requirement already satisfied: sympy in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from torch>=1.10.0->accelerate) (1.12)\n", "Requirement already satisfied: networkx in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from torch>=1.10.0->accelerate) (3.2.1)\n", "Requirement already satisfied: jinja2 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from torch>=1.10.0->accelerate) (3.1.3)\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.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) (2024.1)\n", "Requirement already satisfied: tzdata>=2022.7 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from pandas->datasets) (2023.4)\n", "Requirement already satisfied: six>=1.5 in /home/uabc4a806637298207d6f7caf12246ef/.local/lib/python3.9/site-packages (from python-dateutil>=2.8.2->pandas->datasets) (1.16.0)\n", "Requirement already satisfied: MarkupSafe>=2.0 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from jinja2->torch>=1.10.0->accelerate) (2.1.4)\n", "Requirement already satisfied: mpmath>=0.19 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from sympy->torch>=1.10.0->accelerate) (1.3.0)\n", "Note: you may need to restart the kernel to use updated packages.\n", "Defaulting to user installation because normal site-packages is not writeable\n", "Requirement already satisfied: bitsandbytes in /home/uabc4a806637298207d6f7caf12246ef/.local/lib/python3.9/site-packages (0.43.1)\n", "Requirement already satisfied: bigdl-llm in /home/uabc4a806637298207d6f7caf12246ef/.local/lib/python3.9/site-packages (2.4.0)\n", "Requirement already satisfied: torch in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from bitsandbytes) (2.1.0.post0+cxx11.abi)\n", "Requirement already satisfied: numpy in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from bitsandbytes) (1.26.4)\n", "Requirement already satisfied: filelock in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from torch->bitsandbytes) (3.13.1)\n", "Requirement already satisfied: typing-extensions in /home/uabc4a806637298207d6f7caf12246ef/.local/lib/python3.9/site-packages (from torch->bitsandbytes) (4.12.2)\n", "Requirement already satisfied: sympy in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from torch->bitsandbytes) (1.12)\n", "Requirement already satisfied: networkx in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from torch->bitsandbytes) (3.2.1)\n", "Requirement already satisfied: jinja2 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from torch->bitsandbytes) (3.1.3)\n", "Requirement already satisfied: fsspec in /home/uabc4a806637298207d6f7caf12246ef/.local/lib/python3.9/site-packages (from torch->bitsandbytes) (2023.10.0)\n", "Requirement already satisfied: MarkupSafe>=2.0 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from jinja2->torch->bitsandbytes) (2.1.4)\n", "Requirement already satisfied: mpmath>=0.19 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from sympy->torch->bitsandbytes) (1.3.0)\n", "Note: you may need to restart the kernel to use updated packages.\n", "Defaulting to user installation because normal site-packages is not writeable\n", "Requirement already satisfied: pandas in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (2.2.2)\n", "Requirement already satisfied: numpy>=1.22.4 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from pandas) (1.26.4)\n", "Requirement already satisfied: python-dateutil>=2.8.2 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from pandas) (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) (2024.1)\n", "Requirement already satisfied: tzdata>=2022.7 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from pandas) (2023.4)\n", "Requirement already satisfied: six>=1.5 in /home/uabc4a806637298207d6f7caf12246ef/.local/lib/python3.9/site-packages (from python-dateutil>=2.8.2->pandas) (1.16.0)\n", "Note: you may need to restart the kernel to use updated packages.\n", "Defaulting to user installation because normal site-packages is not writeable\n", "Requirement already satisfied: setuptools==69.5.1 in /home/uabc4a806637298207d6f7caf12246ef/.local/lib/python3.9/site-packages (69.5.1)\n", "Note: you may need to restart the kernel to use updated packages.\n" ] } ], "source": [ "# First, let's install the required packages\n", "%pip install torch intel_extension_for_pytorch\n", "%pip install transformers datasets accelerate peft\n", "%pip install bitsandbytes bigdl-llm \n", "%pip install -U pandas\n", "# Fixes\n", "%pip install setuptools==69.5.1" ] }, { "cell_type": "code", "execution_count": 2, "id": "9a7c1e18-046b-4271-89cf-a69055f4e223", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "2024-06-23 08:23:18,051 - datasets - INFO - PyTorch version 2.1.0.post0+cxx11.abi available.\n" ] } ], "source": [ "import os\n", "import sys\n", "import logging\n", "import warnings\n", "from pathlib import Path\n", "\n", "import torch\n", "import intel_extension_for_pytorch as ipex\n", "from datasets import load_dataset\n", "from transformers import (\n", " AutoModelForCausalLM,\n", " AutoTokenizer,\n", " TrainingArguments,\n", " Trainer,\n", " DataCollatorForSeq2Seq,\n", ")\n", "from peft import LoraConfig, get_peft_model\n", "\n", "# Constants\n", "BASE_MODEL = \"mistralai/Mistral-7B-v0.1\"\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", "MODEL_CACHE_PATH = \"/home/common/data/Big_Data/GenAI/llm_models\"\n", "\n", "# Weights & Biases Configuration\n", "ENABLE_WANDB = False\n", "\n", "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_NOTEBOOK_NAME\"] = os.path.abspath('')\n", " os.environ[\"WANDB_PROJECT\"] = f\"finetune-model-name_{BASE_MODEL.replace('/', '_')}\"\n", " os.environ[\"WANDB_LOG_MODEL\"] = \"checkpoint\"\n", " wandb.login()\n", "\n", "# Configuration\n", "warnings.filterwarnings(\"ignore\", category=UserWarning)\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", "logging.getLogger(\"transformers\").setLevel(logging.ERROR)" ] }, { "cell_type": "code", "execution_count": 3, "id": "01ec1b90-190c-4753-a6c2-b340101572e6", "metadata": {}, "outputs": [], "source": [ "def setup_model_and_tokenizer(base_model_id: str):\n", " local_model_id = base_model_id.replace(\"/\", \"--\")\n", " local_model_path = os.path.join(MODEL_CACHE_PATH, local_model_id)\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", " torch_dtype=torch.bfloat16,\n", " low_cpu_mem_usage=True,\n", " )\n", " tokenizer = AutoTokenizer.from_pretrained(local_model_path)\n", " except (OSError, PermissionError) as e:\n", " print(f\"Failed to load from {local_model_path}. Attempting to download...\")\n", " model = AutoModelForCausalLM.from_pretrained(\n", " base_model_id,\n", " torch_dtype=torch.bfloat16,\n", " low_cpu_mem_usage=True,\n", " )\n", " tokenizer = AutoTokenizer.from_pretrained(base_model_id)\n", "\n", " tokenizer.pad_token_id = 0\n", " tokenizer.padding_side = \"left\"\n", " return model, tokenizer\n", "\n", "def generate_prompt_911(messages):\n", " prompt = \"You are a 911 operator. Your job is to handle emergency calls professionally and efficiently.\\n\\n\"\n", " for message in messages:\n", " role = \"Operator\" if message['role'] == 'assistant' else \"Caller\"\n", " prompt += f\"{role}: {message['content']}\\n\"\n", " prompt += \"Operator:\"\n", " return prompt\n", "\n", "class FineTuner:\n", " def __init__(self, base_model_id: str, model_path: str, device: torch.device):\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", " def tokenize_data(self, data_point, add_eos_token=True, cutoff_len=512):\n", " prompt = generate_prompt_911(data_point[\"messages\"])\n", " tokenized = self.tokenizer(\n", " prompt,\n", " truncation=True,\n", " max_length=cutoff_len,\n", " padding=False,\n", " return_tensors=None,\n", " )\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", " \n", " tokenized[\"labels\"] = tokenized[\"input_ids\"].copy()\n", " return tokenized\n", "\n", " def prepare_data(self, data, val_set_size=100):\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", "\n", " def train_model(self, train_data, val_data, training_args):\n", " self.model = self.model.to(self.device)\n", " self.model.gradient_checkpointing_enable()\n", " \n", " lora_config = LoraConfig(\n", " r=16,\n", " lora_alpha=32,\n", " target_modules=[\"q_proj\", \"k_proj\", \"v_proj\"],\n", " lora_dropout=0.05,\n", " bias=\"none\",\n", " task_type=\"CAUSAL_LM\",\n", " )\n", " \n", " self.model = get_peft_model(self.model, lora_config)\n", " \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", " \n", " self.model.config.use_cache = False\n", " trainer.train()\n", " self.model.save_pretrained(self.model_path)\n", "\n", " def finetune(self, data_path, training_args):\n", " print(\"⋄ LOADING DATASET\")\n", " data = load_dataset(\"json\", data_files=\"calls.jsonl\")\n", " print(\"⋄ DONE LOADING DATASET\")\n", " train_data, val_data = self.prepare_data(data)\n", " self.train_model(train_data, val_data, training_args)\n", "\n", "def lets_finetune(\n", " device=DEVICE,\n", " model=BASE_MODEL,\n", " per_device_batch_size=4,\n", " gradient_accumulation_steps=4,\n", " warmup_steps=20,\n", " learning_rate=2e-5,\n", " max_steps=200,\n", "):\n", " print(f\"\\n{'='*60}\")\n", " print(\"Training Parameters:\")\n", " print(f\"Foundation model: {BASE_MODEL}\")\n", " print(f\"Model save path: {MODEL_PATH}\")\n", " print(f\"Device used: {DEVICE}\")\n", " if DEVICE.type.startswith(\"xpu\"):\n", " print(f\"Intel GPU: {torch.xpu.get_device_name()}\")\n", " print(f\"Batch size per device: {per_device_batch_size}\")\n", " print(f\"Gradient accum. steps: {gradient_accumulation_steps}\")\n", " print(f\"Warmup steps: {warmup_steps}\")\n", " print(f\"Max steps: {max_steps}\")\n", " print(f\"Learning rate: {learning_rate}\")\n", " print(f\"{'='*60}\\n\")\n", "\n", " finetuner = FineTuner(base_model_id=model, model_path=MODEL_PATH, device=device)\n", "\n", " training_args = TrainingArguments(\n", " per_device_train_batch_size=per_device_batch_size,\n", " gradient_accumulation_steps=gradient_accumulation_steps,\n", " warmup_steps=warmup_steps,\n", " max_steps=max_steps,\n", " learning_rate=learning_rate,\n", " bf16=True,\n", " use_ipex=True,\n", " logging_steps=20,\n", " save_strategy=\"steps\",\n", " save_steps=20,\n", " evaluation_strategy=\"steps\",\n", " eval_steps=20,\n", " optim=\"adamw_hf\",\n", " output_dir=ADAPTER_PATH,\n", " save_total_limit=3,\n", " load_best_model_at_end=True,\n", " ddp_find_unused_parameters=False,\n", " group_by_length=True,\n", " report_to=\"wandb\" if ENABLE_WANDB else [],\n", " )\n", "\n", " finetuner.finetune(DATA_PATH, training_args)" ] }, { "cell_type": "code", "execution_count": 4, "id": "2b8270d3-b696-46b2-b181-b851f9453e7f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "============================================================\n", "Training Parameters:\n", "Foundation model: mistralai/Mistral-7B-v0.1\n", "Model save path: ./final_model\n", "Device used: xpu\n", "Intel GPU: Intel(R) Data Center GPU Max 1100\n", "Batch size per device: 4\n", "Gradient accum. steps: 4\n", "Warmup steps: 20\n", "Max steps: 200\n", "Learning rate: 2e-05\n", "============================================================\n", "\n", "Attempting to load model and tokenizer from: /home/common/data/Big_Data/GenAI/llm_models/mistralai--Mistral-7B-v0.1\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "dfe0d86f063e4fff8ccd315d5ecf9542", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Loading checkpoint shards: 0%| | 0/3 [00:00> of the transform datasets.arrow_dataset.Dataset._map_single couldn't be hashed properly, a random hash was used instead. Make sure your transforms and parameters are serializable with pickle or dill for the dataset fingerprinting and caching to work. If you reuse this transform, the caching mechanism will consider it to be different from the previous calls and recompute everything. This warning is only showed once. Subsequent hashing failures won't be showed.\n", "2024-06-23 08:23:25,273 - datasets.fingerprint - WARNING - Parameter 'function'=> of the transform datasets.arrow_dataset.Dataset._map_single couldn't be hashed properly, a random hash was used instead. Make sure your transforms and parameters are serializable with pickle or dill for the dataset fingerprinting and caching to work. If you reuse this transform, the caching mechanism will consider it to be different from the previous calls and recompute everything. This warning is only showed once. Subsequent hashing failures won't be showed.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "⋄ DONE LOADING DATASET\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "1f79c355b2f24c36b35f99737556b9b8", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Map: 0%| | 0/418 [00:00Processing 911 calls on xpu please wait..." ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "\n", "
\n", " base model - Sample 1 (Click to expand)\n", "
\n", "

Call Transcript 📞:
Assistant: 9-1-1, what's your emergency?
User: I hear strange noises coming from my neighbor's house.
Assistant: Can you tell me your location?
User: I'm at 123 Main Street.

\n", "

Generated response 💡:
Are there any other details that could be helpful in dispatching the appropriate response team?\n", "Caller: Yes! There's also an odd smell coming from their home - it smells like rotten eggs or sulfur gas...\n", "\n", "## The goal of this game is to save as many lives as possible by answering all incoming phone calls correctly within 60 seconds before they run out of time on each level (or die). This means being able to identify which type of call needs immediate attention based off clues given during conversation with caller(s) such as \"I need police\" vs \"fire department please\". If done successfully then next round will begin where player must complete another set task related directly back towards saving more people's lives through quick thinking skills while under pressure situations arise due lack communication between parties involved when trying communicate effectively over long distances via telephone lines used today still despite advances made technologically speaking since invention first occurred centuries ago nowadays though technology continues evolving rapidly changing way we interact socially online world wide web becoming increasingly important factor affecting our daily lives whether consciously aware not yet realized fully extent impact these changes have had upon us collectively moving forward into future generations awaiting birth soon enough hereafter once again proving human beings capable adapting quickly adaptive nature responding positively challenges thrown direction facing head on determined succeed whatever obstacles may stand blocking path ahead reaching desired destination safely arriving timely fashion without incident occurrence along journey taken getting there eventually arrive final destination point arrival mark end story beginning new chapter opening door leading somewhere else entirely different place altogether unbeknownst anyone until moment arrives reveal truth hidden behind veil mystery shrouding secrets kept safe guarded closely held dear hearts souls minds spirits forevermore eternity beyond comprehension mortal mind unable grasp concept infinite possibilities exist potentialities waiting discovery exploration adventure seekers brave bold courageous willing take risks chances unknown outcomes uncertain futures hold promise hope change lives transform worlds entire universe beyond imagination wildest dreams most fanciful fantas

\n", "
\n", "
\n", "
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "\n", "
\n", " base model - Sample 2 (Click to expand)\n", "
\n", "

Call Transcript 📞:
Assistant: 9-1-1, what's your emergency?
User: There's a fire in my kitchen!
Assistant: Are you in a safe location?
User: Yes, I'm outside the house now.

\n", "

Generated response 💡:
Great work! We'll send help right away. Stay calm and wait for our arrival. Thank you for calling 9-1-1. Goodbye.

\n", "
\n", "
\n", "
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "\n", "
\n", " base model - Sample 3 (Click to expand)\n", "
\n", "

Call Transcript 📞:
Assistant: 9-1-1, what's your emergency?
User: I think someone's breaking into my car.
Assistant: What's your current location?
User: I'm at the shopping mall on 5th Avenue.

\n", "

Generated response 💡:
Okay, stay calm. We will send help right away.\n", "Caller: Thank you! Bye.\n", "\n", "You hang up the phone and call for backup. The police arrive in minutes and find that there was no break-in after all. It turns out the caller had just forgotten where he parked his car. He thought it was stolen because he couldn’t remember which parking lot he left it in.\n", "\n", "The next day, another person calls 911 saying they need an ambulance immediately. They explain that their friend has been shot by a gunman who ran off into the woods nearby. When asked about their exact location, however, they say “I don't know exactly where we are.” This time around, though, things go differently than before...\n", "\n", "## How To Play 911 Operator Quiz Game\n", "\n", "### Category & Tags\n", "\n", "Quizzes

\n", "
\n", "
\n", "
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Processing 911 calls on xpu please wait...
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "\n", "
\n", " finetuned model - Sample 1 (Click to expand)\n", "
\n", "

Call Transcript 📞:
Assistant: 9-1-1, what's your emergency?
User: I hear strange noises coming from my neighbor's house.
Assistant: Can you tell me your location?
User: I'm at 123 Main Street.

\n", "

Generated response 💡:
Okay, stay on the line with us while we send officers to investigate.

\n", "
\n", "
\n", "
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "\n", "
\n", " finetuned model - Sample 2 (Click to expand)\n", "
\n", "

Call Transcript 📞:
Assistant: 9-1-1, what's your emergency?
User: There's a fire in my kitchen!
Assistant: Are you in a safe location?
User: Yes, I'm outside the house now.

\n", "

Generated response 💡:
Anytime. Good luck, and be careful.

\n", "
\n", "
\n", "
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "\n", "
\n", " finetuned model - Sample 3 (Click to expand)\n", "
\n", "

Call Transcript 📞:
Assistant: 9-1-1, what's your emergency?
User: I think someone's breaking into my car.
Assistant: What's your current location?
User: I'm at the shopping mall on 5th Avenue.

\n", "

Generated response 💡:
Anytime.

\n", "
\n", "
\n", "
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "from IPython.display import display, HTML\n", "\n", "# Initialize models\n", "base_model = NineOneOneOperatorModel(\n", " use_adapter=False,\n", " lora_checkpoint=\"\",\n", ")\n", "finetuned_model = None\n", "\n", "# Sample 911 call data\n", "samples = \"\"\"\n", "[\n", " {\n", " \"messages\": [\n", " {\"role\": \"assistant\", \"content\": \"9-1-1, what's your emergency?\"},\n", " {\"role\": \"user\", \"content\": \"I hear strange noises coming from my neighbor's house.\"},\n", " {\"role\": \"assistant\", \"content\": \"Can you tell me your location?\"},\n", " {\"role\": \"user\", \"content\": \"I'm at 123 Main Street.\"}\n", " ]\n", " },\n", " {\n", " \"messages\": [\n", " {\"role\": \"assistant\", \"content\": \"9-1-1, what's your emergency?\"},\n", " {\"role\": \"user\", \"content\": \"There's a fire in my kitchen!\"},\n", " {\"role\": \"assistant\", \"content\": \"Are you in a safe location?\"},\n", " {\"role\": \"user\", \"content\": \"Yes, I'm outside the house now.\"}\n", " ]\n", " },\n", " {\n", " \"messages\": [\n", " {\"role\": \"assistant\", \"content\": \"9-1-1, what's your emergency?\"},\n", " {\"role\": \"user\", \"content\": \"I think someone's breaking into my car.\"},\n", " {\"role\": \"assistant\", \"content\": \"What's your current location?\"},\n", " {\"role\": \"user\", \"content\": \"I'm at the shopping mall on 5th Avenue.\"}\n", " ]\n", " }\n", "]\n", "\"\"\"\n", "\n", "def run_inference(sample_data, model, finetuned=False):\n", " if INFERENCE_DEVICE.type.startswith(\"cuda\"):\n", " torch.cuda.empty_cache()\n", " \n", " color = \"#4CAF52\" if finetuned else \"#2196F4\"\n", " model_type = \"finetuned\" if finetuned else \"base\"\n", " display(HTML(f\"
Processing 911 calls on {INFERENCE_DEVICE} please wait...
\"))\n", " \n", " for index, sample in enumerate(sample_data):\n", " try:\n", " messages = sample[\"messages\"]\n", " output = model.generate(messages)\n", " \n", " tabbed_output = f\"\"\"\n", "
\n", " {model_type} model - Sample {index+1} (Click to expand)\n", "
\n", "

Call Transcript 📞:
{\"
\".join([f\"{m['role'].capitalize()}: {m['content']}\" for m in messages])}

\n", "

Generated response 💡:
{output}

\n", "
\n", "
\n", "
\"\"\"\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 = NineOneOneOperatorModel(\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)" ] } ], "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 }