malvika2003 commited on
Commit
53d77b0
1 Parent(s): 331c0a1

Upload folder using huggingface_hub

Browse files
.ipynb_checkpoints/llm-question-answering-Copy1 (1)-checkpoint.ipynb ADDED
@@ -0,0 +1,1136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "f6aa8c52-9bde-41a6-a5f7-4fa93d5c2a6c",
6
+ "metadata": {},
7
+ "source": [
8
+ "# LLM Instruction-following pipeline with OpenVINO \n",
9
+ "\n",
10
+ "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",
11
+ "\n",
12
+ "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",
13
+ "\n",
14
+ "The tutorial consists of the following steps:\n",
15
+ "\n",
16
+ "- Install prerequisites\n",
17
+ "- Download and convert the model from a public source using the [OpenVINO integration with Hugging Face Optimum](https://huggingface.co/blog/openvino).\n",
18
+ "- Compress model weights to INT8 and INT4 with [OpenVINO NNCF](https://github.com/openvinotoolkit/nncf)\n",
19
+ "- Create an instruction-following inference pipeline\n",
20
+ "- Run instruction-following pipeline\n",
21
+ "\n",
22
+ "\n",
23
+ "#### Table of contents:\n",
24
+ "\n",
25
+ "- [Prerequisites](#Prerequisites)\n",
26
+ "- [Select model for inference](#Select-model-for-inference)\n",
27
+ "- [Instantiate Model using Optimum Intel](#Instantiate-Model-using-Optimum-Intel)\n",
28
+ "- [Compress model weights](#Compress-model-weights)\n",
29
+ " - [Weights Compression using Optimum Intel](#Weights-Compression-using-Optimum-Intel)\n",
30
+ " - [Weights Compression using NNCF](#Weights-Compression-using-NNCF)\n",
31
+ "- [Select device for inference and model variant](#Select-device-for-inference-and-model-variant)\n",
32
+ "- [Create an instruction-following inference pipeline](#Create-an-instruction-following-inference-pipeline)\n",
33
+ " - [Setup imports](#Setup-imports)\n",
34
+ " - [Prepare template for user prompt](#Prepare-template-for-user-prompt)\n",
35
+ " - [Main generation function](#Main-generation-function)\n",
36
+ " - [Helpers for application](#Helpers-for-application)\n",
37
+ "- [Run instruction-following pipeline](#Run-instruction-following-pipeline)\n",
38
+ "\n"
39
+ ]
40
+ },
41
+ {
42
+ "cell_type": "markdown",
43
+ "id": "027108c2-1fbe-4be5-9e23-3fc359185a42",
44
+ "metadata": {},
45
+ "source": [
46
+ "## Prerequisites\n",
47
+ "[back to top ⬆️](#Table-of-contents:)\n"
48
+ ]
49
+ },
50
+ {
51
+ "cell_type": "code",
52
+ "execution_count": 1,
53
+ "id": "5d0473c6-3734-422d-a370-2e39d576be0e",
54
+ "metadata": {},
55
+ "outputs": [
56
+ {
57
+ "name": "stdout",
58
+ "output_type": "stream",
59
+ "text": [
60
+ "Note: you may need to restart the kernel to use updated packages.\n",
61
+ "Note: you may need to restart the kernel to use updated packages.\n",
62
+ "Note: you may need to restart the kernel to use updated packages.\n",
63
+ "Note: you may need to restart the kernel to use updated packages.\n"
64
+ ]
65
+ }
66
+ ],
67
+ "source": [
68
+ "%pip install -Uq pip\n",
69
+ "%pip uninstall -q -y optimum optimum-intel\n",
70
+ "%pip install --pre -Uq openvino openvino-tokenizers[transformers] --extra-index-url https://storage.openvinotoolkit.org/simple/wheels/nightly\n",
71
+ "%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"
72
+ ]
73
+ },
74
+ {
75
+ "cell_type": "markdown",
76
+ "id": "611cc777-d5bc-4c7b-92e4-a4befa13b2ce",
77
+ "metadata": {},
78
+ "source": [
79
+ "## Select model for inference\n",
80
+ "[back to top ⬆️](#Table-of-contents:)\n",
81
+ "\n",
82
+ "The tutorial supports different models, you can select one from the provided options to compare the quality of open source LLM solutions.\n",
83
+ ">**Note**: conversion of some models can require additional actions from user side and at least 64GB RAM for conversion.\n",
84
+ "\n",
85
+ "The available options are:\n",
86
+ "\n",
87
+ "* **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",
88
+ "* **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",
89
+ "* **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",
90
+ "* **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",
91
+ "* **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",
92
+ "* **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",
93
+ ">**Note**: run model with demo, you will need to accept license agreement. \n",
94
+ ">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",
95
+ ">You can login on Hugging Face Hub in notebook environment, using following code:\n",
96
+ " \n",
97
+ "```python\n",
98
+ " ## login to huggingfacehub to get access to pretrained model \n",
99
+ "\n",
100
+ " from huggingface_hub import notebook_login, whoami\n",
101
+ "\n",
102
+ " try:\n",
103
+ " whoami()\n",
104
+ " print('Authorization token already provided')\n",
105
+ " except OSError:\n",
106
+ " notebook_login()\n",
107
+ "```"
108
+ ]
109
+ },
110
+ {
111
+ "cell_type": "code",
112
+ "execution_count": 5,
113
+ "id": "51920510-effc-49ef-8c6f-81c951d96a9b",
114
+ "metadata": {},
115
+ "outputs": [],
116
+ "source": [
117
+ "from pathlib import Path\n",
118
+ "import requests\n",
119
+ "\n",
120
+ "# Fetch `notebook_utils` module\n",
121
+ "r = requests.get(\n",
122
+ " url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/utils/notebook_utils.py\",\n",
123
+ ")\n",
124
+ "open(\"notebook_utils.py\", \"w\").write(r.text)\n",
125
+ "from notebook_utils import download_file\n",
126
+ "\n",
127
+ "if not Path(\"./config.py\").exists():\n",
128
+ " download_file(url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/notebooks/llm-question-answering/config.py\")\n",
129
+ "from config import SUPPORTED_LLM_MODELS\n",
130
+ "import ipywidgets as widgets"
131
+ ]
132
+ },
133
+ {
134
+ "cell_type": "code",
135
+ "execution_count": 6,
136
+ "id": "27b42290-a9b5-4453-9a4c-ffa44bbd966d",
137
+ "metadata": {},
138
+ "outputs": [
139
+ {
140
+ "data": {
141
+ "application/vnd.jupyter.widget-view+json": {
142
+ "model_id": "f3928b82e676449b8a6bfbded7f4686d",
143
+ "version_major": 2,
144
+ "version_minor": 0
145
+ },
146
+ "text/plain": [
147
+ "Dropdown(description='Model:', index=1, options=('tiny-llama-1b', 'phi-2', 'dolly-v2-3b', 'red-pajama-instruct…"
148
+ ]
149
+ },
150
+ "execution_count": 6,
151
+ "metadata": {},
152
+ "output_type": "execute_result"
153
+ }
154
+ ],
155
+ "source": [
156
+ "model_ids = list(SUPPORTED_LLM_MODELS)\n",
157
+ "\n",
158
+ "model_id = widgets.Dropdown(\n",
159
+ " options=model_ids,\n",
160
+ " value=model_ids[1],\n",
161
+ " description=\"Model:\",\n",
162
+ " disabled=False,\n",
163
+ ")\n",
164
+ "\n",
165
+ "model_id"
166
+ ]
167
+ },
168
+ {
169
+ "cell_type": "code",
170
+ "execution_count": 4,
171
+ "id": "37e9634f-4fc7-4d9c-9ade-b3e8684a0828",
172
+ "metadata": {},
173
+ "outputs": [
174
+ {
175
+ "name": "stdout",
176
+ "output_type": "stream",
177
+ "text": [
178
+ "Selected model phi-2\n"
179
+ ]
180
+ }
181
+ ],
182
+ "source": [
183
+ "model_configuration = SUPPORTED_LLM_MODELS[model_id.value]\n",
184
+ "print(f\"Selected model {model_id.value}\")"
185
+ ]
186
+ },
187
+ {
188
+ "cell_type": "code",
189
+ "execution_count": 7,
190
+ "id": "7937959a-d2a1-49bd-bf12-35554fa901d1",
191
+ "metadata": {},
192
+ "outputs": [
193
+ {
194
+ "data": {
195
+ "text/plain": [
196
+ "{'model_id': 'susnato/phi-2',\n",
197
+ " 'prompt_template': 'Instruct:{instruction}\\nOutput:'}"
198
+ ]
199
+ },
200
+ "execution_count": 7,
201
+ "metadata": {},
202
+ "output_type": "execute_result"
203
+ }
204
+ ],
205
+ "source": [
206
+ "model_configuration = SUPPORTED_LLM_MODELS[model_id.value]\n",
207
+ "model_configuration"
208
+ ]
209
+ },
210
+ {
211
+ "cell_type": "markdown",
212
+ "id": "4e4fd394-b4fb-4eef-8bdc-d116572aa8f0",
213
+ "metadata": {},
214
+ "source": [
215
+ "## Instantiate Model using Optimum Intel\n",
216
+ "[back to top ⬆️](#Table-of-contents:)\n",
217
+ "\n",
218
+ "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",
219
+ "\n",
220
+ "Below is an example of the RedPajama model\n",
221
+ "\n",
222
+ "```diff\n",
223
+ "-from transformers import AutoModelForCausalLM\n",
224
+ "+from optimum.intel.openvino import OVModelForCausalLM\n",
225
+ "from transformers import AutoTokenizer, pipeline\n",
226
+ "\n",
227
+ "model_id = \"togethercomputer/RedPajama-INCITE-Chat-3B-v1\"\n",
228
+ "-model = AutoModelForCausalLM.from_pretrained(model_id)\n",
229
+ "+model = OVModelForCausalLM.from_pretrained(model_id, export=True)\n",
230
+ "```\n",
231
+ "\n",
232
+ "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",
233
+ "Tokenizer class and pipelines API are compatible with Optimum models.\n",
234
+ "\n",
235
+ "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",
236
+ "\n",
237
+ "## Compress model weights\n",
238
+ "[back to top ⬆️](#Table-of-contents:)\n",
239
+ "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",
240
+ "\n",
241
+ "\n",
242
+ "### Weights Compression using Optimum Intel\n",
243
+ "[back to top ⬆️](#Table-of-contents:)\n",
244
+ "\n",
245
+ "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",
246
+ "\n",
247
+ "### Weights Compression using NNCF\n",
248
+ "[back to top ⬆️](#Table-of-contents:)\n",
249
+ "\n",
250
+ "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",
251
+ "\n",
252
+ "\n",
253
+ ">**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",
254
+ ">**Note**: There may be no speedup for INT4/INT8 compressed models on dGPU"
255
+ ]
256
+ },
257
+ {
258
+ "cell_type": "code",
259
+ "execution_count": 5,
260
+ "id": "f81602ca-4674-4b61-b2c8-ca11631428b1",
261
+ "metadata": {},
262
+ "outputs": [
263
+ {
264
+ "data": {
265
+ "application/vnd.jupyter.widget-view+json": {
266
+ "model_id": "f0ca5ccd8cbf49169f5286150875cf5f",
267
+ "version_major": 2,
268
+ "version_minor": 0
269
+ },
270
+ "text/plain": [
271
+ "Checkbox(value=True, description='Prepare INT4 model')"
272
+ ]
273
+ },
274
+ "metadata": {},
275
+ "output_type": "display_data"
276
+ },
277
+ {
278
+ "data": {
279
+ "application/vnd.jupyter.widget-view+json": {
280
+ "model_id": "23304b6eea4f4f23ab2e56867f362471",
281
+ "version_major": 2,
282
+ "version_minor": 0
283
+ },
284
+ "text/plain": [
285
+ "Checkbox(value=False, description='Prepare INT8 model')"
286
+ ]
287
+ },
288
+ "metadata": {},
289
+ "output_type": "display_data"
290
+ },
291
+ {
292
+ "data": {
293
+ "application/vnd.jupyter.widget-view+json": {
294
+ "model_id": "babfd2f23029448ca8144cc2554599cf",
295
+ "version_major": 2,
296
+ "version_minor": 0
297
+ },
298
+ "text/plain": [
299
+ "Checkbox(value=False, description='Prepare FP16 model')"
300
+ ]
301
+ },
302
+ "metadata": {},
303
+ "output_type": "display_data"
304
+ }
305
+ ],
306
+ "source": [
307
+ "from IPython.display import display\n",
308
+ "\n",
309
+ "prepare_int4_model = widgets.Checkbox(\n",
310
+ " value=True,\n",
311
+ " description=\"Prepare INT4 model\",\n",
312
+ " disabled=False,\n",
313
+ ")\n",
314
+ "prepare_int8_model = widgets.Checkbox(\n",
315
+ " value=False,\n",
316
+ " description=\"Prepare INT8 model\",\n",
317
+ " disabled=False,\n",
318
+ ")\n",
319
+ "prepare_fp16_model = widgets.Checkbox(\n",
320
+ " value=False,\n",
321
+ " description=\"Prepare FP16 model\",\n",
322
+ " disabled=False,\n",
323
+ ")\n",
324
+ "\n",
325
+ "display(prepare_int4_model)\n",
326
+ "display(prepare_int8_model)\n",
327
+ "display(prepare_fp16_model)"
328
+ ]
329
+ },
330
+ {
331
+ "cell_type": "code",
332
+ "execution_count": 3,
333
+ "id": "0066fbec-b89b-4caa-94fb-9ea8598c22e0",
334
+ "metadata": {},
335
+ "outputs": [
336
+ {
337
+ "name": "stdout",
338
+ "output_type": "stream",
339
+ "text": [
340
+ "INFO:nncf:NNCF initialized successfully. Supported frameworks detected: torch, onnx, openvino\n"
341
+ ]
342
+ },
343
+ {
344
+ "ename": "NameError",
345
+ "evalue": "name 'model_configuration' is not defined",
346
+ "output_type": "error",
347
+ "traceback": [
348
+ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
349
+ "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)",
350
+ "Cell \u001b[1;32mIn[3], line 11\u001b[0m\n\u001b[0;32m 6\u001b[0m \u001b[38;5;28;01mimport\u001b[39;00m \u001b[38;5;21;01mgc\u001b[39;00m\n\u001b[0;32m 9\u001b[0m nncf\u001b[38;5;241m.\u001b[39mset_log_level(logging\u001b[38;5;241m.\u001b[39mERROR)\n\u001b[1;32m---> 11\u001b[0m pt_model_id \u001b[38;5;241m=\u001b[39m \u001b[43mmodel_configuration\u001b[49m[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mmodel_id\u001b[39m\u001b[38;5;124m\"\u001b[39m]\n\u001b[0;32m 12\u001b[0m fp16_model_dir \u001b[38;5;241m=\u001b[39m Path(model_id\u001b[38;5;241m.\u001b[39mvalue) \u001b[38;5;241m/\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mFP16\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m 13\u001b[0m int8_model_dir \u001b[38;5;241m=\u001b[39m Path(model_id\u001b[38;5;241m.\u001b[39mvalue) \u001b[38;5;241m/\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mINT8_compressed_weights\u001b[39m\u001b[38;5;124m\"\u001b[39m\n",
351
+ "\u001b[1;31mNameError\u001b[0m: name 'model_configuration' is not defined"
352
+ ]
353
+ }
354
+ ],
355
+ "source": [
356
+ "from pathlib import Path\n",
357
+ "import logging\n",
358
+ "import openvino as ov\n",
359
+ "import nncf\n",
360
+ "from optimum.intel.openvino import OVModelForCausalLM, OVWeightQuantizationConfig\n",
361
+ "import gc\n",
362
+ "\n",
363
+ "\n",
364
+ "nncf.set_log_level(logging.ERROR)\n",
365
+ "\n",
366
+ "pt_model_id = model_configuration[\"model_id\"]\n",
367
+ "fp16_model_dir = Path(model_id.value) / \"FP16\"\n",
368
+ "int8_model_dir = Path(model_id.value) / \"INT8_compressed_weights\"\n",
369
+ "int4_model_dir = Path(model_id.value) / \"INT4_compressed_weights\"\n",
370
+ "\n",
371
+ "core = ov.Core()\n",
372
+ "\n",
373
+ "\n",
374
+ "def convert_to_fp16():\n",
375
+ " if (fp16_model_dir / \"openvino_model.xml\").exists():\n",
376
+ " return\n",
377
+ " ov_model = OVModelForCausalLM.from_pretrained(pt_model_id, export=True, compile=False, load_in_8bit=False)\n",
378
+ " ov_model.half()\n",
379
+ " ov_model.save_pretrained(fp16_model_dir)\n",
380
+ " del ov_model\n",
381
+ " gc.collect()\n",
382
+ "\n",
383
+ "\n",
384
+ "def convert_to_int8():\n",
385
+ " if (int8_model_dir / \"openvino_model.xml\").exists():\n",
386
+ " return\n",
387
+ " ov_model = OVModelForCausalLM.from_pretrained(pt_model_id, export=True, compile=False, load_in_8bit=True)\n",
388
+ " ov_model.save_pretrained(int8_model_dir)\n",
389
+ " del ov_model\n",
390
+ " gc.collect()\n",
391
+ "\n",
392
+ "\n",
393
+ "def convert_to_int4():\n",
394
+ " compression_configs = {\n",
395
+ " \"mistral-7b\": {\n",
396
+ " \"sym\": True,\n",
397
+ " \"group_size\": 64,\n",
398
+ " \"ratio\": 0.6,\n",
399
+ " },\n",
400
+ " \"red-pajama-3b-instruct\": {\n",
401
+ " \"sym\": False,\n",
402
+ " \"group_size\": 128,\n",
403
+ " \"ratio\": 0.5,\n",
404
+ " },\n",
405
+ " \"dolly-v2-3b\": {\"sym\": False, \"group_size\": 32, \"ratio\": 0.5},\n",
406
+ " \"llama-3-8b-instruct\": {\"sym\": True, \"group_size\": 128, \"ratio\": 1.0},\n",
407
+ " \"default\": {\n",
408
+ " \"sym\": False,\n",
409
+ " \"group_size\": 128,\n",
410
+ " \"ratio\": 0.8,\n",
411
+ " },\n",
412
+ " }\n",
413
+ "\n",
414
+ " model_compression_params = compression_configs.get(model_id.value, compression_configs[\"default\"])\n",
415
+ " if (int4_model_dir / \"openvino_model.xml\").exists():\n",
416
+ " return\n",
417
+ " ov_model = OVModelForCausalLM.from_pretrained(\n",
418
+ " pt_model_id,\n",
419
+ " export=True,\n",
420
+ " compile=False,\n",
421
+ " quantization_config=OVWeightQuantizationConfig(bits=4, **model_compression_params),\n",
422
+ " )\n",
423
+ " ov_model.save_pretrained(int4_model_dir)\n",
424
+ " del ov_model\n",
425
+ " gc.collect()\n",
426
+ "\n",
427
+ "\n",
428
+ "if prepare_fp16_model.value:\n",
429
+ " convert_to_fp16()\n",
430
+ "if prepare_int8_model.value:\n",
431
+ " convert_to_int8()\n",
432
+ "if prepare_int4_model.value:\n",
433
+ " convert_to_int4()"
434
+ ]
435
+ },
436
+ {
437
+ "cell_type": "code",
438
+ "execution_count": null,
439
+ "id": "b5f31838-c7d6-4f52-aa2d-1f29c6f3b397",
440
+ "metadata": {},
441
+ "outputs": [],
442
+ "source": []
443
+ },
444
+ {
445
+ "cell_type": "markdown",
446
+ "id": "60355f86-2250-4ebe-82ac-950f2d4fb01b",
447
+ "metadata": {},
448
+ "source": [
449
+ "Let's compare model size for different compression types"
450
+ ]
451
+ },
452
+ {
453
+ "cell_type": "code",
454
+ "execution_count": 2,
455
+ "id": "42c7b254-1ce4-4f23-813a-9bdc23aed327",
456
+ "metadata": {},
457
+ "outputs": [
458
+ {
459
+ "ename": "NameError",
460
+ "evalue": "name 'fp16_model_dir' is not defined",
461
+ "output_type": "error",
462
+ "traceback": [
463
+ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
464
+ "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)",
465
+ "Cell \u001b[1;32mIn[2], line 1\u001b[0m\n\u001b[1;32m----> 1\u001b[0m fp16_weights \u001b[38;5;241m=\u001b[39m \u001b[43mfp16_model_dir\u001b[49m \u001b[38;5;241m/\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mopenvino_model.bin\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m 2\u001b[0m int8_weights \u001b[38;5;241m=\u001b[39m int8_model_dir \u001b[38;5;241m/\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mopenvino_model.bin\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m 3\u001b[0m int4_weights \u001b[38;5;241m=\u001b[39m int4_model_dir \u001b[38;5;241m/\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mopenvino_model.bin\u001b[39m\u001b[38;5;124m\"\u001b[39m\n",
466
+ "\u001b[1;31mNameError\u001b[0m: name 'fp16_model_dir' is not defined"
467
+ ]
468
+ }
469
+ ],
470
+ "source": [
471
+ "fp16_weights = fp16_model_dir / \"openvino_model.bin\"\n",
472
+ "int8_weights = int8_model_dir / \"openvino_model.bin\"\n",
473
+ "int4_weights = int4_model_dir / \"openvino_model.bin\"\n",
474
+ "\n",
475
+ "if fp16_weights.exists():\n",
476
+ " print(f\"Size of FP16 model is {fp16_weights.stat().st_size / 1024 / 1024:.2f} MB\")\n",
477
+ "for precision, compressed_weights in zip([8, 4], [int8_weights, int4_weights]):\n",
478
+ " if compressed_weights.exists():\n",
479
+ " print(f\"Size of model with INT{precision} compressed weights is {compressed_weights.stat().st_size / 1024 / 1024:.2f} MB\")\n",
480
+ " if compressed_weights.exists() and fp16_weights.exists():\n",
481
+ " print(f\"Compression rate for INT{precision} model: {fp16_weights.stat().st_size / compressed_weights.stat().st_size:.3f}\")"
482
+ ]
483
+ },
484
+ {
485
+ "cell_type": "markdown",
486
+ "id": "3df73379-bccc-41b1-9c94-c3040819805b",
487
+ "metadata": {},
488
+ "source": [
489
+ "## Select device for inference and model variant\n",
490
+ "[back to top ⬆️](#Table-of-contents:)\n",
491
+ "\n",
492
+ ">**Note**: There may be no speedup for INT4/INT8 compressed models on dGPU."
493
+ ]
494
+ },
495
+ {
496
+ "cell_type": "code",
497
+ "execution_count": 8,
498
+ "id": "d2d7bf5b-8a05-4c3b-a36b-631af5c197e9",
499
+ "metadata": {},
500
+ "outputs": [
501
+ {
502
+ "data": {
503
+ "application/vnd.jupyter.widget-view+json": {
504
+ "model_id": "a934a422dd6f4a2ea9ab918f0c41b437",
505
+ "version_major": 2,
506
+ "version_minor": 0
507
+ },
508
+ "text/plain": [
509
+ "Dropdown(description='Device:', options=('CPU', 'GPU', 'AUTO'), value='CPU')"
510
+ ]
511
+ },
512
+ "execution_count": 8,
513
+ "metadata": {},
514
+ "output_type": "execute_result"
515
+ }
516
+ ],
517
+ "source": [
518
+ "core = ov.Core()\n",
519
+ "\n",
520
+ "support_devices = core.available_devices\n",
521
+ "if \"NPU\" in support_devices:\n",
522
+ " support_devices.remove(\"NPU\")\n",
523
+ "\n",
524
+ "device = widgets.Dropdown(\n",
525
+ " options=support_devices + [\"AUTO\"],\n",
526
+ " value=\"CPU\",\n",
527
+ " description=\"Device:\",\n",
528
+ " disabled=False,\n",
529
+ ")\n",
530
+ "\n",
531
+ "device"
532
+ ]
533
+ },
534
+ {
535
+ "cell_type": "code",
536
+ "execution_count": 20,
537
+ "id": "01673d97-6645-4d2a-8306-293b8064b317",
538
+ "metadata": {},
539
+ "outputs": [
540
+ {
541
+ "data": {
542
+ "application/vnd.jupyter.widget-view+json": {
543
+ "model_id": "a934a422dd6f4a2ea9ab918f0c41b437",
544
+ "version_major": 2,
545
+ "version_minor": 0
546
+ },
547
+ "text/plain": [
548
+ "Dropdown(description='Device:', options=('CPU', 'GPU', 'AUTO'), value='CPU')"
549
+ ]
550
+ },
551
+ "execution_count": 20,
552
+ "metadata": {},
553
+ "output_type": "execute_result"
554
+ }
555
+ ],
556
+ "source": [
557
+ "device"
558
+ ]
559
+ },
560
+ {
561
+ "cell_type": "code",
562
+ "execution_count": 9,
563
+ "id": "24532480-80a5-4953-9cd6-78ac51a1cd8f",
564
+ "metadata": {},
565
+ "outputs": [
566
+ {
567
+ "data": {
568
+ "application/vnd.jupyter.widget-view+json": {
569
+ "model_id": "4a81c4bf7a4d45b89c23aac543b9e027",
570
+ "version_major": 2,
571
+ "version_minor": 0
572
+ },
573
+ "text/plain": [
574
+ "Dropdown(description='Model to run:', options=('INT8',), value='INT8')"
575
+ ]
576
+ },
577
+ "execution_count": 9,
578
+ "metadata": {},
579
+ "output_type": "execute_result"
580
+ }
581
+ ],
582
+ "source": [
583
+ "available_models = []\n",
584
+ "if int4_model_dir.exists():\n",
585
+ " available_models.append(\"INT4\")\n",
586
+ "if int8_model_dir.exists():\n",
587
+ " available_models.append(\"INT8\")\n",
588
+ "if fp16_model_dir.exists():\n",
589
+ " available_models.append(\"FP16\")\n",
590
+ "\n",
591
+ "model_to_run = widgets.Dropdown(\n",
592
+ " options=available_models,\n",
593
+ " value=available_models[0],\n",
594
+ " description=\"Model to run:\",\n",
595
+ " disabled=False,\n",
596
+ ")\n",
597
+ "\n",
598
+ "model_to_run"
599
+ ]
600
+ },
601
+ {
602
+ "cell_type": "code",
603
+ "execution_count": 1,
604
+ "id": "5259c1c5-4128-4210-9ad2-faf33ee40e86",
605
+ "metadata": {},
606
+ "outputs": [
607
+ {
608
+ "ename": "NameError",
609
+ "evalue": "name 'model_to_run' is not defined",
610
+ "output_type": "error",
611
+ "traceback": [
612
+ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
613
+ "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)",
614
+ "Cell \u001b[1;32mIn[1], line 3\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mtransformers\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m AutoTokenizer\n\u001b[1;32m----> 3\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[43mmodel_to_run\u001b[49m\u001b[38;5;241m.\u001b[39mvalue \u001b[38;5;241m==\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mINT4\u001b[39m\u001b[38;5;124m\"\u001b[39m:\n\u001b[0;32m 4\u001b[0m model_dir \u001b[38;5;241m=\u001b[39m int4_model_dir\n\u001b[0;32m 5\u001b[0m \u001b[38;5;28;01melif\u001b[39;00m model_to_run\u001b[38;5;241m.\u001b[39mvalue \u001b[38;5;241m==\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mINT8\u001b[39m\u001b[38;5;124m\"\u001b[39m:\n",
615
+ "\u001b[1;31mNameError\u001b[0m: name 'model_to_run' is not defined"
616
+ ]
617
+ }
618
+ ],
619
+ "source": [
620
+ "from transformers import AutoTokenizer\n",
621
+ "\n",
622
+ "if model_to_run.value == \"INT4\":\n",
623
+ " model_dir = int4_model_dir\n",
624
+ "elif model_to_run.value == \"INT8\":\n",
625
+ " model_dir = int8_model_dir\n",
626
+ "else:\n",
627
+ " model_dir = fp16_model_dir\n",
628
+ "print(f\"Loading model from {model_dir}\")\n",
629
+ "\n",
630
+ "model_name = model_configuration[\"model_id\"]\n",
631
+ "print(model_name)\n",
632
+ "ov_config = {\"PERFORMANCE_HINT\": \"LATENCY\", \"NUM_STREAMS\": \"1\", \"CACHE_DIR\": \"\"}\n",
633
+ "\n",
634
+ "tok = AutoTokenizer.from_pretrained(model_name)\n",
635
+ "\n",
636
+ "ov_model = OVModelForCausalLM.from_pretrained(\n",
637
+ " model_dir,\n",
638
+ " device=device.value,\n",
639
+ " ov_config=ov_config,\n",
640
+ ")"
641
+ ]
642
+ },
643
+ {
644
+ "cell_type": "markdown",
645
+ "id": "bf13f6c3-6671-408e-ae0e-aaa3d8a6eaac",
646
+ "metadata": {},
647
+ "source": [
648
+ "## Create an instruction-following inference pipeline\n",
649
+ "[back to top ⬆️](#Table-of-contents:)\n",
650
+ " \n",
651
+ " 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",
652
+ " \n",
653
+ "The diagram below illustrates how the instruction-following pipeline works\n",
654
+ "\n",
655
+ "![generation pipeline)](https://github.com/openvinotoolkit/openvino_notebooks/assets/29454499/e881f4a4-fcc8-427a-afe1-7dd80aebd66e)\n",
656
+ "\n",
657
+ "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",
658
+ "\n",
659
+ "There are several parameters that can control text generation quality:\n",
660
+ "\n",
661
+ " * `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",
662
+ " Consider the following example: The AI model has to complete the sentence \"The cat is ____.\" with the following token probabilities: \n",
663
+ "\n",
664
+ " playing: 0.5 \n",
665
+ " sleeping: 0.25 \n",
666
+ " eating: 0.15 \n",
667
+ " driving: 0.05 \n",
668
+ " flying: 0.05 \n",
669
+ "\n",
670
+ " - **Low temperature** (e.g., 0.2): The AI model becomes more focused and deterministic, choosing tokens with the highest probability, such as \"playing.\" \n",
671
+ " - **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",
672
+ " - **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",
673
+ " * `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",
674
+ " Using the same example with the cat, consider the following top_p settings: \n",
675
+ " - **Low top_p** (e.g., 0.5): The AI model considers only tokens with the highest cumulative probability, such as \"playing.\" \n",
676
+ " - **Medium top_p** (e.g., 0.8): The AI model considers tokens with a higher cumulative probability, such as \"playing,\" \"sleeping,\" and \"eating.\" \n",
677
+ " - **High top_p** (e.g., 1.0): The AI model considers all tokens, including those with lower probabilities, such as \"driving\" and \"flying.\" \n",
678
+ " * `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",
679
+ "\n",
680
+ "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",
681
+ "\n",
682
+ "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."
683
+ ]
684
+ },
685
+ {
686
+ "cell_type": "markdown",
687
+ "id": "eb7af692-0a15-4493-86ef-a80cda21551c",
688
+ "metadata": {},
689
+ "source": [
690
+ "### Setup imports\n",
691
+ "[back to top ⬆️](#Table-of-contents:)\n"
692
+ ]
693
+ },
694
+ {
695
+ "cell_type": "code",
696
+ "execution_count": 11,
697
+ "id": "19d23a99-3284-42db-b7dc-5805d219f70d",
698
+ "metadata": {},
699
+ "outputs": [],
700
+ "source": [
701
+ "from threading import Thread\n",
702
+ "from time import perf_counter\n",
703
+ "from typing import List\n",
704
+ "import gradio as gr\n",
705
+ "from transformers import AutoTokenizer, TextIteratorStreamer\n",
706
+ "import numpy as np"
707
+ ]
708
+ },
709
+ {
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
+ "cell_type": "markdown",
785
+ "id": "55dbc4ae-da28-4be8-b928-3dd68c197937",
786
+ "metadata": {},
787
+ "source": [
788
+ "### Main generation function\n",
789
+ "[back to top ⬆️](#Table-of-contents:)\n",
790
+ "\n",
791
+ "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."
792
+ ]
793
+ },
794
+ {
795
+ "cell_type": "code",
796
+ "execution_count": 13,
797
+ "id": "27802e81-9d42-4d71-99ea-5f76db5237f1",
798
+ "metadata": {},
799
+ "outputs": [],
800
+ "source": [
801
+ "def run_generation(\n",
802
+ " user_text: str,\n",
803
+ " top_p: float,\n",
804
+ " temperature: float,\n",
805
+ " top_k: int,\n",
806
+ " max_new_tokens: int,\n",
807
+ " perf_text: str,\n",
808
+ "):\n",
809
+ " \"\"\"\n",
810
+ " Text generation function\n",
811
+ "\n",
812
+ " Parameters:\n",
813
+ " user_text (str): User-provided instruction for a generation.\n",
814
+ " 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",
815
+ " temperature (float): The value used to module the logits distribution.\n",
816
+ " top_k (int): The number of highest probability vocabulary tokens to keep for top-k-filtering.\n",
817
+ " max_new_tokens (int): Maximum length of generated sequence.\n",
818
+ " perf_text (str): Content of text field for printing performance results.\n",
819
+ " Returns:\n",
820
+ " model_output (str) - model-generated text\n",
821
+ " perf_text (str) - updated perf text filed content\n",
822
+ " \"\"\"\n",
823
+ "\n",
824
+ " # Prepare input prompt according to model expected template\n",
825
+ " prompt_text = prompt_template.format(instruction=user_text)\n",
826
+ "\n",
827
+ " # Tokenize the user text.\n",
828
+ " model_inputs = tokenizer(prompt_text, return_tensors=\"pt\", **tokenizer_kwargs)\n",
829
+ "\n",
830
+ " # Start generation on a separate thread, so that we don't block the UI. The text is pulled from the streamer\n",
831
+ " # in the main thread. Adds timeout to the streamer to handle exceptions in the generation thread.\n",
832
+ " streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)\n",
833
+ " generate_kwargs = dict(\n",
834
+ " model_inputs,\n",
835
+ " streamer=streamer,\n",
836
+ " max_new_tokens=max_new_tokens,\n",
837
+ " do_sample=True,\n",
838
+ " top_p=top_p,\n",
839
+ " temperature=float(temperature),\n",
840
+ " top_k=top_k,\n",
841
+ " eos_token_id=end_key_token_id,\n",
842
+ " pad_token_id=pad_token_id,\n",
843
+ " )\n",
844
+ " t = Thread(target=ov_model.generate, kwargs=generate_kwargs)\n",
845
+ " t.start()\n",
846
+ "\n",
847
+ " # Pull the generated text from the streamer, and update the model output.\n",
848
+ " model_output = \"\"\n",
849
+ " per_token_time = []\n",
850
+ " num_tokens = 0\n",
851
+ " start = perf_counter()\n",
852
+ " for new_text in streamer:\n",
853
+ " current_time = perf_counter() - start\n",
854
+ " model_output += new_text\n",
855
+ " perf_text, num_tokens = estimate_latency(current_time, perf_text, new_text, per_token_time, num_tokens)\n",
856
+ " yield model_output, perf_text\n",
857
+ " start = perf_counter()\n",
858
+ " return model_output, perf_text"
859
+ ]
860
+ },
861
+ {
862
+ "cell_type": "markdown",
863
+ "id": "6d7b7182-1d9b-485b-81f2-1a9fab6d5cd4",
864
+ "metadata": {},
865
+ "source": [
866
+ "### Helpers for application\n",
867
+ "[back to top ⬆️](#Table-of-contents:)\n",
868
+ "\n",
869
+ "For making interactive user interface we will use Gradio library. The code bellow provides useful functions used for communication with UI elements."
870
+ ]
871
+ },
872
+ {
873
+ "cell_type": "code",
874
+ "execution_count": 14,
875
+ "id": "c9b2a2b7-5a91-470f-98d7-7355664bc1be",
876
+ "metadata": {},
877
+ "outputs": [],
878
+ "source": [
879
+ "def estimate_latency(\n",
880
+ " current_time: float,\n",
881
+ " current_perf_text: str,\n",
882
+ " new_gen_text: str,\n",
883
+ " per_token_time: List[float],\n",
884
+ " num_tokens: int,\n",
885
+ "):\n",
886
+ " \"\"\"\n",
887
+ " Helper function for performance estimation\n",
888
+ "\n",
889
+ " Parameters:\n",
890
+ " current_time (float): This step time in seconds.\n",
891
+ " current_perf_text (str): Current content of performance UI field.\n",
892
+ " new_gen_text (str): New generated text.\n",
893
+ " per_token_time (List[float]): history of performance from previous steps.\n",
894
+ " num_tokens (int): Total number of generated tokens.\n",
895
+ "\n",
896
+ " Returns:\n",
897
+ " update for performance text field\n",
898
+ " update for a total number of tokens\n",
899
+ " \"\"\"\n",
900
+ " num_current_toks = len(tokenizer.encode(new_gen_text))\n",
901
+ " num_tokens += num_current_toks\n",
902
+ " per_token_time.append(num_current_toks / current_time)\n",
903
+ " if len(per_token_time) > 10 and len(per_token_time) % 4 == 0:\n",
904
+ " current_bucket = per_token_time[:-10]\n",
905
+ " return (\n",
906
+ " f\"Average generation speed: {np.mean(current_bucket):.2f} tokens/s. Total generated tokens: {num_tokens}\",\n",
907
+ " num_tokens,\n",
908
+ " )\n",
909
+ " return current_perf_text, num_tokens\n",
910
+ "\n",
911
+ "\n",
912
+ "def reset_textbox(instruction: str, response: str, perf: str):\n",
913
+ " \"\"\"\n",
914
+ " Helper function for resetting content of all text fields\n",
915
+ "\n",
916
+ " Parameters:\n",
917
+ " instruction (str): Content of user instruction field.\n",
918
+ " response (str): Content of model response field.\n",
919
+ " perf (str): Content of performance info filed\n",
920
+ "\n",
921
+ " Returns:\n",
922
+ " empty string for each placeholder\n",
923
+ " \"\"\"\n",
924
+ " return \"\", \"\", \"\""
925
+ ]
926
+ },
927
+ {
928
+ "cell_type": "markdown",
929
+ "id": "31ebb167-0e55-4271-aedd-13814c2356d2",
930
+ "metadata": {},
931
+ "source": [
932
+ "## Run instruction-following pipeline\n",
933
+ "[back to top ⬆️](#Table-of-contents:)\n",
934
+ "\n",
935
+ "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",
936
+ "\n",
937
+ "* `Device` - allows switching inference device. Please note, every time when new device is selected, model will be recompiled and this takes some time.\n",
938
+ "* `Max New Tokens` - maximum size of generated text.\n",
939
+ "* `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",
940
+ "* `Top-k` - the number of highest probability vocabulary tokens to keep for top-k-filtering.\n",
941
+ "* `Temperature` - the value used to module the logits distribution."
942
+ ]
943
+ },
944
+ {
945
+ "cell_type": "code",
946
+ "execution_count": 18,
947
+ "id": "9f222d02-847a-490f-8d66-02608a53259b",
948
+ "metadata": {},
949
+ "outputs": [
950
+ {
951
+ "name": "stdout",
952
+ "output_type": "stream",
953
+ "text": [
954
+ "Running on local URL: http://127.0.0.1:7860\n",
955
+ "\n",
956
+ "To create a public link, set `share=True` in `launch()`.\n"
957
+ ]
958
+ },
959
+ {
960
+ "data": {
961
+ "text/html": [
962
+ "<div><iframe src=\"http://127.0.0.1:7860/\" width=\"100%\" height=\"800\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
963
+ ],
964
+ "text/plain": [
965
+ "<IPython.core.display.HTML object>"
966
+ ]
967
+ },
968
+ "metadata": {},
969
+ "output_type": "display_data"
970
+ }
971
+ ],
972
+ "source": [
973
+ "examples = [\n",
974
+ " \"Give me a recipe for pizza with pineapple\",\n",
975
+ " \"Write me a tweet about the new OpenVINO release\",\n",
976
+ " \"Explain the difference between CPU and GPU\",\n",
977
+ " \"Give five ideas for a great weekend with family\",\n",
978
+ " \"Do Androids dream of Electric sheep?\",\n",
979
+ " \"Who is Dolly?\",\n",
980
+ " \"Please give me advice on how to write resume?\",\n",
981
+ " \"Name 3 advantages to being a cat\",\n",
982
+ " \"Write instructions on how to become a good AI engineer\",\n",
983
+ " \"Write a love letter to my best friend\",\n",
984
+ "]\n",
985
+ "\n",
986
+ "\n",
987
+ "with gr.Blocks() as demo:\n",
988
+ " gr.Markdown(\n",
989
+ " \"# Question Answering with \" + model_id.value + \" and OpenVINO.\\n\"\n",
990
+ " \"Provide instruction which describes a task below or select among predefined examples and model writes response that performs requested task.\"\n",
991
+ " )\n",
992
+ "\n",
993
+ " with gr.Row():\n",
994
+ " with gr.Column(scale=4):\n",
995
+ " user_text = gr.Textbox(\n",
996
+ " placeholder=\"Write an email about an alpaca that likes flan\",\n",
997
+ " label=\"User instruction\",\n",
998
+ " )\n",
999
+ " model_output = gr.Textbox(label=\"Model response\", interactive=False)\n",
1000
+ " performance = gr.Textbox(label=\"Performance\", lines=1, interactive=False)\n",
1001
+ " with gr.Column(scale=1):\n",
1002
+ " button_clear = gr.Button(value=\"Clear\")\n",
1003
+ " button_submit = gr.Button(value=\"Submit\")\n",
1004
+ " gr.Examples(examples, user_text)\n",
1005
+ " with gr.Column(scale=1):\n",
1006
+ " max_new_tokens = gr.Slider(\n",
1007
+ " minimum=1,\n",
1008
+ " maximum=1000,\n",
1009
+ " value=256,\n",
1010
+ " step=1,\n",
1011
+ " interactive=True,\n",
1012
+ " label=\"Max New Tokens\",\n",
1013
+ " )\n",
1014
+ " top_p = gr.Slider(\n",
1015
+ " minimum=0.05,\n",
1016
+ " maximum=1.0,\n",
1017
+ " value=0.92,\n",
1018
+ " step=0.05,\n",
1019
+ " interactive=True,\n",
1020
+ " label=\"Top-p (nucleus sampling)\",\n",
1021
+ " )\n",
1022
+ " top_k = gr.Slider(\n",
1023
+ " minimum=0,\n",
1024
+ " maximum=50,\n",
1025
+ " value=0,\n",
1026
+ " step=1,\n",
1027
+ " interactive=True,\n",
1028
+ " label=\"Top-k\",\n",
1029
+ " )\n",
1030
+ " temperature = gr.Slider(\n",
1031
+ " minimum=0.1,\n",
1032
+ " maximum=5.0,\n",
1033
+ " value=0.8,\n",
1034
+ " step=0.1,\n",
1035
+ " interactive=True,\n",
1036
+ " label=\"Temperature\",\n",
1037
+ " )\n",
1038
+ "\n",
1039
+ " user_text.submit(\n",
1040
+ " run_generation,\n",
1041
+ " [user_text, top_p, temperature, top_k, max_new_tokens, performance],\n",
1042
+ " [model_output, performance],\n",
1043
+ " )\n",
1044
+ " button_submit.click(\n",
1045
+ " run_generation,\n",
1046
+ " [user_text, top_p, temperature, top_k, max_new_tokens, performance],\n",
1047
+ " [model_output, performance],\n",
1048
+ " )\n",
1049
+ " button_clear.click(\n",
1050
+ " reset_textbox,\n",
1051
+ " [user_text, model_output, performance],\n",
1052
+ " [user_text, model_output, performance],\n",
1053
+ " )\n",
1054
+ "\n",
1055
+ "if __name__ == \"__main__\":\n",
1056
+ " demo.queue()\n",
1057
+ " try:\n",
1058
+ " demo.launch(height=800)\n",
1059
+ " except Exception:\n",
1060
+ " demo.launch(share=True, height=800)\n",
1061
+ "\n",
1062
+ "# If you are launching remotely, specify server_name and server_port\n",
1063
+ "# EXAMPLE: `demo.launch(server_name='your server name', server_port='server port in int')`\n",
1064
+ "# To learn more please refer to the Gradio docs: https://gradio.app/docs/"
1065
+ ]
1066
+ },
1067
+ {
1068
+ "cell_type": "code",
1069
+ "execution_count": null,
1070
+ "id": "440417f8-d2e2-4d8d-8311-882d133bb572",
1071
+ "metadata": {},
1072
+ "outputs": [],
1073
+ "source": []
1074
+ },
1075
+ {
1076
+ "cell_type": "code",
1077
+ "execution_count": null,
1078
+ "id": "dd9f90e4-0ec6-4164-8a31-044b1079d3e7",
1079
+ "metadata": {},
1080
+ "outputs": [],
1081
+ "source": []
1082
+ },
1083
+ {
1084
+ "cell_type": "code",
1085
+ "execution_count": null,
1086
+ "id": "7297ddd6-2c3d-4540-aa9b-f1c48c274a86",
1087
+ "metadata": {},
1088
+ "outputs": [],
1089
+ "source": []
1090
+ }
1091
+ ],
1092
+ "metadata": {
1093
+ "kernelspec": {
1094
+ "display_name": "openvino_env",
1095
+ "language": "python",
1096
+ "name": "openvino_env"
1097
+ },
1098
+ "language_info": {
1099
+ "codemirror_mode": {
1100
+ "name": "ipython",
1101
+ "version": 3
1102
+ },
1103
+ "file_extension": ".py",
1104
+ "mimetype": "text/x-python",
1105
+ "name": "python",
1106
+ "nbconvert_exporter": "python",
1107
+ "pygments_lexer": "ipython3",
1108
+ "version": "3.10.9"
1109
+ },
1110
+ "openvino_notebooks": {
1111
+ "imageUrl": "https://github.com/openvinotoolkit/openvino_notebooks/assets/29454499/daafd702-5a42-4f54-ae72-2e4480d73501",
1112
+ "tags": {
1113
+ "categories": [
1114
+ "Model Demos",
1115
+ "AI Trends"
1116
+ ],
1117
+ "libraries": [],
1118
+ "other": [
1119
+ "LLM"
1120
+ ],
1121
+ "tasks": [
1122
+ "Text Generation"
1123
+ ]
1124
+ }
1125
+ },
1126
+ "widgets": {
1127
+ "application/vnd.jupyter.widget-state+json": {
1128
+ "state": {},
1129
+ "version_major": 2,
1130
+ "version_minor": 0
1131
+ }
1132
+ }
1133
+ },
1134
+ "nbformat": 4,
1135
+ "nbformat_minor": 5
1136
+ }
README.md CHANGED
@@ -1,12 +1,6 @@
1
  ---
