{ "cells": [ { "attachments": {}, "cell_type": "markdown", "id": "f6aa8c52-9bde-41a6-a5f7-4fa93d5c2a6c", "metadata": {}, "source": [ "# LLM Instruction-following pipeline with OpenVINO \n", "\n", "LLM stands for “Large Language Model,” which refers to a type of artificial intelligence model that is designed to understand and generate human-like text based on the input it receives. LLMs are trained on large datasets of text to learn patterns, grammar, and semantic relationships, allowing them to generate coherent and contextually relevant responses. One core capability of Large Language Models (LLMs) is to follow natural language instructions. Instruction-following models are capable of generating text in response to prompts and are often used for tasks like writing assistance, chatbots, and content generation.\n", "\n", "In this tutorial, we consider how to run an instruction-following text generation pipeline using popular LLMs and OpenVINO. We will use pre-trained models from the [Hugging Face Transformers](https://huggingface.co/docs/transformers/index) library. To simplify the user experience, the [Hugging Face Optimum Intel](https://huggingface.co/docs/optimum/intel/index) library converts the models to OpenVINO™ IR format.\n", "\n", "The tutorial consists of the following steps:\n", "\n", "- Install prerequisites\n", "- Download and convert the model from a public source using the [OpenVINO integration with Hugging Face Optimum](https://huggingface.co/blog/openvino).\n", "- Compress model weights to INT8 and INT4 with [OpenVINO NNCF](https://github.com/openvinotoolkit/nncf)\n", "- Create an instruction-following inference pipeline\n", "- Run instruction-following pipeline\n", "\n", "\n", "#### Table of contents:\n", "\n", "- [Prerequisites](#Prerequisites)\n", "- [Select model for inference](#Select-model-for-inference)\n", "- [Instantiate Model using Optimum Intel](#Instantiate-Model-using-Optimum-Intel)\n", "- [Compress model weights](#Compress-model-weights)\n", " - [Weights Compression using Optimum Intel](#Weights-Compression-using-Optimum-Intel)\n", " - [Weights Compression using NNCF](#Weights-Compression-using-NNCF)\n", "- [Select device for inference and model variant](#Select-device-for-inference-and-model-variant)\n", "- [Create an instruction-following inference pipeline](#Create-an-instruction-following-inference-pipeline)\n", " - [Setup imports](#Setup-imports)\n", " - [Prepare template for user prompt](#Prepare-template-for-user-prompt)\n", " - [Main generation function](#Main-generation-function)\n", " - [Helpers for application](#Helpers-for-application)\n", "- [Run instruction-following pipeline](#Run-instruction-following-pipeline)\n", "\n" ] }, { "attachments": {}, "cell_type": "markdown", "id": "027108c2-1fbe-4be5-9e23-3fc359185a42", "metadata": {}, "source": [ "## Prerequisites\n", "[back to top ⬆️](#Table-of-contents:)\n" ] }, { "cell_type": "code", "execution_count": 1, "id": "5d0473c6-3734-422d-a370-2e39d576be0e", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Note: you may need to restart the kernel to use updated packages.\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "WARNING: Ignoring invalid distribution -ptimum (c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages)\n", "WARNING: Ignoring invalid distribution -ptimum (c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Note: you may need to restart the kernel to use updated packages.\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "WARNING: Ignoring invalid distribution -ptimum (c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages)\n", "WARNING: Skipping optimum as it is not installed.\n", "WARNING: Ignoring invalid distribution -ptimum (c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages)\n", "WARNING: Skipping optimum-intel as it is not installed.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Note: you may need to restart the kernel to use updated packages.\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "WARNING: Ignoring invalid distribution -ptimum (c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages)\n", "WARNING: Ignoring invalid distribution -ptimum (c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Note: you may need to restart the kernel to use updated packages.\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "WARNING: Ignoring invalid distribution -ptimum (c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages)\n", "WARNING: Ignoring invalid distribution -ptimum (c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages)\n" ] } ], "source": [ "%pip install -Uq pip\n", "%pip uninstall -q -y optimum optimum-intel\n", "%pip install --pre -Uq openvino openvino-tokenizers[transformers] --extra-index-url https://storage.openvinotoolkit.org/simple/wheels/nightly\n", "%pip install -q \"torch>=2.1\" \"nncf>=2.7\" \"transformers>=4.36.0\" onnx \"optimum>=1.16.1\" \"accelerate\" \"datasets>=2.14.6\" \"gradio>=4.19\" \"git+https://github.com/huggingface/optimum-intel.git\" --extra-index-url https://download.pytorch.org/whl/cpu" ] }, { "attachments": {}, "cell_type": "markdown", "id": "611cc777-d5bc-4c7b-92e4-a4befa13b2ce", "metadata": {}, "source": [ "## Select model for inference\n", "[back to top ⬆️](#Table-of-contents:)\n", "\n", "The tutorial supports different models, you can select one from the provided options to compare the quality of open source LLM solutions.\n", ">**Note**: conversion of some models can require additional actions from user side and at least 64GB RAM for conversion.\n", "\n", "The available options are:\n", "\n", "* **tiny-llama-1b-chat** - This is the chat model finetuned on top of [TinyLlama/TinyLlama-1.1B-intermediate-step-1431k-3T](https://huggingface.co/TinyLlama/TinyLlama-1.1B-intermediate-step-1431k-3T). The TinyLlama project aims to pretrain a 1.1B Llama model on 3 trillion tokens with the adoption of the same architecture and tokenizer as Llama 2. This means TinyLlama can be plugged and played in many open-source projects built upon Llama. Besides, TinyLlama is compact with only 1.1B parameters. This compactness allows it to cater to a multitude of applications demanding a restricted computation and memory footprint. More details about model can be found in [model card](https://huggingface.co/TinyLlama/TinyLlama-1.1B-Chat-v1.0)\n", "* **phi-2** - Phi-2 is a Transformer with 2.7 billion parameters. It was trained using the same data sources as [Phi-1.5](https://huggingface.co/microsoft/phi-1_5), augmented with a new data source that consists of various NLP synthetic texts and filtered websites (for safety and educational value). When assessed against benchmarks testing common sense, language understanding, and logical reasoning, Phi-2 showcased a nearly state-of-the-art performance among models with less than 13 billion parameters. More details about model can be found in [model card](https://huggingface.co/microsoft/phi-2#limitations-of-phi-2).\n", "* **dolly-v2-3b** - Dolly 2.0 is an instruction-following large language model trained on the Databricks machine-learning platform that is licensed for commercial use. It is based on [Pythia](https://github.com/EleutherAI/pythia) and is trained on ~15k instruction/response fine-tuning records generated by Databricks employees in various capability domains, including brainstorming, classification, closed QA, generation, information extraction, open QA, and summarization. Dolly 2.0 works by processing natural language instructions and generating responses that follow the given instructions. It can be used for a wide range of applications, including closed question-answering, summarization, and generation. More details about model can be found in [model card](https://huggingface.co/databricks/dolly-v2-3b).\n", "* **red-pajama-3b-instruct** - A 2.8B parameter pre-trained language model based on GPT-NEOX architecture. The model was fine-tuned for few-shot applications on the data of [GPT-JT](https://huggingface.co/togethercomputer/GPT-JT-6B-v1), with exclusion of tasks that overlap with the HELM core scenarios.More details about model can be found in [model card](https://huggingface.co/togethercomputer/RedPajama-INCITE-Instruct-3B-v1).\n", "* **mistral-7b** - The Mistral-7B-v0.2 Large Language Model (LLM) is a pretrained generative text model with 7 billion parameters. You can find more details about model in the [model card](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2), [paper](https://arxiv.org/abs/2310.06825) and [release blog post](https://mistral.ai/news/announcing-mistral-7b/).\n", "* **llama-3-8b-instruct** - Llama 3 is an auto-regressive language model that uses an optimized transformer architecture. The tuned versions use supervised fine-tuning (SFT) and reinforcement learning with human feedback (RLHF) to align with human preferences for helpfulness and safety. The Llama 3 instruction tuned models are optimized for dialogue use cases and outperform many of the available open source chat models on common industry benchmarks. More details about model can be found in [Meta blog post](https://ai.meta.com/blog/meta-llama-3/), [model website](https://llama.meta.com/llama3) and [model card](https://huggingface.co/meta-llama/Meta-Llama-3-8B-Instruct).\n", ">**Note**: run model with demo, you will need to accept license agreement. \n", ">You must be a registered user in 🤗 Hugging Face Hub. Please visit [HuggingFace model card](https://huggingface.co/meta-llama/Llama-2-7b-chat-hf), carefully read terms of usage and click accept button. You will need to use an access token for the code below to run. For more information on access tokens, refer to [this section of the documentation](https://huggingface.co/docs/hub/security-tokens).\n", ">You can login on Hugging Face Hub in notebook environment, using following code:\n", " \n", "```python\n", " ## login to huggingfacehub to get access to pretrained model \n", "\n", " from huggingface_hub import notebook_login, whoami\n", "\n", " try:\n", " whoami()\n", " print('Authorization token already provided')\n", " except OSError:\n", " notebook_login()\n", "```" ] }, { "cell_type": "code", "execution_count": 2, "id": "51920510-effc-49ef-8c6f-81c951d96a9b", "metadata": {}, "outputs": [], "source": [ "from pathlib import Path\n", "import requests\n", "\n", "# Fetch `notebook_utils` module\n", "r = requests.get(\n", " url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/utils/notebook_utils.py\",\n", ")\n", "open(\"notebook_utils.py\", \"w\").write(r.text)\n", "from notebook_utils import download_file\n", "\n", "if not Path(\"./config.py\").exists():\n", " download_file(url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/notebooks/llm-question-answering/config.py\")\n", "from config import SUPPORTED_LLM_MODELS\n", "import ipywidgets as widgets" ] }, { "cell_type": "code", "execution_count": 3, "id": "27b42290-a9b5-4453-9a4c-ffa44bbd966d", "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "b4ac245cad30496283aaa25c8773fda5", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Dropdown(description='Model:', index=1, options=('tiny-llama-1b', 'phi-2', 'dolly-v2-3b', 'red-pajama-instruct…" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "model_ids = list(SUPPORTED_LLM_MODELS)\n", "\n", "model_id = widgets.Dropdown(\n", " options=model_ids,\n", " value=model_ids[1],\n", " description=\"Model:\",\n", " disabled=False,\n", ")\n", "\n", "model_id" ] }, { "cell_type": "code", "execution_count": 4, "id": "37e9634f-4fc7-4d9c-9ade-b3e8684a0828", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Selected model phi-2\n" ] } ], "source": [ "model_configuration = SUPPORTED_LLM_MODELS[model_id.value]\n", "print(f\"Selected model {model_id.value}\")" ] }, { "attachments": {}, "cell_type": "markdown", "id": "4e4fd394-b4fb-4eef-8bdc-d116572aa8f0", "metadata": {}, "source": [ "## Instantiate Model using Optimum Intel\n", "[back to top ⬆️](#Table-of-contents:)\n", "\n", "Optimum Intel can be used to load optimized models from the [Hugging Face Hub](https://huggingface.co/docs/optimum/intel/hf.co/models) and create pipelines to run an inference with OpenVINO Runtime using Hugging Face APIs. The Optimum Inference models are API compatible with Hugging Face Transformers models. This means we just need to replace `AutoModelForXxx` class with the corresponding `OVModelForXxx` class.\n", "\n", "Below is an example of the RedPajama model\n", "\n", "```diff\n", "-from transformers import AutoModelForCausalLM\n", "+from optimum.intel.openvino import OVModelForCausalLM\n", "from transformers import AutoTokenizer, pipeline\n", "\n", "model_id = \"togethercomputer/RedPajama-INCITE-Chat-3B-v1\"\n", "-model = AutoModelForCausalLM.from_pretrained(model_id)\n", "+model = OVModelForCausalLM.from_pretrained(model_id, export=True)\n", "```\n", "\n", "Model class initialization starts with calling `from_pretrained` method. When downloading and converting the Transformers model, the parameter `export=True` should be added. We can save the converted model for the next usage with the `save_pretrained` method.\n", "Tokenizer class and pipelines API are compatible with Optimum models.\n", "\n", "To optimize the generation process and use memory more efficiently, the `use_cache=True` option is enabled. Since the output side is auto-regressive, an output token hidden state remains the same once computed for every further generation step. Therefore, recomputing it every time you want to generate a new token seems wasteful. With the cache, the model saves the hidden state once it has been computed. The model only computes the one for the most recently generated output token at each time step, re-using the saved ones for hidden tokens. This reduces the generation complexity from $O(n^3)$ to $O(n^2)$ for a transformer model. More details about how it works can be found in this [article](https://scale.com/blog/pytorch-improvements#Text%20Translation). With this option, the model gets the previous step's hidden states (cached attention keys and values) as input and additionally provides hidden states for the current step as output. It means for all next iterations, it is enough to provide only a new token obtained from the previous step and cached key values to get the next token prediction. \n", "\n", "## Compress model weights\n", "[back to top ⬆️](#Table-of-contents:)\n", "The Weights Compression algorithm is aimed at compressing the weights of the models and can be used to optimize the model footprint and performance of large models where the size of weights is relatively larger than the size of activations, for example, Large Language Models (LLM). Compared to INT8 compression, INT4 compression improves performance even more but introduces a minor drop in prediction quality.\n", "\n", "\n", "### Weights Compression using Optimum Intel\n", "[back to top ⬆️](#Table-of-contents:)\n", "\n", "Optimum Intel supports weight compression via NNCF out of the box. For 8-bit compression we pass `load_in_8bit=True` to `from_pretrained()` method of `OVModelForCausalLM`. For 4 bit compression we provide `quantization_config=OVWeightQuantizationConfig(bits=4, ...)` argument containing number of bits and other compression parameters. An example of this approach usage you can find in [llm-chatbot notebook](../llm-chatbot)\n", "\n", "### Weights Compression using NNCF\n", "[back to top ⬆️](#Table-of-contents:)\n", "\n", "You also can perform weights compression for OpenVINO models using NNCF directly. `nncf.compress_weights` function accepts the OpenVINO model instance and compresses its weights for Linear and Embedding layers. We will consider this variant in this notebook for both int4 and int8 compression.\n", "\n", "\n", ">**Note**: This tutorial involves conversion model for FP16 and INT4/INT8 weights compression scenarios. It may be memory and time-consuming in the first run. You can manually control the compression precision below.\n", ">**Note**: There may be no speedup for INT4/INT8 compressed models on dGPU" ] }, { "cell_type": "code", "execution_count": 5, "id": "f81602ca-4674-4b61-b2c8-ca11631428b1", "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "b79a483555754690b823ef4d508d6d5a", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Checkbox(value=True, description='Prepare INT4 model')" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "5d95ad1da69041b3a3e40309db257714", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Checkbox(value=False, description='Prepare INT8 model')" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "05ddc6f4a34747afb0b0ddc238f58d19", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Checkbox(value=False, description='Prepare FP16 model')" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "from IPython.display import display\n", "\n", "prepare_int4_model = widgets.Checkbox(\n", " value=True,\n", " description=\"Prepare INT4 model\",\n", " disabled=False,\n", ")\n", "prepare_int8_model = widgets.Checkbox(\n", " value=False,\n", " description=\"Prepare INT8 model\",\n", " disabled=False,\n", ")\n", "prepare_fp16_model = widgets.Checkbox(\n", " value=False,\n", " description=\"Prepare FP16 model\",\n", " disabled=False,\n", ")\n", "\n", "display(prepare_int4_model)\n", "display(prepare_int8_model)\n", "display(prepare_fp16_model)" ] }, { "cell_type": "code", "execution_count": 6, "id": "0066fbec-b89b-4caa-94fb-9ea8598c22e0", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "INFO:nncf:NNCF initialized successfully. Supported frameworks detected: torch, tensorflow, onnx, openvino\n" ] } ], "source": [ "from pathlib import Path\n", "import logging\n", "import openvino as ov\n", "import nncf\n", "from optimum.intel.openvino import OVModelForCausalLM, OVWeightQuantizationConfig\n", "import gc\n", "\n", "\n", "nncf.set_log_level(logging.ERROR)\n", "\n", "pt_model_id = model_configuration[\"model_id\"]\n", "fp16_model_dir = Path(model_id.value) / \"FP16\"\n", "int8_model_dir = Path(model_id.value) / \"INT8_compressed_weights\"\n", "int4_model_dir = Path(model_id.value) / \"INT4_compressed_weights\"\n", "\n", "core = ov.Core()\n", "\n", "\n", "def convert_to_fp16():\n", " if (fp16_model_dir / \"openvino_model.xml\").exists():\n", " return\n", " ov_model = OVModelForCausalLM.from_pretrained(pt_model_id, export=True, compile=False, load_in_8bit=False)\n", " ov_model.half()\n", " ov_model.save_pretrained(fp16_model_dir)\n", " del ov_model\n", " gc.collect()\n", "\n", "\n", "def convert_to_int8():\n", " if (int8_model_dir / \"openvino_model.xml\").exists():\n", " return\n", " ov_model = OVModelForCausalLM.from_pretrained(pt_model_id, export=True, compile=False, load_in_8bit=True)\n", " ov_model.save_pretrained(int8_model_dir)\n", " del ov_model\n", " gc.collect()\n", "\n", "\n", "def convert_to_int4():\n", " compression_configs = {\n", " \"mistral-7b\": {\n", " \"sym\": True,\n", " \"group_size\": 64,\n", " \"ratio\": 0.6,\n", " },\n", " \"red-pajama-3b-instruct\": {\n", " \"sym\": False,\n", " \"group_size\": 128,\n", " \"ratio\": 0.5,\n", " },\n", " \"dolly-v2-3b\": {\"sym\": False, \"group_size\": 32, \"ratio\": 0.5},\n", " \"llama-3-8b-instruct\": {\"sym\": True, \"group_size\": 128, \"ratio\": 1.0},\n", " \"default\": {\n", " \"sym\": False,\n", " \"group_size\": 128,\n", " \"ratio\": 0.8,\n", " },\n", " }\n", "\n", " model_compression_params = compression_configs.get(model_id.value, compression_configs[\"default\"])\n", " if (int4_model_dir / \"openvino_model.xml\").exists():\n", " return\n", " ov_model = OVModelForCausalLM.from_pretrained(\n", " pt_model_id,\n", " export=True,\n", " compile=False,\n", " quantization_config=OVWeightQuantizationConfig(bits=4, **model_compression_params),\n", " )\n", " ov_model.save_pretrained(int4_model_dir)\n", " del ov_model\n", " gc.collect()\n", "\n", "\n", "if prepare_fp16_model.value:\n", " convert_to_fp16()\n", "if prepare_int8_model.value:\n", " convert_to_int8()\n", "if prepare_int4_model.value:\n", " convert_to_int4()" ] }, { "cell_type": "code", "execution_count": null, "id": "b5f31838-c7d6-4f52-aa2d-1f29c6f3b397", "metadata": {}, "outputs": [], "source": [] }, { "attachments": {}, "cell_type": "markdown", "id": "60355f86-2250-4ebe-82ac-950f2d4fb01b", "metadata": {}, "source": [ "Let's compare model size for different compression types" ] }, { "cell_type": "code", "execution_count": 7, "id": "42c7b254-1ce4-4f23-813a-9bdc23aed327", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Size of model with INT4 compressed weights is 1739.13 MB\n" ] } ], "source": [ "fp16_weights = fp16_model_dir / \"openvino_model.bin\"\n", "int8_weights = int8_model_dir / \"openvino_model.bin\"\n", "int4_weights = int4_model_dir / \"openvino_model.bin\"\n", "\n", "if fp16_weights.exists():\n", " print(f\"Size of FP16 model is {fp16_weights.stat().st_size / 1024 / 1024:.2f} MB\")\n", "for precision, compressed_weights in zip([8, 4], [int8_weights, int4_weights]):\n", " if compressed_weights.exists():\n", " print(f\"Size of model with INT{precision} compressed weights is {compressed_weights.stat().st_size / 1024 / 1024:.2f} MB\")\n", " if compressed_weights.exists() and fp16_weights.exists():\n", " print(f\"Compression rate for INT{precision} model: {fp16_weights.stat().st_size / compressed_weights.stat().st_size:.3f}\")" ] }, { "attachments": {}, "cell_type": "markdown", "id": "3df73379-bccc-41b1-9c94-c3040819805b", "metadata": {}, "source": [ "## Select device for inference and model variant\n", "[back to top ⬆️](#Table-of-contents:)\n", "\n", ">**Note**: There may be no speedup for INT4/INT8 compressed models on dGPU." ] }, { "cell_type": "code", "execution_count": 8, "id": "d2d7bf5b-8a05-4c3b-a36b-631af5c197e9", "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "054107d5ef3a470b97b87e28832f8327", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Dropdown(description='Device:', options=('CPU', 'GPU', 'AUTO'), value='CPU')" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "core = ov.Core()\n", "\n", "support_devices = core.available_devices\n", "if \"NPU\" in support_devices:\n", " support_devices.remove(\"NPU\")\n", "\n", "device = widgets.Dropdown(\n", " options=support_devices + [\"AUTO\"],\n", " value=\"CPU\",\n", " description=\"Device:\",\n", " disabled=False,\n", ")\n", "\n", "device" ] }, { "cell_type": "code", "execution_count": 9, "id": "24532480-80a5-4953-9cd6-78ac51a1cd8f", "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "b9ad14d1a4e44d50877d022399b894e9", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Dropdown(description='Model to run:', options=('INT4',), value='INT4')" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "available_models = []\n", "if int4_model_dir.exists():\n", " available_models.append(\"INT4\")\n", "if int8_model_dir.exists():\n", " available_models.append(\"INT8\")\n", "if fp16_model_dir.exists():\n", " available_models.append(\"FP16\")\n", "\n", "model_to_run = widgets.Dropdown(\n", " options=available_models,\n", " value=available_models[0],\n", " description=\"Model to run:\",\n", " disabled=False,\n", ")\n", "\n", "model_to_run" ] }, { "cell_type": "code", "execution_count": 10, "id": "5259c1c5-4128-4210-9ad2-faf33ee40e86", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Loading model from phi-2\\INT4_compressed_weights\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\n", "Compiling the model to CPU ...\n" ] } ], "source": [ "from transformers import AutoTokenizer\n", "\n", "if model_to_run.value == \"INT4\":\n", " model_dir = int4_model_dir\n", "elif model_to_run.value == \"INT8\":\n", " model_dir = int8_model_dir\n", "else:\n", " model_dir = fp16_model_dir\n", "print(f\"Loading model from {model_dir}\")\n", "\n", "model_name = model_configuration[\"model_id\"]\n", "ov_config = {\"PERFORMANCE_HINT\": \"LATENCY\", \"NUM_STREAMS\": \"1\", \"CACHE_DIR\": \"\"}\n", "\n", "tok = AutoTokenizer.from_pretrained(model_name)\n", "\n", "ov_model = OVModelForCausalLM.from_pretrained(\n", " model_dir,\n", " device=device.value,\n", " ov_config=ov_config,\n", ")" ] }, { "attachments": {}, "cell_type": "markdown", "id": "bf13f6c3-6671-408e-ae0e-aaa3d8a6eaac", "metadata": {}, "source": [ "## Create an instruction-following inference pipeline\n", "[back to top ⬆️](#Table-of-contents:)\n", " \n", " The `run_generation` function accepts user-provided text input, tokenizes it, and runs the generation process. Text generation is an iterative process, where each next token depends on previously generated until a maximum number of tokens or stop generation condition is not reached. To obtain intermediate generation results without waiting until when generation is finished, we will use [`TextIteratorStreamer`](https://huggingface.co/docs/transformers/main/en/internal/generation_utils#transformers.TextIteratorStreamer), provided as part of HuggingFace [Streaming API](https://huggingface.co/docs/transformers/main/en/generation_strategies#streaming).\n", " \n", "The diagram below illustrates how the instruction-following pipeline works\n", "\n", "![generation pipeline)](https://github.com/openvinotoolkit/openvino_notebooks/assets/29454499/e881f4a4-fcc8-427a-afe1-7dd80aebd66e)\n", "\n", "As can be seen, on the first iteration, the user provided instructions converted to token ids using a tokenizer, then prepared input provided to the model. The model generates probabilities for all tokens in logits format The way the next token will be selected over predicted probabilities is driven by the selected decoding methodology. You can find more information about the most popular decoding methods in this [blog](https://huggingface.co/blog/how-to-generate).\n", "\n", "There are several parameters that can control text generation quality:\n", "\n", " * `Temperature` is a parameter used to control the level of creativity in AI-generated text. By adjusting the `temperature`, you can influence the AI model's probability distribution, making the text more focused or diverse. \n", " Consider the following example: The AI model has to complete the sentence \"The cat is ____.\" with the following token probabilities: \n", "\n", " playing: 0.5 \n", " sleeping: 0.25 \n", " eating: 0.15 \n", " driving: 0.05 \n", " flying: 0.05 \n", "\n", " - **Low temperature** (e.g., 0.2): The AI model becomes more focused and deterministic, choosing tokens with the highest probability, such as \"playing.\" \n", " - **Medium temperature** (e.g., 1.0): The AI model maintains a balance between creativity and focus, selecting tokens based on their probabilities without significant bias, such as \"playing,\" \"sleeping,\" or \"eating.\" \n", " - **High temperature** (e.g., 2.0): The AI model becomes more adventurous, increasing the chances of selecting less likely tokens, such as \"driving\" and \"flying.\"\n", " * `Top-p`, also known as nucleus sampling, is a parameter used to control the range of tokens considered by the AI model based on their cumulative probability. By adjusting the `top-p` value, you can influence the AI model's token selection, making it more focused or diverse.\n", " Using the same example with the cat, consider the following top_p settings: \n", " - **Low top_p** (e.g., 0.5): The AI model considers only tokens with the highest cumulative probability, such as \"playing.\" \n", " - **Medium top_p** (e.g., 0.8): The AI model considers tokens with a higher cumulative probability, such as \"playing,\" \"sleeping,\" and \"eating.\" \n", " - **High top_p** (e.g., 1.0): The AI model considers all tokens, including those with lower probabilities, such as \"driving\" and \"flying.\" \n", " * `Top-k` is another popular sampling strategy. In comparison with Top-P, which chooses from the smallest possible set of words whose cumulative probability exceeds the probability P, in Top-K sampling K most likely next words are filtered and the probability mass is redistributed among only those K next words. In our example with cat, if k=3, then only \"playing\", \"sleeping\" and \"eating\" will be taken into account as possible next word.\n", "\n", "To optimize the generation process and use memory more efficiently, the `use_cache=True` option is enabled. Since the output side is auto-regressive, an output token hidden state remains the same once computed for every further generation step. Therefore, recomputing it every time you want to generate a new token seems wasteful. With the cache, the model saves the hidden state once it has been computed. The model only computes the one for the most recently generated output token at each time step, re-using the saved ones for hidden tokens. This reduces the generation complexity from O(n^3) to O(n^2) for a transformer model. More details about how it works can be found in this [article](https://scale.com/blog/pytorch-improvements#Text%20Translation). With this option, the model gets the previous step's hidden states (cached attention keys and values) as input and additionally provides hidden states for the current step as output. It means for all next iterations, it is enough to provide only a new token obtained from the previous step and cached key values to get the next token prediction. \n", "\n", "The generation cycle repeats until the end of the sequence token is reached or it also can be interrupted when maximum tokens will be generated. As already mentioned before, we can enable printing current generated tokens without waiting until when the whole generation is finished using Streaming API, it adds a new token to the output queue and then prints them when they are ready." ] }, { "attachments": {}, "cell_type": "markdown", "id": "eb7af692-0a15-4493-86ef-a80cda21551c", "metadata": {}, "source": [ "### Setup imports\n", "[back to top ⬆️](#Table-of-contents:)\n" ] }, { "cell_type": "code", "execution_count": 11, "id": "19d23a99-3284-42db-b7dc-5805d219f70d", "metadata": {}, "outputs": [], "source": [ "from threading import Thread\n", "from time import perf_counter\n", "from typing import List\n", "import gradio as gr\n", "from transformers import AutoTokenizer, TextIteratorStreamer\n", "import numpy as np" ] }, { "attachments": {}, "cell_type": "markdown", "id": "b341a9e6-290d-4780-90da-1ee64cee436d", "metadata": {}, "source": [ "### Prepare template for user prompt\n", "[back to top ⬆️](#Table-of-contents:)\n", "\n", "For effective generation, model expects to have input in specific format. The code below prepare template for passing user instruction into model with providing additional context." ] }, { "cell_type": "code", "execution_count": 12, "id": "e2638c5b-47ad-4213-80da-8cfc2659b3aa", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\n" ] } ], "source": [ "tokenizer = AutoTokenizer.from_pretrained(model_name)\n", "tokenizer_kwargs = model_configuration.get(\"toeknizer_kwargs\", {})\n", "\n", "\n", "def get_special_token_id(tokenizer: AutoTokenizer, key: str) -> int:\n", " \"\"\"\n", " Gets the token ID for a given string that has been added to the tokenizer as a special token.\n", "\n", " Args:\n", " tokenizer (PreTrainedTokenizer): the tokenizer\n", " key (str): the key to convert to a single token\n", "\n", " Raises:\n", " RuntimeError: if more than one ID was generated\n", "\n", " Returns:\n", " int: the token ID for the given key\n", " \"\"\"\n", " token_ids = tokenizer.encode(key)\n", " if len(token_ids) > 1:\n", " raise ValueError(f\"Expected only a single token for '{key}' but found {token_ids}\")\n", " return token_ids[0]\n", "\n", "\n", "response_key = model_configuration.get(\"response_key\")\n", "tokenizer_response_key = None\n", "\n", "if response_key is not None:\n", " tokenizer_response_key = next(\n", " (token for token in tokenizer.additional_special_tokens if token.startswith(response_key)),\n", " None,\n", " )\n", "\n", "end_key_token_id = None\n", "if tokenizer_response_key:\n", " try:\n", " end_key = model_configuration.get(\"end_key\")\n", " if end_key:\n", " end_key_token_id = get_special_token_id(tokenizer, end_key)\n", " # Ensure generation stops once it generates \"### End\"\n", " except ValueError:\n", " pass\n", "\n", "prompt_template = model_configuration.get(\"prompt_template\", \"{instruction}\")\n", "end_key_token_id = end_key_token_id or tokenizer.eos_token_id\n", "pad_token_id = end_key_token_id or tokenizer.pad_token_id" ] }, { "attachments": {}, "cell_type": "markdown", "id": "55dbc4ae-da28-4be8-b928-3dd68c197937", "metadata": {}, "source": [ "### Main generation function\n", "[back to top ⬆️](#Table-of-contents:)\n", "\n", "As it was discussed above, `run_generation` function is the entry point for starting generation. It gets provided input instruction as parameter and returns model response." ] }, { "cell_type": "code", "execution_count": 13, "id": "27802e81-9d42-4d71-99ea-5f76db5237f1", "metadata": {}, "outputs": [], "source": [ "def run_generation(\n", " user_text: str,\n", " top_p: float,\n", " temperature: float,\n", " top_k: int,\n", " max_new_tokens: int,\n", " perf_text: str,\n", "):\n", " \"\"\"\n", " Text generation function\n", "\n", " Parameters:\n", " user_text (str): User-provided instruction for a generation.\n", " top_p (float): Nucleus sampling. If set to < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for a generation.\n", " temperature (float): The value used to module the logits distribution.\n", " top_k (int): The number of highest probability vocabulary tokens to keep for top-k-filtering.\n", " max_new_tokens (int): Maximum length of generated sequence.\n", " perf_text (str): Content of text field for printing performance results.\n", " Returns:\n", " model_output (str) - model-generated text\n", " perf_text (str) - updated perf text filed content\n", " \"\"\"\n", "\n", " # Prepare input prompt according to model expected template\n", " prompt_text = prompt_template.format(instruction=user_text)\n", "\n", " # Tokenize the user text.\n", " model_inputs = tokenizer(prompt_text, return_tensors=\"pt\", **tokenizer_kwargs)\n", "\n", " # Start generation on a separate thread, so that we don't block the UI. The text is pulled from the streamer\n", " # in the main thread. Adds timeout to the streamer to handle exceptions in the generation thread.\n", " streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)\n", " generate_kwargs = dict(\n", " model_inputs,\n", " streamer=streamer,\n", " max_new_tokens=max_new_tokens,\n", " do_sample=True,\n", " top_p=top_p,\n", " temperature=float(temperature),\n", " top_k=top_k,\n", " eos_token_id=end_key_token_id,\n", " pad_token_id=pad_token_id,\n", " )\n", " t = Thread(target=ov_model.generate, kwargs=generate_kwargs)\n", " t.start()\n", "\n", " # Pull the generated text from the streamer, and update the model output.\n", " model_output = \"\"\n", " per_token_time = []\n", " num_tokens = 0\n", " start = perf_counter()\n", " for new_text in streamer:\n", " current_time = perf_counter() - start\n", " model_output += new_text\n", " perf_text, num_tokens = estimate_latency(current_time, perf_text, new_text, per_token_time, num_tokens)\n", " yield model_output, perf_text\n", " start = perf_counter()\n", " return model_output, perf_text" ] }, { "attachments": {}, "cell_type": "markdown", "id": "6d7b7182-1d9b-485b-81f2-1a9fab6d5cd4", "metadata": {}, "source": [ "### Helpers for application\n", "[back to top ⬆️](#Table-of-contents:)\n", "\n", "For making interactive user interface we will use Gradio library. The code bellow provides useful functions used for communication with UI elements." ] }, { "cell_type": "code", "execution_count": 14, "id": "c9b2a2b7-5a91-470f-98d7-7355664bc1be", "metadata": {}, "outputs": [], "source": [ "def estimate_latency(\n", " current_time: float,\n", " current_perf_text: str,\n", " new_gen_text: str,\n", " per_token_time: List[float],\n", " num_tokens: int,\n", "):\n", " \"\"\"\n", " Helper function for performance estimation\n", "\n", " Parameters:\n", " current_time (float): This step time in seconds.\n", " current_perf_text (str): Current content of performance UI field.\n", " new_gen_text (str): New generated text.\n", " per_token_time (List[float]): history of performance from previous steps.\n", " num_tokens (int): Total number of generated tokens.\n", "\n", " Returns:\n", " update for performance text field\n", " update for a total number of tokens\n", " \"\"\"\n", " num_current_toks = len(tokenizer.encode(new_gen_text))\n", " num_tokens += num_current_toks\n", " per_token_time.append(num_current_toks / current_time)\n", " if len(per_token_time) > 10 and len(per_token_time) % 4 == 0:\n", " current_bucket = per_token_time[:-10]\n", " return (\n", " f\"Average generation speed: {np.mean(current_bucket):.2f} tokens/s. Total generated tokens: {num_tokens}\",\n", " num_tokens,\n", " )\n", " return current_perf_text, num_tokens\n", "\n", "\n", "def reset_textbox(instruction: str, response: str, perf: str):\n", " \"\"\"\n", " Helper function for resetting content of all text fields\n", "\n", " Parameters:\n", " instruction (str): Content of user instruction field.\n", " response (str): Content of model response field.\n", " perf (str): Content of performance info filed\n", "\n", " Returns:\n", " empty string for each placeholder\n", " \"\"\"\n", " return \"\", \"\", \"\"" ] }, { "attachments": {}, "cell_type": "markdown", "id": "31ebb167-0e55-4271-aedd-13814c2356d2", "metadata": {}, "source": [ "## Run instruction-following pipeline\n", "[back to top ⬆️](#Table-of-contents:)\n", "\n", "Now, we are ready to explore model capabilities. This demo provides a simple interface that allows communication with a model using text instruction. Type your instruction into the `User instruction` field or select one from predefined examples and click on the `Submit` button to start generation. Additionally, you can modify advanced generation parameters:\n", "\n", "* `Device` - allows switching inference device. Please note, every time when new device is selected, model will be recompiled and this takes some time.\n", "* `Max New Tokens` - maximum size of generated text.\n", "* `Top-p (nucleus sampling)` - if set to < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for a generation.\n", "* `Top-k` - the number of highest probability vocabulary tokens to keep for top-k-filtering.\n", "* `Temperature` - the value used to module the logits distribution." ] }, { "cell_type": "code", "execution_count": 18, "id": "9f222d02-847a-490f-8d66-02608a53259b", "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "7b5b067e1bfb4fc3b480865576634ed1", "version_major": 2, "version_minor": 0 }, "text/plain": [ "VBox(children=(Label(value='Please login to access the demo:'), Text(value='', placeholder='Username'), Passwo…" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "import gradio as gr\n", "import ipywidgets as widgets\n", "from IPython.display import display, clear_output\n", "\n", "# Define your examples and other setup here\n", "examples = [\n", " \"Give me a recipe for pizza with pineapple\",\n", " \"Write me a tweet about the new OpenVINO release\",\n", " \"Explain the difference between CPU and GPU\",\n", " \"Give five ideas for a great weekend with family\",\n", " \"Do Androids dream of Electric sheep?\",\n", " \"Who is Dolly?\",\n", " \"Please give me advice on how to write resume?\",\n", " \"Name 3 advantages to being a cat\",\n", " \"Write instructions on how to become a good AI engineer\",\n", " \"Write a love letter to my best friend\",\n", "]\n", "\n", "# Function to check user credentials\n", "def authenticate(username, password):\n", " # Replace with actual authentication logic\n", " if username == \"user\" and password == \"password\":\n", " return True\n", " else:\n", " return False\n", "\n", "# Function to handle submission\n", "def handle_submit(button):\n", " clear_output()\n", " if authenticate(username.value, password.value):\n", " launch_demo()\n", " else:\n", " print(\"Authentication failed. Please try again.\")\n", "\n", "# Function to launch the Gradio demo\n", "def launch_demo():\n", " with gr.Blocks() as demo:\n", " gr.Markdown(\n", " \"# Question Answering with \" + model_id.value + \" and OpenVINO.\\n\"\n", " \"Provide instruction which describes a task below or select among predefined examples and model writes response that performs requested task.\"\n", " )\n", "\n", " with gr.Row():\n", " with gr.Column(scale=4):\n", " user_text = gr.Textbox(\n", " placeholder=\"Write an email about an alpaca that likes flan\",\n", " label=\"User instruction\",\n", " )\n", " model_output = gr.Textbox(label=\"Model response\", interactive=False)\n", " performance = gr.Textbox(label=\"Performance\", lines=1, interactive=False)\n", " with gr.Column(scale=1):\n", " button_clear = gr.Button(value=\"Clear\")\n", " button_submit = gr.Button(value=\"Submit\")\n", " gr.Examples(examples, user_text)\n", " with gr.Column(scale=1):\n", " max_new_tokens = gr.Slider(\n", " minimum=1,\n", " maximum=1000,\n", " value=256,\n", " step=1,\n", " interactive=True,\n", " label=\"Max New Tokens\",\n", " )\n", " top_p = gr.Slider(\n", " minimum=0.05,\n", " maximum=1.0,\n", " value=0.92,\n", " step=0.05,\n", " interactive=True,\n", " label=\"Top-p (nucleus sampling)\",\n", " )\n", " top_k = gr.Slider(\n", " minimum=0,\n", " maximum=50,\n", " value=0,\n", " step=1,\n", " interactive=True,\n", " label=\"Top-k\",\n", " )\n", " temperature = gr.Slider(\n", " minimum=0.1,\n", " maximum=5.0,\n", " value=0.8,\n", " step=0.1,\n", " interactive=True,\n", " label=\"Temperature\",\n", " )\n", "\n", " user_text.submit(\n", " run_generation,\n", " [user_text, top_p, temperature, top_k, max_new_tokens, performance],\n", " [model_output, performance],\n", " )\n", " button_submit.click(\n", " run_generation,\n", " [user_text, top_p, temperature, top_k, max_new_tokens, performance],\n", " [model_output, performance],\n", " )\n", " button_clear.click(\n", " reset_textbox,\n", " [user_text, model_output, performance],\n", " [user_text, model_output, performance],\n", " )\n", "\n", " demo.launch(height=800,share=True)\n", "\n", "# Define widgets for authentication\n", "username = widgets.Text(placeholder=\"Username\")\n", "password = widgets.Password(placeholder=\"Password\")\n", "submit_button = widgets.Button(description=\"Login\")\n", "submit_button.on_click(handle_submit)\n", "\n", "# Layout for login page\n", "login_page = widgets.VBox([\n", " widgets.Label(\"Please login to access the demo:\"),\n", " username,\n", " password,\n", " submit_button\n", "])\n", "\n", "# Display login page initially\n", "display(login_page)\n" ] }, { "cell_type": "code", "execution_count": null, "id": "440417f8-d2e2-4d8d-8311-882d133bb572", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "dd9f90e4-0ec6-4164-8a31-044b1079d3e7", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "7297ddd6-2c3d-4540-aa9b-f1c48c274a86", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "openvino_env", "language": "python", "name": "openvino_env" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.9" }, "openvino_notebooks": { "imageUrl": "https://github.com/openvinotoolkit/openvino_notebooks/assets/29454499/daafd702-5a42-4f54-ae72-2e4480d73501", "tags": { "categories": [ "Model Demos", "AI Trends" ], "libraries": [], "other": [ "LLM" ], "tasks": [ "Text Generation" ] } }, "widgets": { "application/vnd.jupyter.widget-state+json": { "state": {}, "version_major": 2, "version_minor": 0 } } }, "nbformat": 4, "nbformat_minor": 5 }