malvika2003 commited on
Commit
6be5174
1 Parent(s): b7692d2

Upload llm-question-answering-Copy1 (1).ipynb

Browse files
Files changed (1) hide show
  1. llm-question-answering-Copy1 (1).ipynb +1162 -0
llm-question-answering-Copy1 (1).ipynb ADDED
@@ -0,0 +1,1162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "attachments": {},
5
+ "cell_type": "markdown",
6
+ "id": "f6aa8c52-9bde-41a6-a5f7-4fa93d5c2a6c",
7
+ "metadata": {},
8
+ "source": [
9
+ "# LLM Instruction-following pipeline with OpenVINO \n",
10
+ "\n",
11
+ "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",
12
+ "\n",
13
+ "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",
14
+ "\n",
15
+ "The tutorial consists of the following steps:\n",
16
+ "\n",
17
+ "- Install prerequisites\n",
18
+ "- Download and convert the model from a public source using the [OpenVINO integration with Hugging Face Optimum](https://huggingface.co/blog/openvino).\n",
19
+ "- Compress model weights to INT8 and INT4 with [OpenVINO NNCF](https://github.com/openvinotoolkit/nncf)\n",
20
+ "- Create an instruction-following inference pipeline\n",
21
+ "- Run instruction-following pipeline\n",
22
+ "\n",
23
+ "\n",
24
+ "#### Table of contents:\n",
25
+ "\n",
26
+ "- [Prerequisites](#Prerequisites)\n",
27
+ "- [Select model for inference](#Select-model-for-inference)\n",
28
+ "- [Instantiate Model using Optimum Intel](#Instantiate-Model-using-Optimum-Intel)\n",
29
+ "- [Compress model weights](#Compress-model-weights)\n",
30
+ " - [Weights Compression using Optimum Intel](#Weights-Compression-using-Optimum-Intel)\n",
31
+ " - [Weights Compression using NNCF](#Weights-Compression-using-NNCF)\n",
32
+ "- [Select device for inference and model variant](#Select-device-for-inference-and-model-variant)\n",
33
+ "- [Create an instruction-following inference pipeline](#Create-an-instruction-following-inference-pipeline)\n",
34
+ " - [Setup imports](#Setup-imports)\n",
35
+ " - [Prepare template for user prompt](#Prepare-template-for-user-prompt)\n",
36
+ " - [Main generation function](#Main-generation-function)\n",
37
+ " - [Helpers for application](#Helpers-for-application)\n",
38
+ "- [Run instruction-following pipeline](#Run-instruction-following-pipeline)\n",
39
+ "\n"
40
+ ]
41
+ },
42
+ {
43
+ "attachments": {},
44
+ "cell_type": "markdown",
45
+ "id": "027108c2-1fbe-4be5-9e23-3fc359185a42",
46
+ "metadata": {},
47
+ "source": [
48
+ "## Prerequisites\n",
49
+ "[back to top ⬆️](#Table-of-contents:)\n"
50
+ ]
51
+ },
52
+ {
53
+ "cell_type": "code",
54
+ "execution_count": 1,
55
+ "id": "5d0473c6-3734-422d-a370-2e39d576be0e",
56
+ "metadata": {},
57
+ "outputs": [
58
+ {
59
+ "name": "stdout",
60
+ "output_type": "stream",
61
+ "text": [
62
+ "Note: you may need to restart the kernel to use updated packages.\n"
63
+ ]
64
+ },
65
+ {
66
+ "name": "stderr",
67
+ "output_type": "stream",
68
+ "text": [
69
+ "WARNING: Ignoring invalid distribution -ptimum (c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages)\n",
70
+ "WARNING: Ignoring invalid distribution -ptimum (c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages)\n"
71
+ ]
72
+ },
73
+ {
74
+ "name": "stdout",
75
+ "output_type": "stream",
76
+ "text": [
77
+ "Note: you may need to restart the kernel to use updated packages.\n"
78
+ ]
79
+ },
80
+ {
81
+ "name": "stderr",
82
+ "output_type": "stream",
83
+ "text": [
84
+ "WARNING: Ignoring invalid distribution -ptimum (c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages)\n",
85
+ "WARNING: Skipping optimum as it is not installed.\n",
86
+ "WARNING: Ignoring invalid distribution -ptimum (c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages)\n",
87
+ "WARNING: Skipping optimum-intel as it is not installed.\n"
88
+ ]
89
+ },
90
+ {
91
+ "name": "stdout",
92
+ "output_type": "stream",
93
+ "text": [
94
+ "Note: you may need to restart the kernel to use updated packages.\n"
95
+ ]
96
+ },
97
+ {
98
+ "name": "stderr",
99
+ "output_type": "stream",
100
+ "text": [
101
+ "WARNING: Ignoring invalid distribution -ptimum (c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages)\n",
102
+ "WARNING: Ignoring invalid distribution -ptimum (c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages)\n"
103
+ ]
104
+ },
105
+ {
106
+ "name": "stdout",
107
+ "output_type": "stream",
108
+ "text": [
109
+ "Note: you may need to restart the kernel to use updated packages.\n"
110
+ ]
111
+ },
112
+ {
113
+ "name": "stderr",
114
+ "output_type": "stream",
115
+ "text": [
116
+ "WARNING: Ignoring invalid distribution -ptimum (c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages)\n",
117
+ "WARNING: Ignoring invalid distribution -ptimum (c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages)\n"
118
+ ]
119
+ }
120
+ ],
121
+ "source": [
122
+ "%pip install -Uq pip\n",
123
+ "%pip uninstall -q -y optimum optimum-intel\n",
124
+ "%pip install --pre -Uq openvino openvino-tokenizers[transformers] --extra-index-url https://storage.openvinotoolkit.org/simple/wheels/nightly\n",
125
+ "%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"
126
+ ]
127
+ },
128
+ {
129
+ "attachments": {},
130
+ "cell_type": "markdown",
131
+ "id": "611cc777-d5bc-4c7b-92e4-a4befa13b2ce",
132
+ "metadata": {},
133
+ "source": [
134
+ "## Select model for inference\n",
135
+ "[back to top ⬆️](#Table-of-contents:)\n",
136
+ "\n",
137
+ "The tutorial supports different models, you can select one from the provided options to compare the quality of open source LLM solutions.\n",
138
+ ">**Note**: conversion of some models can require additional actions from user side and at least 64GB RAM for conversion.\n",
139
+ "\n",
140
+ "The available options are:\n",
141
+ "\n",
142
+ "* **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",
143
+ "* **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",
144
+ "* **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",
145
+ "* **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",
146
+ "* **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",
147
+ "* **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",
148
+ ">**Note**: run model with demo, you will need to accept license agreement. \n",
149
+ ">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",
150
+ ">You can login on Hugging Face Hub in notebook environment, using following code:\n",
151
+ " \n",
152
+ "```python\n",
153
+ " ## login to huggingfacehub to get access to pretrained model \n",
154
+ "\n",
155
+ " from huggingface_hub import notebook_login, whoami\n",
156
+ "\n",
157
+ " try:\n",
158
+ " whoami()\n",
159
+ " print('Authorization token already provided')\n",
160
+ " except OSError:\n",
161
+ " notebook_login()\n",
162
+ "```"
163
+ ]
164
+ },
165
+ {
166
+ "cell_type": "code",
167
+ "execution_count": 2,
168
+ "id": "51920510-effc-49ef-8c6f-81c951d96a9b",
169
+ "metadata": {},
170
+ "outputs": [],
171
+ "source": [
172
+ "from pathlib import Path\n",
173
+ "import requests\n",
174
+ "\n",
175
+ "# Fetch `notebook_utils` module\n",
176
+ "r = requests.get(\n",
177
+ " url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/utils/notebook_utils.py\",\n",
178
+ ")\n",
179
+ "open(\"notebook_utils.py\", \"w\").write(r.text)\n",
180
+ "from notebook_utils import download_file\n",
181
+ "\n",
182
+ "if not Path(\"./config.py\").exists():\n",
183
+ " download_file(url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/notebooks/llm-question-answering/config.py\")\n",
184
+ "from config import SUPPORTED_LLM_MODELS\n",
185
+ "import ipywidgets as widgets"
186
+ ]
187
+ },
188
+ {
189
+ "cell_type": "code",
190
+ "execution_count": 3,
191
+ "id": "27b42290-a9b5-4453-9a4c-ffa44bbd966d",
192
+ "metadata": {},
193
+ "outputs": [
194
+ {
195
+ "data": {
196
+ "application/vnd.jupyter.widget-view+json": {
197
+ "model_id": "b4ac245cad30496283aaa25c8773fda5",
198
+ "version_major": 2,
199
+ "version_minor": 0
200
+ },
201
+ "text/plain": [
202
+ "Dropdown(description='Model:', index=1, options=('tiny-llama-1b', 'phi-2', 'dolly-v2-3b', 'red-pajama-instruct…"
203
+ ]
204
+ },
205
+ "execution_count": 3,
206
+ "metadata": {},
207
+ "output_type": "execute_result"
208
+ }
209
+ ],
210
+ "source": [
211
+ "model_ids = list(SUPPORTED_LLM_MODELS)\n",
212
+ "\n",
213
+ "model_id = widgets.Dropdown(\n",
214
+ " options=model_ids,\n",
215
+ " value=model_ids[1],\n",
216
+ " description=\"Model:\",\n",
217
+ " disabled=False,\n",
218
+ ")\n",
219
+ "\n",
220
+ "model_id"
221
+ ]
222
+ },
223
+ {
224
+ "cell_type": "code",
225
+ "execution_count": 4,
226
+ "id": "37e9634f-4fc7-4d9c-9ade-b3e8684a0828",
227
+ "metadata": {},
228
+ "outputs": [
229
+ {
230
+ "name": "stdout",
231
+ "output_type": "stream",
232
+ "text": [
233
+ "Selected model phi-2\n"
234
+ ]
235
+ }
236
+ ],
237
+ "source": [
238
+ "model_configuration = SUPPORTED_LLM_MODELS[model_id.value]\n",
239
+ "print(f\"Selected model {model_id.value}\")"
240
+ ]
241
+ },
242
+ {
243
+ "attachments": {},
244
+ "cell_type": "markdown",
245
+ "id": "4e4fd394-b4fb-4eef-8bdc-d116572aa8f0",
246
+ "metadata": {},
247
+ "source": [
248
+ "## Instantiate Model using Optimum Intel\n",
249
+ "[back to top ⬆️](#Table-of-contents:)\n",
250
+ "\n",
251
+ "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",
252
+ "\n",
253
+ "Below is an example of the RedPajama model\n",
254
+ "\n",
255
+ "```diff\n",
256
+ "-from transformers import AutoModelForCausalLM\n",
257
+ "+from optimum.intel.openvino import OVModelForCausalLM\n",
258
+ "from transformers import AutoTokenizer, pipeline\n",
259
+ "\n",
260
+ "model_id = \"togethercomputer/RedPajama-INCITE-Chat-3B-v1\"\n",
261
+ "-model = AutoModelForCausalLM.from_pretrained(model_id)\n",
262
+ "+model = OVModelForCausalLM.from_pretrained(model_id, export=True)\n",
263
+ "```\n",
264
+ "\n",
265
+ "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",
266
+ "Tokenizer class and pipelines API are compatible with Optimum models.\n",
267
+ "\n",
268
+ "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",
269
+ "\n",
270
+ "## Compress model weights\n",
271
+ "[back to top ⬆️](#Table-of-contents:)\n",
272
+ "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",
273
+ "\n",
274
+ "\n",
275
+ "### Weights Compression using Optimum Intel\n",
276
+ "[back to top ⬆️](#Table-of-contents:)\n",
277
+ "\n",
278
+ "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",
279
+ "\n",
280
+ "### Weights Compression using NNCF\n",
281
+ "[back to top ⬆️](#Table-of-contents:)\n",
282
+ "\n",
283
+ "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",
284
+ "\n",
285
+ "\n",
286
+ ">**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",
287
+ ">**Note**: There may be no speedup for INT4/INT8 compressed models on dGPU"
288
+ ]
289
+ },
290
+ {
291
+ "cell_type": "code",
292
+ "execution_count": 5,
293
+ "id": "f81602ca-4674-4b61-b2c8-ca11631428b1",
294
+ "metadata": {},
295
+ "outputs": [
296
+ {
297
+ "data": {
298
+ "application/vnd.jupyter.widget-view+json": {
299
+ "model_id": "b79a483555754690b823ef4d508d6d5a",
300
+ "version_major": 2,
301
+ "version_minor": 0
302
+ },
303
+ "text/plain": [
304
+ "Checkbox(value=True, description='Prepare INT4 model')"
305
+ ]
306
+ },
307
+ "metadata": {},
308
+ "output_type": "display_data"
309
+ },
310
+ {
311
+ "data": {
312
+ "application/vnd.jupyter.widget-view+json": {
313
+ "model_id": "5d95ad1da69041b3a3e40309db257714",
314
+ "version_major": 2,
315
+ "version_minor": 0
316
+ },
317
+ "text/plain": [
318
+ "Checkbox(value=False, description='Prepare INT8 model')"
319
+ ]
320
+ },
321
+ "metadata": {},
322
+ "output_type": "display_data"
323
+ },
324
+ {
325
+ "data": {
326
+ "application/vnd.jupyter.widget-view+json": {
327
+ "model_id": "05ddc6f4a34747afb0b0ddc238f58d19",
328
+ "version_major": 2,
329
+ "version_minor": 0
330
+ },
331
+ "text/plain": [
332
+ "Checkbox(value=False, description='Prepare FP16 model')"
333
+ ]
334
+ },
335
+ "metadata": {},
336
+ "output_type": "display_data"
337
+ }
338
+ ],
339
+ "source": [
340
+ "from IPython.display import display\n",
341
+ "\n",
342
+ "prepare_int4_model = widgets.Checkbox(\n",
343
+ " value=True,\n",
344
+ " description=\"Prepare INT4 model\",\n",
345
+ " disabled=False,\n",
346
+ ")\n",
347
+ "prepare_int8_model = widgets.Checkbox(\n",
348
+ " value=False,\n",
349
+ " description=\"Prepare INT8 model\",\n",
350
+ " disabled=False,\n",
351
+ ")\n",
352
+ "prepare_fp16_model = widgets.Checkbox(\n",
353
+ " value=False,\n",
354
+ " description=\"Prepare FP16 model\",\n",
355
+ " disabled=False,\n",
356
+ ")\n",
357
+ "\n",
358
+ "display(prepare_int4_model)\n",
359
+ "display(prepare_int8_model)\n",
360
+ "display(prepare_fp16_model)"
361
+ ]
362
+ },
363
+ {
364
+ "cell_type": "code",
365
+ "execution_count": 6,
366
+ "id": "0066fbec-b89b-4caa-94fb-9ea8598c22e0",
367
+ "metadata": {},
368
+ "outputs": [
369
+ {
370
+ "name": "stdout",
371
+ "output_type": "stream",
372
+ "text": [
373
+ "INFO:nncf:NNCF initialized successfully. Supported frameworks detected: torch, tensorflow, onnx, openvino\n"
374
+ ]
375
+ }
376
+ ],
377
+ "source": [
378
+ "from pathlib import Path\n",
379
+ "import logging\n",
380
+ "import openvino as ov\n",
381
+ "import nncf\n",
382
+ "from optimum.intel.openvino import OVModelForCausalLM, OVWeightQuantizationConfig\n",
383
+ "import gc\n",
384
+ "\n",
385
+ "\n",
386
+ "nncf.set_log_level(logging.ERROR)\n",
387
+ "\n",
388
+ "pt_model_id = model_configuration[\"model_id\"]\n",
389
+ "fp16_model_dir = Path(model_id.value) / \"FP16\"\n",
390
+ "int8_model_dir = Path(model_id.value) / \"INT8_compressed_weights\"\n",
391
+ "int4_model_dir = Path(model_id.value) / \"INT4_compressed_weights\"\n",
392
+ "\n",
393
+ "core = ov.Core()\n",
394
+ "\n",
395
+ "\n",
396
+ "def convert_to_fp16():\n",
397
+ " if (fp16_model_dir / \"openvino_model.xml\").exists():\n",
398
+ " return\n",
399
+ " ov_model = OVModelForCausalLM.from_pretrained(pt_model_id, export=True, compile=False, load_in_8bit=False)\n",
400
+ " ov_model.half()\n",
401
+ " ov_model.save_pretrained(fp16_model_dir)\n",
402
+ " del ov_model\n",
403
+ " gc.collect()\n",
404
+ "\n",
405
+ "\n",
406
+ "def convert_to_int8():\n",
407
+ " if (int8_model_dir / \"openvino_model.xml\").exists():\n",
408
+ " return\n",
409
+ " ov_model = OVModelForCausalLM.from_pretrained(pt_model_id, export=True, compile=False, load_in_8bit=True)\n",
410
+ " ov_model.save_pretrained(int8_model_dir)\n",
411
+ " del ov_model\n",
412
+ " gc.collect()\n",
413
+ "\n",
414
+ "\n",
415
+ "def convert_to_int4():\n",
416
+ " compression_configs = {\n",
417
+ " \"mistral-7b\": {\n",
418
+ " \"sym\": True,\n",
419
+ " \"group_size\": 64,\n",
420
+ " \"ratio\": 0.6,\n",
421
+ " },\n",
422
+ " \"red-pajama-3b-instruct\": {\n",
423
+ " \"sym\": False,\n",
424
+ " \"group_size\": 128,\n",
425
+ " \"ratio\": 0.5,\n",
426
+ " },\n",
427
+ " \"dolly-v2-3b\": {\"sym\": False, \"group_size\": 32, \"ratio\": 0.5},\n",
428
+ " \"llama-3-8b-instruct\": {\"sym\": True, \"group_size\": 128, \"ratio\": 1.0},\n",
429
+ " \"default\": {\n",
430
+ " \"sym\": False,\n",
431
+ " \"group_size\": 128,\n",
432
+ " \"ratio\": 0.8,\n",
433
+ " },\n",
434
+ " }\n",
435
+ "\n",
436
+ " model_compression_params = compression_configs.get(model_id.value, compression_configs[\"default\"])\n",
437
+ " if (int4_model_dir / \"openvino_model.xml\").exists():\n",
438
+ " return\n",
439
+ " ov_model = OVModelForCausalLM.from_pretrained(\n",
440
+ " pt_model_id,\n",
441
+ " export=True,\n",
442
+ " compile=False,\n",
443
+ " quantization_config=OVWeightQuantizationConfig(bits=4, **model_compression_params),\n",
444
+ " )\n",
445
+ " ov_model.save_pretrained(int4_model_dir)\n",
446
+ " del ov_model\n",
447
+ " gc.collect()\n",
448
+ "\n",
449
+ "\n",
450
+ "if prepare_fp16_model.value:\n",
451
+ " convert_to_fp16()\n",
452
+ "if prepare_int8_model.value:\n",
453
+ " convert_to_int8()\n",
454
+ "if prepare_int4_model.value:\n",
455
+ " convert_to_int4()"
456
+ ]
457
+ },
458
+ {
459
+ "cell_type": "code",
460
+ "execution_count": null,
461
+ "id": "b5f31838-c7d6-4f52-aa2d-1f29c6f3b397",
462
+ "metadata": {},
463
+ "outputs": [],
464
+ "source": []
465
+ },
466
+ {
467
+ "attachments": {},
468
+ "cell_type": "markdown",
469
+ "id": "60355f86-2250-4ebe-82ac-950f2d4fb01b",
470
+ "metadata": {},
471
+ "source": [
472
+ "Let's compare model size for different compression types"
473
+ ]
474
+ },
475
+ {
476
+ "cell_type": "code",
477
+ "execution_count": 7,
478
+ "id": "42c7b254-1ce4-4f23-813a-9bdc23aed327",
479
+ "metadata": {},
480
+ "outputs": [
481
+ {
482
+ "name": "stdout",
483
+ "output_type": "stream",
484
+ "text": [
485
+ "Size of model with INT4 compressed weights is 1739.13 MB\n"
486
+ ]
487
+ }
488
+ ],
489
+ "source": [
490
+ "fp16_weights = fp16_model_dir / \"openvino_model.bin\"\n",
491
+ "int8_weights = int8_model_dir / \"openvino_model.bin\"\n",
492
+ "int4_weights = int4_model_dir / \"openvino_model.bin\"\n",
493
+ "\n",
494
+ "if fp16_weights.exists():\n",
495
+ " print(f\"Size of FP16 model is {fp16_weights.stat().st_size / 1024 / 1024:.2f} MB\")\n",
496
+ "for precision, compressed_weights in zip([8, 4], [int8_weights, int4_weights]):\n",
497
+ " if compressed_weights.exists():\n",
498
+ " print(f\"Size of model with INT{precision} compressed weights is {compressed_weights.stat().st_size / 1024 / 1024:.2f} MB\")\n",
499
+ " if compressed_weights.exists() and fp16_weights.exists():\n",
500
+ " print(f\"Compression rate for INT{precision} model: {fp16_weights.stat().st_size / compressed_weights.stat().st_size:.3f}\")"
501
+ ]
502
+ },
503
+ {
504
+ "attachments": {},
505
+ "cell_type": "markdown",
506
+ "id": "3df73379-bccc-41b1-9c94-c3040819805b",
507
+ "metadata": {},
508
+ "source": [
509
+ "## Select device for inference and model variant\n",
510
+ "[back to top ⬆️](#Table-of-contents:)\n",
511
+ "\n",
512
+ ">**Note**: There may be no speedup for INT4/INT8 compressed models on dGPU."
513
+ ]
514
+ },
515
+ {
516
+ "cell_type": "code",
517
+ "execution_count": 8,
518
+ "id": "d2d7bf5b-8a05-4c3b-a36b-631af5c197e9",
519
+ "metadata": {},
520
+ "outputs": [
521
+ {
522
+ "data": {
523
+ "application/vnd.jupyter.widget-view+json": {
524
+ "model_id": "054107d5ef3a470b97b87e28832f8327",
525
+ "version_major": 2,
526
+ "version_minor": 0
527
+ },
528
+ "text/plain": [
529
+ "Dropdown(description='Device:', options=('CPU', 'GPU', 'AUTO'), value='CPU')"
530
+ ]
531
+ },
532
+ "execution_count": 8,
533
+ "metadata": {},
534
+ "output_type": "execute_result"
535
+ }
536
+ ],
537
+ "source": [
538
+ "core = ov.Core()\n",
539
+ "\n",
540
+ "support_devices = core.available_devices\n",
541
+ "if \"NPU\" in support_devices:\n",
542
+ " support_devices.remove(\"NPU\")\n",
543
+ "\n",
544
+ "device = widgets.Dropdown(\n",
545
+ " options=support_devices + [\"AUTO\"],\n",
546
+ " value=\"CPU\",\n",
547
+ " description=\"Device:\",\n",
548
+ " disabled=False,\n",
549
+ ")\n",
550
+ "\n",
551
+ "device"
552
+ ]
553
+ },
554
+ {
555
+ "cell_type": "code",
556
+ "execution_count": 9,
557
+ "id": "24532480-80a5-4953-9cd6-78ac51a1cd8f",
558
+ "metadata": {},
559
+ "outputs": [
560
+ {
561
+ "data": {
562
+ "application/vnd.jupyter.widget-view+json": {
563
+ "model_id": "b9ad14d1a4e44d50877d022399b894e9",
564
+ "version_major": 2,
565
+ "version_minor": 0
566
+ },
567
+ "text/plain": [
568
+ "Dropdown(description='Model to run:', options=('INT4',), value='INT4')"
569
+ ]
570
+ },
571
+ "execution_count": 9,
572
+ "metadata": {},
573
+ "output_type": "execute_result"
574
+ }
575
+ ],
576
+ "source": [
577
+ "available_models = []\n",
578
+ "if int4_model_dir.exists():\n",
579
+ " available_models.append(\"INT4\")\n",
580
+ "if int8_model_dir.exists():\n",
581
+ " available_models.append(\"INT8\")\n",
582
+ "if fp16_model_dir.exists():\n",
583
+ " available_models.append(\"FP16\")\n",
584
+ "\n",
585
+ "model_to_run = widgets.Dropdown(\n",
586
+ " options=available_models,\n",
587
+ " value=available_models[0],\n",
588
+ " description=\"Model to run:\",\n",
589
+ " disabled=False,\n",
590
+ ")\n",
591
+ "\n",
592
+ "model_to_run"
593
+ ]
594
+ },
595
+ {
596
+ "cell_type": "code",
597
+ "execution_count": 10,
598
+ "id": "5259c1c5-4128-4210-9ad2-faf33ee40e86",
599
+ "metadata": {},
600
+ "outputs": [
601
+ {
602
+ "name": "stdout",
603
+ "output_type": "stream",
604
+ "text": [
605
+ "Loading model from phi-2\\INT4_compressed_weights\n"
606
+ ]
607
+ },
608
+ {
609
+ "name": "stderr",
610
+ "output_type": "stream",
611
+ "text": [
612
+ "Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\n",
613
+ "Compiling the model to CPU ...\n"
614
+ ]
615
+ }
616
+ ],
617
+ "source": [
618
+ "from transformers import AutoTokenizer\n",
619
+ "\n",
620
+ "if model_to_run.value == \"INT4\":\n",
621
+ " model_dir = int4_model_dir\n",
622
+ "elif model_to_run.value == \"INT8\":\n",
623
+ " model_dir = int8_model_dir\n",
624
+ "else:\n",
625
+ " model_dir = fp16_model_dir\n",
626
+ "print(f\"Loading model from {model_dir}\")\n",
627
+ "\n",
628
+ "model_name = model_configuration[\"model_id\"]\n",
629
+ "ov_config = {\"PERFORMANCE_HINT\": \"LATENCY\", \"NUM_STREAMS\": \"1\", \"CACHE_DIR\": \"\"}\n",
630
+ "\n",
631
+ "tok = AutoTokenizer.from_pretrained(model_name)\n",
632
+ "\n",
633
+ "ov_model = OVModelForCausalLM.from_pretrained(\n",
634
+ " model_dir,\n",
635
+ " device=device.value,\n",
636
+ " ov_config=ov_config,\n",
637
+ ")"
638
+ ]
639
+ },
640
+ {
641
+ "attachments": {},
642
+ "cell_type": "markdown",
643
+ "id": "bf13f6c3-6671-408e-ae0e-aaa3d8a6eaac",
644
+ "metadata": {},
645
+ "source": [
646
+ "## Create an instruction-following inference pipeline\n",
647
+ "[back to top ⬆️](#Table-of-contents:)\n",
648
+ " \n",
649
+ " 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",
650
+ " \n",
651
+ "The diagram below illustrates how the instruction-following pipeline works\n",
652
+ "\n",
653
+ "![generation pipeline)](https://github.com/openvinotoolkit/openvino_notebooks/assets/29454499/e881f4a4-fcc8-427a-afe1-7dd80aebd66e)\n",
654
+ "\n",
655
+ "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",
656
+ "\n",
657
+ "There are several parameters that can control text generation quality:\n",
658
+ "\n",
659
+ " * `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",
660
+ " Consider the following example: The AI model has to complete the sentence \"The cat is ____.\" with the following token probabilities: \n",
661
+ "\n",
662
+ " playing: 0.5 \n",
663
+ " sleeping: 0.25 \n",
664
+ " eating: 0.15 \n",
665
+ " driving: 0.05 \n",
666
+ " flying: 0.05 \n",
667
+ "\n",
668
+ " - **Low temperature** (e.g., 0.2): The AI model becomes more focused and deterministic, choosing tokens with the highest probability, such as \"playing.\" \n",
669
+ " - **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",
670
+ " - **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",
671
+ " * `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",
672
+ " Using the same example with the cat, consider the following top_p settings: \n",
673
+ " - **Low top_p** (e.g., 0.5): The AI model considers only tokens with the highest cumulative probability, such as \"playing.\" \n",
674
+ " - **Medium top_p** (e.g., 0.8): The AI model considers tokens with a higher cumulative probability, such as \"playing,\" \"sleeping,\" and \"eating.\" \n",
675
+ " - **High top_p** (e.g., 1.0): The AI model considers all tokens, including those with lower probabilities, such as \"driving\" and \"flying.\" \n",
676
+ " * `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",
677
+ "\n",
678
+ "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",
679
+ "\n",
680
+ "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."
681
+ ]
682
+ },
683
+ {
684
+ "attachments": {},
685
+ "cell_type": "markdown",
686
+ "id": "eb7af692-0a15-4493-86ef-a80cda21551c",
687
+ "metadata": {},
688
+ "source": [
689
+ "### Setup imports\n",
690
+ "[back to top ⬆️](#Table-of-contents:)\n"
691
+ ]
692
+ },
693
+ {
694
+ "cell_type": "code",
695
+ "execution_count": 11,
696
+ "id": "19d23a99-3284-42db-b7dc-5805d219f70d",
697
+ "metadata": {},
698
+ "outputs": [],
699
+ "source": [
700
+ "from threading import Thread\n",
701
+ "from time import perf_counter\n",
702
+ "from typing import List\n",
703
+ "import gradio as gr\n",
704
+ "from transformers import AutoTokenizer, TextIteratorStreamer\n",
705
+ "import numpy as np"
706
+ ]
707
+ },
708
+ {
709
+ "attachments": {},
710
+ "cell_type": "markdown",
711
+ "id": "b341a9e6-290d-4780-90da-1ee64cee436d",
712
+ "metadata": {},
713
+ "source": [
714
+ "### Prepare template for user prompt\n",
715
+ "[back to top ⬆️](#Table-of-contents:)\n",
716
+ "\n",
717
+ "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."
718
+ ]
719
+ },
720
+ {
721
+ "cell_type": "code",
722
+ "execution_count": 12,
723
+ "id": "e2638c5b-47ad-4213-80da-8cfc2659b3aa",
724
+ "metadata": {},
725
+ "outputs": [
726
+ {
727
+ "name": "stderr",
728
+ "output_type": "stream",
729
+ "text": [
730
+ "Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\n"
731
+ ]
732
+ }
733
+ ],
734
+ "source": [
735
+ "tokenizer = AutoTokenizer.from_pretrained(model_name)\n",
736
+ "tokenizer_kwargs = model_configuration.get(\"toeknizer_kwargs\", {})\n",
737
+ "\n",
738
+ "\n",
739
+ "def get_special_token_id(tokenizer: AutoTokenizer, key: str) -> int:\n",
740
+ " \"\"\"\n",
741
+ " Gets the token ID for a given string that has been added to the tokenizer as a special token.\n",
742
+ "\n",
743
+ " Args:\n",
744
+ " tokenizer (PreTrainedTokenizer): the tokenizer\n",
745
+ " key (str): the key to convert to a single token\n",
746
+ "\n",
747
+ " Raises:\n",
748
+ " RuntimeError: if more than one ID was generated\n",
749
+ "\n",
750
+ " Returns:\n",
751
+ " int: the token ID for the given key\n",
752
+ " \"\"\"\n",
753
+ " token_ids = tokenizer.encode(key)\n",
754
+ " if len(token_ids) > 1:\n",
755
+ " raise ValueError(f\"Expected only a single token for '{key}' but found {token_ids}\")\n",
756
+ " return token_ids[0]\n",
757
+ "\n",
758
+ "\n",
759
+ "response_key = model_configuration.get(\"response_key\")\n",
760
+ "tokenizer_response_key = None\n",
761
+ "\n",
762
+ "if response_key is not None:\n",
763
+ " tokenizer_response_key = next(\n",
764
+ " (token for token in tokenizer.additional_special_tokens if token.startswith(response_key)),\n",
765
+ " None,\n",
766
+ " )\n",
767
+ "\n",
768
+ "end_key_token_id = None\n",
769
+ "if tokenizer_response_key:\n",
770
+ " try:\n",
771
+ " end_key = model_configuration.get(\"end_key\")\n",
772
+ " if end_key:\n",
773
+ " end_key_token_id = get_special_token_id(tokenizer, end_key)\n",
774
+ " # Ensure generation stops once it generates \"### End\"\n",
775
+ " except ValueError:\n",
776
+ " pass\n",
777
+ "\n",
778
+ "prompt_template = model_configuration.get(\"prompt_template\", \"{instruction}\")\n",
779
+ "end_key_token_id = end_key_token_id or tokenizer.eos_token_id\n",
780
+ "pad_token_id = end_key_token_id or tokenizer.pad_token_id"
781
+ ]
782
+ },
783
+ {
784
+ "attachments": {},
785
+ "cell_type": "markdown",
786
+ "id": "55dbc4ae-da28-4be8-b928-3dd68c197937",
787
+ "metadata": {},
788
+ "source": [
789
+ "### Main generation function\n",
790
+ "[back to top ⬆️](#Table-of-contents:)\n",
791
+ "\n",
792
+ "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."
793
+ ]
794
+ },
795
+ {
796
+ "cell_type": "code",
797
+ "execution_count": 13,
798
+ "id": "27802e81-9d42-4d71-99ea-5f76db5237f1",
799
+ "metadata": {},
800
+ "outputs": [],
801
+ "source": [
802
+ "def run_generation(\n",
803
+ " user_text: str,\n",
804
+ " top_p: float,\n",
805
+ " temperature: float,\n",
806
+ " top_k: int,\n",
807
+ " max_new_tokens: int,\n",
808
+ " perf_text: str,\n",
809
+ "):\n",
810
+ " \"\"\"\n",
811
+ " Text generation function\n",
812
+ "\n",
813
+ " Parameters:\n",
814
+ " user_text (str): User-provided instruction for a generation.\n",
815
+ " 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",
816
+ " temperature (float): The value used to module the logits distribution.\n",
817
+ " top_k (int): The number of highest probability vocabulary tokens to keep for top-k-filtering.\n",
818
+ " max_new_tokens (int): Maximum length of generated sequence.\n",
819
+ " perf_text (str): Content of text field for printing performance results.\n",
820
+ " Returns:\n",
821
+ " model_output (str) - model-generated text\n",
822
+ " perf_text (str) - updated perf text filed content\n",
823
+ " \"\"\"\n",
824
+ "\n",
825
+ " # Prepare input prompt according to model expected template\n",
826
+ " prompt_text = prompt_template.format(instruction=user_text)\n",
827
+ "\n",
828
+ " # Tokenize the user text.\n",
829
+ " model_inputs = tokenizer(prompt_text, return_tensors=\"pt\", **tokenizer_kwargs)\n",
830
+ "\n",
831
+ " # Start generation on a separate thread, so that we don't block the UI. The text is pulled from the streamer\n",
832
+ " # in the main thread. Adds timeout to the streamer to handle exceptions in the generation thread.\n",
833
+ " streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)\n",
834
+ " generate_kwargs = dict(\n",
835
+ " model_inputs,\n",
836
+ " streamer=streamer,\n",
837
+ " max_new_tokens=max_new_tokens,\n",
838
+ " do_sample=True,\n",
839
+ " top_p=top_p,\n",
840
+ " temperature=float(temperature),\n",
841
+ " top_k=top_k,\n",
842
+ " eos_token_id=end_key_token_id,\n",
843
+ " pad_token_id=pad_token_id,\n",
844
+ " )\n",
845
+ " t = Thread(target=ov_model.generate, kwargs=generate_kwargs)\n",
846
+ " t.start()\n",
847
+ "\n",
848
+ " # Pull the generated text from the streamer, and update the model output.\n",
849
+ " model_output = \"\"\n",
850
+ " per_token_time = []\n",
851
+ " num_tokens = 0\n",
852
+ " start = perf_counter()\n",
853
+ " for new_text in streamer:\n",
854
+ " current_time = perf_counter() - start\n",
855
+ " model_output += new_text\n",
856
+ " perf_text, num_tokens = estimate_latency(current_time, perf_text, new_text, per_token_time, num_tokens)\n",
857
+ " yield model_output, perf_text\n",
858
+ " start = perf_counter()\n",
859
+ " return model_output, perf_text"
860
+ ]
861
+ },
862
+ {
863
+ "attachments": {},
864
+ "cell_type": "markdown",
865
+ "id": "6d7b7182-1d9b-485b-81f2-1a9fab6d5cd4",
866
+ "metadata": {},
867
+ "source": [
868
+ "### Helpers for application\n",
869
+ "[back to top ⬆️](#Table-of-contents:)\n",
870
+ "\n",
871
+ "For making interactive user interface we will use Gradio library. The code bellow provides useful functions used for communication with UI elements."
872
+ ]
873
+ },
874
+ {
875
+ "cell_type": "code",
876
+ "execution_count": 14,
877
+ "id": "c9b2a2b7-5a91-470f-98d7-7355664bc1be",
878
+ "metadata": {},
879
+ "outputs": [],
880
+ "source": [
881
+ "def estimate_latency(\n",
882
+ " current_time: float,\n",
883
+ " current_perf_text: str,\n",
884
+ " new_gen_text: str,\n",
885
+ " per_token_time: List[float],\n",
886
+ " num_tokens: int,\n",
887
+ "):\n",
888
+ " \"\"\"\n",
889
+ " Helper function for performance estimation\n",
890
+ "\n",
891
+ " Parameters:\n",
892
+ " current_time (float): This step time in seconds.\n",
893
+ " current_perf_text (str): Current content of performance UI field.\n",
894
+ " new_gen_text (str): New generated text.\n",
895
+ " per_token_time (List[float]): history of performance from previous steps.\n",
896
+ " num_tokens (int): Total number of generated tokens.\n",
897
+ "\n",
898
+ " Returns:\n",
899
+ " update for performance text field\n",
900
+ " update for a total number of tokens\n",
901
+ " \"\"\"\n",
902
+ " num_current_toks = len(tokenizer.encode(new_gen_text))\n",
903
+ " num_tokens += num_current_toks\n",
904
+ " per_token_time.append(num_current_toks / current_time)\n",
905
+ " if len(per_token_time) > 10 and len(per_token_time) % 4 == 0:\n",
906
+ " current_bucket = per_token_time[:-10]\n",
907
+ " return (\n",
908
+ " f\"Average generation speed: {np.mean(current_bucket):.2f} tokens/s. Total generated tokens: {num_tokens}\",\n",
909
+ " num_tokens,\n",
910
+ " )\n",
911
+ " return current_perf_text, num_tokens\n",
912
+ "\n",
913
+ "\n",
914
+ "def reset_textbox(instruction: str, response: str, perf: str):\n",
915
+ " \"\"\"\n",
916
+ " Helper function for resetting content of all text fields\n",
917
+ "\n",
918
+ " Parameters:\n",
919
+ " instruction (str): Content of user instruction field.\n",
920
+ " response (str): Content of model response field.\n",
921
+ " perf (str): Content of performance info filed\n",
922
+ "\n",
923
+ " Returns:\n",
924
+ " empty string for each placeholder\n",
925
+ " \"\"\"\n",
926
+ " return \"\", \"\", \"\""
927
+ ]
928
+ },
929
+ {
930
+ "attachments": {},
931
+ "cell_type": "markdown",
932
+ "id": "31ebb167-0e55-4271-aedd-13814c2356d2",
933
+ "metadata": {},
934
+ "source": [
935
+ "## Run instruction-following pipeline\n",
936
+ "[back to top ⬆️](#Table-of-contents:)\n",
937
+ "\n",
938
+ "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",
939
+ "\n",
940
+ "* `Device` - allows switching inference device. Please note, every time when new device is selected, model will be recompiled and this takes some time.\n",
941
+ "* `Max New Tokens` - maximum size of generated text.\n",
942
+ "* `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",
943
+ "* `Top-k` - the number of highest probability vocabulary tokens to keep for top-k-filtering.\n",
944
+ "* `Temperature` - the value used to module the logits distribution."
945
+ ]
946
+ },
947
+ {
948
+ "cell_type": "code",
949
+ "execution_count": 18,
950
+ "id": "9f222d02-847a-490f-8d66-02608a53259b",
951
+ "metadata": {},
952
+ "outputs": [
953
+ {
954
+ "data": {
955
+ "application/vnd.jupyter.widget-view+json": {
956
+ "model_id": "7b5b067e1bfb4fc3b480865576634ed1",
957
+ "version_major": 2,
958
+ "version_minor": 0
959
+ },
960
+ "text/plain": [
961
+ "VBox(children=(Label(value='Please login to access the demo:'), Text(value='', placeholder='Username'), Passwo…"
962
+ ]
963
+ },
964
+ "metadata": {},
965
+ "output_type": "display_data"
966
+ }
967
+ ],
968
+ "source": [
969
+ "import gradio as gr\n",
970
+ "import ipywidgets as widgets\n",
971
+ "from IPython.display import display, clear_output\n",
972
+ "\n",
973
+ "# Define your examples and other setup here\n",
974
+ "examples = [\n",
975
+ " \"Give me a recipe for pizza with pineapple\",\n",
976
+ " \"Write me a tweet about the new OpenVINO release\",\n",
977
+ " \"Explain the difference between CPU and GPU\",\n",
978
+ " \"Give five ideas for a great weekend with family\",\n",
979
+ " \"Do Androids dream of Electric sheep?\",\n",
980
+ " \"Who is Dolly?\",\n",
981
+ " \"Please give me advice on how to write resume?\",\n",
982
+ " \"Name 3 advantages to being a cat\",\n",
983
+ " \"Write instructions on how to become a good AI engineer\",\n",
984
+ " \"Write a love letter to my best friend\",\n",
985
+ "]\n",
986
+ "\n",
987
+ "# Function to check user credentials\n",
988
+ "def authenticate(username, password):\n",
989
+ " # Replace with actual authentication logic\n",
990
+ " if username == \"user\" and password == \"password\":\n",
991
+ " return True\n",
992
+ " else:\n",
993
+ " return False\n",
994
+ "\n",
995
+ "# Function to handle submission\n",
996
+ "def handle_submit(button):\n",
997
+ " clear_output()\n",
998
+ " if authenticate(username.value, password.value):\n",
999
+ " launch_demo()\n",
1000
+ " else:\n",
1001
+ " print(\"Authentication failed. Please try again.\")\n",
1002
+ "\n",
1003
+ "# Function to launch the Gradio demo\n",
1004
+ "def launch_demo():\n",
1005
+ " with gr.Blocks() as demo:\n",
1006
+ " gr.Markdown(\n",
1007
+ " \"# Question Answering with \" + model_id.value + \" and OpenVINO.\\n\"\n",
1008
+ " \"Provide instruction which describes a task below or select among predefined examples and model writes response that performs requested task.\"\n",
1009
+ " )\n",
1010
+ "\n",
1011
+ " with gr.Row():\n",
1012
+ " with gr.Column(scale=4):\n",
1013
+ " user_text = gr.Textbox(\n",
1014
+ " placeholder=\"Write an email about an alpaca that likes flan\",\n",
1015
+ " label=\"User instruction\",\n",
1016
+ " )\n",
1017
+ " model_output = gr.Textbox(label=\"Model response\", interactive=False)\n",
1018
+ " performance = gr.Textbox(label=\"Performance\", lines=1, interactive=False)\n",
1019
+ " with gr.Column(scale=1):\n",
1020
+ " button_clear = gr.Button(value=\"Clear\")\n",
1021
+ " button_submit = gr.Button(value=\"Submit\")\n",
1022
+ " gr.Examples(examples, user_text)\n",
1023
+ " with gr.Column(scale=1):\n",
1024
+ " max_new_tokens = gr.Slider(\n",
1025
+ " minimum=1,\n",
1026
+ " maximum=1000,\n",
1027
+ " value=256,\n",
1028
+ " step=1,\n",
1029
+ " interactive=True,\n",
1030
+ " label=\"Max New Tokens\",\n",
1031
+ " )\n",
1032
+ " top_p = gr.Slider(\n",
1033
+ " minimum=0.05,\n",
1034
+ " maximum=1.0,\n",
1035
+ " value=0.92,\n",
1036
+ " step=0.05,\n",
1037
+ " interactive=True,\n",
1038
+ " label=\"Top-p (nucleus sampling)\",\n",
1039
+ " )\n",
1040
+ " top_k = gr.Slider(\n",
1041
+ " minimum=0,\n",
1042
+ " maximum=50,\n",
1043
+ " value=0,\n",
1044
+ " step=1,\n",
1045
+ " interactive=True,\n",
1046
+ " label=\"Top-k\",\n",
1047
+ " )\n",
1048
+ " temperature = gr.Slider(\n",
1049
+ " minimum=0.1,\n",
1050
+ " maximum=5.0,\n",
1051
+ " value=0.8,\n",
1052
+ " step=0.1,\n",
1053
+ " interactive=True,\n",
1054
+ " label=\"Temperature\",\n",
1055
+ " )\n",
1056
+ "\n",
1057
+ " user_text.submit(\n",
1058
+ " run_generation,\n",
1059
+ " [user_text, top_p, temperature, top_k, max_new_tokens, performance],\n",
1060
+ " [model_output, performance],\n",
1061
+ " )\n",
1062
+ " button_submit.click(\n",
1063
+ " run_generation,\n",
1064
+ " [user_text, top_p, temperature, top_k, max_new_tokens, performance],\n",
1065
+ " [model_output, performance],\n",
1066
+ " )\n",
1067
+ " button_clear.click(\n",
1068
+ " reset_textbox,\n",
1069
+ " [user_text, model_output, performance],\n",
1070
+ " [user_text, model_output, performance],\n",
1071
+ " )\n",
1072
+ "\n",
1073
+ " demo.launch(height=800,share=True)\n",
1074
+ "\n",
1075
+ "# Define widgets for authentication\n",
1076
+ "username = widgets.Text(placeholder=\"Username\")\n",
1077
+ "password = widgets.Password(placeholder=\"Password\")\n",
1078
+ "submit_button = widgets.Button(description=\"Login\")\n",
1079
+ "submit_button.on_click(handle_submit)\n",
1080
+ "\n",
1081
+ "# Layout for login page\n",
1082
+ "login_page = widgets.VBox([\n",
1083
+ " widgets.Label(\"Please login to access the demo:\"),\n",
1084
+ " username,\n",
1085
+ " password,\n",
1086
+ " submit_button\n",
1087
+ "])\n",
1088
+ "\n",
1089
+ "# Display login page initially\n",
1090
+ "display(login_page)\n"
1091
+ ]
1092
+ },
1093
+ {
1094
+ "cell_type": "code",
1095
+ "execution_count": null,
1096
+ "id": "440417f8-d2e2-4d8d-8311-882d133bb572",
1097
+ "metadata": {},
1098
+ "outputs": [],
1099
+ "source": []
1100
+ },
1101
+ {
1102
+ "cell_type": "code",
1103
+ "execution_count": null,
1104
+ "id": "dd9f90e4-0ec6-4164-8a31-044b1079d3e7",
1105
+ "metadata": {},
1106
+ "outputs": [],
1107
+ "source": []
1108
+ },
1109
+ {
1110
+ "cell_type": "code",
1111
+ "execution_count": null,
1112
+ "id": "7297ddd6-2c3d-4540-aa9b-f1c48c274a86",
1113
+ "metadata": {},
1114
+ "outputs": [],
1115
+ "source": []
1116
+ }
1117
+ ],
1118
+ "metadata": {
1119
+ "kernelspec": {
1120
+ "display_name": "openvino_env",
1121
+ "language": "python",
1122
+ "name": "openvino_env"
1123
+ },
1124
+ "language_info": {
1125
+ "codemirror_mode": {
1126
+ "name": "ipython",
1127
+ "version": 3
1128
+ },
1129
+ "file_extension": ".py",
1130
+ "mimetype": "text/x-python",
1131
+ "name": "python",
1132
+ "nbconvert_exporter": "python",
1133
+ "pygments_lexer": "ipython3",
1134
+ "version": "3.10.9"
1135
+ },
1136
+ "openvino_notebooks": {
1137
+ "imageUrl": "https://github.com/openvinotoolkit/openvino_notebooks/assets/29454499/daafd702-5a42-4f54-ae72-2e4480d73501",
1138
+ "tags": {
1139
+ "categories": [
1140
+ "Model Demos",
1141
+ "AI Trends"
1142
+ ],
1143
+ "libraries": [],
1144
+ "other": [
1145
+ "LLM"
1146
+ ],
1147
+ "tasks": [
1148
+ "Text Generation"
1149
+ ]
1150
+ }
1151
+ },
1152
+ "widgets": {
1153
+ "application/vnd.jupyter.widget-state+json": {
1154
+ "state": {},
1155
+ "version_major": 2,
1156
+ "version_minor": 0
1157
+ }
1158
+ }
1159
+ },
1160
+ "nbformat": 4,
1161
+ "nbformat_minor": 5
1162
+ }