2
  title: INTEL
3
- emoji: ⚡
4
- colorFrom: green
5
- colorTo: pink
6
- sdk: gradio
7
- sdk_version: 4.37.2
8
  app_file: app.py
9
- pinned: false
 
10
  ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
  title: INTEL
 
 
 
 
 
3
  app_file: app.py
4
+ sdk: gradio
5
+ sdk_version: 4.36.1
6
  ---
 
 
__pycache__/app.cpython-310.pyc ADDED
Binary file (10 kB). View file
 
__pycache__/config.cpython-310.pyc ADDED
Binary file (1.36 kB). View file
 
__pycache__/generation_utils.cpython-310.pyc ADDED
Binary file (4.97 kB). View file
 
__pycache__/notebook_utils.cpython-310.pyc ADDED
Binary file (20.9 kB). View file
 
app.py ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from transformers import AutoTokenizer, AutoConfig
3
+ from optimum.intel.openvino import OVModelForCausalLM
4
+ from generation_utils import run_generation, estimate_latency, reset_textbox,get_special_token_id
5
+ from config import SUPPORTED_LLM_MODELS
6
+ import gradio as gr
7
+ from threading import Thread
8
+ from time import perf_counter
9
+ from typing import List
10
+ from transformers import AutoTokenizer, TextIteratorStreamer
11
+ import numpy as np
12
+ import os
13
+ from flask import Flask, render_template, redirect, url_for, request, flash
14
+ from flask_sqlalchemy import SQLAlchemy
15
+ from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
16
+ from werkzeug.security import generate_password_hash, check_password_hash
17
+
18
+ app = Flask(__name__)
19
+ app.config['SECRET_KEY'] = 'your_secret_key'
20
+ app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
21
+ db = SQLAlchemy(app)
22
+ login_manager = LoginManager()
23
+ login_manager.init_app(app)
24
+ login_manager.login_view = 'login'
25
+
26
+ class User(db.Model):
27
+ id = db.Column(db.Integer, primary_key=True)
28
+ username = db.Column(db.String(80), unique=True, nullable=False)
29
+ email = db.Column(db.String(120), unique=True, nullable=False)
30
+
31
+ def __repr__(self):
32
+ return '<User %r>' % self.username
33
+
34
+ # Create the database tables
35
+ with app.app_context():
36
+ db.create_all()
37
+
38
+ @login_manager.user_loader
39
+ def load_user(user_id):
40
+ return User.query.get(int(user_id))
41
+
42
+ @app.route('/signup', methods=['GET', 'POST'])
43
+ def signup():
44
+ if request.method == 'POST':
45
+ username = request.form['username']
46
+ password = request.form['password']
47
+ hashed_password = generate_password_hash(password, method='sha256')
48
+
49
+ new_user = User(username=username, password=hashed_password)
50
+ db.session.add(new_user)
51
+ db.session.commit()
52
+ flash('Signup successful!', 'success')
53
+ return redirect(url_for('login'))
54
+
55
+ return render_template('signup.html')
56
+
57
+ @app.route('/login', methods=['GET', 'POST'])
58
+ def login():
59
+ if request.method == 'POST':
60
+ username = request.form['username']
61
+ password = request.form['password']
62
+ user = User.query.filter_by(username=username).first()
63
+ if user and check_password_hash(user.password, password):
64
+ login_user(user)
65
+ return redirect(url_for('dashboard'))
66
+ flash('Invalid username or password', 'danger')
67
+
68
+ return render_template('login.html')
69
+
70
+ @app.route('/dashboard')
71
+ @login_required
72
+ def dashboard():
73
+ return render_template('dashboard.html', name=current_user.username)
74
+
75
+ @app.route('/logout')
76
+ @login_required
77
+ def logout():
78
+ logout_user()
79
+ return redirect(url_for('login'))
80
+
81
+ if __name__ == '__main__':
82
+ app.run(debug=True)
83
+ model_dir = "C:/Users/KIIT/OneDrive/Desktop/INTEL/phi-2/INT8_compressed_weights"
84
+ print(f"Checking model directory: {model_dir}")
85
+ print(f"Contents: {os.listdir(model_dir)}") # Check contents of the directory
86
+
87
+ print(f"Loading model from {model_dir}")
88
+
89
+
90
+ model_name = "susnato/phi-2"
91
+ model_configuration = SUPPORTED_LLM_MODELS["phi-2"]
92
+ ov_config = {"PERFORMANCE_HINT": "LATENCY", "NUM_STREAMS": "1", "CACHE_DIR": ""}
93
+
94
+ tok = AutoTokenizer.from_pretrained(model_name)
95
+
96
+ ov_model = OVModelForCausalLM.from_pretrained(
97
+ model_dir,
98
+ device="CPU",
99
+ ov_config=ov_config,
100
+ )
101
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
102
+ tokenizer_kwargs = model_configuration.get("toeknizer_kwargs", {})
103
+ # Continue with your tokenizer usage
104
+ response_key = model_configuration.get("response_key")
105
+ tokenizer_response_key = None
106
+
107
+ def get_special_token_id(tokenizer: AutoTokenizer, key: str) -> int:
108
+ """
109
+ Gets the token ID for a given string that has been added to the tokenizer as a special token.
110
+
111
+ Args:
112
+ tokenizer (PreTrainedTokenizer): the tokenizer
113
+ key (str): the key to convert to a single token
114
+
115
+ Raises:
116
+ ValueError: if more than one ID was generated
117
+
118
+ Returns:
119
+ int: the token ID for the given key
120
+ """
121
+ token_ids = tokenizer.encode(key)
122
+ if len(token_ids) > 1:
123
+ raise ValueError(f"Expected only a single token for '{key}' but found {token_ids}")
124
+ return token_ids[0]
125
+ if response_key is not None:
126
+ tokenizer_response_key = next(
127
+ (token for token in tokenizer.additional_special_tokens if token.startswith(response_key)),
128
+ None,
129
+ )
130
+
131
+ end_key_token_id = None
132
+ if tokenizer_response_key:
133
+ try:
134
+ end_key = model_configuration.get("end_key")
135
+ if end_key:
136
+ end_key_token_id =get_special_token_id(tokenizer, end_key)
137
+ # Ensure generation stops once it generates "### End"
138
+ except ValueError:
139
+ pass
140
+
141
+ prompt_template = model_configuration.get("prompt_template", "{instruction}")
142
+ end_key_token_id = end_key_token_id or tokenizer.eos_token_id
143
+ pad_token_id = end_key_token_id or tokenizer.pad_token_id
144
+
145
+ def estimate_latency(
146
+ current_time: float,
147
+ current_perf_text: str,
148
+ new_gen_text: str,
149
+ per_token_time: List[float],
150
+ num_tokens: int,
151
+ ):
152
+ """
153
+ Helper function for performance estimation
154
+
155
+ Parameters:
156
+ current_time (float): This step time in seconds.
157
+ current_perf_text (str): Current content of performance UI field.
158
+ new_gen_text (str): New generated text.
159
+ per_token_time (List[float]): history of performance from previous steps.
160
+ num_tokens (int): Total number of generated tokens.
161
+
162
+ Returns:
163
+ update for performance text field
164
+ update for a total number of tokens
165
+ """
166
+ num_current_toks = len(tokenizer.encode(new_gen_text))
167
+ num_tokens += num_current_toks
168
+ per_token_time.append(num_current_toks / current_time)
169
+ if len(per_token_time) > 10 and len(per_token_time) % 4 == 0:
170
+ current_bucket = per_token_time[:-10]
171
+ return (
172
+ f"Average generation speed: {np.mean(current_bucket):.2f} tokens/s. Total generated tokens: {num_tokens}",
173
+ num_tokens,
174
+ )
175
+ return current_perf_text, num_tokens
176
+ def run_generation(
177
+ user_text: str,
178
+ top_p: float,
179
+ temperature: float,
180
+ top_k: int,
181
+ max_new_tokens: int,
182
+ perf_text: str,
183
+ ):
184
+ """
185
+ Text generation function
186
+
187
+ Parameters:
188
+ user_text (str): User-provided instruction for a generation.
189
+ 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.
190
+ temperature (float): The value used to module the logits distribution.
191
+ top_k (int): The number of highest probability vocabulary tokens to keep for top-k-filtering.
192
+ max_new_tokens (int): Maximum length of generated sequence.
193
+ perf_text (str): Content of text field for printing performance results.
194
+ Returns:
195
+ model_output (str) - model-generated text
196
+ perf_text (str) - updated perf text filed content
197
+ """
198
+
199
+ # Prepare input prompt according to model expected template
200
+ prompt_text = prompt_template.format(instruction=user_text)
201
+
202
+ # Tokenize the user text.
203
+ model_inputs = tokenizer(prompt_text, return_tensors="pt", **tokenizer_kwargs)
204
+
205
+ # Start generation on a separate thread, so that we don't block the UI. The text is pulled from the streamer
206
+ # in the main thread. Adds timeout to the streamer to handle exceptions in the generation thread.
207
+ streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
208
+ generate_kwargs = dict(
209
+ model_inputs,
210
+ streamer=streamer,
211
+ max_new_tokens=max_new_tokens,
212
+ do_sample=True,
213
+ top_p=top_p,
214
+ temperature=float(temperature),
215
+ top_k=top_k,
216
+ eos_token_id=end_key_token_id,
217
+ pad_token_id=pad_token_id,
218
+ )
219
+ t = Thread(target=ov_model.generate, kwargs=generate_kwargs)
220
+ t.start()
221
+
222
+ # Pull the generated text from the streamer, and update the model output.
223
+ model_output = ""
224
+ per_token_time = []
225
+ num_tokens = 0
226
+ start = perf_counter()
227
+ for new_text in streamer:
228
+ current_time = perf_counter() - start
229
+ model_output += new_text
230
+ perf_text, num_tokens = estimate_latency(current_time, perf_text, new_text, per_token_time, num_tokens)
231
+ yield model_output, perf_text
232
+ start = perf_counter()
233
+ return model_output, perf_text
234
+ def reset_textbox(instruction: str, response: str, perf: str):
235
+ """
236
+ Helper function for resetting content of all text fields
237
+
238
+ Parameters:
239
+ instruction (str): Content of user instruction field.
240
+ response (str): Content of model response field.
241
+ perf (str): Content of performance info filed
242
+
243
+ Returns:
244
+ empty string for each placeholder
245
+ """
246
+ return "", "", ""
247
+
248
+
249
+
250
+ examples = [
251
+ "Give me a recipe for pizza with pineapple",
252
+ "Write me a tweet about the new OpenVINO release",
253
+ "Explain the difference between CPU and GPU",
254
+ "Give five ideas for a great weekend with family",
255
+ "Do Androids dream of Electric sheep?",
256
+ "Who is Dolly?",
257
+ "Please give me advice on how to write resume?",
258
+ "Name 3 advantages to being a cat",
259
+ "Write instructions on how to become a good AI engineer",
260
+ "Write a love letter to my best friend",
261
+ ]
262
+
263
+ def main():
264
+ with gr.Blocks() as demo:
265
+ gr.Markdown(
266
+ "# Question Answering with Model and OpenVINO.\n"
267
+ "Provide instruction which describes a task below or select among predefined examples and model writes response that performs requested task."
268
+ )
269
+
270
+ with gr.Row():
271
+ with gr.Column(scale=4):
272
+ user_text = gr.Textbox(
273
+ placeholder="Write an email about an alpaca that likes flan",
274
+ label="User instruction",
275
+ )
276
+ model_output = gr.Textbox(label="Model response", interactive=False)
277
+ performance = gr.Textbox(label="Performance", lines=1, interactive=False)
278
+ with gr.Column(scale=1):
279
+ button_clear = gr.Button(value="Clear")
280
+ button_submit = gr.Button(value="Submit")
281
+ gr.Examples(examples, user_text)
282
+ with gr.Column(scale=1):
283
+ max_new_tokens = gr.Slider(
284
+ minimum=1,
285
+ maximum=1000,
286
+ value=256,
287
+ step=1,
288
+ interactive=True,
289
+ label="Max New Tokens",
290
+ )
291
+ top_p = gr.Slider(
292
+ minimum=0.05,
293
+ maximum=1.0,
294
+ value=0.92,
295
+ step=0.05,
296
+ interactive=True,
297
+ label="Top-p (nucleus sampling)",
298
+ )
299
+ top_k = gr.Slider(
300
+ minimum=0,
301
+ maximum=50,
302
+ value=0,
303
+ step=1,
304
+ interactive=True,
305
+ label="Top-k",
306
+ )
307
+ temperature = gr.Slider(
308
+ minimum=0.1,
309
+ maximum=5.0,
310
+ value=0.8,
311
+ step=0.1,
312
+ interactive=True,
313
+ label="Temperature",
314
+ )
315
+
316
+ user_text.submit(
317
+ run_generation,
318
+ [user_text, top_p, temperature, top_k, max_new_tokens, performance],
319
+ [model_output, performance],
320
+ )
321
+ button_submit.click(
322
+ run_generation,
323
+ [user_text, top_p, temperature, top_k, max_new_tokens, performance],
324
+ [model_output, performance],
325
+ )
326
+ button_clear.click(
327
+ reset_textbox,
328
+ [user_text, model_output, performance],
329
+ [user_text, model_output, performance],
330
+ )
331
+
332
+ if __name__ == "__main__":
333
+ demo.queue()
334
+ try:
335
+ demo.launch(height=800)
336
+ except Exception:
337
+ demo.launch(share=True, height=800)
338
+
339
+ # Call main function to start Gradio interface
340
+ main()
app1.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+
3
+ import os
4
+ from flask import Flask, render_template, redirect, url_for, request, flash
5
+ from flask_sqlalchemy import SQLAlchemy
6
+ from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
7
+ from werkzeug.security import generate_password_hash, check_password_hash
8
+ from app import run_generation
9
+
10
+ app = Flask(__name__)
11
+ app.config['SECRET_KEY'] = 'your_secret_key'
12
+ app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
13
+ db = SQLAlchemy(app)
14
+ login_manager = LoginManager()
15
+ login_manager.init_app(app)
16
+ login_manager.login_view = 'login'
17
+
18
+ class User(db.Model, UserMixin):
19
+ id = db.Column(db.Integer, primary_key=True)
20
+ username = db.Column(db.String(80), unique=True, nullable=False)
21
+ password = db.Column(db.String(120), nullable=False)
22
+
23
+ def __repr__(self):
24
+ return '<User %r>' % self.username
25
+
26
+ # Create the database tables
27
+ with app.app_context():
28
+ db.drop_all()
29
+ db.create_all()
30
+
31
+ @login_manager.user_loader
32
+ def load_user(user_id):
33
+ return User.query.get(int(user_id))
34
+
35
+ @app.route('/', methods=['GET', 'POST'])
36
+ def signup():
37
+ if request.method == 'POST':
38
+ username = request.form['username']
39
+ password = request.form['password']
40
+ hashed_password = generate_password_hash(password, method='pbkdf2:sha256')
41
+
42
+ new_user = User(username=username, password=hashed_password)
43
+ db.session.add(new_user)
44
+ db.session.commit()
45
+ flash('Signup successful!', 'success')
46
+ return redirect(url_for('login'))
47
+
48
+ return render_template('signup.html')
49
+
50
+ @app.route('/login', methods=['GET', 'POST'])
51
+ def login():
52
+ if request.method == 'POST':
53
+ username = request.form['username']
54
+ password = request.form['password']
55
+ user = User.query.filter_by(username=username).first()
56
+ if user and check_password_hash(user.password, password):
57
+ login_user(user)
58
+ return redirect(url_for('dashboard'))
59
+ flash('Invalid username or password', 'danger')
60
+
61
+ return render_template('login.html')
62
+
63
+ @app.route('/app.run_generation')
64
+ @login_required
65
+
66
+ @app.route('/dashboard')
67
+ @login_required
68
+ def dashboard():
69
+ return render_template('dashboard.html', name=current_user.username)
70
+
71
+ @app.route('/logout')
72
+ @login_required
73
+ def logout():
74
+ logout_user()
75
+ return redirect(url_for('login'))
76
+
77
+ if __name__ == '__main__':
78
+ app.run(debug=True)
app2.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, render_template, redirect, url_for, request, flash
2
+ from flask_sqlalchemy import SQLAlchemy
3
+ from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
4
+ from werkzeug.security import generate_password_hash, check_password_hash
5
+
6
+ app = Flask(__name__)
7
+ app.config['SECRET_KEY'] = 'your_secret_key'
8
+ app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
9
+ db = SQLAlchemy(app)
10
+ login_manager = LoginManager()
11
+ login_manager.init_app(app)
12
+ login_manager.login_view = 'login'
13
+
14
+ class User(db.Model, UserMixin):
15
+ id = db.Column(db.Integer, primary_key=True)
16
+ username = db.Column(db.String(80), unique=True, nullable=False)
17
+ password = db.Column(db.String(120), nullable=False)
18
+
19
+ def __repr__(self):
20
+ return '<User %r>' % self.username
21
+
22
+ # Create the database tables
23
+ with app.app_context():
24
+ db.drop_all()
25
+ db.create_all()
26
+
27
+ @login_manager.user_loader
28
+ def load_user(user_id):
29
+ return User.query.get(int(user_id))
30
+
31
+ @app.route('/', methods=['GET', 'POST'])
32
+ def signup():
33
+ if request.method == 'POST':
34
+ username = request.form['username']
35
+ password = request.form['password']
36
+ hashed_password = generate_password_hash(password, method='pbkdf2:sha256')
37
+
38
+ new_user = User(username=username, password=hashed_password)
39
+ db.session.add(new_user)
40
+ db.session.commit()
41
+ flash('Signup successful!', 'success')
42
+ return redirect(url_for('login'))
43
+
44
+ return render_template('signup.html')
45
+
46
+ @app.route('/login', methods=['GET', 'POST'])
47
+ def login():
48
+ if request.method == 'POST':
49
+ username = request.form['username']
50
+ password = request.form['password']
51
+ user = User.query.filter_by(username=username).first()
52
+ if user and check_password_hash(user.password, password):
53
+ login_user(user)
54
+ return redirect(url_for('dashboard'))
55
+ flash('Invalid username or password', 'danger')
56
+
57
+ return render_template('login.html')
58
+
59
+ @app.route('/run_generation')
60
+ @login_required
61
+ def run_generation_route():
62
+ # Call the run_generation function here
63
+ result = run_generation()
64
+ return render_template('generation.html', result=result)
65
+
66
+ @app.route('/dashboard')
67
+ @login_required
68
+ def dashboard():
69
+ return render_template('dashboard.html', name=current_user.username)
70
+
71
+ @app.route('/logout')
72
+ @login_required
73
+ def logout():
74
+ logout_user()
75
+ return redirect(url_for('login'))
76
+
77
+ if __name__ == '__main__':
78
+ app.run(debug=True)
app3.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from flask import Flask, render_template, redirect, url_for, request, flash
3
+ from flask_sqlalchemy import SQLAlchemy
4
+ from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
5
+ from werkzeug.security import generate_password_hash, check_password_hash
6
+ from transformers import AutoTokenizer
7
+ from optimum.intel.openvino import OVModelForCausalLM
8
+ import gradio as gr
9
+ from threading import Thread
10
+ from time import perf_counter
11
+ from typing import List
12
+ import numpy as np
13
+
14
+ app = Flask(__name__)
15
+ app.config['SECRET_KEY'] = 'your_secret_key'
16
+ app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
17
+ db = SQLAlchemy(app)
18
+ login_manager = LoginManager()
19
+ login_manager.init_app(app)
20
+ login_manager.login_view = 'login'
21
+
22
+ class User(db.Model, UserMixin):
23
+ id = db.Column(db.Integer, primary_key=True)
24
+ username = db.Column(db.String(80), unique=True, nullable=False)
25
+ password = db.Column(db.String(120), nullable=False)
26
+
27
+ def __repr__(self):
28
+ return '<User %r>' % self.username
29
+
30
+ # Create the database tables
31
+ with app.app_context():
32
+ db.create_all()
33
+
34
+ @login_manager.user_loader
35
+ def load_user(user_id):
36
+ return User.query.get(int(user_id))
37
+
38
+ @app.route('/', methods=['GET', 'POST'])
39
+ def signup():
40
+ if request.method == 'POST':
41
+ username = request.form['username']
42
+ password = request.form['password']
43
+ hashed_password = generate_password_hash(password, method='pbkdf2:sha256')
44
+
45
+ new_user = User(username=username, password=hashed_password)
46
+ db.session.add(new_user)
47
+ db.session.commit()
48
+ flash('Signup successful!', 'success')
49
+ return redirect(url_for('login'))
50
+
51
+ return render_template('signup.html')
52
+
53
+ @app.route('/login', methods=['GET', 'POST'])
54
+ def login():
55
+ if request.method == 'POST':
56
+ username = request.form['username']
57
+ password = request.form['password']
58
+ user = User.query.filter_by(username=username).first()
59
+ if user and check_password_hash(user.password, password):
60
+ login_user(user)
61
+ return redirect(url_for('dashboard'))
62
+ flash('Invalid username or password', 'danger')
63
+
64
+ return render_template('login.html')
65
+
66
+ @app.route('/dashboard')
67
+ @login_required
68
+ def dashboard():
69
+ return render_template('dashboard.html', name=current_user.username)
70
+
71
+ @app.route('/logout')
72
+ @login_required
73
+ def logout():
74
+ logout_user()
75
+ return redirect(url_for('login'))
76
+
77
+ # Gradio app integration
78
+ model_dir = "C:/Users/KIIT/OneDrive/Desktop/INTEL/phi-2/INT8_compressed_weights"
79
+ model_name = "susnato/phi-2"
80
+ ov_config = {"PERFORMANCE_HINT": "LATENCY", "NUM_STREAMS": "1", "CACHE_DIR": ""}
81
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
82
+ ov_model = OVModelForCausalLM.from_pretrained(model_dir, device="CPU", ov_config=ov_config)
83
+
84
+ prompt_template = "{instruction}"
85
+ end_key_token_id = tokenizer.eos_token_id
86
+ pad_token_id = tokenizer.pad_token_id
87
+
88
+ def estimate_latency(current_time, current_perf_text, new_gen_text, per_token_time, num_tokens):
89
+ num_current_toks = len(tokenizer.encode(new_gen_text))
90
+ num_tokens += num_current_toks
91
+ per_token_time.append(num_current_toks / current_time)
92
+ if len(per_token_time) > 10 and len(per_token_time) % 4 == 0:
93
+ current_bucket = per_token_time[:-10]
94
+ return f"Average generation speed: {np.mean(current_bucket):.2f} tokens/s. Total generated tokens: {num_tokens}", num_tokens
95
+ return current_perf_text, num_tokens
96
+
97
+ def run_generation(user_text, top_p, temperature, top_k, max_new_tokens, perf_text):
98
+ prompt_text = prompt_template.format(instruction=user_text)
99
+ model_inputs = tokenizer(prompt_text, return_tensors="pt")
100
+
101
+ streamer = gr.utils.TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
102
+ generate_kwargs = dict(
103
+ model_inputs,
104
+ streamer=streamer,
105
+ max_new_tokens=max_new_tokens,
106
+ do_sample=True,
107
+ top_p=top_p,
108
+ temperature=temperature,
109
+ top_k=top_k,
110
+ eos_token_id=end_key_token_id,
111
+ pad_token_id=pad_token_id,
112
+ )
113
+ t = Thread(target=ov_model.generate, kwargs=generate_kwargs)
114
+ t.start()
115
+
116
+ model_output = ""
117
+ per_token_time = []
118
+ num_tokens = 0
119
+ start = perf_counter()
120
+ for new_text in streamer:
121
+ current_time = perf_counter() - start
122
+ model_output += new_text
123
+ perf_text, num_tokens = estimate_latency(current_time, perf_text, new_text, per_token_time, num_tokens)
124
+ yield model_output, perf_text
125
+ start = perf_counter()
126
+ return model_output, perf_text
127
+
128
+ def reset_textbox(instruction, response, perf):
129
+ return "", "", ""
130
+
131
+ examples = [
132
+ "Give me a recipe for pizza with pineapple",
133
+ "Write me a tweet about the new OpenVINO release",
134
+ "Explain the difference between CPU and GPU",
135
+ "Give five ideas for a great weekend with family",
136
+ "Do Androids dream of Electric sheep?",
137
+ "Who is Dolly?",
138
+ "Please give me advice on how to write resume?",
139
+ "Name 3 advantages to being a cat",
140
+ "Write instructions on how to become a good AI engineer",
141
+ "Write a love letter to my best friend",
142
+ ]
143
+
144
+ @app.route('/gradio')
145
+ @login_required
146
+ def gradio():
147
+ with gr.Blocks() as demo:
148
+ gr.Markdown("# Question Answering with Model and OpenVINO.\nProvide instruction which describes a task below or select among predefined examples and model writes response that performs requested task.")
149
+ with gr.Row():
150
+ with gr.Column(scale=4):
151
+ user_text = gr.Textbox(placeholder="Write an email about an alpaca that likes flan", label="User instruction")
152
+ model_output = gr.Textbox(label="Model response", interactive=False)
153
+ performance = gr.Textbox(label="Performance", lines=1, interactive=False)
154
+ with gr.Column(scale=1):
155
+ button_clear = gr.Button(value="Clear")
156
+ button_submit = gr.Button(value="Submit")
157
+ gr.Examples(examples, user_text)
158
+ with gr.Column(scale=1):
159
+ max_new_tokens = gr.Slider(minimum=1, maximum=1000, value=256, step=1, interactive=True, label="Max New Tokens")
160
+ top_p = gr.Slider(minimum=0.05, maximum=1.0, value=0.92, step=0.05, interactive=True, label="Top-p (nucleus sampling)")
161
+ top_k = gr.Slider(minimum=0, maximum=50, value=0, step=1, interactive=True, label="Top-k")
162
+ temperature = gr.Slider(minimum=0.1, maximum=5.0, value=0.8, step=0.1, interactive=True, label="Temperature")
163
+
164
+ user_text.submit(run_generation, [user_text, top_p, temperature, top_k, max_new_tokens, performance], [model_output, performance])
165
+ button_submit.click(run_generation, [user_text, top_p, temperature, top_k, max_new_tokens, performance], [model_output, performance])
166
+ button_clear.click(reset_textbox, [user_text, model_output, performance], [user_text, model_output, performance])
167
+
168
+ return demo.launch(share=True)
169
+
170
+ if __name__ == '__main__':
171
+ app.run(debug=True)
config.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ SUPPORTED_LLM_MODELS = {
2
+ "tiny-llama-1b": {
3
+ "model_id": "TinyLlama/TinyLlama-1.1B-Chat-v1.0",
4
+ "prompt_template": "<|user|>\n{instruction}</s> \n<|assistant|>\n",
5
+ "tokenizer_kwargs": {"add_special_tokens": False},
6
+ },
7
+ "phi-2": {
8
+ "model_id": "susnato/phi-2",
9
+ "prompt_template": "Instruct:{instruction}\nOutput:",
10
+ },
11
+ "dolly-v2-3b": {
12
+ "model_id": "databricks/dolly-v2-3b",
13
+ "instriction_key": "### Instruction:",
14
+ "response_key": "### Response:",
15
+ "end_key": "### End",
16
+ "prompt_template": """Below is an instruction that describes a task. Write a response that appropriately completes the request.
17
+
18
+ ### Instruction:
19
+ {instruction}
20
+
21
+ ### Response:
22
+ """,
23
+ },
24
+ "red-pajama-instruct-3b": {
25
+ "model_id": "togethercomputer/RedPajama-INCITE-Instruct-3B-v1",
26
+ "prompt_template": "Q: {instruction}\nA:",
27
+ },
28
+ "mistral-7b": {
29
+ "model_id": "mistralai/Mistral-7B-Instruct-v0.2",
30
+ "prompt_template": "<s> [INST] {instruction} [/INST] </s>",
31
+ "tokenizer_kwargs": {"add_special_tokens": False},
32
+ },
33
+ "llama-3-8b-instruct": {
34
+ "model_id": "meta-llama/Meta-Llama-3-8B-Instruct",
35
+ "end_key": "<|eot_id|>",
36
+ "prompt_template": "<|start_header_id|>system<|end_header_id|>\n\nBelow is an instruction that describes a task. Write a response that appropriately completes the request.<|eot_id|><|start_header_id|>user<|end_header_id|>Instruction: {instruction} Answer:<|eot_id|><|start_header_id|>assistant<|end_header_id|>",
37
+ },
38
+ }
generation_utils.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # generation_utils.py
2
+
3
+ from threading import Thread
4
+ from time import perf_counter
5
+ from typing import List
6
+ import gradio as gr
7
+ from transformers import AutoTokenizer, TextIteratorStreamer
8
+ import numpy as np
9
+ import os
10
+
11
+ def get_special_token_id(tokenizer: AutoTokenizer, key: str) -> int:
12
+ """
13
+ Gets the token ID for a given string that has been added to the tokenizer as a special token.
14
+
15
+ Args:
16
+ tokenizer (PreTrainedTokenizer): the tokenizer
17
+ key (str): the key to convert to a single token
18
+
19
+ Raises:
20
+ ValueError: if more than one ID was generated
21
+
22
+ Returns:
23
+ int: the token ID for the given key
24
+ """
25
+ token_ids = tokenizer.encode(key)
26
+ if len(token_ids) > 1:
27
+ raise ValueError(f"Expected only a single token for '{key}' but found {token_ids}")
28
+ return token_ids[0]
29
+
30
+
31
+ def estimate_latency(
32
+ current_time: float,
33
+ current_perf_text: str,
34
+ new_gen_text: str,
35
+ per_token_time: List[float],
36
+ num_tokens: int,
37
+ ) -> tuple:
38
+ """
39
+ Helper function for performance estimation
40
+
41
+ Parameters:
42
+ current_time (float): This step time in seconds.
43
+ current_perf_text (str): Current content of performance UI field.
44
+ new_gen_text (str): New generated text.
45
+ per_token_time (List[float]): history of performance from previous steps.
46
+ num_tokens (int): Total number of generated tokens.
47
+
48
+ Returns:
49
+ update for performance text field
50
+ update for a total number of tokens
51
+ """
52
+ num_current_toks = len(tokenizer.encode(new_gen_text))
53
+ num_tokens += num_current_toks
54
+ per_token_time.append(num_current_toks / current_time)
55
+ if len(per_token_time) > 10 and len(per_token_time) % 4 == 0:
56
+ current_bucket = per_token_time[:-10]
57
+ return (
58
+ f"Average generation speed: {np.mean(current_bucket):.2f} tokens/s. Total generated tokens: {num_tokens}",
59
+ num_tokens,
60
+ )
61
+ return current_perf_text, num_tokens
62
+
63
+
64
+ def run_generation(
65
+ user_text: str,
66
+ top_p: float,
67
+ temperature: float,
68
+ top_k: int,
69
+ max_new_tokens: int,
70
+ perf_text: str,
71
+ tokenizer: AutoTokenizer,
72
+ tokenizer_kwargs: dict,
73
+ model_configuration: dict,
74
+ ov_model,
75
+ ) -> tuple:
76
+ """
77
+ Text generation function
78
+
79
+ Parameters:
80
+ user_text (str): User-provided instruction for generation.
81
+ top_p (float): Nucleus sampling. If < 1, keeps smallest set of most probable tokens.
82
+ temperature (float): Modulates logits distribution.
83
+ top_k (int): Number of highest probability vocabulary tokens to keep for top-k-filtering.
84
+ max_new_tokens (int): Maximum length of generated sequence.
85
+ perf_text (str): Content of text field for performance results.
86
+ tokenizer (AutoTokenizer): The tokenizer object.
87
+ tokenizer_kwargs (dict): Additional kwargs for tokenizer.
88
+ model_configuration (dict): Configuration for the model.
89
+ ov_model: Your OpenVINO model object.
90
+
91
+ Returns:
92
+ model_output (str): Model-generated text.
93
+ perf_text (str): Updated performance text.
94
+ """
95
+
96
+ # Extract necessary configurations from model_configuration
97
+ response_key = model_configuration.get("response_key")
98
+ prompt_template = model_configuration.get("prompt_template", "{instruction}")
99
+ end_key = model_configuration.get("end_key")
100
+ end_key_token_id = None
101
+
102
+ # Handle special tokens
103
+ if response_key:
104
+ tokenizer_response_key = next(
105
+ (token for token in tokenizer.additional_special_tokens if token.startswith(response_key)),
106
+ None,
107
+ )
108
+ if tokenizer_response_key and end_key:
109
+ try:
110
+ end_key_token_id = get_special_token_id(tokenizer, end_key)
111
+ except ValueError:
112
+ pass
113
+
114
+ # Ensure defaults for token IDs
115
+ end_key_token_id = end_key_token_id or tokenizer.eos_token_id
116
+ pad_token_id = end_key_token_id or tokenizer.pad_token_id
117
+
118
+ # Prepare input prompt according to model expected template
119
+ prompt_text = prompt_template.format(instruction=user_text)
120
+
121
+ # Tokenize the user text.
122
+ model_inputs = tokenizer(prompt_text, return_tensors="pt", **tokenizer_kwargs)
123
+
124
+ # Start generation on a separate thread, so that we don't block the UI.
125
+ streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
126
+ generate_kwargs = {
127
+ **model_inputs,
128
+ "streamer": streamer,
129
+ "max_new_tokens": max_new_tokens,
130
+ "do_sample": True,
131
+ "top_p": top_p,
132
+ "temperature": float(temperature),
133
+ "top_k": top_k,
134
+ "eos_token_id": end_key_token_id,
135
+ "pad_token_id": pad_token_id,
136
+ }
137
+
138
+ # Start generation in a separate thread
139
+ t = Thread(target=ov_model.generate, kwargs=generate_kwargs)
140
+ t.start()
141
+
142
+ # Pull the generated text from the streamer and update model output
143
+ model_output = ""
144
+ per_token_time = []
145
+ num_tokens = 0
146
+ start = perf_counter()
147
+
148
+ for new_text in streamer:
149
+ current_time = perf_counter() - start
150
+ model_output += new_text
151
+ perf_text, num_tokens = estimate_latency(current_time, perf_text, new_text, per_token_time, num_tokens)
152
+ yield model_output, perf_text
153
+ start = perf_counter()
154
+
155
+ return model_output, perf_text
156
+ def estimate_latency(
157
+ current_time: float,
158
+ current_perf_text: str,
159
+ new_gen_text: str,
160
+ per_token_time: List[float],
161
+ num_tokens: int,
162
+ ):
163
+ """
164
+ Helper function for performance estimation
165
+
166
+ Parameters:
167
+ current_time (float): This step time in seconds.
168
+ current_perf_text (str): Current content of performance UI field.
169
+ new_gen_text (str): New generated text.
170
+ per_token_time (List[float]): history of performance from previous steps.
171
+ num_tokens (int): Total number of generated tokens.
172
+
173
+ Returns:
174
+ update for performance text field
175
+ update for a total number of tokens
176
+ """
177
+ num_current_toks = len(tokenizer.encode(new_gen_text))
178
+ num_tokens += num_current_toks
179
+ per_token_time.append(num_current_toks / current_time)
180
+ if len(per_token_time) > 10 and len(per_token_time) % 4 == 0:
181
+ current_bucket = per_token_time[:-10]
182
+ return (
183
+ f"Average generation speed: {np.mean(current_bucket):.2f} tokens/s. Total generated tokens: {num_tokens}",
184
+ num_tokens,
185
+ )
186
+ return current_perf_text, num_tokens
187
+
188
+
189
+ def reset_textbox(instruction: str, response: str, perf: str):
190
+ """
191
+ Helper function for resetting content of all text fields
192
+
193
+ Parameters:
194
+ instruction (str): Content of user instruction field.
195
+ response (str): Content of model response field.
196
+ perf (str): Content of performance info filed
197
+
198
+ Returns:
199
+ empty string for each placeholder
200
+ """
201
+ return "", "", ""
instance/users.db ADDED
Binary file (16.4 kB). View file
 
