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