File size: 57,168 Bytes
db5855f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "a1dafb31-bac1-4d01-9356-102114115c51",
   "metadata": {},
   "source": [
    "# LLM-powered chatbot using Stable-Zephyr-3b and OpenVINO\n",
    "\n",
    "In the rapidly evolving world of artificial intelligence (AI), chatbots have become powerful tools for businesses to enhance customer interactions and streamline operations. \n",
    "Large Language Models (LLMs) are artificial intelligence systems that can understand and generate human language. They use deep learning algorithms and massive amounts of data to learn the nuances of language and produce coherent and relevant responses.\n",
    "While a decent intent-based chatbot can answer basic, one-touch inquiries like order management, FAQs, and policy questions, LLM chatbots can tackle more complex, multi-touch questions. LLM enables chatbots to provide support in a conversational manner, similar to how humans do, through contextual memory. Leveraging the capabilities of Language Models, chatbots are becoming increasingly intelligent, capable of understanding and responding to human language with remarkable accuracy.\n",
    "\n",
    "`Stable Zephyr 3B` is a 3 billion parameter model that demonstrated outstanding results on many LLM evaluation benchmarks outperforming many popular models in relatively small size. Inspired by [HugginFaceH4's Zephyr 7B](https://huggingface.co/HuggingFaceH4/zephyr-7b-beta) training pipeline this model was trained on a mix of publicly available datasets, synthetic datasets using [Direct Preference Optimization (DPO)](https://arxiv.org/abs/2305.18290), evaluation for this model based on [MT Bench](https://tatsu-lab.github.io/alpaca_eval/) and [Alpaca Benchmark](https://tatsu-lab.github.io/alpaca_eval/). More details about model can be found in [model card](https://huggingface.co/stabilityai/stablelm-zephyr-3b)\n",
    "\n",
    "In this tutorial, we consider how to optimize and run this model using the OpenVINO toolkit. For the convenience of the conversion step and model performance evaluation, we will use [llm_bench](https://github.com/openvinotoolkit/openvino.genai/tree/master/llm_bench/python) tool, which provides a unified approach to estimate performance for LLM. It is based on pipelines provided by Optimum-Intel and allows to estimate performance for Pytorch and OpenVINO models using almost the same code. We also demonstrate how to make model stateful, that provides opportunity for processing model cache state.\n",
    "\n",
    "\n",
    "#### Table of contents:\n",
    "\n",
    "- [Prerequisites](#Prerequisites)\n",
    "- [Convert model to OpenVINO Intermediate Representation (IR) and compress model weights to INT4 using NNCF](#Convert-model-to-OpenVINO-Intermediate-Representation-(IR)-and-compress-model-weights-to-INT4-using-NNCF)\n",
    "- [Apply stateful transformation for automatic handling model state](#Apply-stateful-transformation-for-automatic-handling-model-state)\n",
    "- [Select device for inference](#Select-device-for-inference)\n",
    "- [Estimate model performance](#Estimate-model-performance)\n",
    "- [Using model with Optimum Intel](#Using-model-with-Optimum-Intel)\n",
    "- [Interactive chatbot demo](#Interactive-chatbot-demo)\n",
    "\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "93504605-33cc-4eb1-8331-dd7d7ea9a51d",
   "metadata": {},
   "source": [
    "## Prerequisites\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "For starting work, we should install required packages first"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "dd1d538e-c22b-4a6e-9f5b-4462b1a2a43f",
   "metadata": {},
   "outputs": [],
   "source": [
    "from pathlib import Path\n",
    "import sys\n",
    "\n",
    "\n",
    "genai_llm_bench = Path(\"openvino.genai/llm_bench/python\")\n",
    "\n",
    "if not genai_llm_bench.exists():\n",
    "    !git clone  https://github.com/openvinotoolkit/openvino.genai.git\n",
    "\n",
    "sys.path.append(str(genai_llm_bench))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "342d2a0e-08cb-4a65-9164-98cb82f25d8c",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install -q \"transformers>=4.38.2\"\n",
    "%pip install -q --extra-index-url https://download.pytorch.org/whl/cpu -r ./openvino.genai/llm_bench/python/requirements.txt\n",
    "%pip install --pre -Uq openvino openvino-tokenizers[transformers] --extra-index-url https://storage.openvinotoolkit.org/simple/wheels/nightly\n",
    "%pip install -q \"gradio>=4.19\""
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "eb0882f4-e206-4dde-a67e-67d40b73250b",
   "metadata": {},
   "source": [
    "## Convert model to OpenVINO Intermediate Representation (IR) and compress model weights to INT4 using NNCF\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "llm_bench provides conversion script for converting LLMS into OpenVINO IR format compatible with Optimum-Intel. It also allows to compress model weights into INT8 or INT4 precision with [NNCF](https://github.com/openvinotoolkit/nncf). For enabling weights compression in INT4 we should use `--compress_weights 4BIT_DEFAULT` argument. The Weights Compression algorithm is aimed at compressing the weights of the models and can be used to optimize the model footprint and performance of large models where the size of weights is relatively larger than the size of activations, for example, Large Language Models (LLM). Compared to INT8 compression, INT4 compression improves performance even more but introduces a minor drop in prediction quality.\n",
    "\n",
    "## Apply stateful transformation for automatic handling model state\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Stable Zephyr is a decoder-only transformer model and generates text token by token in an autoregressive fashion. 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.  To optimize the generation process and use memory more efficiently, HuggingFace transformers API provides a mechanism for caching model state externally using `use_cache=True` parameter and `past_key_values` argument in inputs and outputs. 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. With this option, the model gets the previous step's hidden states (cached attention keys and values) as input and additionally provides hidden states for the current step as output. It means for all next iterations, it is enough to provide only a new token obtained from the previous step and cached key values to get the next token prediction.\n",
    "\n",
    "With increasing model size like in modern LLMs, we also can note an increase in the number of attention blocks and size past key values tensors respectively. The strategy for handling cache state as model inputs and outputs in the inference cycle may become a bottleneck for memory-bounded systems, especially with processing long input sequences, for example in a chatbot scenario. OpenVINO suggests a transformation that removes inputs and corresponding outputs with cache tensors from the model keeping cache handling logic inside the model. Hiding the cache enables storing and updating the cache values in a more device-friendly representation. It helps to reduce memory consumption and additionally optimize model performance.\n",
    "\n",
    "llm_bench convert model in stateful format by default, if you want disable this behavior you can specify `--disable_stateful` flag for that"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "aeacd53b-755a-464f-b984-d88c3625d687",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:nncf:NNCF initialized successfully. Supported frameworks detected: torch, tensorflow, onnx, openvino\n",
      "2024-03-05 13:50:49.184866: I tensorflow/core/util/port.cc:110] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`.\n",
      "2024-03-05 13:50:49.186797: I tensorflow/tsl/cuda/cudart_stub.cc:28] Could not find cuda drivers on your machine, GPU will not be used.\n",
      "2024-03-05 13:50:49.223416: I tensorflow/tsl/cuda/cudart_stub.cc:28] Could not find cuda drivers on your machine, GPU will not be used.\n",
      "2024-03-05 13:50:49.223832: I tensorflow/core/platform/cpu_feature_guard.cc:182] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.\n",
      "To enable the following instructions: AVX2 AVX512F AVX512_VNNI FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.\n",
      "2024-03-05 13:50:49.887707: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT\n",
      "WARNING[XFORMERS]: xFormers can't load C++/CUDA extensions. xFormers was built for:\n",
      "    PyTorch 2.1.0+cu121 with CUDA 1201 (you have 2.2.0+cpu)\n",
      "    Python  3.8.18 (you have 3.8.10)\n",
      "  Please reinstall xformers (see https://github.com/facebookresearch/xformers#installing-xformers)\n",
      "  Memory-efficient attention, SwiGLU, sparse and more won't be available.\n",
      "  Set XFORMERS_MORE_DETAILS=1 for more details\n",
      "/home/ea/work/my_optimum_intel/optimum_env/lib/python3.8/site-packages/diffusers/utils/outputs.py:63: UserWarning: torch.utils._pytree._register_pytree_node is deprecated. Please use torch.utils._pytree.register_pytree_node instead.\n",
      "  torch.utils._pytree._register_pytree_node(\n",
      "WARNING:nncf:NNCF provides best results with torch==2.2.1, while current torch version is 2.2.0+cpu. If you encounter issues, consider switching to torch==2.2.1\n",
      "/home/ea/work/my_optimum_intel/optimum_env/lib/python3.8/site-packages/bitsandbytes/cextension.py:34: UserWarning: The installed version of bitsandbytes was compiled without GPU support. 8-bit optimizers, 8-bit multiplication, and GPU quantization are unavailable.\n",
      "  warn(\"The installed version of bitsandbytes was compiled without GPU support. \"\n",
      "/home/ea/work/my_optimum_intel/optimum_env/lib/python3.8/site-packages/bitsandbytes/libbitsandbytes_cpu.so: undefined symbol: cadam32bit_grad_fp32\n",
      "[ INFO ] openvino runtime version: 2024.1.0-14645-e6dc0865128\n",
      "Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\n",
      "[ INFO ] Model conversion to FP16 will be skipped as found converted model stable-zephyr-3b-stateful/pytorch/dldt/FP16/openvino_model.xml.If it is not expected behaviour, please remove previously converted model or use --force_convert option\n",
      "[ INFO ] Compress model weights to 4BIT_DEFAULT\n",
      "[ INFO ] Compression options:\n",
      "[ INFO ] {'mode': <CompressWeightsMode.INT4_SYM: 'int4_sym'>, 'group_size': 128}\n",
      "INFO:nncf:Statistics of the bitwidth distribution:\n",
      "+--------------+---------------------------+-----------------------------------+\n",
      "| Num bits (N) | % all parameters (layers) |    % ratio-defining parameters    |\n",
      "|              |                           |             (layers)              |\n",
      "+==============+===========================+===================================+\n",
      "| 8            | 9% (2 / 226)              | 0% (0 / 224)                      |\n",
      "+--------------+---------------------------+-----------------------------------+\n",
      "| 4            | 91% (224 / 226)           | 100% (224 / 224)                  |\n",
      "+--------------+---------------------------+-----------------------------------+\n",
      "\u001b[2KApplying Weight Compression \u001b[38;2;114;156;31m━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[35m100%\u001b[0m \u001b[38;2;0;104;181m226/226\u001b[0m • \u001b[38;2;0;104;181m0:01:29\u001b[0m • \u001b[38;2;0;104;181m0:00:00\u001b[0m;0;104;181m0:00:01\u001b[0m181m0:00:05\u001b[0m\n",
      "\u001b[?25h"
     ]
    }
   ],
   "source": [
    "stateful_model_path = Path(\"stable-zephyr-3b-stateful/pytorch/dldt/compressed_weights/OV_FP16-4BIT_DEFAULT\")\n",
    "\n",
    "convert_script = genai_llm_bench / \"convert.py\"\n",
    "\n",
    "if not (stateful_model_path / \"openvino_model.xml\").exists():\n",
    "    !python $convert_script --model_id stabilityai/stable-zephyr-3b --precision FP16 --compress_weights 4BIT_DEFAULT --output stable-zephyr-3b-stateful --force_convert"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "4c64f567-78d0-44bc-9f62-e3b03bcf8467",
   "metadata": {},
   "source": [
    "## Select device for inference\n",
    "[back to top ⬆️](#Table-of-contents:)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "994ebd02-8e54-41dd-9fc6-aa95bec46bca",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "bd380d7c5b044d02a29085bb584067e5",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Dropdown(description='Device:', options=('CPU', 'GPU.0', 'GPU.1'), value='CPU')"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import ipywidgets as widgets\n",
    "import openvino as ov\n",
    "\n",
    "core = ov.Core()\n",
    "\n",
    "device = widgets.Dropdown(\n",
    "    options=core.available_devices,\n",
    "    value=\"CPU\",\n",
    "    description=\"Device:\",\n",
    "    disabled=False,\n",
    ")\n",
    "\n",
    "device"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "98c8167c-d17c-43e8-9ff9-a9aa2f16cf3f",
   "metadata": {},
   "source": [
    "## Estimate model performance\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "openvino.genai / llm_bench / python / benchmark.py script allow to estimate text generation pipeline inference on specific input prompt with given number of maximum generated tokens."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "f57f0ac8-74ea-4709-a1a8-eb8c4d6da3fc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "/home/ea/work/my_optimum_intel/optimum_env/lib/python3.8/site-packages/diffusers/utils/outputs.py:63: UserWarning: torch.utils._pytree._register_pytree_node is deprecated. Please use torch.utils._pytree.register_pytree_node instead.\n",
      "  torch.utils._pytree._register_pytree_node(\n",
      "WARNING[XFORMERS]: xFormers can't load C++/CUDA extensions. xFormers was built for:\n",
      "    PyTorch 2.1.0+cu121 with CUDA 1201 (you have 2.2.0+cpu)\n",
      "    Python  3.8.18 (you have 3.8.10)\n",
      "  Please reinstall xformers (see https://github.com/facebookresearch/xformers#installing-xformers)\n",
      "  Memory-efficient attention, SwiGLU, sparse and more won't be available.\n",
      "  Set XFORMERS_MORE_DETAILS=1 for more details\n",
      "/home/ea/work/my_optimum_intel/optimum_env/lib/python3.8/site-packages/diffusers/utils/outputs.py:63: UserWarning: torch.utils._pytree._register_pytree_node is deprecated. Please use torch.utils._pytree.register_pytree_node instead.\n",
      "  torch.utils._pytree._register_pytree_node(\n",
      "INFO:nncf:NNCF initialized successfully. Supported frameworks detected: torch, tensorflow, onnx, openvino\n",
      "2024-03-05 13:52:39.048911: I tensorflow/core/util/port.cc:110] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`.\n",
      "2024-03-05 13:52:39.050779: I tensorflow/tsl/cuda/cudart_stub.cc:28] Could not find cuda drivers on your machine, GPU will not be used.\n",
      "2024-03-05 13:52:39.088178: I tensorflow/tsl/cuda/cudart_stub.cc:28] Could not find cuda drivers on your machine, GPU will not be used.\n",
      "2024-03-05 13:52:39.088623: I tensorflow/core/platform/cpu_feature_guard.cc:182] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.\n",
      "To enable the following instructions: AVX2 AVX512F AVX512_VNNI FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.\n",
      "2024-03-05 13:52:39.754578: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT\n",
      "/home/ea/work/my_optimum_intel/optimum_env/lib/python3.8/site-packages/bitsandbytes/cextension.py:34: UserWarning: The installed version of bitsandbytes was compiled without GPU support. 8-bit optimizers, 8-bit multiplication, and GPU quantization are unavailable.\n",
      "  warn(\"The installed version of bitsandbytes was compiled without GPU support. \"\n",
      "/home/ea/work/my_optimum_intel/optimum_env/lib/python3.8/site-packages/bitsandbytes/libbitsandbytes_cpu.so: undefined symbol: cadam32bit_grad_fp32\n",
      "/home/ea/work/my_optimum_intel/optimum_env/lib/python3.8/site-packages/diffusers/utils/outputs.py:63: UserWarning: torch.utils._pytree._register_pytree_node is deprecated. Please use torch.utils._pytree.register_pytree_node instead.\n",
      "  torch.utils._pytree._register_pytree_node(\n",
      "[ INFO ] ==SUCCESS FOUND==: use_case: text_gen, model_type: stable-zephyr-3b-stateful\n",
      "[ INFO ] OV Config={'PERFORMANCE_HINT': 'LATENCY', 'CACHE_DIR': '', 'NUM_STREAMS': '1'}\n",
      "[ INFO ] OPENVINO_TORCH_BACKEND_DEVICE=CPU\n",
      "[ INFO ] Model path=stable-zephyr-3b-stateful/pytorch/dldt/compressed_weights/OV_FP16-4BIT_DEFAULT, openvino runtime version: 2024.1.0-14645-e6dc0865128\n",
      "Compiling the model to CPU ...\n",
      "[ INFO ] From pretrained time: 3.21s\n",
      "Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\n",
      "[ INFO ] Numbeams: 1, benchmarking iter nums(exclude warm-up): 0, prompt nums: 1\n",
      "[ INFO ] [warm-up] Input text: Tell me story about cats\n",
      "Setting `pad_token_id` to `eos_token_id`:0 for open-end generation.\n",
      "[ INFO ] [warm-up] Input token size: 5, Output size: 336, Infer count: 512, Tokenization Time: 2.23ms, Detokenization Time: 0.51ms, Generation Time: 23.79s, Latency: 70.80 ms/token\n",
      "[ INFO ] [warm-up] First token latency: 837.58 ms/token, other tokens latency: 68.43 ms/token, len of tokens: 336\n",
      "[ INFO ] [warm-up] First infer latency: 836.44 ms/infer, other infers latency: 67.89 ms/infer, inference count: 336\n",
      "[ INFO ] [warm-up] Result MD5:['601aa0958ff0e0f9b844a9e6d186fbd9']\n",
      "[ INFO ] [warm-up] Generated: Tell me story about cats and dogs.\n",
      "Once upon a time, in a small village, there lived a young girl named Lily. She had two pets, a cat named Mittens and a dog named Max. Mittens was a beautiful black cat with green eyes, and Max was a big lovable golden retriever with a wagging tail.\n",
      "One sunny day, Lily decided to take her pets for a walk in the nearby forest. As they were walking, they heard a loud barking sound. Suddenly, a group of dogs appeared from the bushes, led by a big brown dog with a friendly smile.\n",
      "Lily was scared at first, but Max quickly jumped in front of her and growled at the dogs. The big brown dog introduced himself as Rocky and explained that he and his friends were just out for a walk too.\n",
      "Lily and Rocky became fast friends, and they often went on walks together. Max and Rocky got along well too, and they would play together in the forest.\n",
      "One day, while Lily was at school, Mittens and Max decided to explore the forest and stumbled upon a group of stray cats. The cats were hungry and scared, so Mittens and Max decided to help them by giving them some food.\n",
      "The cats were grateful and thanked Mittens and Max for their kindness. They even allowed Mittens to climb on their backs and enjoy the sun.\n",
      "From that day on, Mittens and Max became known as the village's cat and dog heroes. They were always there to help their furry friends in need.\n",
      "And so, Lily learned that sometimes the best friends are the ones that share the same love for pets.<|endoftext|>\n"
     ]
    }
   ],
   "source": [
    "benchmark_script = genai_llm_bench / \"benchmark.py\"\n",
    "\n",
    "!python $benchmark_script -m $stateful_model_path -ic 512 -p \"Tell me story about cats\" -d $device.value"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "1ac23ffe-a3ef-4c81-b193-a51bf3e392b7",
   "metadata": {},
   "source": [
    "### Compare with model without state\n",
    "[back to top ⬆️](#Table-of-contents:)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "a586d0be-bb8e-449f-8dd5-61bc4f0a2e20",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:nncf:NNCF initialized successfully. Supported frameworks detected: torch, tensorflow, onnx, openvino\n",
      "2024-03-05 13:53:12.727472: I tensorflow/core/util/port.cc:110] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`.\n",
      "2024-03-05 13:53:12.729379: I tensorflow/tsl/cuda/cudart_stub.cc:28] Could not find cuda drivers on your machine, GPU will not be used.\n",
      "2024-03-05 13:53:12.765262: I tensorflow/tsl/cuda/cudart_stub.cc:28] Could not find cuda drivers on your machine, GPU will not be used.\n",
      "2024-03-05 13:53:12.765680: I tensorflow/core/platform/cpu_feature_guard.cc:182] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.\n",
      "To enable the following instructions: AVX2 AVX512F AVX512_VNNI FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.\n",
      "2024-03-05 13:53:13.414451: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT\n",
      "WARNING[XFORMERS]: xFormers can't load C++/CUDA extensions. xFormers was built for:\n",
      "    PyTorch 2.1.0+cu121 with CUDA 1201 (you have 2.2.0+cpu)\n",
      "    Python  3.8.18 (you have 3.8.10)\n",
      "  Please reinstall xformers (see https://github.com/facebookresearch/xformers#installing-xformers)\n",
      "  Memory-efficient attention, SwiGLU, sparse and more won't be available.\n",
      "  Set XFORMERS_MORE_DETAILS=1 for more details\n",
      "/home/ea/work/my_optimum_intel/optimum_env/lib/python3.8/site-packages/diffusers/utils/outputs.py:63: UserWarning: torch.utils._pytree._register_pytree_node is deprecated. Please use torch.utils._pytree.register_pytree_node instead.\n",
      "  torch.utils._pytree._register_pytree_node(\n",
      "WARNING:nncf:NNCF provides best results with torch==2.2.1, while current torch version is 2.2.0+cpu. If you encounter issues, consider switching to torch==2.2.1\n",
      "/home/ea/work/my_optimum_intel/optimum_env/lib/python3.8/site-packages/bitsandbytes/cextension.py:34: UserWarning: The installed version of bitsandbytes was compiled without GPU support. 8-bit optimizers, 8-bit multiplication, and GPU quantization are unavailable.\n",
      "  warn(\"The installed version of bitsandbytes was compiled without GPU support. \"\n",
      "/home/ea/work/my_optimum_intel/optimum_env/lib/python3.8/site-packages/bitsandbytes/libbitsandbytes_cpu.so: undefined symbol: cadam32bit_grad_fp32\n",
      "[ INFO ] openvino runtime version: 2024.1.0-14645-e6dc0865128\n",
      "Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\n",
      "Using the export variant default. Available variants are:\n",
      "    - default: The default ONNX variant.\n",
      "Using framework PyTorch: 2.2.0+cpu\n",
      "Overriding 1 configuration item(s)\n",
      "\t- use_cache -> True\n",
      "/home/ea/work/my_optimum_intel/optimum_env/lib/python3.8/site-packages/transformers/modeling_utils.py:4193: FutureWarning: `_is_quantized_training_enabled` is going to be deprecated in transformers 4.39.0. Please use `model.hf_quantizer.is_trainable` instead\n",
      "  warnings.warn(\n",
      "/home/ea/work/my_optimum_intel/optimum_env/lib/python3.8/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",
      "  if (input_shape[-1] > 1 or self.sliding_window is not None) and self.is_causal:\n",
      "/home/ea/work/my_optimum_intel/optimum_env/lib/python3.8/site-packages/optimum/exporters/onnx/model_patcher.py:299: 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",
      "  if past_key_values_length > 0:\n",
      "/home/ea/work/my_optimum_intel/optimum_env/lib/python3.8/site-packages/transformers/models/stablelm/modeling_stablelm.py:97: 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",
      "  if seq_len > self.max_seq_len_cached:\n",
      "/home/ea/work/my_optimum_intel/optimum_env/lib/python3.8/site-packages/transformers/models/stablelm/modeling_stablelm.py:341: 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",
      "  if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):\n",
      "/home/ea/work/my_optimum_intel/optimum_env/lib/python3.8/site-packages/transformers/models/stablelm/modeling_stablelm.py:348: 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",
      "  if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):\n",
      "/home/ea/work/my_optimum_intel/optimum_env/lib/python3.8/site-packages/transformers/models/stablelm/modeling_stablelm.py:360: 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",
      "  if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):\n",
      "[ INFO ] Compress model weights to 4BIT_DEFAULT\n",
      "[ INFO ] Compression options:\n",
      "[ INFO ] {'mode': <CompressWeightsMode.INT4_SYM: 'int4_sym'>, 'group_size': 128}\n",
      "INFO:nncf:Statistics of the bitwidth distribution:\n",
      "+--------------+---------------------------+-----------------------------------+\n",
      "| Num bits (N) | % all parameters (layers) |    % ratio-defining parameters    |\n",
      "|              |                           |             (layers)              |\n",
      "+==============+===========================+===================================+\n",
      "| 8            | 9% (2 / 226)              | 0% (0 / 224)                      |\n",
      "+--------------+---------------------------+-----------------------------------+\n",
      "| 4            | 91% (224 / 226)           | 100% (224 / 224)                  |\n",
      "+--------------+---------------------------+-----------------------------------+\n",
      "\u001b[2KApplying Weight Compression \u001b[38;2;114;156;31m━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[35m100%\u001b[0m \u001b[38;2;0;104;181m226/226\u001b[0m • \u001b[38;2;0;104;181m0:01:29\u001b[0m • \u001b[38;2;0;104;181m0:00:00\u001b[0m;0;104;181m0:00:01\u001b[0m181m0:00:05\u001b[0m\n",
      "\u001b[?25h"
     ]
    }
   ],
   "source": [
    "stateless_model_path = Path(\"stable-zephyr-3b-stateless/pytorch/dldt/compressed_weights/OV_FP16-4BIT_DEFAULT\")\n",
    "\n",
    "if not (stateless_model_path / \"openvino_model.xml\").exists():\n",
    "    !python $convert_script --model_id stabilityai/stable-zephyr-3b --precision FP16 --compress_weights 4BIT_DEFAULT --output stable-zephyr-3b-stateless --force_convert --disable-stateful"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "8c12bd81-b88e-426c-822b-01df7749abab",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "/home/ea/work/my_optimum_intel/optimum_env/lib/python3.8/site-packages/diffusers/utils/outputs.py:63: UserWarning: torch.utils._pytree._register_pytree_node is deprecated. Please use torch.utils._pytree.register_pytree_node instead.\n",
      "  torch.utils._pytree._register_pytree_node(\n",
      "WARNING[XFORMERS]: xFormers can't load C++/CUDA extensions. xFormers was built for:\n",
      "    PyTorch 2.1.0+cu121 with CUDA 1201 (you have 2.2.0+cpu)\n",
      "    Python  3.8.18 (you have 3.8.10)\n",
      "  Please reinstall xformers (see https://github.com/facebookresearch/xformers#installing-xformers)\n",
      "  Memory-efficient attention, SwiGLU, sparse and more won't be available.\n",
      "  Set XFORMERS_MORE_DETAILS=1 for more details\n",
      "/home/ea/work/my_optimum_intel/optimum_env/lib/python3.8/site-packages/diffusers/utils/outputs.py:63: UserWarning: torch.utils._pytree._register_pytree_node is deprecated. Please use torch.utils._pytree.register_pytree_node instead.\n",
      "  torch.utils._pytree._register_pytree_node(\n",
      "INFO:nncf:NNCF initialized successfully. Supported frameworks detected: torch, tensorflow, onnx, openvino\n",
      "2024-03-05 13:55:27.540258: I tensorflow/core/util/port.cc:110] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`.\n",
      "2024-03-05 13:55:27.542166: I tensorflow/tsl/cuda/cudart_stub.cc:28] Could not find cuda drivers on your machine, GPU will not be used.\n",
      "2024-03-05 13:55:27.578718: I tensorflow/tsl/cuda/cudart_stub.cc:28] Could not find cuda drivers on your machine, GPU will not be used.\n",
      "2024-03-05 13:55:27.579116: I tensorflow/core/platform/cpu_feature_guard.cc:182] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.\n",
      "To enable the following instructions: AVX2 AVX512F AVX512_VNNI FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.\n",
      "2024-03-05 13:55:28.229026: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT\n",
      "/home/ea/work/my_optimum_intel/optimum_env/lib/python3.8/site-packages/bitsandbytes/cextension.py:34: UserWarning: The installed version of bitsandbytes was compiled without GPU support. 8-bit optimizers, 8-bit multiplication, and GPU quantization are unavailable.\n",
      "  warn(\"The installed version of bitsandbytes was compiled without GPU support. \"\n",
      "/home/ea/work/my_optimum_intel/optimum_env/lib/python3.8/site-packages/bitsandbytes/libbitsandbytes_cpu.so: undefined symbol: cadam32bit_grad_fp32\n",
      "/home/ea/work/my_optimum_intel/optimum_env/lib/python3.8/site-packages/diffusers/utils/outputs.py:63: UserWarning: torch.utils._pytree._register_pytree_node is deprecated. Please use torch.utils._pytree.register_pytree_node instead.\n",
      "  torch.utils._pytree._register_pytree_node(\n",
      "[ INFO ] ==SUCCESS FOUND==: use_case: text_gen, model_type: stable-zephyr-3b-stateless\n",
      "[ INFO ] OV Config={'PERFORMANCE_HINT': 'LATENCY', 'CACHE_DIR': '', 'NUM_STREAMS': '1'}\n",
      "[ INFO ] OPENVINO_TORCH_BACKEND_DEVICE=CPU\n",
      "[ INFO ] Model path=stable-zephyr-3b-stateless/pytorch/dldt/compressed_weights/OV_FP16-4BIT_DEFAULT, openvino runtime version: 2024.1.0-14645-e6dc0865128\n",
      "Provided model does not contain state. It may lead to sub-optimal performance.Please reexport model with updated OpenVINO version >= 2023.3.0 calling the `from_pretrained` method with original model and `export=True` parameter\n",
      "Compiling the model to CPU ...\n",
      "[ INFO ] From pretrained time: 3.15s\n",
      "Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\n",
      "[ INFO ] Numbeams: 1, benchmarking iter nums(exclude warm-up): 0, prompt nums: 1\n",
      "[ INFO ] [warm-up] Input text: Tell me story about cats\n",
      "Setting `pad_token_id` to `eos_token_id`:0 for open-end generation.\n",
      "[ INFO ] [warm-up] Input token size: 5, Output size: 336, Infer count: 512, Tokenization Time: 2.02ms, Detokenization Time: 0.51ms, Generation Time: 18.59s, Latency: 55.32 ms/token\n",
      "[ INFO ] [warm-up] First token latency: 990.01 ms/token, other tokens latency: 52.47 ms/token, len of tokens: 336\n",
      "[ INFO ] [warm-up] First infer latency: 989.00 ms/infer, other infers latency: 51.98 ms/infer, inference count: 336\n",
      "[ INFO ] [warm-up] Result MD5:['601aa0958ff0e0f9b844a9e6d186fbd9']\n",
      "[ INFO ] [warm-up] Generated: Tell me story about cats and dogs.\n",
      "Once upon a time, in a small village, there lived a young girl named Lily. She had two pets, a cat named Mittens and a dog named Max. Mittens was a beautiful black cat with green eyes, and Max was a big lovable golden retriever with a wagging tail.\n",
      "One sunny day, Lily decided to take her pets for a walk in the nearby forest. As they were walking, they heard a loud barking sound. Suddenly, a group of dogs appeared from the bushes, led by a big brown dog with a friendly smile.\n",
      "Lily was scared at first, but Max quickly jumped in front of her and growled at the dogs. The big brown dog introduced himself as Rocky and explained that he and his friends were just out for a walk too.\n",
      "Lily and Rocky became fast friends, and they often went on walks together. Max and Rocky got along well too, and they would play together in the forest.\n",
      "One day, while Lily was at school, Mittens and Max decided to explore the forest and stumbled upon a group of stray cats. The cats were hungry and scared, so Mittens and Max decided to help them by giving them some food.\n",
      "The cats were grateful and thanked Mittens and Max for their kindness. They even allowed Mittens to climb on their backs and enjoy the sun.\n",
      "From that day on, Mittens and Max became known as the village's cat and dog heroes. They were always there to help their furry friends in need.\n",
      "And so, Lily learned that sometimes the best friends are the ones that share the same love for pets.<|endoftext|>\n"
     ]
    }
   ],
   "source": [
    "!python $benchmark_script -m $stateless_model_path -ic 512 -p \"Tell me story about cats\" -d $device.value"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "b32d0beb-b564-47f0-99f0-4e11e4a68678",
   "metadata": {},
   "source": [
    "## Using model with Optimum Intel\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Running model with Optimum-Intel API required following steps:\n",
    "1. register normalized config for model\n",
    "2. create instance of `OVModelForCausalLM` class using `from_pretrained` method.\n",
    "\n",
    "The model text generation interface remains without changes, the text generation process started with running `ov_model.generate` method and passing text encoded by the tokenizer as input. This method returns a sequence of generated token ids that should be decoded using a tokenizer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "433988ee-bda7-4224-9bf5-b013de4fcd65",
   "metadata": {},
   "outputs": [],
   "source": [
    "from optimum.intel.openvino import OVModelForCausalLM\n",
    "from transformers import AutoConfig\n",
    "\n",
    "ov_model = OVModelForCausalLM.from_pretrained(\n",
    "    stateful_model_path,\n",
    "    config=AutoConfig.from_pretrained(stateful_model_path, trust_remote_code=True),\n",
    "    device=device.value,\n",
    ")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "ef1e67fa-422c-4b7b-b3dd-cad81318b9b2",
   "metadata": {},
   "source": [
    "## Interactive chatbot demo\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Now, our model ready to use. Let's see it in action. We will use Gradio interface for interaction with model. Put text message into `Chat message box` and click `Submit` button for starting conversation.\n",
    "There are several parameters that can control text generation quality: \n",
    "  * `Temperature` is a parameter used to control the level of creativity in AI-generated text. By adjusting the `temperature`, you can influence the AI model's probability distribution, making the text more focused or diverse.  \n",
    "  Consider the following example: The AI model has to complete the sentence \"The cat is ____.\" with the following token probabilities:  \n",
    "\n",
    "    playing: 0.5  \n",
    "    sleeping: 0.25  \n",
    "    eating: 0.15  \n",
    "    driving: 0.05  \n",
    "    flying: 0.05  \n",
    "\n",
    "    - **Low temperature** (e.g., 0.2): The AI model becomes more focused and deterministic, choosing tokens with the highest probability, such as \"playing.\"  \n",
    "    - **Medium temperature** (e.g., 1.0): The AI model maintains a balance between creativity and focus, selecting tokens based on their probabilities without significant bias, such as \"playing,\" \"sleeping,\" or \"eating.\"  \n",
    "    - **High temperature** (e.g., 2.0): The AI model becomes more adventurous, increasing the chances of selecting less likely tokens, such as \"driving\" and \"flying.\"\n",
    "  * `Top-p`, also known as nucleus sampling, is a parameter used to control the range of tokens considered by the AI model based on their cumulative probability. By adjusting the `top-p` value, you can influence the AI model's token selection, making it more focused or diverse.\n",
    "  Using the same example with the cat, consider the following top_p settings:  \n",
    "    - **Low top_p** (e.g., 0.5): The AI model considers only tokens with the highest cumulative probability, such as \"playing.\"  \n",
    "    - **Medium top_p** (e.g., 0.8): The AI model considers tokens with a higher cumulative probability, such as \"playing,\" \"sleeping,\" and \"eating.\"  \n",
    "    - **High top_p** (e.g., 1.0): The AI model considers all tokens, including those with lower probabilities, such as \"driving\" and \"flying.\" \n",
    "  * `Top-k` is an 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",
    "  * `Repetition Penalty` This parameter can help penalize tokens based on how frequently they occur in the text, including the input prompt. A token that has already appeared five times is penalized more heavily than a token that has appeared only one time. A value of 1 means that there is no penalty and values larger than 1 discourage repeated tokens.\n",
    "\n",
    "You can modify them in `Advanced generation options` section."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b7f014a4-2b3b-41fc-aae1-b4b0729b978d",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "from threading import Event, Thread\n",
    "from uuid import uuid4\n",
    "from typing import List, Tuple\n",
    "import gradio as gr\n",
    "from transformers import (\n",
    "    AutoTokenizer,\n",
    "    StoppingCriteria,\n",
    "    StoppingCriteriaList,\n",
    "    TextIteratorStreamer,\n",
    ")\n",
    "\n",
    "model_name = \"stable-zephyr-3b\"\n",
    "\n",
    "tok = AutoTokenizer.from_pretrained(stateful_model_path)\n",
    "\n",
    "DEFAULT_SYSTEM_PROMPT = \"\"\"\\\n",

    "You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe.  Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.\n",

    "If a question does not make any sense or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.\\\n",

    "\"\"\"\n",
    "\n",
    "model_configuration = {\n",
    "    \"start_message\": f\"<|system|>\\n {DEFAULT_SYSTEM_PROMPT }<|endoftext|>\",\n",
    "    \"history_template\": \"<|user|>\\n{user}<|endoftext|><|assistant|>\\n{assistant}<|endoftext|>\",\n",
    "    \"current_message_template\": \"<|user|>\\n{user}<|endoftext|><|assistant|>\\n{assistant}\",\n",
    "}\n",
    "history_template = model_configuration[\"history_template\"]\n",
    "current_message_template = model_configuration[\"current_message_template\"]\n",
    "start_message = model_configuration[\"start_message\"]\n",
    "stop_tokens = model_configuration.get(\"stop_tokens\")\n",
    "tokenizer_kwargs = model_configuration.get(\"tokenizer_kwargs\", {})\n",
    "\n",
    "examples = [\n",
    "    [\"Hello there! How are you doing?\"],\n",
    "    [\"What is OpenVINO?\"],\n",
    "    [\"Who are you?\"],\n",
    "    [\"Can you explain to me briefly what is Python programming language?\"],\n",
    "    [\"Explain the plot of Cinderella in a sentence.\"],\n",
    "    [\"What are some common mistakes to avoid when writing code?\"],\n",
    "    [\"Write a 100-word blog post on “Benefits of Artificial Intelligence and OpenVINO“\"],\n",
    "]\n",
    "\n",
    "max_new_tokens = 256\n",
    "\n",
    "\n",
    "class StopOnTokens(StoppingCriteria):\n",
    "    def __init__(self, token_ids):\n",
    "        self.token_ids = token_ids\n",
    "\n",
    "    def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:\n",
    "        for stop_id in self.token_ids:\n",
    "            if input_ids[0][-1] == stop_id:\n",
    "                return True\n",
    "        return False\n",
    "\n",
    "\n",
    "if stop_tokens is not None:\n",
    "    if isinstance(stop_tokens[0], str):\n",
    "        stop_tokens = tok.convert_tokens_to_ids(stop_tokens)\n",
    "\n",
    "    stop_tokens = [StopOnTokens(stop_tokens)]\n",
    "\n",
    "\n",
    "def default_partial_text_processor(partial_text: str, new_text: str):\n",
    "    \"\"\"\n",

    "    helper for updating partially generated answer, used by de\n",

    "\n",

    "    Params:\n",

    "      partial_text: text buffer for storing previosly generated text\n",

    "      new_text: text update for the current step\n",

    "    Returns:\n",

    "      updated text string\n",

    "\n",

    "    \"\"\"\n",
    "    partial_text += new_text\n",
    "    return partial_text\n",
    "\n",
    "\n",
    "text_processor = model_configuration.get(\"partial_text_processor\", default_partial_text_processor)\n",
    "\n",
    "\n",
    "def convert_history_to_text(history: List[Tuple[str, str]]):\n",
    "    \"\"\"\n",

    "    function for conversion history stored as list pairs of user and assistant messages to string according to model expected conversation template\n",

    "    Params:\n",

    "      history: dialogue history\n",

    "    Returns:\n",

    "      history in text format\n",

    "    \"\"\"\n",
    "    text = start_message + \"\".join([\"\".join([history_template.format(num=round, user=item[0], assistant=item[1])]) for round, item in enumerate(history[:-1])])\n",
    "    text += \"\".join(\n",
    "        [\n",
    "            \"\".join(\n",
    "                [\n",
    "                    current_message_template.format(\n",
    "                        num=len(history) + 1,\n",
    "                        user=history[-1][0],\n",
    "                        assistant=history[-1][1],\n",
    "                    )\n",
    "                ]\n",
    "            )\n",
    "        ]\n",
    "    )\n",
    "    return text\n",
    "\n",
    "\n",
    "def user(message, history):\n",
    "    \"\"\"\n",

    "    callback function for updating user messages in interface on submit button click\n",

    "\n",

    "    Params:\n",

    "      message: current message\n",

    "      history: conversation history\n",

    "    Returns:\n",

    "      None\n",

    "    \"\"\"\n",
    "    # Append the user's message to the conversation history\n",
    "    return \"\", history + [[message, \"\"]]\n",
    "\n",
    "\n",
    "def bot(history, temperature, top_p, top_k, repetition_penalty, conversation_id):\n",
    "    \"\"\"\n",

    "    callback function for running chatbot on submit button click\n",

    "\n",

    "    Params:\n",

    "      history: conversation history\n",

    "      temperature:  parameter for control the level of creativity in AI-generated text.\n",

    "                    By adjusting the `temperature`, you can influence the AI model's probability distribution, making the text more focused or diverse.\n",

    "      top_p: parameter for control the range of tokens considered by the AI model based on their cumulative probability.\n",

    "      top_k: parameter for control the range of tokens considered by the AI model based on their cumulative probability, selecting number of tokens with highest probability.\n",

    "      repetition_penalty: parameter for penalizing tokens based on how frequently they occur in the text.\n",

    "      conversation_id: unique conversation identifier.\n",

    "\n",

    "    \"\"\"\n",

    "\n",

    "    # Construct the input message string for the model by concatenating the current system message and conversation history\n",

    "    messages = convert_history_to_text(history)\n",

    "\n",

    "    # Tokenize the messages string\n",

    "    input_ids = tok(messages, return_tensors=\"pt\", **tokenizer_kwargs).input_ids\n",

    "    if input_ids.shape[1] > 2000:\n",

    "        history = [history[-1]]\n",

    "        messages = convert_history_to_text(history)\n",

    "        input_ids = tok(messages, return_tensors=\"pt\", **tokenizer_kwargs).input_ids\n",

    "    streamer = TextIteratorStreamer(tok, timeout=30.0, skip_prompt=True, skip_special_tokens=True)\n",

    "    generate_kwargs = dict(\n",

    "        input_ids=input_ids,\n",

    "        max_new_tokens=max_new_tokens,\n",

    "        temperature=temperature,\n",

    "        do_sample=temperature > 0.0,\n",

    "        top_p=top_p,\n",

    "        top_k=top_k,\n",

    "        repetition_penalty=repetition_penalty,\n",

    "        streamer=streamer,\n",

    "    )\n",

    "    if stop_tokens is not None:\n",

    "        generate_kwargs[\"stopping_criteria\"] = StoppingCriteriaList(stop_tokens)\n",

    "\n",

    "    stream_complete = Event()\n",

    "\n",

    "    def generate_and_signal_complete():\n",

    "        \"\"\"\n",

    "        genration function for single thread\n",

    "        \"\"\"\n",

    "        global start_time\n",

    "        ov_model.generate(**generate_kwargs)\n",

    "        stream_complete.set()\n",

    "\n",

    "    t1 = Thread(target=generate_and_signal_complete)\n",

    "    t1.start()\n",

    "\n",

    "    # Initialize an empty string to store the generated text\n",

    "    partial_text = \"\"\n",

    "    for new_text in streamer:\n",

    "        partial_text = text_processor(partial_text, new_text)\n",

    "        history[-1][1] = partial_text\n",

    "        yield history\n",

    "\n",

    "\n",

    "def get_uuid():\n",

    "    \"\"\"\n",

    "    universal unique identifier for thread\n",

    "    \"\"\"\n",

    "    return str(uuid4())\n",

    "\n",

    "\n",

    "with gr.Blocks(\n",

    "    theme=gr.themes.Soft(),\n",

    "    css=\".disclaimer {font-variant-caps: all-small-caps;}\",\n",

    ") as demo:\n",

    "    conversation_id = gr.State(get_uuid)\n",

    "    gr.Markdown(f\"\"\"<h1><center>OpenVINO {model_name} Chatbot</center></h1>\"\"\")\n",

    "    chatbot = gr.Chatbot(height=500)\n",

    "    with gr.Row():\n",

    "        with gr.Column():\n",

    "            msg = gr.Textbox(\n",

    "                label=\"Chat Message Box\",\n",

    "                placeholder=\"Chat Message Box\",\n",

    "                show_label=False,\n",

    "                container=False,\n",

    "            )\n",

    "        with gr.Column():\n",

    "            with gr.Row():\n",

    "                submit = gr.Button(\"Submit\")\n",

    "                stop = gr.Button(\"Stop\")\n",

    "                clear = gr.Button(\"Clear\")\n",

    "    with gr.Row():\n",

    "        with gr.Accordion(\"Advanced Options:\", open=False):\n",

    "            with gr.Row():\n",

    "                with gr.Column():\n",

    "                    with gr.Row():\n",

    "                        temperature = gr.Slider(\n",

    "                            label=\"Temperature\",\n",

    "                            value=0.1,\n",

    "                            minimum=0.0,\n",

    "                            maximum=1.0,\n",

    "                            step=0.1,\n",

    "                            interactive=True,\n",

    "                            info=\"Higher values produce more diverse outputs\",\n",

    "                        )\n",

    "                with gr.Column():\n",

    "                    with gr.Row():\n",

    "                        top_p = gr.Slider(\n",

    "                            label=\"Top-p (nucleus sampling)\",\n",

    "                            value=1.0,\n",

    "                            minimum=0.0,\n",

    "                            maximum=1,\n",

    "                            step=0.01,\n",

    "                            interactive=True,\n",

    "                            info=(\n",

    "                                \"Sample from the smallest possible set of tokens whose cumulative probability \"\n",

    "                                \"exceeds top_p. Set to 1 to disable and sample from all tokens.\"\n",

    "                            ),\n",

    "                        )\n",

    "                with gr.Column():\n",

    "                    with gr.Row():\n",

    "                        top_k = gr.Slider(\n",

    "                            label=\"Top-k\",\n",

    "                            value=50,\n",

    "                            minimum=0.0,\n",

    "                            maximum=200,\n",

    "                            step=1,\n",

    "                            interactive=True,\n",

    "                            info=\"Sample from a shortlist of top-k tokens — 0 to disable and sample from all tokens.\",\n",

    "                        )\n",

    "                with gr.Column():\n",

    "                    with gr.Row():\n",

    "                        repetition_penalty = gr.Slider(\n",

    "                            label=\"Repetition Penalty\",\n",

    "                            value=1.1,\n",

    "                            minimum=1.0,\n",

    "                            maximum=2.0,\n",

    "                            step=0.1,\n",

    "                            interactive=True,\n",

    "                            info=\"Penalize repetition — 1.0 to disable.\",\n",

    "                        )\n",

    "    gr.Examples(examples, inputs=msg, label=\"Click on any example and press the 'Submit' button\")\n",

    "\n",

    "    submit_event = msg.submit(\n",

    "        fn=user,\n",

    "        inputs=[msg, chatbot],\n",

    "        outputs=[msg, chatbot],\n",

    "        queue=False,\n",

    "    ).then(\n",

    "        fn=bot,\n",

    "        inputs=[\n",

    "            chatbot,\n",

    "            temperature,\n",

    "            top_p,\n",

    "            top_k,\n",

    "            repetition_penalty,\n",

    "            conversation_id,\n",

    "        ],\n",

    "        outputs=chatbot,\n",

    "        queue=True,\n",

    "    )\n",

    "    submit_click_event = submit.click(\n",

    "        fn=user,\n",

    "        inputs=[msg, chatbot],\n",

    "        outputs=[msg, chatbot],\n",

    "        queue=False,\n",

    "    ).then(\n",

    "        fn=bot,\n",

    "        inputs=[\n",

    "            chatbot,\n",

    "            temperature,\n",

    "            top_p,\n",

    "            top_k,\n",

    "            repetition_penalty,\n",

    "            conversation_id,\n",

    "        ],\n",

    "        outputs=chatbot,\n",

    "        queue=True,\n",

    "    )\n",

    "    stop.click(\n",

    "        fn=None,\n",

    "        inputs=None,\n",

    "        outputs=None,\n",

    "        cancels=[submit_event, submit_click_event],\n",

    "        queue=False,\n",

    "    )\n",

    "    clear.click(lambda: None, None, chatbot, queue=False)\n",

    "\n",

    "demo.queue(max_size=2)\n",

    "# if you are launching remotely, specify server_name and server_port\n",

    "#  demo.launch(server_name='your server name', server_port='server port in int')\n",

    "# if you have any issue to launch on your platform, you can pass share=True to launch method:\n",

    "# demo.launch(share=True)\n",

    "# it creates a publicly shareable link for the interface. Read more in the docs: https://gradio.app/docs/\n",

    "demo.launch(share=True)"

   ]

  }

 ],

 "metadata": {

  "kernelspec": {

   "display_name": "Python 3 (ipykernel)",

   "language": "python",

   "name": "python3"

  },

  "language_info": {

   "codemirror_mode": {

    "name": "ipython",

    "version": 3

   },

   "file_extension": ".py",

   "mimetype": "text/x-python",

   "name": "python",

   "nbconvert_exporter": "python",

   "pygments_lexer": "ipython3",

   "version": "3.8.10"

  },

  "openvino_notebooks": {

   "imageUrl": "https://github.com/openvinotoolkit/openvino_notebooks/assets/29454499/cfac6ddb-6f22-4343-855c-e513269cf2bf",

   "tags": {

    "categories": [

     "Model Demos",

     "AI Trends"

    ],

    "libraries": [],

    "other": [

     "LLM"

    ],

    "tasks": [

     "Text Generation",

     "Conversational"

    ]

   }

  },

  "widgets": {

   "application/vnd.jupyter.widget-state+json": {

    "state": {},

    "version_major": 2,

    "version_minor": 0

   }

  }

 },

 "nbformat": 4,

 "nbformat_minor": 5

}