llm-question-answering-Copy1 (1).ipynb ADDED
@@ -0,0 +1,1249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "f6aa8c52-9bde-41a6-a5f7-4fa93d5c2a6c",
6
+ "metadata": {},
7
+ "source": [
8
+ "# LLM Instruction-following pipeline with OpenVINO \n",
9
+ "\n",
10
+ "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",
11
+ "\n",
12
+ "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",
13
+ "\n",
14
+ "The tutorial consists of the following steps:\n",
15
+ "\n",
16
+ "- Install prerequisites\n",
17
+ "- Download and convert the model from a public source using the [OpenVINO integration with Hugging Face Optimum](https://huggingface.co/blog/openvino).\n",
18
+ "- Compress model weights to INT8 and INT4 with [OpenVINO NNCF](https://github.com/openvinotoolkit/nncf)\n",
19
+ "- Create an instruction-following inference pipeline\n",
20
+ "- Run instruction-following pipeline\n",
21
+ "\n",
22
+ "\n",
23
+ "#### Table of contents:\n",
24
+ "\n",
25
+ "- [Prerequisites](#Prerequisites)\n",
26
+ "- [Select model for inference](#Select-model-for-inference)\n",
27
+ "- [Instantiate Model using Optimum Intel](#Instantiate-Model-using-Optimum-Intel)\n",
28
+ "- [Compress model weights](#Compress-model-weights)\n",
29
+ " - [Weights Compression using Optimum Intel](#Weights-Compression-using-Optimum-Intel)\n",
30
+ " - [Weights Compression using NNCF](#Weights-Compression-using-NNCF)\n",
31
+ "- [Select device for inference and model variant](#Select-device-for-inference-and-model-variant)\n",
32
+ "- [Create an instruction-following inference pipeline](#Create-an-instruction-following-inference-pipeline)\n",
33
+ " - [Setup imports](#Setup-imports)\n",
34
+ " - [Prepare template for user prompt](#Prepare-template-for-user-prompt)\n",
35
+ " - [Main generation function](#Main-generation-function)\n",
36
+ " - [Helpers for application](#Helpers-for-application)\n",
37
+ "- [Run instruction-following pipeline](#Run-instruction-following-pipeline)\n",
38
+ "\n"
39
+ ]
40
+ },
41
+ {
42
+ "cell_type": "markdown",
43
+ "id": "027108c2-1fbe-4be5-9e23-3fc359185a42",
44
+ "metadata": {},
45
+ "source": [
46
+ "## Prerequisites\n",
47
+ "[back to top ⬆️](#Table-of-contents:)\n"
48
+ ]
49
+ },
50
+ {
51
+ "cell_type": "code",
52
+ "execution_count": 1,
53
+ "id": "5d0473c6-3734-422d-a370-2e39d576be0e",
54
+ "metadata": {},
55
+ "outputs": [
56
+ {
57
+ "name": "stdout",
58
+ "output_type": "stream",
59
+ "text": [
60
+ "Note: you may need to restart the kernel to use updated packages.\n"
61
+ ]
62
+ },
63
+ {
64
+ "name": "stderr",
65
+ "output_type": "stream",
66
+ "text": [
67
+ "WARNING: Ignoring invalid distribution -ptimum (c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages)\n",
68
+ "WARNING: Ignoring invalid distribution -ptimum (c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages)\n"
69
+ ]
70
+ },
71
+ {
72
+ "name": "stdout",
73
+ "output_type": "stream",
74
+ "text": [
75
+ "Note: you may need to restart the kernel to use updated packages.\n",
76
+ "Note: you may need to restart the kernel to use updated packages.\n"
77
+ ]
78
+ },
79
+ {
80
+ "name": "stderr",
81
+ "output_type": "stream",
82
+ "text": [
83
+ "WARNING: Ignoring invalid distribution -ptimum (c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages)\n",
84
+ "WARNING: Ignoring invalid distribution -ptimum (c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages)\n"
85
+ ]
86
+ },
87
+ {
88
+ "name": "stdout",
89
+ "output_type": "stream",
90
+ "text": [
91
+ "Note: you may need to restart the kernel to use updated packages.\n"
92
+ ]
93
+ },
94
+ {
95
+ "name": "stderr",
96
+ "output_type": "stream",
97
+ "text": [
98
+ "WARNING: Ignoring invalid distribution -ptimum (c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages)\n",
99
+ "WARNING: Ignoring invalid distribution -ptimum (c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages)\n"
100
+ ]
101
+ }
102
+ ],
103
+ "source": [
104
+ "%pip install -Uq pip\n",
105
+ "%pip uninstall -q -y optimum optimum-intel\n",
106
+ "%pip install --pre -Uq openvino openvino-tokenizers[transformers] --extra-index-url https://storage.openvinotoolkit.org/simple/wheels/nightly\n",
107
+ "%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"
108
+ ]
109
+ },
110
+ {
111
+ "cell_type": "markdown",
112
+ "id": "611cc777-d5bc-4c7b-92e4-a4befa13b2ce",
113
+ "metadata": {},
114
+ "source": [
115
+ "## Select model for inference\n",
116
+ "[back to top ⬆️](#Table-of-contents:)\n",
117
+ "\n",
118
+ "The tutorial supports different models, you can select one from the provided options to compare the quality of open source LLM solutions.\n",
119
+ ">**Note**: conversion of some models can require additional actions from user side and at least 64GB RAM for conversion.\n",
120
+ "\n",
121
+ "The available options are:\n",
122
+ "\n",
123
+ "* **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",
124
+ "* **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",
125
+ "* **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",
126
+ "* **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",
127
+ "* **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",
128
+ "* **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",
129
+ ">**Note**: run model with demo, you will need to accept license agreement. \n",
130
+ ">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",
131
+ ">You can login on Hugging Face Hub in notebook environment, using following code:\n",
132
+ " \n",
133
+ "```python\n",
134
+ " ## login to huggingfacehub to get access to pretrained model \n",
135
+ "\n",
136
+ " from huggingface_hub import notebook_login, whoami\n",
137
+ "\n",
138
+ " try:\n",
139
+ " whoami()\n",
140
+ " print('Authorization token already provided')\n",
141
+ " except OSError:\n",
142
+ " notebook_login()\n",
143
+ "```"
144
+ ]
145
+ },
146
+ {
147
+ "cell_type": "code",
148
+ "execution_count": 2,
149
+ "id": "51920510-effc-49ef-8c6f-81c951d96a9b",
150
+ "metadata": {},
151
+ "outputs": [],
152
+ "source": [
153
+ "from pathlib import Path\n",
154
+ "import requests\n",
155
+ "\n",
156
+ "# Fetch `notebook_utils` module\n",
157
+ "r = requests.get(\n",
158
+ " url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/utils/notebook_utils.py\",\n",
159
+ ")\n",
160
+ "open(\"notebook_utils.py\", \"w\").write(r.text)\n",
161
+ "from notebook_utils import download_file\n",
162
+ "\n",
163
+ "if not Path(\"./config.py\").exists():\n",
164
+ " download_file(url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/notebooks/llm-question-answering/config.py\")\n",
165
+ "from config import SUPPORTED_LLM_MODELS\n",
166
+ "import ipywidgets as widgets"
167
+ ]
168
+ },
169
+ {
170
+ "cell_type": "code",
171
+ "execution_count": 3,
172
+ "id": "27b42290-a9b5-4453-9a4c-ffa44bbd966d",
173
+ "metadata": {},
174
+ "outputs": [
175
+ {
176
+ "data": {
177
+ "application/vnd.jupyter.widget-view+json": {
178
+ "model_id": "ac9109fc5e134507839e2b6da803cc48",
179
+ "version_major": 2,
180
+ "version_minor": 0
181
+ },
182
+ "text/plain": [
183
+ "Dropdown(description='Model:', index=1, options=('tiny-llama-1b', 'phi-2', 'dolly-v2-3b', 'red-pajama-instruct…"
184
+ ]
185
+ },
186
+ "execution_count": 3,
187
+ "metadata": {},
188
+ "output_type": "execute_result"
189
+ }
190
+ ],
191
+ "source": [
192
+ "model_ids = list(SUPPORTED_LLM_MODELS)\n",
193
+ "\n",
194
+ "model_id = widgets.Dropdown(\n",
195
+ " options=model_ids,\n",
196
+ " value=model_ids[1],\n",
197
+ " description=\"Model:\",\n",
198
+ " disabled=False,\n",
199
+ ")\n",
200
+ "\n",
201
+ "model_id"
202
+ ]
203
+ },
204
+ {
205
+ "cell_type": "code",
206
+ "execution_count": 4,
207
+ "id": "37e9634f-4fc7-4d9c-9ade-b3e8684a0828",
208
+ "metadata": {},
209
+ "outputs": [
210
+ {
211
+ "name": "stdout",
212
+ "output_type": "stream",
213
+ "text": [
214
+ "Selected model phi-2\n"
215
+ ]
216
+ }
217
+ ],
218
+ "source": [
219
+ "model_configuration = SUPPORTED_LLM_MODELS[model_id.value]\n",
220
+ "print(f\"Selected model {model_id.value}\")"
221
+ ]
222
+ },
223
+ {
224
+ "cell_type": "code",
225
+ "execution_count": 5,
226
+ "id": "7937959a-d2a1-49bd-bf12-35554fa901d1",
227
+ "metadata": {},
228
+ "outputs": [
229
+ {
230
+ "data": {
231
+ "text/plain": [
232
+ "{'model_id': 'susnato/phi-2',\n",
233
+ " 'prompt_template': 'Instruct:{instruction}\\nOutput:'}"
234
+ ]
235
+ },
236
+ "execution_count": 5,
237
+ "metadata": {},
238
+ "output_type": "execute_result"
239
+ }
240
+ ],
241
+ "source": [
242
+ "model_configuration = SUPPORTED_LLM_MODELS[model_id.value]\n",
243
+ "model_configuration"
244
+ ]
245
+ },
246
+ {
247
+ "cell_type": "markdown",
248
+ "id": "4e4fd394-b4fb-4eef-8bdc-d116572aa8f0",
249
+ "metadata": {},
250
+ "source": [
251
+ "## Instantiate Model using Optimum Intel\n",
252
+ "[back to top ⬆️](#Table-of-contents:)\n",
253
+ "\n",
254
+ "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",
255
+ "\n",
256
+ "Below is an example of the RedPajama model\n",
257
+ "\n",
258
+ "```diff\n",
259
+ "-from transformers import AutoModelForCausalLM\n",
260
+ "+from optimum.intel.openvino import OVModelForCausalLM\n",
261
+ "from transformers import AutoTokenizer, pipeline\n",
262
+ "\n",
263
+ "model_id = \"togethercomputer/RedPajama-INCITE-Chat-3B-v1\"\n",
264
+ "-model = AutoModelForCausalLM.from_pretrained(model_id)\n",
265
+ "+model = OVModelForCausalLM.from_pretrained(model_id, export=True)\n",
266
+ "```\n",
267
+ "\n",
268
+ "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",
269
+ "Tokenizer class and pipelines API are compatible with Optimum models.\n",
270
+ "\n",
271
+ "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",
272
+ "\n",
273
+ "## Compress model weights\n",
274
+ "[back to top ⬆️](#Table-of-contents:)\n",
275
+ "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",
276
+ "\n",
277
+ "\n",
278
+ "### Weights Compression using Optimum Intel\n",
279
+ "[back to top ⬆️](#Table-of-contents:)\n",
280
+ "\n",
281
+ "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",
282
+ "\n",
283
+ "### Weights Compression using NNCF\n",
284
+ "[back to top ⬆️](#Table-of-contents:)\n",
285
+ "\n",
286
+ "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",
287
+ "\n",
288
+ "\n",
289
+ ">**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",
290
+ ">**Note**: There may be no speedup for INT4/INT8 compressed models on dGPU"
291
+ ]
292
+ },
293
+ {
294
+ "cell_type": "code",
295
+ "execution_count": 6,
296
+ "id": "f81602ca-4674-4b61-b2c8-ca11631428b1",
297
+ "metadata": {},
298
+ "outputs": [
299
+ {
300
+ "data": {
301
+ "application/vnd.jupyter.widget-view+json": {
302
+ "model_id": "03c417061a1845e9bceb4e40078ffc67",
303
+ "version_major": 2,
304
+ "version_minor": 0
305
+ },
306
+ "text/plain": [
307
+ "Checkbox(value=True, description='Prepare INT4 model')"
308
+ ]
309
+ },
310
+ "metadata": {},
311
+ "output_type": "display_data"
312
+ },
313
+ {
314
+ "data": {
315
+ "application/vnd.jupyter.widget-view+json": {
316
+ "model_id": "6dac25b3d6824cfebae7f076cefaac98",
317
+ "version_major": 2,
318
+ "version_minor": 0
319
+ },
320
+ "text/plain": [
321
+ "Checkbox(value=False, description='Prepare INT8 model')"
322
+ ]
323
+ },
324
+ "metadata": {},
325
+ "output_type": "display_data"
326
+ },
327
+ {
328
+ "data": {
329
+ "application/vnd.jupyter.widget-view+json": {
330
+ "model_id": "4fac7143c54545c4944f3dc4d83a8a71",
331
+ "version_major": 2,
332
+ "version_minor": 0
333
+ },
334
+ "text/plain": [
335
+ "Checkbox(value=False, description='Prepare FP16 model')"
336
+ ]
337
+ },
338
+ "metadata": {},
339
+ "output_type": "display_data"
340
+ }
341
+ ],
342
+ "source": [
343
+ "from IPython.display import display\n",
344
+ "\n",
345
+ "prepare_int4_model = widgets.Checkbox(\n",
346
+ " value=True,\n",
347
+ " description=\"Prepare INT4 model\",\n",
348
+ " disabled=False,\n",
349
+ ")\n",
350
+ "prepare_int8_model = widgets.Checkbox(\n",
351
+ " value=False,\n",
352
+ " description=\"Prepare INT8 model\",\n",
353
+ " disabled=False,\n",
354
+ ")\n",
355
+ "prepare_fp16_model = widgets.Checkbox(\n",
356
+ " value=False,\n",
357
+ " description=\"Prepare FP16 model\",\n",
358
+ " disabled=False,\n",
359
+ ")\n",
360
+ "\n",
361
+ "display(prepare_int4_model)\n",
362
+ "display(prepare_int8_model)\n",
363
+ "display(prepare_fp16_model)"
364
+ ]
365
+ },
366
+ {
367
+ "cell_type": "code",
368
+ "execution_count": 7,
369
+ "id": "0066fbec-b89b-4caa-94fb-9ea8598c22e0",
370
+ "metadata": {
371
+ "scrolled": true
372
+ },
373
+ "outputs": [
374
+ {
375
+ "name": "stdout",
376
+ "output_type": "stream",
377
+ "text": [
378
+ "INFO:nncf:NNCF initialized successfully. Supported frameworks detected: torch, tensorflow, onnx, openvino\n"
379
+ ]
380
+ },
381
+ {
382
+ "name": "stderr",
383
+ "output_type": "stream",
384
+ "text": [
385
+ "Framework not specified. Using pt to export the model.\n"
386
+ ]
387
+ },
388
+ {
389
+ "data": {
390
+ "application/vnd.jupyter.widget-view+json": {
391
+ "model_id": "ac0d64ad764b4edf96d653f7634b3be6",
392
+ "version_major": 2,
393
+ "version_minor": 0
394
+ },
395
+ "text/plain": [
396
+ "Loading checkpoint shards: 0%| | 0/2 [00:00<?, ?it/s]"
397
+ ]
398
+ },
399
+ "metadata": {},
400
+ "output_type": "display_data"
401
+ },
402
+ {
403
+ "name": "stderr",
404
+ "output_type": "stream",
405
+ "text": [
406
+ "Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\n",
407
+ "Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\n",
408
+ "Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\n",
409
+ "Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\n",
410
+ "Using framework PyTorch: 2.3.1+cpu\n",
411
+ "Overriding 1 configuration item(s)\n",
412
+ "\t- use_cache -> True\n",
413
+ "C:\\Users\\KIIT\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\transformers\\modeling_attn_mask_utils.py:114: TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!\n",
414
+ " if (input_shape[-1] > 1 or self.sliding_window is not None) and self.is_causal:\n",
415
+ "C:\\Users\\KIIT\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\optimum\\exporters\\onnx\\model_patcher.py:303: TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!\n",
416
+ " if past_key_values_length > 0:\n",
417
+ "C:\\Users\\KIIT\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\transformers\\models\\phi\\modeling_phi.py:107: TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!\n",
418
+ " if seq_len > self.max_seq_len_cached:\n"
419
+ ]
420
+ },
421
+ {
422
+ "data": {
423
+ "application/vnd.jupyter.widget-view+json": {
424
+ "model_id": "057d63d7db3943f7b0549182c24e97fe",
425
+ "version_major": 2,
426
+ "version_minor": 0
427
+ },
428
+ "text/plain": [
429
+ "Output()"
430
+ ]
431
+ },
432
+ "metadata": {},
433
+ "output_type": "display_data"
434
+ },
435
+ {
436
+ "data": {
437
+ "text/html": [
438
+ "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>\n"
439
+ ],
440
+ "text/plain": []
441
+ },
442
+ "metadata": {},
443
+ "output_type": "display_data"
444
+ },
445
+ {
446
+ "data": {
447
+ "text/html": [
448
+ "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">\n",
449
+ "</pre>\n"
450
+ ],
451
+ "text/plain": [
452
+ "\n"
453
+ ]
454
+ },
455
+ "metadata": {},
456
+ "output_type": "display_data"
457
+ },
458
+ {
459
+ "name": "stderr",
460
+ "output_type": "stream",
461
+ "text": [
462
+ "Configuration saved in phi-2\\INT8_compressed_weights\\openvino_config.json\n"
463
+ ]
464
+ }
465
+ ],
466
+ "source": [
467
+ "from pathlib import Path\n",
468
+ "import logging\n",
469
+ "import openvino as ov\n",
470
+ "import nncf\n",
471
+ "from optimum.intel.openvino import OVModelForCausalLM, OVWeightQuantizationConfig\n",
472
+ "import gc\n",
473
+ "\n",
474
+ "\n",
475
+ "nncf.set_log_level(logging.ERROR)\n",
476
+ "\n",
477
+ "pt_model_id = model_configuration[\"model_id\"]\n",
478
+ "fp16_model_dir = Path(model_id.value) / \"FP16\"\n",
479
+ "int8_model_dir = Path(model_id.value) / \"INT8_compressed_weights\"\n",
480
+ "int4_model_dir = Path(model_id.value) / \"INT4_compressed_weights\"\n",
481
+ "\n",
482
+ "core = ov.Core()\n",
483
+ "\n",
484
+ "\n",
485
+ "def convert_to_fp16():\n",
486
+ " if (fp16_model_dir / \"openvino_model.xml\").exists():\n",
487
+ " return\n",
488
+ " ov_model = OVModelForCausalLM.from_pretrained(pt_model_id, export=True, compile=False, load_in_8bit=False)\n",
489
+ " ov_model.half()\n",
490
+ " ov_model.save_pretrained(fp16_model_dir)\n",
491
+ " del ov_model\n",
492
+ " gc.collect()\n",
493
+ "\n",
494
+ "\n",
495
+ "def convert_to_int8():\n",
496
+ " if (int8_model_dir / \"openvino_model.xml\").exists():\n",
497
+ " return\n",
498
+ " ov_model = OVModelForCausalLM.from_pretrained(pt_model_id, export=True, compile=False, load_in_8bit=True)\n",
499
+ " ov_model.save_pretrained(int8_model_dir)\n",
500
+ " del ov_model\n",
501
+ " gc.collect()\n",
502
+ "\n",
503
+ "\n",
504
+ "def convert_to_int4():\n",
505
+ " compression_configs = {\n",
506
+ " \"mistral-7b\": {\n",
507
+ " \"sym\": True,\n",
508
+ " \"group_size\": 64,\n",
509
+ " \"ratio\": 0.6,\n",
510
+ " },\n",
511
+ " \"red-pajama-3b-instruct\": {\n",
512
+ " \"sym\": False,\n",
513
+ " \"group_size\": 128,\n",
514
+ " \"ratio\": 0.5,\n",
515
+ " },\n",
516
+ " \"dolly-v2-3b\": {\"sym\": False, \"group_size\": 32, \"ratio\": 0.5},\n",
517
+ " \"llama-3-8b-instruct\": {\"sym\": True, \"group_size\": 128, \"ratio\": 1.0},\n",
518
+ " \"default\": {\n",
519
+ " \"sym\": False,\n",
520
+ " \"group_size\": 128,\n",
521
+ " \"ratio\": 0.8,\n",
522
+ " },\n",
523
+ " }\n",
524
+ "\n",
525
+ " model_compression_params = compression_configs.get(model_id.value, compression_configs[\"default\"])\n",
526
+ " if (int4_model_dir / \"openvino_model.xml\").exists():\n",
527
+ " return\n",
528
+ " ov_model = OVModelForCausalLM.from_pretrained(\n",
529
+ " pt_model_id,\n",
530
+ " export=True,\n",
531
+ " compile=False,\n",
532
+ " quantization_config=OVWeightQuantizationConfig(bits=4, **model_compression_params),\n",
533
+ " )\n",
534
+ " ov_model.save_pretrained(int4_model_dir)\n",
535
+ " del ov_model\n",
536
+ " gc.collect()\n",
537
+ "\n",
538
+ "\n",
539
+ "if prepare_fp16_model.value:\n",
540
+ " convert_to_fp16()\n",
541
+ "if prepare_int8_model.value:\n",
542
+ " convert_to_int8()\n",
543
+ "if prepare_int4_model.value:\n",
544
+ " convert_to_int4()"
545
+ ]
546
+ },
547
+ {
548
+ "cell_type": "code",
549
+ "execution_count": null,
550
+ "id": "b5f31838-c7d6-4f52-aa2d-1f29c6f3b397",
551
+ "metadata": {},
552
+ "outputs": [],
553
+ "source": []
554
+ },
555
+ {
556
+ "cell_type": "markdown",
557
+ "id": "60355f86-2250-4ebe-82ac-950f2d4fb01b",
558
+ "metadata": {},
559
+ "source": [
560
+ "Let's compare model size for different compression types"
561
+ ]
562
+ },
563
+ {
564
+ "cell_type": "code",
565
+ "execution_count": 8,
566
+ "id": "42c7b254-1ce4-4f23-813a-9bdc23aed327",
567
+ "metadata": {},
568
+ "outputs": [
569
+ {
570
+ "name": "stdout",
571
+ "output_type": "stream",
572
+ "text": [
573
+ "Size of model with INT8 compressed weights is 2656.55 MB\n",
574
+ "Size of model with INT4 compressed weights is 1739.13 MB\n"
575
+ ]
576
+ }
577
+ ],
578
+ "source": [
579
+ "fp16_weights = fp16_model_dir / \"openvino_model.bin\"\n",
580
+ "int8_weights = int8_model_dir / \"openvino_model.bin\"\n",
581
+ "int4_weights = int4_model_dir / \"openvino_model.bin\"\n",
582
+ "\n",
583
+ "if fp16_weights.exists():\n",
584
+ " print(f\"Size of FP16 model is {fp16_weights.stat().st_size / 1024 / 1024:.2f} MB\")\n",
585
+ "for precision, compressed_weights in zip([8, 4], [int8_weights, int4_weights]):\n",
586
+ " if compressed_weights.exists():\n",
587
+ " print(f\"Size of model with INT{precision} compressed weights is {compressed_weights.stat().st_size / 1024 / 1024:.2f} MB\")\n",
588
+ " if compressed_weights.exists() and fp16_weights.exists():\n",
589
+ " print(f\"Compression rate for INT{precision} model: {fp16_weights.stat().st_size / compressed_weights.stat().st_size:.3f}\")"
590
+ ]
591
+ },
592
+ {
593
+ "cell_type": "markdown",
594
+ "id": "3df73379-bccc-41b1-9c94-c3040819805b",
595
+ "metadata": {},
596
+ "source": [
597
+ "## Select device for inference and model variant\n",
598
+ "[back to top ⬆️](#Table-of-contents:)\n",
599
+ "\n",
600
+ ">**Note**: There may be no speedup for INT4/INT8 compressed models on dGPU."
601
+ ]
602
+ },
603
+ {
604
+ "cell_type": "code",
605
+ "execution_count": 9,
606
+ "id": "d2d7bf5b-8a05-4c3b-a36b-631af5c197e9",
607
+ "metadata": {},
608
+ "outputs": [
609
+ {
610
+ "data": {
611
+ "application/vnd.jupyter.widget-view+json": {
612
+ "model_id": "49fc667dcf434c9f80db2d130b45212b",
613
+ "version_major": 2,
614
+ "version_minor": 0
615
+ },
616
+ "text/plain": [
617
+ "Dropdown(description='Device:', options=('CPU', 'GPU', 'AUTO'), value='CPU')"
618
+ ]
619
+ },
620
+ "execution_count": 9,
621
+ "metadata": {},
622
+ "output_type": "execute_result"
623
+ }
624
+ ],
625
+ "source": [
626
+ "core = ov.Core()\n",
627
+ "\n",
628
+ "support_devices = core.available_devices\n",
629
+ "if \"NPU\" in support_devices:\n",
630
+ " support_devices.remove(\"NPU\")\n",
631
+ "\n",
632
+ "device = widgets.Dropdown(\n",
633
+ " options=support_devices + [\"AUTO\"],\n",
634
+ " value=\"CPU\",\n",
635
+ " description=\"Device:\",\n",
636
+ " disabled=False,\n",
637
+ ")\n",
638
+ "\n",
639
+ "device"
640
+ ]
641
+ },
642
+ {
643
+ "cell_type": "code",
644
+ "execution_count": 10,
645
+ "id": "01673d97-6645-4d2a-8306-293b8064b317",
646
+ "metadata": {},
647
+ "outputs": [
648
+ {
649
+ "data": {
650
+ "application/vnd.jupyter.widget-view+json": {
651
+ "model_id": "49fc667dcf434c9f80db2d130b45212b",
652
+ "version_major": 2,
653
+ "version_minor": 0
654
+ },
655
+ "text/plain": [
656
+ "Dropdown(description='Device:', options=('CPU', 'GPU', 'AUTO'), value='CPU')"
657
+ ]
658
+ },
659
+ "execution_count": 10,
660
+ "metadata": {},
661
+ "output_type": "execute_result"
662
+ }
663
+ ],
664
+ "source": [
665
+ "device"
666
+ ]
667
+ },
668
+ {
669
+ "cell_type": "code",
670
+ "execution_count": 11,
671
+ "id": "24532480-80a5-4953-9cd6-78ac51a1cd8f",
672
+ "metadata": {},
673
+ "outputs": [
674
+ {
675
+ "data": {
676
+ "application/vnd.jupyter.widget-view+json": {
677
+ "model_id": "58cde7d954a748baa50af1f82626c883",
678
+ "version_major": 2,
679
+ "version_minor": 0
680
+ },
681
+ "text/plain": [
682
+ "Dropdown(description='Model to run:', options=('INT4', 'INT8'), value='INT4')"
683
+ ]
684
+ },
685
+ "execution_count": 11,
686
+ "metadata": {},
687
+ "output_type": "execute_result"
688
+ }
689
+ ],
690
+ "source": [
691
+ "available_models = []\n",
692
+ "if int4_model_dir.exists():\n",
693
+ " available_models.append(\"INT4\")\n",
694
+ "if int8_model_dir.exists():\n",
695
+ " available_models.append(\"INT8\")\n",
696
+ "if fp16_model_dir.exists():\n",
697
+ " available_models.append(\"FP16\")\n",
698
+ "\n",
699
+ "model_to_run = widgets.Dropdown(\n",
700
+ " options=available_models,\n",
701
+ " value=available_models[0],\n",
702
+ " description=\"Model to run:\",\n",
703
+ " disabled=False,\n",
704
+ ")\n",
705
+ "\n",
706
+ "model_to_run"
707
+ ]
708
+ },
709
+ {
710
+ "cell_type": "code",
711
+ "execution_count": 18,
712
+ "id": "5259c1c5-4128-4210-9ad2-faf33ee40e86",
713
+ "metadata": {},
714
+ "outputs": [
715
+ {
716
+ "name": "stdout",
717
+ "output_type": "stream",
718
+ "text": [
719
+ "Loading model from phi-2\\INT8_compressed_weights\n",
720
+ "susnato/phi-2\n"
721
+ ]
722
+ },
723
+ {
724
+ "name": "stderr",
725
+ "output_type": "stream",
726
+ "text": [
727
+ "Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\n",
728
+ "Compiling the model to CPU ...\n"
729
+ ]
730
+ }
731
+ ],
732
+ "source": [
733
+ "from transformers import AutoTokenizer\n",
734
+ "\n",
735
+ "if model_to_run.value == \"INT4\":\n",
736
+ " model_dir = int4_model_dir\n",
737
+ "elif model_to_run.value == \"INT8\":\n",
738
+ " model_dir = int8_model_dir\n",
739
+ "else:\n",
740
+ " model_dir = fp16_model_dir\n",
741
+ "print(f\"Loading model from {model_dir}\")\n",
742
+ "\n",
743
+ "model_name = model_configuration[\"model_id\"]\n",
744
+ "print(model_name)\n",
745
+ "ov_config = {\"PERFORMANCE_HINT\": \"LATENCY\", \"NUM_STREAMS\": \"1\", \"CACHE_DIR\": \"\"}\n",
746
+ "\n",
747
+ "tok = AutoTokenizer.from_pretrained(model_name)\n",
748
+ "\n",
749
+ "ov_model = OVModelForCausalLM.from_pretrained(\n",
750
+ " model_dir,\n",
751
+ " device=device.value,\n",
752
+ " ov_config=ov_config,\n",
753
+ ")"
754
+ ]
755
+ },
756
+ {
757
+ "cell_type": "markdown",
758
+ "id": "bf13f6c3-6671-408e-ae0e-aaa3d8a6eaac",
759
+ "metadata": {},
760
+ "source": [
761
+ "## Create an instruction-following inference pipeline\n",
762
+ "[back to top ⬆️](#Table-of-contents:)\n",
763
+ " \n",
764
+ " 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",
765
+ " \n",
766
+ "The diagram below illustrates how the instruction-following pipeline works\n",
767
+ "\n",
768
+ "![generation pipeline)](https://github.com/openvinotoolkit/openvino_notebooks/assets/29454499/e881f4a4-fcc8-427a-afe1-7dd80aebd66e)\n",
769
+ "\n",
770
+ "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",
771
+ "\n",
772
+ "There are several parameters that can control text generation quality:\n",
773
+ "\n",
774
+ " * `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",
775
+ " Consider the following example: The AI model has to complete the sentence \"The cat is ____.\" with the following token probabilities: \n",
776
+ "\n",
777
+ " playing: 0.5 \n",
778
+ " sleeping: 0.25 \n",
779
+ " eating: 0.15 \n",
780
+ " driving: 0.05 \n",
781
+ " flying: 0.05 \n",
782
+ "\n",
783
+ " - **Low temperature** (e.g., 0.2): The AI model becomes more focused and deterministic, choosing tokens with the highest probability, such as \"playing.\" \n",
784
+ " - **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",
785
+ " - **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",
786
+ " * `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",
787
+ " Using the same example with the cat, consider the following top_p settings: \n",
788
+ " - **Low top_p** (e.g., 0.5): The AI model considers only tokens with the highest cumulative probability, such as \"playing.\" \n",
789
+ " - **Medium top_p** (e.g., 0.8): The AI model considers tokens with a higher cumulative probability, such as \"playing,\" \"sleeping,\" and \"eating.\" \n",
790
+ " - **High top_p** (e.g., 1.0): The AI model considers all tokens, including those with lower probabilities, such as \"driving\" and \"flying.\" \n",
791
+ " * `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",
792
+ "\n",
793
+ "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",
794
+ "\n",
795
+ "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."
796
+ ]
797
+ },
798
+ {
799
+ "cell_type": "markdown",
800
+ "id": "eb7af692-0a15-4493-86ef-a80cda21551c",
801
+ "metadata": {},
802
+ "source": [
803
+ "### Setup imports\n",
804
+ "[back to top ⬆️](#Table-of-contents:)\n"
805
+ ]
806
+ },
807
+ {
808
+ "cell_type": "code",
809
+ "execution_count": 19,
810
+ "id": "19d23a99-3284-42db-b7dc-5805d219f70d",
811
+ "metadata": {},
812
+ "outputs": [],
813
+ "source": [
814
+ "from threading import Thread\n",
815
+ "from time import perf_counter\n",
816
+ "from typing import List\n",
817
+ "import gradio as gr\n",
818
+ "from transformers import AutoTokenizer, TextIteratorStreamer\n",
819
+ "import numpy as np"
820
+ ]
821
+ },
822
+ {
823
+ "cell_type": "markdown",
824
+ "id": "b341a9e6-290d-4780-90da-1ee64cee436d",
825
+ "metadata": {},
826
+ "source": [
827
+ "### Prepare template for user prompt\n",
828
+ "[back to top ⬆️](#Table-of-contents:)\n",
829
+ "\n",
830
+ "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."
831
+ ]
832
+ },
833
+ {
834
+ "cell_type": "code",
835
+ "execution_count": 20,
836
+ "id": "e2638c5b-47ad-4213-80da-8cfc2659b3aa",
837
+ "metadata": {},
838
+ "outputs": [
839
+ {
840
+ "name": "stderr",
841
+ "output_type": "stream",
842
+ "text": [
843
+ "Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\n"
844
+ ]
845
+ }
846
+ ],
847
+ "source": [
848
+ "tokenizer = AutoTokenizer.from_pretrained(model_name)\n",
849
+ "tokenizer_kwargs = model_configuration.get(\"toeknizer_kwargs\", {})\n",
850
+ "\n",
851
+ "\n",
852
+ "def get_special_token_id(tokenizer: AutoTokenizer, key: str) -> int:\n",
853
+ " \"\"\"\n",
854
+ " Gets the token ID for a given string that has been added to the tokenizer as a special token.\n",
855
+ "\n",
856
+ " Args:\n",
857
+ " tokenizer (PreTrainedTokenizer): the tokenizer\n",
858
+ " key (str): the key to convert to a single token\n",
859
+ "\n",
860
+ " Raises:\n",
861
+ " RuntimeError: if more than one ID was generated\n",
862
+ "\n",
863
+ " Returns:\n",
864
+ " int: the token ID for the given key\n",
865
+ " \"\"\"\n",
866
+ " token_ids = tokenizer.encode(key)\n",
867
+ " if len(token_ids) > 1:\n",
868
+ " raise ValueError(f\"Expected only a single token for '{key}' but found {token_ids}\")\n",
869
+ " return token_ids[0]\n",
870
+ "\n",
871
+ "\n",
872
+ "response_key = model_configuration.get(\"response_key\")\n",
873
+ "tokenizer_response_key = None\n",
874
+ "\n",
875
+ "if response_key is not None:\n",
876
+ " tokenizer_response_key = next(\n",
877
+ " (token for token in tokenizer.additional_special_tokens if token.startswith(response_key)),\n",
878
+ " None,\n",
879
+ " )\n",
880
+ "\n",
881
+ "end_key_token_id = None\n",
882
+ "if tokenizer_response_key:\n",
883
+ " try:\n",
884
+ " end_key = model_configuration.get(\"end_key\")\n",
885
+ " if end_key:\n",
886
+ " end_key_token_id = get_special_token_id(tokenizer, end_key)\n",
887
+ " # Ensure generation stops once it generates \"### End\"\n",
888
+ " except ValueError:\n",
889
+ " pass\n",
890
+ "\n",
891
+ "prompt_template = model_configuration.get(\"prompt_template\", \"{instruction}\")\n",
892
+ "end_key_token_id = end_key_token_id or tokenizer.eos_token_id\n",
893
+ "pad_token_id = end_key_token_id or tokenizer.pad_token_id"
894
+ ]
895
+ },
896
+ {
897
+ "cell_type": "markdown",
898
+ "id": "55dbc4ae-da28-4be8-b928-3dd68c197937",
899
+ "metadata": {},
900
+ "source": [
901
+ "### Main generation function\n",
902
+ "[back to top ⬆️](#Table-of-contents:)\n",
903
+ "\n",
904
+ "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."
905
+ ]
906
+ },
907
+ {
908
+ "cell_type": "code",
909
+ "execution_count": 21,
910
+ "id": "27802e81-9d42-4d71-99ea-5f76db5237f1",
911
+ "metadata": {},
912
+ "outputs": [],
913
+ "source": [
914
+ "def run_generation(\n",
915
+ " user_text: str,\n",
916
+ " top_p: float,\n",
917
+ " temperature: float,\n",
918
+ " top_k: int,\n",
919
+ " max_new_tokens: int,\n",
920
+ " perf_text: str,\n",
921
+ "):\n",
922
+ " \"\"\"\n",
923
+ " Text generation function\n",
924
+ "\n",
925
+ " Parameters:\n",
926
+ " user_text (str): User-provided instruction for a generation.\n",
927
+ " 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",
928
+ " temperature (float): The value used to module the logits distribution.\n",
929
+ " top_k (int): The number of highest probability vocabulary tokens to keep for top-k-filtering.\n",
930
+ " max_new_tokens (int): Maximum length of generated sequence.\n",
931
+ " perf_text (str): Content of text field for printing performance results.\n",
932
+ " Returns:\n",
933
+ " model_output (str) - model-generated text\n",
934
+ " perf_text (str) - updated perf text filed content\n",
935
+ " \"\"\"\n",
936
+ "\n",
937
+ " # Prepare input prompt according to model expected template\n",
938
+ " prompt_text = prompt_template.format(instruction=user_text)\n",
939
+ "\n",
940
+ " # Tokenize the user text.\n",
941
+ " model_inputs = tokenizer(prompt_text, return_tensors=\"pt\", **tokenizer_kwargs)\n",
942
+ "\n",
943
+ " # Start generation on a separate thread, so that we don't block the UI. The text is pulled from the streamer\n",
944
+ " # in the main thread. Adds timeout to the streamer to handle exceptions in the generation thread.\n",
945
+ " streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)\n",
946
+ " generate_kwargs = dict(\n",
947
+ " model_inputs,\n",
948
+ " streamer=streamer,\n",
949
+ " max_new_tokens=max_new_tokens,\n",
950
+ " do_sample=True,\n",
951
+ " top_p=top_p,\n",
952
+ " temperature=float(temperature),\n",
953
+ " top_k=top_k,\n",
954
+ " eos_token_id=end_key_token_id,\n",
955
+ " pad_token_id=pad_token_id,\n",
956
+ " )\n",
957
+ " t = Thread(target=ov_model.generate, kwargs=generate_kwargs)\n",
958
+ " t.start()\n",
959
+ "\n",
960
+ " # Pull the generated text from the streamer, and update the model output.\n",
961
+ " model_output = \"\"\n",
962
+ " per_token_time = []\n",
963
+ " num_tokens = 0\n",
964
+ " start = perf_counter()\n",
965
+ " for new_text in streamer:\n",
966
+ " current_time = perf_counter() - start\n",
967
+ " model_output += new_text\n",
968
+ " perf_text, num_tokens = estimate_latency(current_time, perf_text, new_text, per_token_time, num_tokens)\n",
969
+ " yield model_output, perf_text\n",
970
+ " start = perf_counter()\n",
971
+ " return model_output, perf_text"
972
+ ]
973
+ },
974
+ {
975
+ "cell_type": "markdown",
976
+ "id": "6d7b7182-1d9b-485b-81f2-1a9fab6d5cd4",
977
+ "metadata": {},
978
+ "source": [
979
+ "### Helpers for application\n",
980
+ "[back to top ⬆️](#Table-of-contents:)\n",
981
+ "\n",
982
+ "For making interactive user interface we will use Gradio library. The code bellow provides useful functions used for communication with UI elements."
983
+ ]
984
+ },
985
+ {
986
+ "cell_type": "code",
987
+ "execution_count": 22,
988
+ "id": "c9b2a2b7-5a91-470f-98d7-7355664bc1be",
989
+ "metadata": {},
990
+ "outputs": [],
991
+ "source": [
992
+ "def estimate_latency(\n",
993
+ " current_time: float,\n",
994
+ " current_perf_text: str,\n",
995
+ " new_gen_text: str,\n",
996
+ " per_token_time: List[float],\n",
997
+ " num_tokens: int,\n",
998
+ "):\n",
999
+ " \"\"\"\n",
1000
+ " Helper function for performance estimation\n",
1001
+ "\n",
1002
+ " Parameters:\n",
1003
+ " current_time (float): This step time in seconds.\n",
1004
+ " current_perf_text (str): Current content of performance UI field.\n",
1005
+ " new_gen_text (str): New generated text.\n",
1006
+ " per_token_time (List[float]): history of performance from previous steps.\n",
1007
+ " num_tokens (int): Total number of generated tokens.\n",
1008
+ "\n",
1009
+ " Returns:\n",
1010
+ " update for performance text field\n",
1011
+ " update for a total number of tokens\n",
1012
+ " \"\"\"\n",
1013
+ " num_current_toks = len(tokenizer.encode(new_gen_text))\n",
1014
+ " num_tokens += num_current_toks\n",
1015
+ " per_token_time.append(num_current_toks / current_time)\n",
1016
+ " if len(per_token_time) > 10 and len(per_token_time) % 4 == 0:\n",
1017
+ " current_bucket = per_token_time[:-10]\n",
1018
+ " return (\n",
1019
+ " f\"Average generation speed: {np.mean(current_bucket):.2f} tokens/s. Total generated tokens: {num_tokens}\",\n",
1020
+ " num_tokens,\n",
1021
+ " )\n",
1022
+ " return current_perf_text, num_tokens\n",
1023
+ "\n",
1024
+ "\n",
1025
+ "def reset_textbox(instruction: str, response: str, perf: str):\n",
1026
+ " \"\"\"\n",
1027
+ " Helper function for resetting content of all text fields\n",
1028
+ "\n",
1029
+ " Parameters:\n",
1030
+ " instruction (str): Content of user instruction field.\n",
1031
+ " response (str): Content of model response field.\n",
1032
+ " perf (str): Content of performance info filed\n",
1033
+ "\n",
1034
+ " Returns:\n",
1035
+ " empty string for each placeholder\n",
1036
+ " \"\"\"\n",
1037
+ " return \"\", \"\", \"\""
1038
+ ]
1039
+ },
1040
+ {
1041
+ "cell_type": "markdown",
1042
+ "id": "31ebb167-0e55-4271-aedd-13814c2356d2",
1043
+ "metadata": {},
1044
+ "source": [
1045
+ "## Run instruction-following pipeline\n",
1046
+ "[back to top ⬆️](#Table-of-contents:)\n",
1047
+ "\n",
1048
+ "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",
1049
+ "\n",
1050
+ "* `Device` - allows switching inference device. Please note, every time when new device is selected, model will be recompiled and this takes some time.\n",
1051
+ "* `Max New Tokens` - maximum size of generated text.\n",
1052
+ "* `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",
1053
+ "* `Top-k` - the number of highest probability vocabulary tokens to keep for top-k-filtering.\n",
1054
+ "* `Temperature` - the value used to module the logits distribution."
1055
+ ]
1056
+ },
1057
+ {
1058
+ "cell_type": "code",
1059
+ "execution_count": 23,
1060
+ "id": "9f222d02-847a-490f-8d66-02608a53259b",
1061
+ "metadata": {},
1062
+ "outputs": [
1063
+ {
1064
+ "name": "stdout",
1065
+ "output_type": "stream",
1066
+ "text": [
1067
+ "Running on local URL: http://127.0.0.1:7861\n",
1068
+ "\n",
1069
+ "To create a public link, set `share=True` in `launch()`.\n"
1070
+ ]
1071
+ },
1072
+ {
1073
+ "data": {
1074
+ "text/html": [
1075
+ "<div><iframe src=\"http://127.0.0.1:7861/\" width=\"100%\" height=\"800\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
1076
+ ],
1077
+ "text/plain": [
1078
+ "<IPython.core.display.HTML object>"
1079
+ ]
1080
+ },
1081
+ "metadata": {},
1082
+ "output_type": "display_data"
1083
+ }
1084
+ ],
1085
+ "source": [
1086
+ "examples = [\n",
1087
+ " \"Give me a recipe for pizza with pineapple\",\n",
1088
+ " \"Write me a tweet about the new OpenVINO release\",\n",
1089
+ " \"Explain the difference between CPU and GPU\",\n",
1090
+ " \"Give five ideas for a great weekend with family\",\n",
1091
+ " \"Do Androids dream of Electric sheep?\",\n",
1092
+ " \"Who is Dolly?\",\n",
1093
+ " \"Please give me advice on how to write resume?\",\n",
1094
+ " \"Name 3 advantages to being a cat\",\n",
1095
+ " \"Write instructions on how to become a good AI engineer\",\n",
1096
+ " \"Write a love letter to my best friend\",\n",
1097
+ "]\n",
1098
+ "\n",
1099
+ "\n",
1100
+ "with gr.Blocks() as demo:\n",
1101
+ " gr.Markdown(\n",
1102
+ " \"# Question Answering with \" + model_id.value + \" and OpenVINO.\\n\"\n",
1103
+ " \"Provide instruction which describes a task below or select among predefined examples and model writes response that performs requested task.\"\n",
1104
+ " )\n",
1105
+ "\n",
1106
+ " with gr.Row():\n",
1107
+ " with gr.Column(scale=4):\n",
1108
+ " user_text = gr.Textbox(\n",
1109
+ " placeholder=\"Write an email about an alpaca that likes flan\",\n",
1110
+ " label=\"User instruction\",\n",
1111
+ " )\n",
1112
+ " model_output = gr.Textbox(label=\"Model response\", interactive=False)\n",
1113
+ " performance = gr.Textbox(label=\"Performance\", lines=1, interactive=False)\n",
1114
+ " with gr.Column(scale=1):\n",
1115
+ " button_clear = gr.Button(value=\"Clear\")\n",
1116
+ " button_submit = gr.Button(value=\"Submit\")\n",
1117
+ " gr.Examples(examples, user_text)\n",
1118
+ " with gr.Column(scale=1):\n",
1119
+ " max_new_tokens = gr.Slider(\n",
1120
+ " minimum=1,\n",
1121
+ " maximum=1000,\n",
1122
+ " value=256,\n",
1123
+ " step=1,\n",
1124
+ " interactive=True,\n",
1125
+ " label=\"Max New Tokens\",\n",
1126
+ " )\n",
1127
+ " top_p = gr.Slider(\n",
1128
+ " minimum=0.05,\n",
1129
+ " maximum=1.0,\n",
1130
+ " value=0.92,\n",
1131
+ " step=0.05,\n",
1132
+ " interactive=True,\n",
1133
+ " label=\"Top-p (nucleus sampling)\",\n",
1134
+ " )\n",
1135
+ " top_k = gr.Slider(\n",
1136
+ " minimum=0,\n",
1137
+ " maximum=50,\n",
1138
+ " value=0,\n",
1139
+ " step=1,\n",
1140
+ " interactive=True,\n",
1141
+ " label=\"Top-k\",\n",
1142
+ " )\n",
1143
+ " temperature = gr.Slider(\n",
1144
+ " minimum=0.1,\n",
1145
+ " maximum=5.0,\n",
1146
+ " value=0.8,\n",
1147
+ " step=0.1,\n",
1148
+ " interactive=True,\n",
1149
+ " label=\"Temperature\",\n",
1150
+ " )\n",
1151
+ "\n",
1152
+ " user_text.submit(\n",
1153
+ " run_generation,\n",
1154
+ " [user_text, top_p, temperature, top_k, max_new_tokens, performance],\n",
1155
+ " [model_output, performance],\n",
1156
+ " )\n",
1157
+ " button_submit.click(\n",
1158
+ " run_generation,\n",
1159
+ " [user_text, top_p, temperature, top_k, max_new_tokens, performance],\n",
1160
+ " [model_output, performance],\n",
1161
+ " )\n",
1162
+ " button_clear.click(\n",
1163
+ " reset_textbox,\n",
1164
+ " [user_text, model_output, performance],\n",
1165
+ " [user_text, model_output, performance],\n",
1166
+ " )\n",
1167
+ "\n",
1168
+ "if __name__ == \"__main__\":\n",
1169
+ " demo.queue()\n",
1170
+ " try:\n",
1171
+ " demo.launch(height=800)\n",
1172
+ " except Exception:\n",
1173
+ " demo.launch(share=True, height=800)\n",
1174
+ "\n",
1175
+ "# If you are launching remotely, specify server_name and server_port\n",
1176
+ "# EXAMPLE: `demo.launch(server_name='your server name', server_port='server port in int')`\n",
1177
+ "# To learn more please refer to the Gradio docs: https://gradio.app/docs/"
1178
+ ]
1179
+ },
1180
+ {
1181
+ "cell_type": "code",
1182
+ "execution_count": null,
1183
+ "id": "440417f8-d2e2-4d8d-8311-882d133bb572",
1184
+ "metadata": {},
1185
+ "outputs": [],
1186
+ "source": []
1187
+ },
1188
+ {
1189
+ "cell_type": "code",
1190
+ "execution_count": null,
1191
+ "id": "dd9f90e4-0ec6-4164-8a31-044b1079d3e7",
1192
+ "metadata": {},
1193
+ "outputs": [],
1194
+ "source": []
1195
+ },
1196
+ {
1197
+ "cell_type": "code",
1198
+ "execution_count": null,
1199
+ "id": "7297ddd6-2c3d-4540-aa9b-f1c48c274a86",
1200
+ "metadata": {},
1201
+ "outputs": [],
1202
+ "source": []
1203
+ }
1204
+ ],
1205
+ "metadata": {
1206
+ "kernelspec": {
1207
+ "display_name": "openvino_env",
1208
+ "language": "python",
1209
+ "name": "openvino_env"
1210
+ },
1211
+ "language_info": {
1212
+ "codemirror_mode": {
1213
+ "name": "ipython",
1214
+ "version": 3
1215
+ },
1216
+ "file_extension": ".py",
1217
+ "mimetype": "text/x-python",
1218
+ "name": "python",
1219
+ "nbconvert_exporter": "python",
1220
+ "pygments_lexer": "ipython3",
1221
+ "version": "3.10.9"
1222
+ },
1223
+ "openvino_notebooks": {
1224
+ "imageUrl": "https://github.com/openvinotoolkit/openvino_notebooks/assets/29454499/daafd702-5a42-4f54-ae72-2e4480d73501",
1225
+ "tags": {
1226
+ "categories": [
1227
+ "Model Demos",
1228
+ "AI Trends"
1229
+ ],
1230
+ "libraries": [],
1231
+ "other": [
1232
+ "LLM"
1233
+ ],
1234
+ "tasks": [
1235
+ "Text Generation"
1236
+ ]
1237
+ }
1238
+ },
1239
+ "widgets": {
1240
+ "application/vnd.jupyter.widget-state+json": {
1241
+ "state": {},
1242
+ "version_major": 2,
1243
+ "version_minor": 0
1244
+ }
1245
+ }
1246
+ },
1247
+ "nbformat": 4,
1248
+ "nbformat_minor": 5
1249
+ }
notebook_utils.py ADDED
@@ -0,0 +1,660 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding: utf-8
3
+
4
+ # In[ ]:
5
+
6
+
7
+ import os
8
+ import threading
9
+ import time
10
+ import urllib.parse
11
+ from os import PathLike
12
+ from pathlib import Path
13
+ from typing import List, NamedTuple, Optional, Tuple
14
+
15
+ import numpy as np
16
+ from openvino.runtime import Core, Type, get_version
17
+ from IPython.display import HTML, Image, display
18
+
19
+ import openvino as ov
20
+ from openvino.runtime.passes import Manager, MatcherPass, WrapType, Matcher
21
+ from openvino.runtime import opset10 as ops
22
+
23
+
24
+ # ## Files
25
+ #
26
+ # Load an image, download a file, download an IR model, and create a progress bar to show download progress.
27
+
28
+ # In[ ]:
29
+
30
+
31
+ def load_image(path: str) -> np.ndarray:
32
+ """
33
+ Loads an image from `path` and returns it as BGR numpy array. `path`
34
+ should point to an image file, either a local filename or a url. The image is
35
+ not stored to the filesystem. Use the `download_file` function to download and
36
+ store an image.
37
+
38
+ :param path: Local path name or URL to image.
39
+ :return: image as BGR numpy array
40
+ """
41
+ import cv2
42
+ import requests
43
+
44
+ if path.startswith("http"):
45
+ # Set User-Agent to Mozilla because some websites block
46
+ # requests with User-Agent Python
47
+ response = requests.get(path, headers={"User-Agent": "Mozilla/5.0"})
48
+ array = np.asarray(bytearray(response.content), dtype="uint8")
49
+ image = cv2.imdecode(array, -1) # Loads the image as BGR
50
+ else:
51
+ image = cv2.imread(path)
52
+ return image
53
+
54
+
55
+ def download_file(
56
+ url: PathLike,
57
+ filename: PathLike = None,
58
+ directory: PathLike = None,
59
+ show_progress: bool = True,
60
+ silent: bool = False,
61
+ timeout: int = 10,
62
+ ) -> PathLike:
63
+ """
64
+ Download a file from a url and save it to the local filesystem. The file is saved to the
65
+ current directory by default, or to `directory` if specified. If a filename is not given,
66
+ the filename of the URL will be used.
67
+
68
+ :param url: URL that points to the file to download
69
+ :param filename: Name of the local file to save. Should point to the name of the file only,
70
+ not the full path. If None the filename from the url will be used
71
+ :param directory: Directory to save the file to. Will be created if it doesn't exist
72
+ If None the file will be saved to the current working directory
73
+ :param show_progress: If True, show an TQDM ProgressBar
74
+ :param silent: If True, do not print a message if the file already exists
75
+ :param timeout: Number of seconds before cancelling the connection attempt
76
+ :return: path to downloaded file
77
+ """
78
+ from tqdm.notebook import tqdm_notebook
79
+ import requests
80
+
81
+ filename = filename or Path(urllib.parse.urlparse(url).path).name
82
+ chunk_size = 16384 # make chunks bigger so that not too many updates are triggered for Jupyter front-end
83
+
84
+ filename = Path(filename)
85
+ if len(filename.parts) > 1:
86
+ raise ValueError(
87
+ "`filename` should refer to the name of the file, excluding the directory. "
88
+ "Use the `directory` parameter to specify a target directory for the downloaded file."
89
+ )
90
+
91
+ # create the directory if it does not exist, and add the directory to the filename
92
+ if directory is not None:
93
+ directory = Path(directory)
94
+ directory.mkdir(parents=True, exist_ok=True)
95
+ filename = directory / Path(filename)
96
+
97
+ try:
98
+ response = requests.get(url=url, headers={"User-agent": "Mozilla/5.0"}, stream=True)
99
+ response.raise_for_status()
100
+ except (
101
+ requests.exceptions.HTTPError
102
+ ) as error: # For error associated with not-200 codes. Will output something like: "404 Client Error: Not Found for url: {url}"
103
+ raise Exception(error) from None
104
+ except requests.exceptions.Timeout:
105
+ raise Exception(
106
+ "Connection timed out. If you access the internet through a proxy server, please "
107
+ "make sure the proxy is set in the shell from where you launched Jupyter."
108
+ ) from None
109
+ except requests.exceptions.RequestException as error:
110
+ raise Exception(f"File downloading failed with error: {error}") from None
111
+
112
+ # download the file if it does not exist, or if it exists with an incorrect file size
113
+ filesize = int(response.headers.get("Content-length", 0))
114
+ if not filename.exists() or (os.stat(filename).st_size != filesize):
115
+ with tqdm_notebook(
116
+ total=filesize,
117
+ unit="B",
118
+ unit_scale=True,
119
+ unit_divisor=1024,
120
+ desc=str(filename),
121
+ disable=not show_progress,
122
+ ) as progress_bar:
123
+ with open(filename, "wb") as file_object:
124
+ for chunk in response.iter_content(chunk_size):
125
+ file_object.write(chunk)
126
+ progress_bar.update(len(chunk))
127
+ progress_bar.refresh()
128
+ else:
129
+ if not silent:
130
+ print(f"'{filename}' already exists.")
131
+
132
+ response.close()
133
+
134
+ return filename.resolve()
135
+
136
+
137
+ def download_ir_model(model_xml_url: str, destination_folder: PathLike = None) -> PathLike:
138
+ """
139
+ Download IR model from `model_xml_url`. Downloads model xml and bin file; the weights file is
140
+ assumed to exist at the same location and name as model_xml_url with a ".bin" extension.
141
+
142
+ :param model_xml_url: URL to model xml file to download
143
+ :param destination_folder: Directory where downloaded model xml and bin are saved. If None, model
144
+ files are saved to the current directory
145
+ :return: path to downloaded xml model file
146
+ """
147
+ model_bin_url = model_xml_url[:-4] + ".bin"
148
+ model_xml_path = download_file(model_xml_url, directory=destination_folder, show_progress=False)
149
+ download_file(model_bin_url, directory=destination_folder)
150
+ return model_xml_path
151
+
152
+
153
+ # ## Images
154
+
155
+ # ### Convert Pixel Data
156
+ #
157
+ # Normalize image pixel values between 0 and 1, and convert images to RGB and BGR.
158
+
159
+ # In[ ]:
160
+
161
+
162
+ def normalize_minmax(data):
163
+ """
164
+ Normalizes the values in `data` between 0 and 1
165
+ """
166
+ if data.max() == data.min():
167
+ raise ValueError("Normalization is not possible because all elements of" f"`data` have the same value: {data.max()}.")
168
+ return (data - data.min()) / (data.max() - data.min())
169
+
170
+
171
+ def to_rgb(image_data: np.ndarray) -> np.ndarray:
172
+ """
173
+ Convert image_data from BGR to RGB
174
+ """
175
+ import cv2
176
+
177
+ return cv2.cvtColor(image_data, cv2.COLOR_BGR2RGB)
178
+
179
+
180
+ def to_bgr(image_data: np.ndarray) -> np.ndarray:
181
+ """
182
+ Convert image_data from RGB to BGR
183
+ """
184
+ import cv2
185
+
186
+ return cv2.cvtColor(image_data, cv2.COLOR_RGB2BGR)
187
+
188
+
189
+ # ## Videos
190
+
191
+ # ### Video Player
192
+ #
193
+ # Custom video player to fulfill FPS requirements. You can set target FPS and output size, flip the video horizontally or skip first N frames.
194
+
195
+ # In[ ]:
196
+
197
+
198
+ class VideoPlayer:
199
+ """
200
+ Custom video player to fulfill FPS requirements. You can set target FPS and output size,
201
+ flip the video horizontally or skip first N frames.
202
+
203
+ :param source: Video source. It could be either camera device or video file.
204
+ :param size: Output frame size.
205
+ :param flip: Flip source horizontally.
206
+ :param fps: Target FPS.
207
+ :param skip_first_frames: Skip first N frames.
208
+ """
209
+
210
+ def __init__(self, source, size=None, flip=False, fps=None, skip_first_frames=0):
211
+ import cv2
212
+
213
+ self.cv2 = cv2 # This is done to access the package in class methods
214
+ self.__cap = cv2.VideoCapture(source)
215
+ if not self.__cap.isOpened():
216
+ raise RuntimeError(f"Cannot open {'camera' if isinstance(source, int) else ''} {source}")
217
+ # skip first N frames
218
+ self.__cap.set(cv2.CAP_PROP_POS_FRAMES, skip_first_frames)
219
+ # fps of input file
220
+ self.__input_fps = self.__cap.get(cv2.CAP_PROP_FPS)
221
+ if self.__input_fps <= 0:
222
+ self.__input_fps = 60
223
+ # target fps given by user
224
+ self.__output_fps = fps if fps is not None else self.__input_fps
225
+ self.__flip = flip
226
+ self.__size = None
227
+ self.__interpolation = None
228
+ if size is not None:
229
+ self.__size = size
230
+ # AREA better for shrinking, LINEAR better for enlarging
231
+ self.__interpolation = cv2.INTER_AREA if size[0] < self.__cap.get(cv2.CAP_PROP_FRAME_WIDTH) else cv2.INTER_LINEAR
232
+ # first frame
233
+ _, self.__frame = self.__cap.read()
234
+ self.__lock = threading.Lock()
235
+ self.__thread = None
236
+ self.__stop = False
237
+
238
+ """
239
+ Start playing.
240
+ """
241
+
242
+ def start(self):
243
+ self.__stop = False
244
+ self.__thread = threading.Thread(target=self.__run, daemon=True)
245
+ self.__thread.start()
246
+
247
+ """
248
+ Stop playing and release resources.
249
+ """
250
+
251
+ def stop(self):
252
+ self.__stop = True
253
+ if self.__thread is not None:
254
+ self.__thread.join()
255
+ self.__cap.release()
256
+
257
+ def __run(self):
258
+ prev_time = 0
259
+ while not self.__stop:
260
+ t1 = time.time()
261
+ ret, frame = self.__cap.read()
262
+ if not ret:
263
+ break
264
+
265
+ # fulfill target fps
266
+ if 1 / self.__output_fps < time.time() - prev_time:
267
+ prev_time = time.time()
268
+ # replace by current frame
269
+ with self.__lock:
270
+ self.__frame = frame
271
+
272
+ t2 = time.time()
273
+ # time to wait [s] to fulfill input fps
274
+ wait_time = 1 / self.__input_fps - (t2 - t1)
275
+ # wait until
276
+ time.sleep(max(0, wait_time))
277
+
278
+ self.__frame = None
279
+
280
+ """
281
+ Get current frame.
282
+ """
283
+
284
+ def next(self):
285
+ import cv2
286
+
287
+ with self.__lock:
288
+ if self.__frame is None:
289
+ return None
290
+ # need to copy frame, because can be cached and reused if fps is low
291
+ frame = self.__frame.copy()
292
+ if self.__size is not None:
293
+ frame = self.cv2.resize(frame, self.__size, interpolation=self.__interpolation)
294
+ if self.__flip:
295
+ frame = self.cv2.flip(frame, 1)
296
+ return frame
297
+
298
+
299
+ # ## Visualization
300
+
301
+ # ### Segmentation
302
+ #
303
+ # Define a SegmentationMap NamedTuple that keeps the labels and colormap for a segmentation project/dataset. Create CityScapesSegmentation and BinarySegmentation SegmentationMaps. Create a function to convert a segmentation map to an RGB image with a colormap, and to show the segmentation result as an overlay over the original image.
304
+
305
+ # In[ ]:
306
+
307
+
308
+ class Label(NamedTuple):
309
+ index: int
310
+ color: Tuple
311
+ name: Optional[str] = None
312
+
313
+
314
+ # In[ ]:
315
+
316
+
317
+ class SegmentationMap(NamedTuple):
318
+ labels: List
319
+
320
+ def get_colormap(self):
321
+ return np.array([label.color for label in self.labels])
322
+
323
+ def get_labels(self):
324
+ labelnames = [label.name for label in self.labels]
325
+ if any(labelnames):
326
+ return labelnames
327
+ else:
328
+ return None
329
+
330
+
331
+ # In[ ]:
332
+
333
+
334
+ cityscape_labels = [
335
+ Label(index=0, color=(128, 64, 128), name="road"),
336
+ Label(index=1, color=(244, 35, 232), name="sidewalk"),
337
+ Label(index=2, color=(70, 70, 70), name="building"),
338
+ Label(index=3, color=(102, 102, 156), name="wall"),
339
+ Label(index=4, color=(190, 153, 153), name="fence"),
340
+ Label(index=5, color=(153, 153, 153), name="pole"),
341
+ Label(index=6, color=(250, 170, 30), name="traffic light"),
342
+ Label(index=7, color=(220, 220, 0), name="traffic sign"),
343
+ Label(index=8, color=(107, 142, 35), name="vegetation"),
344
+ Label(index=9, color=(152, 251, 152), name="terrain"),
345
+ Label(index=10, color=(70, 130, 180), name="sky"),
346
+ Label(index=11, color=(220, 20, 60), name="person"),
347
+ Label(index=12, color=(255, 0, 0), name="rider"),
348
+ Label(index=13, color=(0, 0, 142), name="car"),
349
+ Label(index=14, color=(0, 0, 70), name="truck"),
350
+ Label(index=15, color=(0, 60, 100), name="bus"),
351
+ Label(index=16, color=(0, 80, 100), name="train"),
352
+ Label(index=17, color=(0, 0, 230), name="motorcycle"),
353
+ Label(index=18, color=(119, 11, 32), name="bicycle"),
354
+ Label(index=19, color=(255, 255, 255), name="background"),
355
+ ]
356
+
357
+ CityScapesSegmentation = SegmentationMap(cityscape_labels)
358
+
359
+ binary_labels = [
360
+ Label(index=0, color=(255, 255, 255), name="background"),
361
+ Label(index=1, color=(0, 0, 0), name="foreground"),
362
+ ]
363
+
364
+ BinarySegmentation = SegmentationMap(binary_labels)
365
+
366
+
367
+ # In[ ]:
368
+
369
+
370
+ def segmentation_map_to_image(result: np.ndarray, colormap: np.ndarray, remove_holes: bool = False) -> np.ndarray:
371
+ """
372
+ Convert network result of floating point numbers to an RGB image with
373
+ integer values from 0-255 by applying a colormap.
374
+
375
+ :param result: A single network result after converting to pixel values in H,W or 1,H,W shape.
376
+ :param colormap: A numpy array of shape (num_classes, 3) with an RGB value per class.
377
+ :param remove_holes: If True, remove holes in the segmentation result.
378
+ :return: An RGB image where each pixel is an int8 value according to colormap.
379
+ """
380
+ import cv2
381
+
382
+ if len(result.shape) != 2 and result.shape[0] != 1:
383
+ raise ValueError(f"Expected result with shape (H,W) or (1,H,W), got result with shape {result.shape}")
384
+
385
+ if len(np.unique(result)) > colormap.shape[0]:
386
+ raise ValueError(
387
+ f"Expected max {colormap[0]} classes in result, got {len(np.unique(result))} "
388
+ "different output values. Please make sure to convert the network output to "
389
+ "pixel values before calling this function."
390
+ )
391
+ elif result.shape[0] == 1:
392
+ result = result.squeeze(0)
393
+
394
+ result = result.astype(np.uint8)
395
+
396
+ contour_mode = cv2.RETR_EXTERNAL if remove_holes else cv2.RETR_TREE
397
+ mask = np.zeros((result.shape[0], result.shape[1], 3), dtype=np.uint8)
398
+ for label_index, color in enumerate(colormap):
399
+ label_index_map = result == label_index
400
+ label_index_map = label_index_map.astype(np.uint8) * 255
401
+ contours, hierarchies = cv2.findContours(label_index_map, contour_mode, cv2.CHAIN_APPROX_SIMPLE)
402
+ cv2.drawContours(
403
+ mask,
404
+ contours,
405
+ contourIdx=-1,
406
+ color=color.tolist(),
407
+ thickness=cv2.FILLED,
408
+ )
409
+
410
+ return mask
411
+
412
+
413
+ def segmentation_map_to_overlay(image, result, alpha, colormap, remove_holes=False) -> np.ndarray:
414
+ """
415
+ Returns a new image where a segmentation mask (created with colormap) is overlayed on
416
+ the source image.
417
+
418
+ :param image: Source image.
419
+ :param result: A single network result after converting to pixel values in H,W or 1,H,W shape.
420
+ :param alpha: Alpha transparency value for the overlay image.
421
+ :param colormap: A numpy array of shape (num_classes, 3) with an RGB value per class.
422
+ :param remove_holes: If True, remove holes in the segmentation result.
423
+ :return: An RGP image with segmentation mask overlayed on the source image.
424
+ """
425
+ import cv2
426
+
427
+ if len(image.shape) == 2:
428
+ image = np.repeat(np.expand_dims(image, -1), 3, 2)
429
+ mask = segmentation_map_to_image(result, colormap, remove_holes)
430
+ image_height, image_width = image.shape[:2]
431
+ mask = cv2.resize(src=mask, dsize=(image_width, image_height))
432
+ return cv2.addWeighted(mask, alpha, image, 1 - alpha, 0)
433
+
434
+
435
+ # ### Network Results
436
+ #
437
+ # Show network result image, optionally together with the source image and a legend with labels.
438
+
439
+ # In[ ]:
440
+
441
+
442
+ def viz_result_image(
443
+ result_image: np.ndarray,
444
+ source_image: np.ndarray = None,
445
+ source_title: str = None,
446
+ result_title: str = None,
447
+ labels: List[Label] = None,
448
+ resize: bool = False,
449
+ bgr_to_rgb: bool = False,
450
+ hide_axes: bool = False,
451
+ ):
452
+ """
453
+ Show result image, optionally together with source images, and a legend with labels.
454
+
455
+ :param result_image: Numpy array of RGB result image.
456
+ :param source_image: Numpy array of source image. If provided this image will be shown
457
+ next to the result image. source_image is expected to be in RGB format.
458
+ Set bgr_to_rgb to True if source_image is in BGR format.
459
+ :param source_title: Title to display for the source image.
460
+ :param result_title: Title to display for the result image.
461
+ :param labels: List of labels. If provided, a legend will be shown with the given labels.
462
+ :param resize: If true, resize the result image to the same shape as the source image.
463
+ :param bgr_to_rgb: If true, convert the source image from BGR to RGB. Use this option if
464
+ source_image is a BGR image.
465
+ :param hide_axes: If true, do not show matplotlib axes.
466
+ :return: Matplotlib figure with result image
467
+ """
468
+ import cv2
469
+ import matplotlib.pyplot as plt
470
+ from matplotlib.lines import Line2D
471
+
472
+ if bgr_to_rgb:
473
+ source_image = to_rgb(source_image)
474
+ if resize:
475
+ result_image = cv2.resize(result_image, (source_image.shape[1], source_image.shape[0]))
476
+
477
+ num_images = 1 if source_image is None else 2
478
+
479
+ fig, ax = plt.subplots(1, num_images, figsize=(16, 8), squeeze=False)
480
+ if source_image is not None:
481
+ ax[0, 0].imshow(source_image)
482
+ ax[0, 0].set_title(source_title)
483
+
484
+ ax[0, num_images - 1].imshow(result_image)
485
+ ax[0, num_images - 1].set_title(result_title)
486
+
487
+ if hide_axes:
488
+ for a in ax.ravel():
489
+ a.axis("off")
490
+ if labels:
491
+ colors = labels.get_colormap()
492
+ lines = [
493
+ Line2D(
494
+ [0],
495
+ [0],
496
+ color=[item / 255 for item in c.tolist()],
497
+ linewidth=3,
498
+ linestyle="-",
499
+ )
500
+ for c in colors
501
+ ]
502
+ plt.legend(
503
+ lines,
504
+ labels.get_labels(),
505
+ bbox_to_anchor=(1, 1),
506
+ loc="upper left",
507
+ prop={"size": 12},
508
+ )
509
+ plt.close(fig)
510
+ return fig
511
+
512
+
513
+ # ### Live Inference
514
+
515
+ # In[ ]:
516
+
517
+
518
+ def show_array(frame: np.ndarray, display_handle=None):
519
+ """
520
+ Display array `frame`. Replace information at `display_handle` with `frame`
521
+ encoded as jpeg image. `frame` is expected to have data in BGR order.
522
+
523
+ Create a display_handle with: `display_handle = display(display_id=True)`
524
+ """
525
+ import cv2
526
+
527
+ _, frame = cv2.imencode(ext=".jpeg", img=frame)
528
+ if display_handle is None:
529
+ display_handle = display(Image(data=frame.tobytes()), display_id=True)
530
+ else:
531
+ display_handle.update(Image(data=frame.tobytes()))
532
+ return display_handle
533
+
534
+
535
+ # ## Checks and Alerts
536
+ #
537
+ # Create an alert class to show stylized info/error/warning messages and a `check_device` function that checks whether a given device is available.
538
+
539
+ # In[ ]:
540
+
541
+
542
+ class NotebookAlert(Exception):
543
+ def __init__(self, message: str, alert_class: str):
544
+ """
545
+ Show an alert box with the given message.
546
+
547
+ :param message: The message to display.
548
+ :param alert_class: The class for styling the message. Options: info, warning, success, danger.
549
+ """
550
+ self.message = message
551
+ self.alert_class = alert_class
552
+ self.show_message()
553
+
554
+ def show_message(self):
555
+ display(HTML(f"""<div class="alert alert-{self.alert_class}">{self.message}"""))
556
+
557
+
558
+ class DeviceNotFoundAlert(NotebookAlert):
559
+ def __init__(self, device: str):
560
+ """
561
+ Show a warning message about an unavailable device. This class does not check whether or
562
+ not the device is available, use the `check_device` function to check this. `check_device`
563
+ also shows the warning if the device is not found.
564
+
565
+ :param device: The unavailable device.
566
+ :return: A formatted alert box with the message that `device` is not available, and a list
567
+ of devices that are available.
568
+ """
569
+ ie = Core()
570
+ supported_devices = ie.available_devices
571
+ self.message = f"Running this cell requires a {device} device, " "which is not available on this system. "
572
+ self.alert_class = "warning"
573
+ if len(supported_devices) == 1:
574
+ self.message += f"The following device is available: {ie.available_devices[0]}"
575
+ else:
576
+ self.message += "The following devices are available: " f"{', '.join(ie.available_devices)}"
577
+ super().__init__(self.message, self.alert_class)
578
+
579
+
580
+ def check_device(device: str) -> bool:
581
+ """
582
+ Check if the specified device is available on the system.
583
+
584
+ :param device: Device to check. e.g. CPU, GPU
585
+ :return: True if the device is available, False if not. If the device is not available,
586
+ a DeviceNotFoundAlert will be shown.
587
+ """
588
+ ie = Core()
589
+ if device not in ie.available_devices:
590
+ DeviceNotFoundAlert(device)
591
+ return False
592
+ else:
593
+ return True
594
+
595
+
596
+ def check_openvino_version(version: str) -> bool:
597
+ """
598
+ Check if the specified OpenVINO version is installed.
599
+
600
+ :param version: the OpenVINO version to check. Example: 2021.4
601
+ :return: True if the version is installed, False if not. If the version is not installed,
602
+ an alert message will be shown.
603
+ """
604
+ installed_version = get_version()
605
+ if version not in installed_version:
606
+ NotebookAlert(
607
+ f"This notebook requires OpenVINO {version}. "
608
+ f"The version on your system is: <i>{installed_version}</i>.<br>"
609
+ "Please run <span style='font-family:monospace'>pip install --upgrade -r requirements.txt</span> "
610
+ "in the openvino_env environment to install this version. "
611
+ "See the <a href='https://github.com/openvinotoolkit/openvino_notebooks'>"
612
+ "OpenVINO Notebooks README</a> for detailed instructions",
613
+ alert_class="danger",
614
+ )
615
+ return False
616
+ else:
617
+ return True
618
+
619
+
620
+ packed_layername_tensor_dict_list = [{"name": "aten::mul/Multiply"}]
621
+
622
+
623
+ class ReplaceTensor(MatcherPass):
624
+ def __init__(self, packed_layername_tensor_dict_list):
625
+ MatcherPass.__init__(self)
626
+ self.model_changed = False
627
+
628
+ param = WrapType("opset10.Multiply")
629
+
630
+ def callback(matcher: Matcher) -> bool:
631
+ root = matcher.get_match_root()
632
+ if root is None:
633
+ return False
634
+ for y in packed_layername_tensor_dict_list:
635
+ root_name = root.get_friendly_name()
636
+ if root_name.find(y["name"]) != -1:
637
+ max_fp16 = np.array([[[[-np.finfo(np.float16).max]]]]).astype(np.float32)
638
+ new_tenser = ops.constant(max_fp16, Type.f32, name="Constant_4431")
639
+ root.set_arguments([root.input_value(0).node, new_tenser])
640
+ packed_layername_tensor_dict_list.remove(y)
641
+
642
+ return True
643
+
644
+ self.register_matcher(Matcher(param, "ReplaceTensor"), callback)
645
+
646
+
647
+ def optimize_bge_embedding(model_path, output_model_path):
648
+ """
649
+ optimize_bge_embedding used to optimize BGE model for NPU device
650
+
651
+ Arguments:
652
+ model_path {str} -- original BGE IR model path
653
+ output_model_path {str} -- Converted BGE IR model path
654
+ """
655
+ core = Core()
656
+ ov_model = core.read_model(model_path)
657
+ manager = Manager()
658
+ manager.register_pass(ReplaceTensor(packed_layername_tensor_dict_list))
659
+ manager.run_passes(ov_model)
660
+ ov.save_model(ov_model, output_model_path, compress_to_fp16=False)
phi-2/INT4_compressed_weights/config.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "susnato/phi-2",
3
+ "architectures": [
4
+ "PhiForCausalLM"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "bos_token_id": 1,
8
+ "embd_pdrop": 0.0,
9
+ "eos_token_id": 2,
10
+ "hidden_act": "gelu_new",
11
+ "hidden_size": 2560,
12
+ "initializer_range": 0.02,
13
+ "intermediate_size": 10240,
14
+ "is_decoder": true,
15
+ "layer_norm_eps": 1e-05,
16
+ "max_position_embeddings": 2048,
17
+ "model_type": "phi",
18
+ "num_attention_heads": 32,
19
+ "num_hidden_layers": 32,
20
+ "num_key_value_heads": 32,
21
+ "partial_rotary_factor": 0.4,
22
+ "pretraining_tp": 1,
23
+ "qk_layernorm": false,
24
+ "resid_pdrop": 0.1,
25
+ "rope_scaling": null,
26
+ "rope_theta": 10000.0,
27
+ "tie_word_embeddings": false,
28
+ "torch_dtype": "float16",
29
+ "transformers_version": "4.41.2",
30
+ "use_cache": true,
31
+ "vocab_size": 51200
32
+ }
phi-2/INT4_compressed_weights/generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "transformers_version": "4.41.2"
4
+ }
phi-2/INT4_compressed_weights/openvino_config.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "compression": null,
3
+ "dtype": "int4",
4
+ "input_info": null,
5
+ "optimum_version": "1.21.0",
6
+ "quantization_config": {
7
+ "all_layers": null,
8
+ "bits": 4,
9
+ "dataset": null,
10
+ "group_size": 128,
11
+ "ignored_scope": null,
12
+ "num_samples": null,
13
+ "quant_method": "default",
14
+ "ratio": 0.8,
15
+ "scale_estimation": null,
16
+ "sensitivity_metric": null,
17
+ "sym": false,
18
+ "tokenizer": null
19
+ },
20
+ "save_onnx_model": false,
21
+ "transformers_version": "4.41.2"
22
+ }
phi-2/INT4_compressed_weights/openvino_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:203aaad089bbdfd1590bcc913733ac8f255a399ca308b7d43b268eaf7ca922dc
3
+ size 1823610588
phi-2/INT4_compressed_weights/openvino_model.xml ADDED
The diff for this file is too large to render. See raw diff
 
