File size: 71,097 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
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
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e5501f221fd5d19f",
   "metadata": {},
   "source": [
    "# Text-to-Image Generation with Stable Diffusion v2 and OpenVINO™\n",
    "\n",
    "Stable Diffusion v2 is the next generation of Stable Diffusion model a Text-to-Image latent diffusion model created by the researchers and engineers from [Stability AI](https://stability.ai/) and [LAION](https://laion.ai/). \n",
    "\n",
    "General diffusion models are machine learning systems that are trained to denoise random gaussian noise step by step, to get to a sample of interest, such as an image.\n",
    "Diffusion models have shown to achieve state-of-the-art results for generating image data. But one downside of diffusion models is that the reverse denoising process is slow. In addition, these models consume a lot of memory because they operate in pixel space, which becomes unreasonably expensive when generating high-resolution images. Therefore, it is challenging to train these models and also use them for inference. OpenVINO brings capabilities to run model inference on Intel hardware and opens the door to the fantastic world of diffusion models for everyone!\n",
    "\n",
    "In previous notebooks, we already discussed how to run [Text-to-Image generation and Image-to-Image generation using Stable Diffusion v1](../stable-diffusion-text-to-image/stable-diffusion-text-to-image.ipynb) and [controlling its generation process using ControlNet](./controlnet-stable-diffusion/controlnet-stable-diffusion.ipynb). Now is turn of Stable Diffusion v2.\n",
    "\n",
    "## Stable Diffusion v2: What’s new?\n",
    "\n",
    "The new stable diffusion model offers a bunch of new features inspired by the other models that have emerged since the introduction of the first iteration. Some of the features that can be found in the new model are:\n",
    "\n",
    "* The model comes with a new robust encoder, OpenCLIP, created by LAION and aided by Stability AI; this version v2 significantly enhances the produced photos over the V1 versions. \n",
    "* The model can now generate images in a 768x768 resolution, offering more information to be shown in the generated images.\n",
    "* The model finetuned with [v-objective](https://arxiv.org/abs/2202.00512). The v-parameterization is particularly useful for numerical stability throughout the diffusion process to enable progressive distillation for models. For models that operate at higher resolution, it is also discovered that the v-parameterization avoids color shifting artifacts that are known to affect high resolution diffusion models, and in the video setting it avoids temporal color shifting that sometimes appears with epsilon-prediction used in Stable Diffusion v1. \n",
    "* The model also comes with a new diffusion model capable of running upscaling on the images generated. Upscaled images can be adjusted up to 4 times the original image. Provided as separated model, for more details please check [stable-diffusion-x4-upscaler](https://huggingface.co/stabilityai/stable-diffusion-x4-upscaler)\n",
    "* The model comes with a new refined depth architecture capable of preserving context from prior generation layers in an image-to-image setting. This structure preservation helps generate images that preserving forms and shadow of objects, but with different content.\n",
    "* The model comes with an updated inpainting module built upon the previous model. This text-guided inpainting makes switching out parts in the image easier than before.\n",
    "\n",
    "This notebook demonstrates how to convert and run Stable Diffusion v2 model using OpenVINO.\n",
    "\n",
    "Notebook contains the following steps:\n",
    "\n",
    "1. Create PyTorch models pipeline using Diffusers library.\n",
    "2. Convert PyTorch models to OpenVINO IR format, using model conversion API.\n",
    "3. Apply hybrid post-training quantization to UNet model with [NNCF](https://github.com/openvinotoolkit/nncf/).\n",
    "4. Run Stable Diffusion v2 Text-to-Image pipeline with OpenVINO.\n",
    "\n",
    "**Note:** This is the full version of the Stable Diffusion text-to-image implementation. If you would like to get started and run the notebook quickly, check out [stable-diffusion-v2-text-to-image-demo notebook](../stable-diffusion-v2/stable-diffusion-v2-text-to-image-demo.ipynb).\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e2bceddde9f8d526",
   "metadata": {},
   "source": [
    "#### Table of contents:\n",
    "\n",
    "- [Prerequisites](#Prerequisites)\n",
    "- [Stable Diffusion v2 for Text-to-Image Generation](#Stable-Diffusion-v2-for-Text-to-Image-Generation)\n",
    "    - [Stable Diffusion in Diffusers library](#Stable-Diffusion-in-Diffusers-library)\n",
    "    - [Convert models to OpenVINO Intermediate representation (IR) format](#Convert-models-to-OpenVINO-Intermediate-representation-(IR)-format)\n",
    "    - [Text Encoder](#Text-Encoder)\n",
    "    - [U-Net](#U-Net)\n",
    "    - [VAE](#VAE)\n",
    "    - [Prepare Inference Pipeline](#Prepare-Inference-Pipeline)\n",
    "    - [Configure Inference Pipeline](#Configure-Inference-Pipeline)\n",
    "- [Quantization](#Quantization)\n",
    "    - [Prepare calibration dataset](#Prepare-calibration-dataset)\n",
    "    - [Run Hybrid Model Quantization](#Run-Hybrid-Model-Quantization)\n",
    "    - [Compare inference time of the FP16 and INT8 pipelines](#Compare-inference-time-of-the-FP16-and-INT8-pipelines)\n",
    "- [Run Text-to-Image generation](#Run-Text-to-Image-generation)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1a571d16e81bf3c4",
   "metadata": {},
   "source": [
    "## Prerequisites\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "install required packages"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "6723fa8e346926b7",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-02-13T13:29:10.765014Z",
     "start_time": "2024-02-13T13:29:08.472566Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    }
   ],
   "source": [
    "%pip install -q \"diffusers>=0.14.0\" \"openvino>=2023.1.0\" \"datasets>=2.14.6\" \"transformers>=4.25.1\" \"gradio>=4.19\" \"torch>=2.1\" Pillow opencv-python --extra-index-url https://download.pytorch.org/whl/cpu\n",
    "%pip install -q \"nncf>=2.9.0\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3c4a678aa7817277",
   "metadata": {},
   "source": [
    "## Stable Diffusion v2 for Text-to-Image Generation\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "To start, let's look on Text-to-Image process for Stable Diffusion v2. We will use [Stable Diffusion v2-1](https://huggingface.co/stabilityai/stable-diffusion-2-1) model for these purposes. The main difference from Stable Diffusion v2 and Stable Diffusion v2.1 is usage of more data, more training, and less restrictive filtering of the dataset, that gives promising results for selecting wide range of input text prompts. More details about model can be found in [Stability AI blog post](https://stability.ai/blog/stablediffusion2-1-release7-dec-2022) and original model [repository](https://github.com/Stability-AI/stablediffusion).\n",
    "\n",
    "### Stable Diffusion in Diffusers library\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "To work with Stable Diffusion v2, we will use Hugging Face [Diffusers](https://github.com/huggingface/diffusers) library. To experiment with Stable Diffusion models, Diffusers exposes the [`StableDiffusionPipeline`](https://huggingface.co/docs/diffusers/using-diffusers/conditional_image_generation) similar to the [other Diffusers pipelines](https://huggingface.co/docs/diffusers/api/pipelines/overview).  The code below demonstrates how to create `StableDiffusionPipeline` using `stable-diffusion-2-1`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "d277beedf7e92c43",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-02-13T13:29:13.431319Z",
     "start_time": "2024-02-13T13:29:10.766275Z"
    }
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "35c151ae50214855ac10300a2e2bb495",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Loading pipeline components...:   0%|          | 0/6 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from diffusers import StableDiffusionPipeline\n",
    "\n",
    "pipe = StableDiffusionPipeline.from_pretrained(\"stabilityai/stable-diffusion-2-1-base\").to(\"cpu\")\n",
    "\n",
    "# for reducing memory consumption get all components from pipeline independently\n",
    "text_encoder = pipe.text_encoder\n",
    "text_encoder.eval()\n",
    "unet = pipe.unet\n",
    "unet.eval()\n",
    "vae = pipe.vae\n",
    "vae.eval()\n",
    "\n",
    "conf = pipe.scheduler.config\n",
    "\n",
    "del pipe"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a636f5007c3781e",
   "metadata": {},
   "source": [
    "### Convert models to OpenVINO Intermediate representation (IR) format\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Starting from 2023.0 release, OpenVINO supports PyTorch models directly via Model Conversion API. `ov.convert_model` function accepts instance of PyTorch model and example inputs for tracing and returns object of `ov.Model` class, ready to use or save on disk using `ov.save_model` function. \n",
    "\n",
    "\n",
    "The pipeline consists of three important parts:\n",
    "\n",
    "* Text Encoder to create condition to generate an image from a text prompt.\n",
    "* U-Net for step-by-step denoising latent image representation.\n",
    "* Autoencoder (VAE) for decoding latent space to image.\n",
    "\n",
    "Let us convert each part:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d4f14633b43a9034",
   "metadata": {},
   "source": [
    "### Text Encoder\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "The text-encoder is responsible for transforming the input prompt, for example, \"a photo of an astronaut riding a horse\" into an embedding space that can be understood by the U-Net. It is usually a simple transformer-based encoder that maps a sequence of input tokens to a sequence of latent text embeddings.\n",
    "\n",
    "The input of the text encoder is tensor `input_ids`, which contains indexes of tokens from text processed by the tokenizer and padded to the maximum length accepted by the model. Model outputs are two tensors: `last_hidden_state` - hidden state from the last MultiHeadAttention layer in the model and `pooler_out` - pooled output for whole model hidden states."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "3fd5f7ff0751a146",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-02-13T13:29:13.434571Z",
     "start_time": "2024-02-13T13:29:13.432325Z"
    }
   },
   "outputs": [],
   "source": [
    "from pathlib import Path\n",
    "\n",
    "sd2_1_model_dir = Path(\"sd2.1\")\n",
    "sd2_1_model_dir.mkdir(exist_ok=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "19a36c5ca10a998a",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-02-13T13:29:20.605486Z",
     "start_time": "2024-02-13T13:29:13.435752Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Text encoder will be loaded from sd2.1/text_encoder.xml\n"
     ]
    }
   ],
   "source": [
    "import gc\n",
    "import torch\n",
    "import openvino as ov\n",
    "\n",
    "TEXT_ENCODER_OV_PATH = sd2_1_model_dir / \"text_encoder.xml\"\n",
    "\n",
    "\n",
    "def cleanup_torchscript_cache():\n",
    "    \"\"\"\n",

    "    Helper for removing cached model representation\n",

    "    \"\"\"\n",
    "    torch._C._jit_clear_class_registry()\n",
    "    torch.jit._recursive.concrete_type_store = torch.jit._recursive.ConcreteTypeStore()\n",
    "    torch.jit._state._clear_class_state()\n",
    "\n",
    "\n",
    "def convert_encoder(text_encoder: torch.nn.Module, ir_path: Path):\n",
    "    \"\"\"\n",

    "    Convert Text Encoder model to IR.\n",

    "    Function accepts pipeline, prepares example inputs for conversion\n",

    "    Parameters:\n",

    "        text_encoder (torch.nn.Module): text encoder PyTorch model\n",

    "        ir_path (Path): File for storing model\n",

    "    Returns:\n",

    "        None\n",

    "    \"\"\"\n",
    "    if not ir_path.exists():\n",
    "        input_ids = torch.ones((1, 77), dtype=torch.long)\n",
    "        # switch model to inference mode\n",
    "        text_encoder.eval()\n",
    "\n",
    "        # disable gradients calculation for reducing memory consumption\n",
    "        with torch.no_grad():\n",
    "            # export model\n",
    "            ov_model = ov.convert_model(\n",
    "                text_encoder,  # model instance\n",
    "                example_input=input_ids,  # example inputs for model tracing\n",
    "                input=([1, 77],),  # input shape for conversion\n",
    "            )\n",
    "            ov.save_model(ov_model, ir_path)\n",
    "            del ov_model\n",
    "            cleanup_torchscript_cache()\n",
    "        print(\"Text Encoder successfully converted to IR\")\n",
    "\n",
    "\n",
    "if not TEXT_ENCODER_OV_PATH.exists():\n",
    "    convert_encoder(text_encoder, TEXT_ENCODER_OV_PATH)\n",
    "else:\n",
    "    print(f\"Text encoder will be loaded from {TEXT_ENCODER_OV_PATH}\")\n",
    "\n",
    "del text_encoder\n",
    "gc.collect();"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ccaba8325efa1177",
   "metadata": {},
   "source": [
    "### U-Net\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "U-Net model gradually denoises latent image representation guided by text encoder hidden state.\n",
    "\n",
    "U-Net model has three inputs:\n",
    "\n",
    "* `sample` - latent image sample from previous step. Generation process has not been started yet, so you will use random noise.\n",
    "* `timestep` - current scheduler step.\n",
    "* `encoder_hidden_state` - hidden state of text encoder.\n",
    "\n",
    "Model predicts the `sample` state for the next step.\n",
    "\n",
    "Generally, U-Net model conversion process remain the same like in Stable Diffusion v1, expect small changes in input sample size.  Our model was pretrained to generate images with resolution 768x768, initial latent sample size for this case is 96x96. Besides that, for different use cases like inpainting and depth to image generation model also can accept additional image information: depth map or mask as channel-wise concatenation with initial latent sample. For converting U-Net model for such use cases required to modify number of input channels."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "dbf8ba161bad414",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-02-13T13:29:44.429898Z",
     "start_time": "2024-02-13T13:29:20.606525Z"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "UNET_OV_PATH = sd2_1_model_dir / \"unet.xml\"\n",
    "\n",
    "\n",
    "def convert_unet(\n",
    "    unet: torch.nn.Module,\n",
    "    ir_path: Path,\n",
    "    num_channels: int = 4,\n",
    "    width: int = 64,\n",
    "    height: int = 64,\n",
    "):\n",
    "    \"\"\"\n",

    "    Convert Unet model to IR format.\n",

    "    Function accepts pipeline, prepares example inputs for conversion\n",

    "    Parameters:\n",

    "        unet (torch.nn.Module): UNet PyTorch model\n",

    "        ir_path (Path): File for storing model\n",

    "        num_channels (int, optional, 4): number of input channels\n",

    "        width (int, optional, 64): input width\n",

    "        height (int, optional, 64): input height\n",

    "    Returns:\n",

    "        None\n",

    "    \"\"\"\n",
    "    dtype_mapping = {torch.float32: ov.Type.f32, torch.float64: ov.Type.f64}\n",
    "    if not ir_path.exists():\n",
    "        # prepare inputs\n",
    "        encoder_hidden_state = torch.ones((2, 77, 1024))\n",
    "        latents_shape = (2, num_channels, width, height)\n",
    "        latents = torch.randn(latents_shape)\n",
    "        t = torch.from_numpy(np.array(1, dtype=np.float32))\n",
    "        unet.eval()\n",
    "        dummy_inputs = (latents, t, encoder_hidden_state)\n",
    "        input_info = []\n",
    "        for input_tensor in dummy_inputs:\n",
    "            shape = ov.PartialShape(tuple(input_tensor.shape))\n",
    "            element_type = dtype_mapping[input_tensor.dtype]\n",
    "            input_info.append((shape, element_type))\n",
    "\n",
    "        with torch.no_grad():\n",
    "            ov_model = ov.convert_model(unet, example_input=dummy_inputs, input=input_info)\n",
    "        ov.save_model(ov_model, ir_path)\n",
    "        del ov_model\n",
    "        cleanup_torchscript_cache()\n",
    "        print(\"U-Net successfully converted to IR\")\n",
    "\n",
    "\n",
    "if not UNET_OV_PATH.exists():\n",
    "    convert_unet(unet, UNET_OV_PATH, width=96, height=96)\n",
    "    del unet\n",
    "    gc.collect()\n",
    "else:\n",
    "    del unet\n",
    "gc.collect();"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e52e6090fd6a87b3",
   "metadata": {},
   "source": [
    "### VAE\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "The VAE model has two parts, an encoder and a decoder. The encoder is used to convert the image into a low dimensional latent representation, which will serve as the input to the U-Net model. The decoder, conversely, transforms the latent representation back into an image.\n",
    "\n",
    "During latent diffusion training, the encoder is used to get the latent representations (latents) of the images for the forward diffusion process, which applies more and more noise at each step. During inference, the denoised latents generated by the reverse diffusion process are converted back into images using the VAE decoder. When you run inference for Text-to-Image, there is no initial image as a starting point. You can skip this step and directly generate initial random noise.\n",
    "\n",
    "When running Text-to-Image pipeline, we will see that we **only need the VAE decoder**, but preserve VAE encoder conversion, it will be useful in next chapter of our tutorial. \n",
    "\n",
    "Note: This process will take a few minutes and use significant amount of RAM (recommended at least 32GB)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "442461d2f19e8c99",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-02-13T13:30:16.030912Z",
     "start_time": "2024-02-13T13:29:44.431075Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "VAE encoder will be loaded from sd2.1/vae_encoder.xml\n",
      "VAE decoder will be loaded from sd2.1/vae_decoder.xml\n"
     ]
    }
   ],
   "source": [
    "VAE_ENCODER_OV_PATH = sd2_1_model_dir / \"vae_encoder.xml\"\n",
    "\n",
    "\n",
    "def convert_vae_encoder(vae: torch.nn.Module, ir_path: Path, width: int = 512, height: int = 512):\n",
    "    \"\"\"\n",

    "    Convert VAE model to IR format.\n",

    "    VAE model, creates wrapper class for export only necessary for inference part,\n",

    "    prepares example inputs for onversion\n",

    "    Parameters:\n",

    "        vae (torch.nn.Module): VAE PyTorch model\n",

    "        ir_path (Path): File for storing model\n",

    "        width (int, optional, 512): input width\n",

    "        height (int, optional, 512): input height\n",

    "    Returns:\n",

    "        None\n",

    "    \"\"\"\n",
    "\n",
    "    class VAEEncoderWrapper(torch.nn.Module):\n",
    "        def __init__(self, vae):\n",
    "            super().__init__()\n",
    "            self.vae = vae\n",
    "\n",
    "        def forward(self, image):\n",
    "            return self.vae.encode(x=image)[\"latent_dist\"].sample()\n",
    "\n",
    "    if not ir_path.exists():\n",
    "        vae_encoder = VAEEncoderWrapper(vae)\n",
    "        vae_encoder.eval()\n",
    "        image = torch.zeros((1, 3, width, height))\n",
    "        with torch.no_grad():\n",
    "            ov_model = ov.convert_model(vae_encoder, example_input=image, input=([1, 3, width, height],))\n",
    "        ov.save_model(ov_model, ir_path)\n",
    "        del ov_model\n",
    "        cleanup_torchscript_cache()\n",
    "        print(\"VAE encoder successfully converted to IR\")\n",
    "\n",
    "\n",
    "def convert_vae_decoder(vae: torch.nn.Module, ir_path: Path, width: int = 64, height: int = 64):\n",
    "    \"\"\"\n",

    "    Convert VAE decoder model to IR format.\n",

    "    Function accepts VAE model, creates wrapper class for export only necessary for inference part,\n",

    "    prepares example inputs for conversion\n",

    "    Parameters:\n",

    "        vae (torch.nn.Module): VAE model\n",

    "        ir_path (Path): File for storing model\n",

    "        width (int, optional, 64): input width\n",

    "        height (int, optional, 64): input height\n",

    "    Returns:\n",

    "        None\n",

    "    \"\"\"\n",
    "\n",
    "    class VAEDecoderWrapper(torch.nn.Module):\n",
    "        def __init__(self, vae):\n",
    "            super().__init__()\n",
    "            self.vae = vae\n",
    "\n",
    "        def forward(self, latents):\n",
    "            return self.vae.decode(latents)\n",
    "\n",
    "    if not ir_path.exists():\n",
    "        vae_decoder = VAEDecoderWrapper(vae)\n",
    "        latents = torch.zeros((1, 4, width, height))\n",
    "\n",
    "        vae_decoder.eval()\n",
    "        with torch.no_grad():\n",
    "            ov_model = ov.convert_model(vae_decoder, example_input=latents, input=([1, 4, width, height],))\n",
    "        ov.save_model(ov_model, ir_path)\n",
    "        del ov_model\n",
    "        cleanup_torchscript_cache()\n",
    "        print(\"VAE decoder successfully converted to IR\")\n",
    "\n",
    "\n",
    "if not VAE_ENCODER_OV_PATH.exists():\n",
    "    convert_vae_encoder(vae, VAE_ENCODER_OV_PATH, 768, 768)\n",
    "else:\n",
    "    print(f\"VAE encoder will be loaded from {VAE_ENCODER_OV_PATH}\")\n",
    "\n",
    "VAE_DECODER_OV_PATH = sd2_1_model_dir / \"vae_decoder.xml\"\n",
    "\n",
    "if not VAE_DECODER_OV_PATH.exists():\n",
    "    convert_vae_decoder(vae, VAE_DECODER_OV_PATH, 96, 96)\n",
    "else:\n",
    "    print(f\"VAE decoder will be loaded from {VAE_DECODER_OV_PATH}\")\n",
    "\n",
    "del vae\n",
    "gc.collect();"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2009916bbc6c3ec8",
   "metadata": {},
   "source": [
    "### Prepare Inference Pipeline\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Putting it all together, let us now take a closer look at how the model works in inference by illustrating the logical flow.\n",
    "\n",
    "![text2img-stable-diffusion v2](https://github.com/openvinotoolkit/openvino_notebooks/assets/22090501/ec454103-0d28-48e3-a18e-b55da3fab381)\n",
    "\n",
    "The stable diffusion model takes both a latent seed and a text prompt as input. The latent seed is then used to generate random latent image representations of size $96 \\times 96$ where as the text prompt is transformed to text embeddings of size $77 \\times 1024$ via OpenCLIP's text encoder.\n",
    "\n",
    "Next, the U-Net iteratively *denoises* the random latent image representations while being conditioned on the text embeddings. The output of the U-Net, being the noise residual, is used to compute a denoised latent image representation via a scheduler algorithm. Many different scheduler algorithms can be used for this computation, each having its pros and cons. For Stable Diffusion, it is recommended to use one of:\n",
    "\n",
    "- [PNDM scheduler](https://github.com/huggingface/diffusers/blob/main/src/diffusers/schedulers/scheduling_pndm.py)\n",
    "- [DDIM scheduler](https://github.com/huggingface/diffusers/blob/main/src/diffusers/schedulers/scheduling_ddim.py)\n",
    "- [K-LMS scheduler](https://github.com/huggingface/diffusers/blob/main/src/diffusers/schedulers/scheduling_lms_discrete.py)\n",
    "\n",
    "Theory on how the scheduler algorithm function works is out of scope for this notebook, but in short, you should remember that they compute the predicted denoised image representation from the previous noise representation and the predicted noise residual.\n",
    "For more information, it is recommended to look into [Elucidating the Design Space of Diffusion-Based Generative Models](https://arxiv.org/abs/2206.00364).\n",
    "\n",
    "\n",
    "The chart above looks very similar to Stable Diffusion V1 from [notebook](../stable-diffusion-text-to-image/stable-diffusion-text-to-image.ipynb), but there is some small difference in details:\n",
    "\n",
    "* Changed input resolution for U-Net model.\n",
    "* Changed text encoder and as the result size of its hidden state embeddings.\n",
    "* Additionally, to improve image generation quality authors introduced negative prompting. Technically, positive prompt steers the diffusion toward the images associated with it, while negative prompt steers the diffusion away from it.In other words, negative prompt declares undesired concepts for generation image, e.g. if we want to have colorful and bright image, gray scale image will be result which we want to avoid, in this case gray scale can be treated as negative prompt. The positive and negative prompt are in equal footing. You can always use one with or without the other. More explanation of how it works can be found in this [article](https://stable-diffusion-art.com/how-negative-prompt-work/). "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "ba60aaf6be593f39",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-02-13T13:30:16.082794Z",
     "start_time": "2024-02-13T13:30:16.032084Z"
    }
   },
   "outputs": [],
   "source": [
    "import inspect\n",
    "from typing import List, Optional, Union, Dict\n",
    "\n",
    "import PIL\n",
    "import cv2\n",
    "import torch\n",
    "\n",
    "from transformers import CLIPTokenizer\n",
    "from diffusers import DiffusionPipeline\n",
    "from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler\n",
    "\n",
    "\n",
    "def scale_fit_to_window(dst_width: int, dst_height: int, image_width: int, image_height: int):\n",
    "    \"\"\"\n",

    "    Preprocessing helper function for calculating image size for resize with peserving original aspect ratio\n",

    "    and fitting image to specific window size\n",

    "\n",

    "    Parameters:\n",

    "      dst_width (int): destination window width\n",

    "      dst_height (int): destination window height\n",

    "      image_width (int): source image width\n",

    "      image_height (int): source image height\n",

    "    Returns:\n",

    "      result_width (int): calculated width for resize\n",

    "      result_height (int): calculated height for resize\n",

    "    \"\"\"\n",
    "    im_scale = min(dst_height / image_height, dst_width / image_width)\n",
    "    return int(im_scale * image_width), int(im_scale * image_height)\n",
    "\n",
    "\n",
    "def preprocess(image: PIL.Image.Image):\n",
    "    \"\"\"\n",

    "    Image preprocessing function. Takes image in PIL.Image format, resizes it to keep aspect ration and fits to model input window 512x512,\n",

    "    then converts it to np.ndarray and adds padding with zeros on right or bottom side of image (depends from aspect ratio), after that\n",

    "    converts data to float32 data type and change range of values from [0, 255] to [-1, 1], finally, converts data layout from planar NHWC to NCHW.\n",

    "    The function returns preprocessed input tensor and padding size, which can be used in postprocessing.\n",

    "\n",

    "    Parameters:\n",

    "      image (PIL.Image.Image): input image\n",

    "    Returns:\n",

    "       image (np.ndarray): preprocessed image tensor\n",

    "       meta (Dict): dictionary with preprocessing metadata info\n",

    "    \"\"\"\n",
    "    src_width, src_height = image.size\n",
    "    dst_width, dst_height = scale_fit_to_window(512, 512, src_width, src_height)\n",
    "    image = np.array(image.resize((dst_width, dst_height), resample=PIL.Image.Resampling.LANCZOS))[None, :]\n",
    "    pad_width = 512 - dst_width\n",
    "    pad_height = 512 - dst_height\n",
    "    pad = ((0, 0), (0, pad_height), (0, pad_width), (0, 0))\n",
    "    image = np.pad(image, pad, mode=\"constant\")\n",
    "    image = image.astype(np.float32) / 255.0\n",
    "    image = 2.0 * image - 1.0\n",
    "    image = image.transpose(0, 3, 1, 2)\n",
    "    return image, {\"padding\": pad, \"src_width\": src_width, \"src_height\": src_height}\n",
    "\n",
    "\n",
    "class OVStableDiffusionPipeline(DiffusionPipeline):\n",
    "    def __init__(\n",
    "        self,\n",
    "        vae_decoder: ov.Model,\n",
    "        text_encoder: ov.Model,\n",
    "        tokenizer: CLIPTokenizer,\n",
    "        unet: ov.Model,\n",
    "        scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],\n",
    "        vae_encoder: ov.Model = None,\n",
    "    ):\n",
    "        \"\"\"\n",

    "        Pipeline for text-to-image generation using Stable Diffusion.\n",

    "        Parameters:\n",

    "            vae_decoder (Model):\n",

    "                Variational Auto-Encoder (VAE) Model to decode images to and from latent representations.\n",

    "            text_encoder (Model):\n",

    "                Frozen text-encoder. Stable Diffusion uses the text portion of\n",

    "                [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically\n",

    "                the clip-vit-large-patch14(https://huggingface.co/openai/clip-vit-large-patch14) variant.\n",

    "            tokenizer (CLIPTokenizer):\n",

    "                Tokenizer of class CLIPTokenizer(https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).\n",

    "            unet (Model): Conditional U-Net architecture to denoise the encoded image latents.\n",

    "            vae_encoder (Model):\n",

    "                Variational Auto-Encoder (VAE) Model to encode images to latent representation.\n",

    "            scheduler (SchedulerMixin):\n",

    "                A scheduler to be used in combination with unet to denoise the encoded image latents. Can be one of\n",

    "                DDIMScheduler, LMSDiscreteScheduler, or PNDMScheduler.\n",

    "        \"\"\"\n",
    "        super().__init__()\n",
    "        self.scheduler = scheduler\n",
    "        self.vae_decoder = vae_decoder\n",
    "        self.vae_encoder = vae_encoder\n",
    "        self.text_encoder = text_encoder\n",
    "        self.unet = unet\n",
    "        self.register_to_config(unet=unet)\n",
    "        self._text_encoder_output = text_encoder.output(0)\n",
    "        self._unet_output = unet.output(0)\n",
    "        self._vae_d_output = vae_decoder.output(0)\n",
    "        self._vae_e_output = vae_encoder.output(0) if vae_encoder is not None else None\n",
    "        self.height = self.unet.input(0).shape[2] * 8\n",
    "        self.width = self.unet.input(0).shape[3] * 8\n",
    "        self.tokenizer = tokenizer\n",
    "\n",
    "    def __call__(\n",
    "        self,\n",
    "        prompt: Union[str, List[str]],\n",
    "        image: PIL.Image.Image = None,\n",
    "        negative_prompt: Union[str, List[str]] = None,\n",
    "        num_inference_steps: Optional[int] = 50,\n",
    "        guidance_scale: Optional[float] = 7.5,\n",
    "        eta: Optional[float] = 0.0,\n",
    "        output_type: Optional[str] = \"pil\",\n",
    "        seed: Optional[int] = None,\n",
    "        strength: float = 1.0,\n",
    "    ):\n",
    "        \"\"\"\n",

    "        Function invoked when calling the pipeline for generation.\n",

    "        Parameters:\n",

    "            prompt (str or List[str]):\n",

    "                The prompt or prompts to guide the image generation.\n",

    "            image (PIL.Image.Image, *optional*, None):\n",

    "                 Intinal image for generation.\n",

    "            negative_prompt (str or List[str]):\n",

    "                The negative prompt or prompts to guide the image generation.\n",

    "            num_inference_steps (int, *optional*, defaults to 50):\n",

    "                The number of denoising steps. More denoising steps usually lead to a higher quality image at the\n",

    "                expense of slower inference.\n",

    "            guidance_scale (float, *optional*, defaults to 7.5):\n",

    "                Guidance scale as defined in Classifier-Free Diffusion Guidance(https://arxiv.org/abs/2207.12598).\n",

    "                guidance_scale is defined as `w` of equation 2.\n",

    "                Higher guidance scale encourages to generate images that are closely linked to the text prompt,\n",

    "                usually at the expense of lower image quality.\n",

    "            eta (float, *optional*, defaults to 0.0):\n",

    "                Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to\n",

    "                [DDIMScheduler], will be ignored for others.\n",

    "            output_type (`str`, *optional*, defaults to \"pil\"):\n",

    "                The output format of the generate image. Choose between\n",

    "                [PIL](https://pillow.readthedocs.io/en/stable/): PIL.Image.Image or np.array.\n",

    "            seed (int, *optional*, None):\n",

    "                Seed for random generator state initialization.\n",

    "            strength (int, *optional*, 1.0):\n",

    "                strength between initial image and generated in Image-to-Image pipeline, do not used in Text-to-Image\n",

    "        Returns:\n",

    "            Dictionary with keys:\n",

    "                sample - the last generated image PIL.Image.Image or np.array\n",

    "        \"\"\"\n",
    "        if seed is not None:\n",
    "            np.random.seed(seed)\n",
    "        # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)\n",
    "        # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`\n",
    "        # corresponds to doing no classifier free guidance.\n",
    "        do_classifier_free_guidance = guidance_scale > 1.0\n",
    "        # get prompt text embeddings\n",
    "        text_embeddings = self._encode_prompt(\n",
    "            prompt,\n",
    "            do_classifier_free_guidance=do_classifier_free_guidance,\n",
    "            negative_prompt=negative_prompt,\n",
    "        )\n",
    "        # set timesteps\n",
    "        accepts_offset = \"offset\" in set(inspect.signature(self.scheduler.set_timesteps).parameters.keys())\n",
    "        extra_set_kwargs = {}\n",
    "        if accepts_offset:\n",
    "            extra_set_kwargs[\"offset\"] = 1\n",
    "\n",
    "        self.scheduler.set_timesteps(num_inference_steps, **extra_set_kwargs)\n",
    "        timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength)\n",
    "        latent_timestep = timesteps[:1]\n",
    "\n",
    "        # get the initial random noise unless the user supplied it\n",
    "        latents, meta = self.prepare_latents(image, latent_timestep)\n",
    "\n",
    "        # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature\n",
    "        # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.\n",
    "        # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502\n",
    "        # and should be between [0, 1]\n",
    "        accepts_eta = \"eta\" in set(inspect.signature(self.scheduler.step).parameters.keys())\n",
    "        extra_step_kwargs = {}\n",
    "        if accepts_eta:\n",
    "            extra_step_kwargs[\"eta\"] = eta\n",
    "\n",
    "        for t in self.progress_bar(timesteps):\n",
    "            # expand the latents if we are doing classifier free guidance\n",
    "            latent_model_input = np.concatenate([latents] * 2) if do_classifier_free_guidance else latents\n",
    "            latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)\n",
    "\n",
    "            # predict the noise residual\n",
    "            noise_pred = self.unet([latent_model_input, np.array(t, dtype=np.float32), text_embeddings])[self._unet_output]\n",
    "            # perform guidance\n",
    "            if do_classifier_free_guidance:\n",
    "                noise_pred_uncond, noise_pred_text = noise_pred[0], noise_pred[1]\n",
    "                noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)\n",
    "\n",
    "            # compute the previous noisy sample x_t -> x_t-1\n",
    "            latents = self.scheduler.step(torch.from_numpy(noise_pred), t, torch.from_numpy(latents), **extra_step_kwargs)[\"prev_sample\"].numpy()\n",
    "        # scale and decode the image latents with vae\n",
    "        image = self.vae_decoder(latents * (1 / 0.18215))[self._vae_d_output]\n",
    "\n",
    "        image = self.postprocess_image(image, meta, output_type)\n",
    "        return {\"sample\": image}\n",
    "\n",
    "    def _encode_prompt(\n",
    "        self,\n",
    "        prompt: Union[str, List[str]],\n",
    "        num_images_per_prompt: int = 1,\n",
    "        do_classifier_free_guidance: bool = True,\n",
    "        negative_prompt: Union[str, List[str]] = None,\n",
    "    ):\n",
    "        \"\"\"\n",

    "        Encodes the prompt into text encoder hidden states.\n",

    "\n",

    "        Parameters:\n",

    "            prompt (str or list(str)): prompt to be encoded\n",

    "            num_images_per_prompt (int): number of images that should be generated per prompt\n",

    "            do_classifier_free_guidance (bool): whether to use classifier free guidance or not\n",

    "            negative_prompt (str or list(str)): negative prompt to be encoded\n",

    "        Returns:\n",

    "            text_embeddings (np.ndarray): text encoder hidden states\n",

    "        \"\"\"\n",
    "        batch_size = len(prompt) if isinstance(prompt, list) else 1\n",
    "\n",
    "        # tokenize input prompts\n",
    "        text_inputs = self.tokenizer(\n",
    "            prompt,\n",
    "            padding=\"max_length\",\n",
    "            max_length=self.tokenizer.model_max_length,\n",
    "            truncation=True,\n",
    "            return_tensors=\"np\",\n",
    "        )\n",
    "        text_input_ids = text_inputs.input_ids\n",
    "\n",
    "        text_embeddings = self.text_encoder(text_input_ids)[self._text_encoder_output]\n",
    "\n",
    "        # duplicate text embeddings for each generation per prompt\n",
    "        if num_images_per_prompt != 1:\n",
    "            bs_embed, seq_len, _ = text_embeddings.shape\n",
    "            text_embeddings = np.tile(text_embeddings, (1, num_images_per_prompt, 1))\n",
    "            text_embeddings = np.reshape(text_embeddings, (bs_embed * num_images_per_prompt, seq_len, -1))\n",
    "\n",
    "        # get unconditional embeddings for classifier free guidance\n",
    "        if do_classifier_free_guidance:\n",
    "            uncond_tokens: List[str]\n",
    "            max_length = text_input_ids.shape[-1]\n",
    "            if negative_prompt is None:\n",
    "                uncond_tokens = [\"\"] * batch_size\n",
    "            elif isinstance(negative_prompt, str):\n",
    "                uncond_tokens = [negative_prompt]\n",
    "            else:\n",
    "                uncond_tokens = negative_prompt\n",
    "            uncond_input = self.tokenizer(\n",
    "                uncond_tokens,\n",
    "                padding=\"max_length\",\n",
    "                max_length=max_length,\n",
    "                truncation=True,\n",
    "                return_tensors=\"np\",\n",
    "            )\n",
    "\n",
    "            uncond_embeddings = self.text_encoder(uncond_input.input_ids)[self._text_encoder_output]\n",
    "\n",
    "            # duplicate unconditional embeddings for each generation per prompt, using mps friendly method\n",
    "            seq_len = uncond_embeddings.shape[1]\n",
    "            uncond_embeddings = np.tile(uncond_embeddings, (1, num_images_per_prompt, 1))\n",
    "            uncond_embeddings = np.reshape(uncond_embeddings, (batch_size * num_images_per_prompt, seq_len, -1))\n",
    "\n",
    "            # For classifier free guidance, we need to do two forward passes.\n",
    "            # Here we concatenate the unconditional and text embeddings into a single batch\n",
    "            # to avoid doing two forward passes\n",
    "            text_embeddings = np.concatenate([uncond_embeddings, text_embeddings])\n",
    "\n",
    "        return text_embeddings\n",
    "\n",
    "    def prepare_latents(self, image: PIL.Image.Image = None, latent_timestep: torch.Tensor = None):\n",
    "        \"\"\"\n",

    "        Function for getting initial latents for starting generation\n",

    "\n",

    "        Parameters:\n",

    "            image (PIL.Image.Image, *optional*, None):\n",

    "                Input image for generation, if not provided randon noise will be used as starting point\n",

    "            latent_timestep (torch.Tensor, *optional*, None):\n",

    "                Predicted by scheduler initial step for image generation, required for latent image mixing with nosie\n",

    "        Returns:\n",

    "            latents (np.ndarray):\n",

    "                Image encoded in latent space\n",

    "        \"\"\"\n",
    "        latents_shape = (1, 4, self.height // 8, self.width // 8)\n",
    "        noise = np.random.randn(*latents_shape).astype(np.float32)\n",
    "        if image is None:\n",
    "            # if we use LMSDiscreteScheduler, let's make sure latents are mulitplied by sigmas\n",
    "            if isinstance(self.scheduler, LMSDiscreteScheduler):\n",
    "                noise = noise * self.scheduler.sigmas[0].numpy()\n",
    "            return noise, {}\n",
    "        input_image, meta = preprocess(image)\n",
    "        latents = self.vae_encoder(input_image)[self._vae_e_output]\n",
    "        latents = latents * 0.18215\n",
    "        latents = self.scheduler.add_noise(torch.from_numpy(latents), torch.from_numpy(noise), latent_timestep).numpy()\n",
    "        return latents, meta\n",
    "\n",
    "    def postprocess_image(self, image: np.ndarray, meta: Dict, output_type: str = \"pil\"):\n",
    "        \"\"\"\n",

    "        Postprocessing for decoded image. Takes generated image decoded by VAE decoder, unpad it to initila image size (if required),\n",

    "        normalize and convert to [0, 255] pixels range. Optionally, convertes it from np.ndarray to PIL.Image format\n",

    "\n",

    "        Parameters:\n",

    "            image (np.ndarray):\n",

    "                Generated image\n",

    "            meta (Dict):\n",

    "                Metadata obtained on latents preparing step, can be empty\n",

    "            output_type (str, *optional*, pil):\n",

    "                Output format for result, can be pil or numpy\n",

    "        Returns:\n",

    "            image (List of np.ndarray or PIL.Image.Image):\n",

    "                Postprocessed images\n",

    "        \"\"\"\n",
    "        if \"padding\" in meta:\n",
    "            pad = meta[\"padding\"]\n",
    "            (_, end_h), (_, end_w) = pad[1:3]\n",
    "            h, w = image.shape[2:]\n",
    "            unpad_h = h - end_h\n",
    "            unpad_w = w - end_w\n",
    "            image = image[:, :, :unpad_h, :unpad_w]\n",
    "        image = np.clip(image / 2 + 0.5, 0, 1)\n",
    "        image = np.transpose(image, (0, 2, 3, 1))\n",
    "        # 9. Convert to PIL\n",
    "        if output_type == \"pil\":\n",
    "            image = self.numpy_to_pil(image)\n",
    "            if \"src_height\" in meta:\n",
    "                orig_height, orig_width = meta[\"src_height\"], meta[\"src_width\"]\n",
    "                image = [img.resize((orig_width, orig_height), PIL.Image.Resampling.LANCZOS) for img in image]\n",
    "        else:\n",
    "            if \"src_height\" in meta:\n",
    "                orig_height, orig_width = meta[\"src_height\"], meta[\"src_width\"]\n",
    "                image = [cv2.resize(img, (orig_width, orig_width)) for img in image]\n",
    "        return image\n",
    "\n",
    "    def get_timesteps(self, num_inference_steps: int, strength: float):\n",
    "        \"\"\"\n",

    "        Helper function for getting scheduler timesteps for generation\n",

    "        In case of image-to-image generation, it updates number of steps according to strength\n",

    "\n",

    "        Parameters:\n",

    "           num_inference_steps (int):\n",

    "              number of inference steps for generation\n",

    "           strength (float):\n",

    "               value between 0.0 and 1.0, that controls the amount of noise that is added to the input image.\n",

    "               Values that approach 1.0 allow for lots of variations but will also produce images that are not semantically consistent with the input.\n",

    "        \"\"\"\n",
    "        # get the original timestep using init_timestep\n",
    "        init_timestep = min(int(num_inference_steps * strength), num_inference_steps)\n",
    "\n",
    "        t_start = max(num_inference_steps - init_timestep, 0)\n",
    "        timesteps = self.scheduler.timesteps[t_start:]\n",
    "\n",
    "        return timesteps, num_inference_steps - t_start"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8ae7b18e9f8c995a",
   "metadata": {},
   "source": [
    "### Configure Inference Pipeline\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "First, you should create instances of OpenVINO Model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "635200a7b5d84bf3",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-02-13T13:30:16.325848Z",
     "start_time": "2024-02-13T13:30:16.083685Z"
    }
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "68783cc794cb49a1b5ca674b689805d1",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Dropdown(description='Device:', index=4, options=('CPU', 'GPU.0', 'GPU.1', 'GPU.2', 'AUTO'), value='AUTO')"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import ipywidgets as widgets\n",
    "\n",
    "core = ov.Core()\n",
    "device = widgets.Dropdown(\n",
    "    options=core.available_devices + [\"AUTO\"],\n",
    "    value=\"AUTO\",\n",
    "    description=\"Device:\",\n",
    "    disabled=False,\n",
    ")\n",
    "\n",
    "device"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "ab277c23095fa5a7",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-02-13T13:30:19.234103Z",
     "start_time": "2024-02-13T13:30:16.326662Z"
    }
   },
   "outputs": [],
   "source": [
    "ov_config = {\"INFERENCE_PRECISION_HINT\": \"f32\"} if device.value != \"CPU\" else {}\n",
    "\n",
    "text_enc = core.compile_model(TEXT_ENCODER_OV_PATH, device.value)\n",
    "unet_model = core.compile_model(UNET_OV_PATH, device.value)\n",
    "vae_decoder = core.compile_model(VAE_DECODER_OV_PATH, device.value, ov_config)\n",
    "vae_encoder = core.compile_model(VAE_ENCODER_OV_PATH, device.value, ov_config)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e0cdcdb5a1c10f1a",
   "metadata": {},
   "source": [
    "Model tokenizer and scheduler are also important parts of the pipeline. Let us define them and put all components together."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "25897d22da482d91",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-02-13T13:30:19.432106Z",
     "start_time": "2024-02-13T13:30:19.236629Z"
    }
   },
   "outputs": [],
   "source": [
    "from transformers import CLIPTokenizer\n",
    "\n",
    "scheduler = DDIMScheduler.from_config(conf)  # DDIMScheduler is used because UNet quantization produces better results with it\n",
    "tokenizer = CLIPTokenizer.from_pretrained(\"openai/clip-vit-large-patch14\")\n",
    "\n",
    "ov_pipe = OVStableDiffusionPipeline(\n",
    "    tokenizer=tokenizer,\n",
    "    text_encoder=text_enc,\n",
    "    unet=unet_model,\n",
    "    vae_encoder=vae_encoder,\n",
    "    vae_decoder=vae_decoder,\n",
    "    scheduler=scheduler,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5a5f91dfea77c91",
   "metadata": {},
   "source": [
    "## Quantization\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "[NNCF](https://github.com/openvinotoolkit/nncf/) enables post-training quantization by adding quantization layers into model graph and then using a subset of the training dataset to initialize the parameters of these additional quantization layers. Quantized operations are executed in `INT8` instead of `FP32`/`FP16` making model inference faster.\n",
    "\n",
    "According to `Stable Diffusion v2` structure, the UNet model takes up significant portion of the overall pipeline execution time. Now we will show you how to optimize the UNet part using [NNCF](https://github.com/openvinotoolkit/nncf/) to reduce computation cost and speed up the pipeline. Quantizing the rest of the pipeline does not significantly improve inference performance but can lead to a substantial degradation of accuracy.\n",
    "\n",
    "For this model we apply quantization in hybrid mode which means that we quantize: (1) weights of MatMul and Embedding layers and (2) activations of other layers. The steps are the following:\n",
    "\n",
    "1. Create a calibration dataset for quantization.\n",
    "2. Collect operations with weights.\n",
    "3. Run `nncf.compress_model()` to compress only the model weights.\n",
    "4. Run `nncf.quantize()` on the compressed model with weighted operations ignored by providing `ignored_scope` parameter.\n",
    "5. Save the `INT8` model using `openvino.save_model()` function.\n",
    "\n",
    "Please select below whether you would like to run quantization to improve model inference speed.\n",
    "\n",
    "> **NOTE**: Quantization is time and memory consuming operation. Running quantization code below may take some time."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "d5850cecdf32cb56",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-02-13T13:30:19.437075Z",
     "start_time": "2024-02-13T13:30:19.433071Z"
    }
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "a254008cba184c21844c547636b96931",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Checkbox(value=True, description='Quantization')"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "to_quantize = widgets.Checkbox(\n",
    "    value=True,\n",
    "    description=\"Quantization\",\n",
    "    disabled=False,\n",
    ")\n",
    "\n",
    "to_quantize"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "7f9846bbc13089cd",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-02-13T13:30:19.441469Z",
     "start_time": "2024-02-13T13:30:19.437809Z"
    }
   },
   "outputs": [],
   "source": [
    "# Fetch `skip_kernel_extension` module\n",
    "import requests\n",
    "\n",
    "r = requests.get(\n",
    "    url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/utils/skip_kernel_extension.py\",\n",
    ")\n",
    "open(\"skip_kernel_extension.py\", \"w\").write(r.text)\n",
    "\n",
    "int8_ov_pipe = None\n",
    "\n",
    "%load_ext skip_kernel_extension"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "75734990a15dcf4b",
   "metadata": {},
   "source": [
    "### Prepare calibration dataset\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "We use a portion of [conceptual_captions](https://huggingface.co/datasets/conceptual_captions) dataset from Hugging Face as calibration data.\n",
    "To collect intermediate model inputs for calibration we should customize `CompiledModel`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "e277c7ebebde9973",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-02-13T13:30:20.034818Z",
     "start_time": "2024-02-13T13:30:19.442211Z"
    }
   },
   "outputs": [],
   "source": [
    "%%skip not $to_quantize.value\n",
    "\n",
    "import datasets\n",
    "import numpy as np\n",
    "from tqdm.notebook import tqdm\n",
    "from typing import Any, Dict, List\n",
    "\n",
    "\n",
    "def disable_progress_bar(pipeline, disable=True):\n",
    "    if not hasattr(pipeline, \"_progress_bar_config\"):\n",
    "        pipeline._progress_bar_config = {'disable': disable}\n",
    "    else:\n",
    "        pipeline._progress_bar_config['disable'] = disable\n",
    "\n",
    "\n",
    "class CompiledModelDecorator(ov.CompiledModel):\n",
    "    def __init__(self, compiled_model: ov.CompiledModel, data_cache: List[Any] = None, keep_prob: float = 0.5):\n",
    "        super().__init__(compiled_model)\n",
    "        self.data_cache = data_cache if data_cache is not None else []\n",
    "        self.keep_prob = keep_prob\n",
    "\n",
    "    def __call__(self, *args, **kwargs):\n",
    "        if np.random.rand() <= self.keep_prob:\n",
    "            self.data_cache.append(*args)\n",
    "        return super().__call__(*args, **kwargs)\n",
    "\n",
    "\n",
    "def collect_calibration_data(ov_pipe, calibration_dataset_size: int, num_inference_steps: int) -> List[Dict]:\n",
    "    original_unet = ov_pipe.unet\n",
    "    calibration_data = []\n",
    "    ov_pipe.unet = CompiledModelDecorator(original_unet, calibration_data, keep_prob=0.7)\n",
    "    disable_progress_bar(ov_pipe)\n",
    "\n",
    "    dataset = datasets.load_dataset(\"conceptual_captions\", split=\"train\").shuffle(seed=42)\n",
    "\n",
    "    # Run inference for data collection\n",
    "    pbar = tqdm(total=calibration_dataset_size)\n",
    "    for batch in dataset:\n",
    "        prompt = batch[\"caption\"]\n",
    "        if len(prompt) > ov_pipe.tokenizer.model_max_length:\n",
    "            continue\n",
    "        ov_pipe(prompt, num_inference_steps=num_inference_steps, seed=1)\n",
    "        pbar.update(len(calibration_data) - pbar.n)\n",
    "        if pbar.n >= calibration_dataset_size:\n",
    "            break\n",
    "\n",
    "    disable_progress_bar(ov_pipe, disable=False)\n",
    "    ov_pipe.unet = original_unet\n",
    "    return calibration_data"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1a5d9c1dcbebb1a8",
   "metadata": {},
   "source": [
    "### Run Hybrid Model Quantization\n",
    "[back to top ⬆️](#Table-of-contents:)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "586920796dacd8db",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-02-13T14:31:36.656460Z",
     "start_time": "2024-02-13T13:32:03.144519Z"
    },
    "test_replace": {
    "calibration_dataset_size = 300": "calibration_dataset_size = 10",
    "num_inference_steps=50)": "num_inference_steps=10)"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:nncf:NNCF initialized successfully. Supported frameworks detected: torch, onnx, openvino\n"
     ]
    }
   ],
   "source": [
    "%%skip not $to_quantize.value\n",
    "\n",
    "from collections import deque\n",
    "from transformers import set_seed\n",
    "import nncf\n",
    "\n",
    "def get_operation_const_op(operation, const_port_id: int):\n",
    "    node = operation.input_value(const_port_id).get_node()\n",
    "    queue = deque([node])\n",
    "    constant_node = None\n",
    "    allowed_propagation_types_list = [\"Convert\", \"FakeQuantize\", \"Reshape\"]\n",
    "\n",
    "    while len(queue) != 0:\n",
    "        curr_node = queue.popleft()\n",
    "        if curr_node.get_type_name() == \"Constant\":\n",
    "            constant_node = curr_node\n",
    "            break\n",
    "        if len(curr_node.inputs()) == 0:\n",
    "            break\n",
    "        if curr_node.get_type_name() in allowed_propagation_types_list:\n",
    "            queue.append(curr_node.input_value(0).get_node())\n",
    "\n",
    "    return constant_node\n",
    "\n",
    "\n",
    "def is_embedding(node) -> bool:\n",
    "    allowed_types_list = [\"f16\", \"f32\", \"f64\"]\n",
    "    const_port_id = 0\n",
    "    input_tensor = node.input_value(const_port_id)\n",
    "    if input_tensor.get_element_type().get_type_name() in allowed_types_list:\n",
    "        const_node = get_operation_const_op(node, const_port_id)\n",
    "        if const_node is not None:\n",
    "            return True\n",
    "\n",
    "    return False\n",
    "\n",
    "\n",
    "def collect_ops_with_weights(model):\n",
    "    ops_with_weights = []\n",
    "    for op in model.get_ops():\n",
    "        if op.get_type_name() == \"MatMul\":\n",
    "            constant_node_0 = get_operation_const_op(op, const_port_id=0)\n",
    "            constant_node_1 = get_operation_const_op(op, const_port_id=1)\n",
    "            if constant_node_0 or constant_node_1:\n",
    "                ops_with_weights.append(op.get_friendly_name())\n",
    "        if op.get_type_name() == \"Gather\" and is_embedding(op):\n",
    "            ops_with_weights.append(op.get_friendly_name())\n",
    "\n",
    "    return ops_with_weights\n",
    "\n",
    "UNET_INT8_OV_PATH = sd2_1_model_dir / 'unet_optimized.xml'\n",
    "if not UNET_INT8_OV_PATH.exists():\n",
    "    calibration_dataset_size = 300\n",
    "    set_seed(1)\n",
    "    unet_calibration_data = collect_calibration_data(ov_pipe,\n",
    "                                                     calibration_dataset_size=calibration_dataset_size,\n",
    "                                                     num_inference_steps=50)\n",
    "\n",
    "    unet = core.read_model(UNET_OV_PATH)\n",
    "    \n",
    "    # Collect operations which weights will be compressed\n",
    "    unet_ignored_scope = collect_ops_with_weights(unet)\n",
    "    \n",
    "    # Compress model weights\n",
    "    compressed_unet = nncf.compress_weights(unet, ignored_scope=nncf.IgnoredScope(types=['Convolution']))\n",
    "    \n",
    "    # Quantize both weights and activations of Convolution layers\n",
    "    quantized_unet = nncf.quantize(\n",
    "        model=compressed_unet,\n",
    "        calibration_dataset=nncf.Dataset(unet_calibration_data),\n",
    "        subset_size=calibration_dataset_size,\n",
    "        model_type=nncf.ModelType.TRANSFORMER,\n",
    "        ignored_scope=nncf.IgnoredScope(names=unet_ignored_scope),\n",
    "        advanced_parameters=nncf.AdvancedQuantizationParameters(smooth_quant_alpha=-1)\n",
    "    )\n",
    "    \n",
    "    ov.save_model(quantized_unet, UNET_INT8_OV_PATH)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "b5d398a5a7b87506",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-02-13T14:32:27.192039Z",
     "start_time": "2024-02-13T14:32:23.567293Z"
    }
   },
   "outputs": [],
   "source": [
    "%%skip not $to_quantize.value\n",
    "\n",
    "int8_unet_model = core.compile_model(UNET_INT8_OV_PATH, device.value)\n",
    "int8_ov_pipe = OVStableDiffusionPipeline(\n",
    "    tokenizer=tokenizer,\n",
    "    text_encoder=text_enc,\n",
    "    unet=int8_unet_model,\n",
    "    vae_encoder=vae_encoder,\n",
    "    vae_decoder=vae_decoder,\n",
    "    scheduler=scheduler\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "73151859000e9305",
   "metadata": {},
   "source": [
    "### Compare UNet file size"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "4cf380af026bfaac",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-02-13T14:32:27.198596Z",
     "start_time": "2024-02-13T14:32:27.195616Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "FP16 model size: 1691232.51 KB\n",
      "INT8 model size: 846918.58 KB\n",
      "Model compression rate: 1.997\n"
     ]
    }
   ],
   "source": [
    "%%skip not $to_quantize.value\n",
    "\n",
    "fp16_ir_model_size = UNET_OV_PATH.with_suffix(\".bin\").stat().st_size / 1024\n",
    "quantized_model_size = UNET_INT8_OV_PATH.with_suffix(\".bin\").stat().st_size / 1024\n",
    "\n",
    "print(f\"FP16 model size: {fp16_ir_model_size:.2f} KB\")\n",
    "print(f\"INT8 model size: {quantized_model_size:.2f} KB\")\n",
    "print(f\"Model compression rate: {fp16_ir_model_size / quantized_model_size:.3f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "637babca1053f709",
   "metadata": {},
   "source": [
    "### Compare inference time of the FP16 and INT8 pipelines\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "To measure the inference performance of the `FP16` and `INT8` pipelines, we use median inference time on calibration subset.\n",
    "\n",
    "> **NOTE**: For the most accurate performance estimation, it is recommended to run `benchmark_app` in a terminal/command prompt after closing other applications."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "b653073baccacaa1",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-02-13T14:32:29.452397Z",
     "start_time": "2024-02-13T14:32:29.449204Z"
    }
   },
   "outputs": [],
   "source": [
    "%%skip not $to_quantize.value\n",
    "\n",
    "import time\n",
    "\n",
    "def calculate_inference_time(pipeline, validation_data):\n",
    "    inference_time = []\n",
    "    pipeline.set_progress_bar_config(disable=True)\n",
    "    for prompt in validation_data:\n",
    "        start = time.perf_counter()\n",
    "        _ = pipeline(prompt, num_inference_steps=10, seed=0)\n",
    "        end = time.perf_counter()\n",
    "        delta = end - start\n",
    "        inference_time.append(delta)\n",
    "    return np.median(inference_time)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "cd270c546efe7b33",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-02-13T14:44:53.370640Z",
     "start_time": "2024-02-13T14:32:30.218862Z"
    }
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/nsavel/venvs/ov_notebooks_tmp/lib/python3.8/site-packages/datasets/load.py:1429: FutureWarning: The repository for conceptual_captions contains custom code which must be executed to correctly load the dataset. You can inspect the repository content at https://hf.co/datasets/conceptual_captions\n",
      "You can avoid this message in future by passing the argument `trust_remote_code=True`.\n",
      "Passing `trust_remote_code=True` will be mandatory to load this dataset from the next major release of `datasets`.\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Performance speed-up: 1.232\n"
     ]
    }
   ],
   "source": [
    "%%skip not $to_quantize.value\n",
    "\n",
    "validation_size = 10\n",
    "validation_dataset = datasets.load_dataset(\"conceptual_captions\", split=\"train\", streaming=True).take(validation_size)\n",
    "validation_data = [batch[\"caption\"] for batch in validation_dataset]\n",
    "\n",
    "fp_latency = calculate_inference_time(ov_pipe, validation_data)\n",
    "int8_latency = calculate_inference_time(int8_ov_pipe, validation_data)\n",
    "print(f\"Performance speed-up: {fp_latency / int8_latency:.3f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3b7f93ec1bd55a2f",
   "metadata": {},
   "source": [
    "## Run Text-to-Image generation\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Now, you can define a text prompts for image generation and run inference pipeline.\n",
    "Optionally, you can also change the random generator seed for latent state initialization and number of steps.\n",
    "\n",
    "> **Note**: Consider increasing `steps` to get more precise results. A suggested value is `50`, but it will take longer time to process."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cd89fdab77ca1f8c",
   "metadata": {},
   "source": [
    "Please select below whether you would like to use the quantized model to launch the interactive demo."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "edd734469b49f2f8",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-02-13T14:44:53.376186Z",
     "start_time": "2024-02-13T14:44:53.371802Z"
    }
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "2bb8194dc4f24c1087fc33e4efe5e5e9",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Checkbox(value=True, description='Use quantized model')"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "quantized_model_present = int8_ov_pipe is not None\n",
    "\n",
    "use_quantized_model = widgets.Checkbox(\n",
    "    value=True if quantized_model_present else False,\n",
    "    description=\"Use quantized model\",\n",
    "    disabled=not quantized_model_present,\n",
    ")\n",
    "\n",
    "use_quantized_model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f1136e88de27fec2",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-02-13T14:44:55.067276Z",
     "start_time": "2024-02-13T14:44:53.376929Z"
    }
   },
   "outputs": [],
   "source": [
    "import gradio as gr\n",
    "\n",
    "\n",
    "pipeline = int8_ov_pipe if use_quantized_model.value else ov_pipe\n",
    "\n",
    "\n",
    "def generate(prompt, negative_prompt, seed, num_steps, _=gr.Progress(track_tqdm=True)):\n",
    "    result = pipeline(\n",
    "        prompt,\n",
    "        negative_prompt=negative_prompt,\n",
    "        num_inference_steps=num_steps,\n",
    "        seed=seed,\n",
    "    )\n",
    "    return result[\"sample\"][0]\n",
    "\n",
    "\n",
    "gr.close_all()\n",
    "demo = gr.Interface(\n",
    "    generate,\n",
    "    [\n",
    "        gr.Textbox(\n",
    "            \"valley in the Alps at sunset, epic vista, beautiful landscape, 4k, 8k\",\n",
    "            label=\"Prompt\",\n",
    "        ),\n",
    "        gr.Textbox(\n",
    "            \"frames, borderline, text, charachter, duplicate, error, out of frame, watermark, low quality, ugly, deformed, blur\",\n",
    "            label=\"Negative prompt\",\n",
    "        ),\n",
    "        gr.Slider(value=42, label=\"Seed\", maximum=10000000),\n",
    "        gr.Slider(value=25, label=\"Steps\", minimum=1, maximum=50),\n",
    "    ],\n",
    "    \"image\",\n",
    ")\n",
    "\n",
    "try:\n",
    "    demo.queue().launch()\n",
    "except Exception:\n",
    "    demo.queue().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/blob/latest/notebooks/stable-diffusion-v2/stable-diffusion-v2-optimum-demo.png?raw=true",
   "tags": {
    "categories": [
     "Model Demos",
     "AI Trends"
    ],
    "libraries": [],
    "other": [
     "Stable Diffusion"
    ],
    "tasks": [
     "Text-to-Image"
    ]
   }
  },
  "widgets": {
   "application/vnd.jupyter.widget-state+json": {
    "state": {},
    "version_major": 2,
    "version_minor": 0
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}