phi-2/INT8_compressed_weights/config.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "susnato/phi-2",
3
+ "architectures": [
4
+ "PhiForCausalLM"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "bos_token_id": 1,
8
+ "embd_pdrop": 0.0,
9
+ "eos_token_id": 2,
10
+ "hidden_act": "gelu_new",
11
+ "hidden_size": 2560,
12
+ "initializer_range": 0.02,
13
+ "intermediate_size": 10240,
14
+ "is_decoder": true,
15
+ "layer_norm_eps": 1e-05,
16
+ "max_position_embeddings": 2048,
17
+ "model_type": "phi",
18
+ "num_attention_heads": 32,
19
+ "num_hidden_layers": 32,
20
+ "num_key_value_heads": 32,
21
+ "partial_rotary_factor": 0.4,
22
+ "pretraining_tp": 1,
23
+ "qk_layernorm": false,
24
+ "resid_pdrop": 0.1,
25
+ "rope_scaling": null,
26
+ "rope_theta": 10000.0,
27
+ "tie_word_embeddings": false,
28
+ "torch_dtype": "float16",
29
+ "transformers_version": "4.41.2",
30
+ "use_cache": true,
31
+ "vocab_size": 51200
32
+ }
phi-2/INT8_compressed_weights/generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "transformers_version": "4.41.2"
4
+ }
phi-2/INT8_compressed_weights/openvino_config.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "compression": null,
3
+ "dtype": "int8",
4
+ "input_info": null,
5
+ "optimum_version": "1.21.0",
6
+ "quantization_config": {
7
+ "all_layers": null,
8
+ "bits": 8,
9
+ "dataset": null,
10
+ "group_size": -1,
11
+ "ignored_scope": null,
12
+ "num_samples": null,
13
+ "quant_method": "default",
14
+ "ratio": 1.0,
15
+ "scale_estimation": null,
16
+ "sensitivity_metric": null,
17
+ "sym": false,
18
+ "tokenizer": null
19
+ },
20
+ "save_onnx_model": false,
21
+ "transformers_version": "4.41.2"
22
+ }
phi-2/INT8_compressed_weights/openvino_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:81274a4f75f1197be9f86cf61f84e9482106ff269fad755ab559291549cd1b53
3
+ size 2785599684
phi-2/INT8_compressed_weights/openvino_model.xml ADDED
The diff for this file is too large to render. See raw diff
 
templates/dashboard.html ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Dashboard</title>
7
+ <style>
8
+ body {
9
+ font-family: Arial, sans-serif;
10
+ background-color: #f4f4f4;
11
+ margin: 0;
12
+ padding: 0;
13
+ }
14
+ .container {
15
+ max-width: 1200px;
16
+ margin: 0 auto;
17
+ padding: 20px;
18
+ }
19
+ h1 {
20
+ color: #333;
21
+ }
22
+ .gradio-container {
23
+ margin-top: 20px;
24
+ }
25
+ iframe {
26
+ border: none;
27
+ width: 100%;
28
+ height: 800px;
29
+ }
30
+ .logout {
31
+ margin-top: 20px;
32
+ text-align: right;
33
+ }
34
+ .start-button {
35
+ margin-top: 20px;
36
+ background-color: #4CAF50;
37
+ color: white;
38
+ border: none;
39
+ padding: 10px 20px;
40
+ text-align: center;
41
+ text-decoration: none;
42
+ display: inline-block;
43
+ font-size: 16px;
44
+ cursor: pointer;
45
+ border-radius: 4px;
46
+ }
47
+ </style>
48
+ <script>
49
+ function openGradioInNewWindow() {
50
+ window.open("{{ url_for('gradio') }}");
51
+ }
52
+ </script>
53
+ </head>
54
+ <body>
55
+ <div class="container">
56
+ <h1>Welcome, {{ name }}!</h1>
57
+ <button class="start-button" onclick="openGradioInNewWindow()">Start the Chatbot</button>
58
+
59
+ <div class="logout">
60
+ <a href="{{ url_for('logout') }}">Logout</a>
61
+ </div>
62
+ </div>
63
+ </body>
64
+ </html>
templates/login.html ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <title>Login</title>
3
+ <h1>Login</h1>
4
+ <form method="post">
5
+ <input type="text" name="username" placeholder="Username" required>
6
+ <input type="password" name="password" placeholder="Password" required>
7
+ <button type="submit">Login</button>
8
+ </form>
9
+ <a href="{{ url_for('signup') }}">Don't have an account? Sign Up</a>
templates/signup.html ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <title>Sign Up</title>
3
+ <h1>Sign Up</h1>
4
+ <form method="post">
5
+ <input type="text" name="username" placeholder="Username" required>
6
+ <input type="password" name="password" placeholder="Password" required>
7
+ <button type="submit">Sign Up</button>
8
+ </form>
9
+ <a href="{{ url_for('login') }}">Already have an account? Login</a>