File size: 124,941 Bytes
9c197a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "1cc557a5-5a55-4bae-8555-a2b655abfa4a",
   "metadata": {},
   "source": [
    "SPDX-License-Identifier: Apache-2.0\n",
    "Copyright (c) 2023, Rahul Unnikrishnan Nair <[email protected]>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2123be0f-586b-47c9-af17-9d667f28eb3d",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "**Text to SQL Generation: Fine-Tuning LLMs with QLoRA on Intel**\n",
    "\n",
    "👋 Hello and welcome! In this Jupyter Notebook, we will walkthrough the process of fine-tuning a large language model (LLM) to improve its capabilities in generating SQL queries from natural language input. The notebook is suitable for AI engineers and practitioners looking to tune LLMs for specialized tasks such as Text-to-SQL conversions.\n",
    "\n",
    "**What you will learn with this Notebook**\n",
    "\n",
    "- 🛠️ Fine-tune a Language Model with either a pre-existing dataset or a custom dataset tailored to your needs on Intel Hw.\n",
    "- 💡 Gain insights into the fine-tuning process, including how to manipulate various training parameters to optimize your model's performance.\n",
    "- 📊 Test different configurations and observe the results in real-time.\n",
    "\n",
    "**Hardware Compatibility**\n",
    "\n",
    "- 🖥️ Designed for 4th Generation Intel® Xeon® Scalable Processors (CPU) and Intel® Data Center GPU Max Series 1100 (XPU)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "67c0e67f-8473-44d6-8065-edfc63a6459d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "List of Intel GPUs available on the system:\n",
      "+-----------+--------------------------------------------------------------------------------------+\n",
      "| Device ID | Device Information                                                                   |\n",
      "+-----------+--------------------------------------------------------------------------------------+\n",
      "| 0         | Device Name: Intel(R) Data Center GPU Max 1100                                       |\n",
      "|           | Vendor Name: Intel(R) Corporation                                                    |\n",
      "|           | SOC UUID: 00000000-0000-0029-0000-002f0bda8086                                       |\n",
      "|           | PCI BDF Address: 0000:29:00.0                                                        |\n",
      "|           | DRM Device: /dev/dri/card0                                                           |\n",
      "|           | Function Type: physical                                                              |\n",
      "+-----------+--------------------------------------------------------------------------------------+\n",
      "| 1         | Device Name: Intel(R) Data Center GPU Max 1100                                       |\n",
      "|           | Vendor Name: Intel(R) Corporation                                                    |\n",
      "|           | SOC UUID: 00000000-0000-003a-0000-002f0bda8086                                       |\n",
      "|           | PCI BDF Address: 0000:3a:00.0                                                        |\n",
      "|           | DRM Device: /dev/dri/card2                                                           |\n",
      "|           | Function Type: physical                                                              |\n",
      "+-----------+--------------------------------------------------------------------------------------+\n",
      "| 2         | Device Name: Intel(R) Data Center GPU Max 1100                                       |\n",
      "|           | Vendor Name: Intel(R) Corporation                                                    |\n",
      "|           | SOC UUID: 00000000-0000-009a-0000-002f0bda8086                                       |\n",
      "|           | PCI BDF Address: 0000:9a:00.0                                                        |\n",
      "|           | DRM Device: /dev/dri/card3                                                           |\n",
      "|           | Function Type: physical                                                              |\n",
      "+-----------+--------------------------------------------------------------------------------------+\n",
      "| 3         | Device Name: Intel(R) Data Center GPU Max 1100                                       |\n",
      "|           | Vendor Name: Intel(R) Corporation                                                    |\n",
      "|           | SOC UUID: 00000000-0000-00ca-0000-002f0bda8086                                       |\n",
      "|           | PCI BDF Address: 0000:ca:00.0                                                        |\n",
      "|           | DRM Device: /dev/dri/card4                                                           |\n",
      "|           | Function Type: physical                                                              |\n",
      "+-----------+--------------------------------------------------------------------------------------+\n",
      "Intel Xeon CPU used by this notebook:\n",
      "Model name:                         Intel(R) Xeon(R) Platinum 8480+\n"
     ]
    }
   ],
   "source": [
    "!echo \"List of Intel GPUs available on the system:\"\n",
    "!xpu-smi  discovery 2> /dev/null\n",
    "!echo \"Intel Xeon CPU used by this notebook:\"\n",
    "!lscpu | grep \"Model name\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "76293a12-551e-421a-8eb3-06387931d307",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true
   },
   "source": [
    "---\n",
    "\n",
    "**Fine-Tuning with QLoRA: Balancing Memory Efficiency and Adaptability**\n",
    "\n",
    "We leverage the QLoRA methodology for fine-tuning, enabling the loading and refinement of LLMs within the constraints of available GPU memory. Quantized Low Rank Adaptation or QLoRA achieves this by applying a clever combination of weight quantization and adapter-based finetuning.\n",
    "\n",
    "**How Does QLoRA Work?**\n",
    "\n",
    "- QLoRA reduces memory footprint via weight quantization. It compresses the pre-trained model weights significantly.\n",
    "- During fine-tuning, it focuses on optimizing adapter parameters—low-rank matrices added to the network, tailored for the specific task.\n",
    "- This selective training is computationally efficient, targeting a smaller set of trainable parameters.\n",
    "\n",
    "\n",
    "**What is the Big Picture?**\n",
    "\n",
    "- Think reparameterization: We inject LoRA weights, training only these, not the entire layer, for fine-tuning.\n",
    "- This technique is key for task-specific model adaptation.\n",
    "- Imagine a hub-and-spoke model for deployment: The hub is the foundational model, and the spokes are task-specific LoRA adapters.\n",
    "\n",
    "Below, on the left, is an overview of the reparameterization implemented with LoRA (with Quantization). This involves a set of low-rank matrices—think of these as an essential subset of larger weight matrices—trained specifically for the task. On the right, there's a high-level view of a hub-and-spoke model for LLM deployment, where the hub represents the foundational model, and the spokes are the LoRA adapters.\n",
    "\n",
    "<div align=\"center\">\n",
    "    <img src=\"https://github.com/rahulunair/sql_llm/assets/786476/c30d7fb4-2051-428c-9c55-fc4130cb11bc\" alt=\"lora_adapters_reparameterization\" width=\"75%\">\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6362a562-f3ce-4dce-9678-ce317e554a04",
   "metadata": {},
   "source": [
    "## Initialization\n",
    "\n",
    "Let's first install and import all the necessary packages required for the fine-tuning process.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "9236e9d1-e75e-4089-9a4d-27421521cfd5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Installation in progress, please wait...\n",
      "Defaulting to user installation because normal site-packages is not writeable\n",
      "\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n",
      "\u001b[0mLooking in links: https://developer.intel.com/ipex-whl-stable-xpu\n",
      "Requirement already satisfied: bigdl-llm==2.5.0b20240318 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bigdl-llm[xpu]==2.5.0b20240318) (2.5.0b20240318)\n",
      "Requirement already satisfied: py-cpuinfo in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bigdl-llm[xpu]==2.5.0b20240318) (9.0.0)\n",
      "Requirement already satisfied: protobuf in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bigdl-llm[xpu]==2.5.0b20240318) (4.25.3)\n",
      "Requirement already satisfied: mpmath==1.3.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bigdl-llm[xpu]==2.5.0b20240318) (1.3.0)\n",
      "Requirement already satisfied: numpy==1.26.4 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bigdl-llm[xpu]==2.5.0b20240318) (1.26.4)\n",
      "Requirement already satisfied: transformers==4.31.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bigdl-llm[xpu]==2.5.0b20240318) (4.31.0)\n",
      "Requirement already satisfied: sentencepiece in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bigdl-llm[xpu]==2.5.0b20240318) (0.2.0)\n",
      "Requirement already satisfied: tokenizers==0.13.3 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bigdl-llm[xpu]==2.5.0b20240318) (0.13.3)\n",
      "Collecting accelerate==0.21.0 (from bigdl-llm[xpu]==2.5.0b20240318)\n",
      "  Downloading accelerate-0.21.0-py3-none-any.whl.metadata (17 kB)\n",
      "Requirement already satisfied: tabulate in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bigdl-llm[xpu]==2.5.0b20240318) (0.9.0)\n",
      "Requirement already satisfied: torch==2.1.0a0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bigdl-llm[xpu]==2.5.0b20240318) (2.1.0a0+cxx11.abi)\n",
      "Requirement already satisfied: torchvision==0.16.0a0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bigdl-llm[xpu]==2.5.0b20240318) (0.16.0a0+cxx11.abi)\n",
      "Requirement already satisfied: intel-extension-for-pytorch==2.1.10+xpu in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bigdl-llm[xpu]==2.5.0b20240318) (2.1.10+xpu)\n",
      "Requirement already satisfied: bigdl-core-xe-21==2.5.0b20240318 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bigdl-llm[xpu]==2.5.0b20240318) (2.5.0b20240318)\n",
      "Requirement already satisfied: intel-openmp in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bigdl-llm[xpu]==2.5.0b20240318) (2024.0.3)\n",
      "Requirement already satisfied: bigdl-core-xe-esimd-21==2.5.0b20240318 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bigdl-llm[xpu]==2.5.0b20240318) (2.5.0b20240318)\n",
      "Requirement already satisfied: packaging>=20.0 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from accelerate==0.21.0->bigdl-llm[xpu]==2.5.0b20240318) (23.2)\n",
      "Requirement already satisfied: psutil in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from accelerate==0.21.0->bigdl-llm[xpu]==2.5.0b20240318) (5.9.8)\n",
      "Requirement already satisfied: pyyaml in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from accelerate==0.21.0->bigdl-llm[xpu]==2.5.0b20240318) (6.0.1)\n",
      "Requirement already satisfied: pydantic in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from intel-extension-for-pytorch==2.1.10+xpu->bigdl-llm[xpu]==2.5.0b20240318) (2.6.4)\n",
      "Requirement already satisfied: filelock in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch==2.1.0a0->bigdl-llm[xpu]==2.5.0b20240318) (3.13.1)\n",
      "Requirement already satisfied: typing-extensions in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch==2.1.0a0->bigdl-llm[xpu]==2.5.0b20240318) (4.10.0)\n",
      "Requirement already satisfied: sympy in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch==2.1.0a0->bigdl-llm[xpu]==2.5.0b20240318) (1.12)\n",
      "Requirement already satisfied: networkx in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch==2.1.0a0->bigdl-llm[xpu]==2.5.0b20240318) (3.2.1)\n",
      "Requirement already satisfied: jinja2 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch==2.1.0a0->bigdl-llm[xpu]==2.5.0b20240318) (3.1.3)\n",
      "Requirement already satisfied: fsspec in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch==2.1.0a0->bigdl-llm[xpu]==2.5.0b20240318) (2023.10.0)\n",
      "Requirement already satisfied: requests in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torchvision==0.16.0a0->bigdl-llm[xpu]==2.5.0b20240318) (2.31.0)\n",
      "Requirement already satisfied: pillow!=8.3.*,>=5.3.0 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from torchvision==0.16.0a0->bigdl-llm[xpu]==2.5.0b20240318) (10.0.1)\n",
      "Requirement already satisfied: huggingface-hub<1.0,>=0.14.1 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from transformers==4.31.0->bigdl-llm[xpu]==2.5.0b20240318) (0.17.3)\n",
      "Requirement already satisfied: regex!=2019.12.17 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from transformers==4.31.0->bigdl-llm[xpu]==2.5.0b20240318) (2023.12.25)\n",
      "Requirement already satisfied: safetensors>=0.3.1 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from transformers==4.31.0->bigdl-llm[xpu]==2.5.0b20240318) (0.4.2)\n",
      "Requirement already satisfied: tqdm>=4.27 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from transformers==4.31.0->bigdl-llm[xpu]==2.5.0b20240318) (4.66.2)\n",
      "Requirement already satisfied: MarkupSafe>=2.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from jinja2->torch==2.1.0a0->bigdl-llm[xpu]==2.5.0b20240318) (2.1.5)\n",
      "Requirement already satisfied: annotated-types>=0.4.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from pydantic->intel-extension-for-pytorch==2.1.10+xpu->bigdl-llm[xpu]==2.5.0b20240318) (0.6.0)\n",
      "Requirement already satisfied: pydantic-core==2.16.3 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from pydantic->intel-extension-for-pytorch==2.1.10+xpu->bigdl-llm[xpu]==2.5.0b20240318) (2.16.3)\n",
      "Requirement already satisfied: charset-normalizer<4,>=2 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->torchvision==0.16.0a0->bigdl-llm[xpu]==2.5.0b20240318) (3.3.2)\n",
      "Requirement already satisfied: idna<4,>=2.5 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->torchvision==0.16.0a0->bigdl-llm[xpu]==2.5.0b20240318) (3.6)\n",
      "Requirement already satisfied: urllib3<3,>=1.21.1 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->torchvision==0.16.0a0->bigdl-llm[xpu]==2.5.0b20240318) (2.2.1)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->torchvision==0.16.0a0->bigdl-llm[xpu]==2.5.0b20240318) (2024.2.2)\n",
      "Downloading accelerate-0.21.0-py3-none-any.whl (244 kB)\n",
      "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m244.2/244.2 kB\u001b[0m \u001b[31m5.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0ma \u001b[36m0:00:01\u001b[0m\n",
      "\u001b[?25h\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n",
      "\u001b[0mInstalling collected packages: accelerate\n",
      "  Attempting uninstall: accelerate\n",
      "    Found existing installation: accelerate 0.23.0\n",
      "    Uninstalling accelerate-0.23.0:\n",
      "      Successfully uninstalled accelerate-0.23.0\n",
      "\u001b[33m  WARNING: The scripts accelerate, accelerate-config and accelerate-launch are installed in '/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/bin' which is not on PATH.\n",
      "  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.\u001b[0m\u001b[33m\n",
      "\u001b[0mSuccessfully installed accelerate-0.21.0\n",
      "\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n",
      "\u001b[0m\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n",
      "\u001b[0mDefaulting to user installation because normal site-packages is not writeable\n",
      "\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n",
      "\u001b[0mRequirement already satisfied: peft==0.5.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (0.5.0)\n",
      "Requirement already satisfied: numpy>=1.17 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from peft==0.5.0) (1.26.4)\n",
      "Requirement already satisfied: packaging>=20.0 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from peft==0.5.0) (23.2)\n",
      "Requirement already satisfied: psutil in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from peft==0.5.0) (5.9.8)\n",
      "Requirement already satisfied: pyyaml in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from peft==0.5.0) (6.0.1)\n",
      "Requirement already satisfied: torch>=1.13.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from peft==0.5.0) (2.1.0a0+cxx11.abi)\n",
      "Requirement already satisfied: transformers in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from peft==0.5.0) (4.31.0)\n",
      "Requirement already satisfied: tqdm in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from peft==0.5.0) (4.66.2)\n",
      "Requirement already satisfied: accelerate in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from peft==0.5.0) (0.21.0)\n",
      "Requirement already satisfied: safetensors in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from peft==0.5.0) (0.4.2)\n",
      "Requirement already satisfied: filelock in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch>=1.13.0->peft==0.5.0) (3.13.1)\n",
      "Requirement already satisfied: typing-extensions in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch>=1.13.0->peft==0.5.0) (4.10.0)\n",
      "Requirement already satisfied: sympy in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch>=1.13.0->peft==0.5.0) (1.12)\n",
      "Requirement already satisfied: networkx in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch>=1.13.0->peft==0.5.0) (3.2.1)\n",
      "Requirement already satisfied: jinja2 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch>=1.13.0->peft==0.5.0) (3.1.3)\n",
      "Requirement already satisfied: fsspec in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch>=1.13.0->peft==0.5.0) (2023.10.0)\n",
      "Requirement already satisfied: huggingface-hub<1.0,>=0.14.1 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from transformers->peft==0.5.0) (0.17.3)\n",
      "Requirement already satisfied: regex!=2019.12.17 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from transformers->peft==0.5.0) (2023.12.25)\n",
      "Requirement already satisfied: requests in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from transformers->peft==0.5.0) (2.31.0)\n",
      "Requirement already satisfied: tokenizers!=0.11.3,<0.14,>=0.11.1 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from transformers->peft==0.5.0) (0.13.3)\n",
      "Requirement already satisfied: MarkupSafe>=2.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from jinja2->torch>=1.13.0->peft==0.5.0) (2.1.5)\n",
      "Requirement already satisfied: charset-normalizer<4,>=2 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->transformers->peft==0.5.0) (3.3.2)\n",
      "Requirement already satisfied: idna<4,>=2.5 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->transformers->peft==0.5.0) (3.6)\n",
      "Requirement already satisfied: urllib3<3,>=1.21.1 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->transformers->peft==0.5.0) (2.2.1)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->transformers->peft==0.5.0) (2024.2.2)\n",
      "Requirement already satisfied: mpmath>=0.19 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from sympy->torch>=1.13.0->peft==0.5.0) (1.3.0)\n",
      "\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n",
      "\u001b[0m\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n",
      "\u001b[0m\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n",
      "\u001b[0mDefaulting to user installation because normal site-packages is not writeable\n",
      "\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n",
      "\u001b[0mCollecting accelerate==0.23.0\n",
      "  Downloading accelerate-0.23.0-py3-none-any.whl.metadata (18 kB)\n",
      "Requirement already satisfied: numpy>=1.17 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from accelerate==0.23.0) (1.26.4)\n",
      "Requirement already satisfied: packaging>=20.0 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from accelerate==0.23.0) (23.2)\n",
      "Requirement already satisfied: psutil in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from accelerate==0.23.0) (5.9.8)\n",
      "Requirement already satisfied: pyyaml in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from accelerate==0.23.0) (6.0.1)\n",
      "Requirement already satisfied: torch>=1.10.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from accelerate==0.23.0) (2.1.0a0+cxx11.abi)\n",
      "Requirement already satisfied: huggingface-hub in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from accelerate==0.23.0) (0.17.3)\n",
      "Requirement already satisfied: filelock in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch>=1.10.0->accelerate==0.23.0) (3.13.1)\n",
      "Requirement already satisfied: typing-extensions in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch>=1.10.0->accelerate==0.23.0) (4.10.0)\n",
      "Requirement already satisfied: sympy in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch>=1.10.0->accelerate==0.23.0) (1.12)\n",
      "Requirement already satisfied: networkx in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch>=1.10.0->accelerate==0.23.0) (3.2.1)\n",
      "Requirement already satisfied: jinja2 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch>=1.10.0->accelerate==0.23.0) (3.1.3)\n",
      "Requirement already satisfied: fsspec in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch>=1.10.0->accelerate==0.23.0) (2023.10.0)\n",
      "Requirement already satisfied: requests in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from huggingface-hub->accelerate==0.23.0) (2.31.0)\n",
      "Requirement already satisfied: tqdm>=4.42.1 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from huggingface-hub->accelerate==0.23.0) (4.66.2)\n",
      "Requirement already satisfied: MarkupSafe>=2.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from jinja2->torch>=1.10.0->accelerate==0.23.0) (2.1.5)\n",
      "Requirement already satisfied: charset-normalizer<4,>=2 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->huggingface-hub->accelerate==0.23.0) (3.3.2)\n",
      "Requirement already satisfied: idna<4,>=2.5 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->huggingface-hub->accelerate==0.23.0) (3.6)\n",
      "Requirement already satisfied: urllib3<3,>=1.21.1 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->huggingface-hub->accelerate==0.23.0) (2.2.1)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->huggingface-hub->accelerate==0.23.0) (2024.2.2)\n",
      "Requirement already satisfied: mpmath>=0.19 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from sympy->torch>=1.10.0->accelerate==0.23.0) (1.3.0)\n",
      "Downloading accelerate-0.23.0-py3-none-any.whl (258 kB)\n",
      "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m258.1/258.1 kB\u001b[0m \u001b[31m3.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m00:01\u001b[0m0:01\u001b[0m\n",
      "\u001b[?25h\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n",
      "\u001b[0mInstalling collected packages: accelerate\n",
      "  Attempting uninstall: accelerate\n",
      "    Found existing installation: accelerate 0.21.0\n",
      "    Uninstalling accelerate-0.21.0:\n",
      "      Successfully uninstalled accelerate-0.21.0\n",
      "Successfully installed accelerate-0.23.0\n",
      "\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n",
      "\u001b[0m\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n",
      "\u001b[0mDefaulting to user installation because normal site-packages is not writeable\n",
      "\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n",
      "\u001b[0mCollecting transformers==4.34.0\n",
      "  Downloading transformers-4.34.0-py3-none-any.whl.metadata (121 kB)\n",
      "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m121.5/121.5 kB\u001b[0m \u001b[31m2.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0ma \u001b[36m0:00:01\u001b[0m\n",
      "\u001b[?25hRequirement already satisfied: filelock in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from transformers==4.34.0) (3.13.1)\n",
      "Requirement already satisfied: huggingface-hub<1.0,>=0.16.4 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from transformers==4.34.0) (0.17.3)\n",
      "Requirement already satisfied: numpy>=1.17 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from transformers==4.34.0) (1.26.4)\n",
      "Requirement already satisfied: packaging>=20.0 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from transformers==4.34.0) (23.2)\n",
      "Requirement already satisfied: pyyaml>=5.1 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from transformers==4.34.0) (6.0.1)\n",
      "Requirement already satisfied: regex!=2019.12.17 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from transformers==4.34.0) (2023.12.25)\n",
      "Requirement already satisfied: requests in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from transformers==4.34.0) (2.31.0)\n",
      "Collecting tokenizers<0.15,>=0.14 (from transformers==4.34.0)\n",
      "  Downloading tokenizers-0.14.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (6.7 kB)\n",
      "Requirement already satisfied: safetensors>=0.3.1 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from transformers==4.34.0) (0.4.2)\n",
      "Requirement already satisfied: tqdm>=4.27 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from transformers==4.34.0) (4.66.2)\n",
      "Requirement already satisfied: fsspec in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from huggingface-hub<1.0,>=0.16.4->transformers==4.34.0) (2023.10.0)\n",
      "Requirement already satisfied: typing-extensions>=3.7.4.3 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from huggingface-hub<1.0,>=0.16.4->transformers==4.34.0) (4.10.0)\n",
      "Requirement already satisfied: charset-normalizer<4,>=2 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->transformers==4.34.0) (3.3.2)\n",
      "Requirement already satisfied: idna<4,>=2.5 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->transformers==4.34.0) (3.6)\n",
      "Requirement already satisfied: urllib3<3,>=1.21.1 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->transformers==4.34.0) (2.2.1)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests->transformers==4.34.0) (2024.2.2)\n",
      "Downloading transformers-4.34.0-py3-none-any.whl (7.7 MB)\n",
      "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m7.7/7.7 MB\u001b[0m \u001b[31m68.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m00:01\u001b[0m00:01\u001b[0m\n",
      "\u001b[?25hDownloading tokenizers-0.14.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (3.8 MB)\n",
      "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m3.8/3.8 MB\u001b[0m \u001b[31m97.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m:00:01\u001b[0m\n",
      "\u001b[?25h\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n",
      "\u001b[0mInstalling collected packages: tokenizers, transformers\n",
      "  Attempting uninstall: tokenizers\n",
      "    Found existing installation: tokenizers 0.13.3\n",
      "    Uninstalling tokenizers-0.13.3:\n",
      "      Successfully uninstalled tokenizers-0.13.3\n",
      "  Attempting uninstall: transformers\n",
      "    Found existing installation: transformers 4.31.0\n",
      "    Uninstalling transformers-4.31.0:\n",
      "      Successfully uninstalled transformers-4.31.0\n",
      "Successfully installed tokenizers-0.14.1 transformers-4.34.0\n",
      "\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n",
      "\u001b[0m\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n",
      "\u001b[0mDefaulting to user installation because normal site-packages is not writeable\n",
      "\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n",
      "\u001b[0mRequirement already satisfied: datasets==2.14.6 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (2.14.6)\n",
      "Requirement already satisfied: numpy>=1.17 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from datasets==2.14.6) (1.26.4)\n",
      "Requirement already satisfied: pyarrow>=8.0.0 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from datasets==2.14.6) (15.0.0)\n",
      "Requirement already satisfied: dill<0.3.8,>=0.3.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from datasets==2.14.6) (0.3.7)\n",
      "Requirement already satisfied: pandas in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from datasets==2.14.6) (2.2.1)\n",
      "Requirement already satisfied: requests>=2.19.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from datasets==2.14.6) (2.31.0)\n",
      "Requirement already satisfied: tqdm>=4.62.1 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from datasets==2.14.6) (4.66.2)\n",
      "Requirement already satisfied: xxhash in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from datasets==2.14.6) (3.4.1)\n",
      "Requirement already satisfied: multiprocess in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from datasets==2.14.6) (0.70.15)\n",
      "Requirement already satisfied: fsspec<=2023.10.0,>=2023.1.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from fsspec[http]<=2023.10.0,>=2023.1.0->datasets==2.14.6) (2023.10.0)\n",
      "Requirement already satisfied: aiohttp in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from datasets==2.14.6) (3.9.3)\n",
      "Requirement already satisfied: huggingface-hub<1.0.0,>=0.14.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from datasets==2.14.6) (0.17.3)\n",
      "Requirement already satisfied: packaging in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from datasets==2.14.6) (23.2)\n",
      "Requirement already satisfied: pyyaml>=5.1 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from datasets==2.14.6) (6.0.1)\n",
      "Requirement already satisfied: aiosignal>=1.1.2 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from aiohttp->datasets==2.14.6) (1.3.1)\n",
      "Requirement already satisfied: attrs>=17.3.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from aiohttp->datasets==2.14.6) (23.2.0)\n",
      "Requirement already satisfied: frozenlist>=1.1.1 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from aiohttp->datasets==2.14.6) (1.4.1)\n",
      "Requirement already satisfied: multidict<7.0,>=4.5 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from aiohttp->datasets==2.14.6) (6.0.5)\n",
      "Requirement already satisfied: yarl<2.0,>=1.0 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from aiohttp->datasets==2.14.6) (1.9.4)\n",
      "Requirement already satisfied: async-timeout<5.0,>=4.0 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from aiohttp->datasets==2.14.6) (4.0.3)\n",
      "Requirement already satisfied: filelock in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from huggingface-hub<1.0.0,>=0.14.0->datasets==2.14.6) (3.13.1)\n",
      "Requirement already satisfied: typing-extensions>=3.7.4.3 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from huggingface-hub<1.0.0,>=0.14.0->datasets==2.14.6) (4.10.0)\n",
      "Requirement already satisfied: charset-normalizer<4,>=2 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests>=2.19.0->datasets==2.14.6) (3.3.2)\n",
      "Requirement already satisfied: idna<4,>=2.5 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests>=2.19.0->datasets==2.14.6) (3.6)\n",
      "Requirement already satisfied: urllib3<3,>=1.21.1 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests>=2.19.0->datasets==2.14.6) (2.2.1)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from requests>=2.19.0->datasets==2.14.6) (2024.2.2)\n",
      "Requirement already satisfied: python-dateutil>=2.8.2 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from pandas->datasets==2.14.6) (2.8.2)\n",
      "Requirement already satisfied: pytz>=2020.1 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from pandas->datasets==2.14.6) (2023.3.post1)\n",
      "Requirement already satisfied: tzdata>=2022.7 in /opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/site-packages (from pandas->datasets==2.14.6) (2023.3)\n",
      "Requirement already satisfied: six>=1.5 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from python-dateutil>=2.8.2->pandas->datasets==2.14.6) (1.16.0)\n",
      "\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n",
      "\u001b[0m\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n",
      "\u001b[0m\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n",
      "\u001b[0mDefaulting to user installation because normal site-packages is not writeable\n",
      "\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n",
      "\u001b[0mRequirement already satisfied: bitsandbytes==0.43.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (0.43.0)\n",
      "Requirement already satisfied: scipy==1.12.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (1.12.0)\n",
      "Requirement already satisfied: torch in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bitsandbytes==0.43.0) (2.1.0a0+cxx11.abi)\n",
      "Requirement already satisfied: numpy in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from bitsandbytes==0.43.0) (1.26.4)\n",
      "Requirement already satisfied: filelock in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch->bitsandbytes==0.43.0) (3.13.1)\n",
      "Requirement already satisfied: typing-extensions in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch->bitsandbytes==0.43.0) (4.10.0)\n",
      "Requirement already satisfied: sympy in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch->bitsandbytes==0.43.0) (1.12)\n",
      "Requirement already satisfied: networkx in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch->bitsandbytes==0.43.0) (3.2.1)\n",
      "Requirement already satisfied: jinja2 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch->bitsandbytes==0.43.0) (3.1.3)\n",
      "Requirement already satisfied: fsspec in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from torch->bitsandbytes==0.43.0) (2023.10.0)\n",
      "Requirement already satisfied: MarkupSafe>=2.0 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from jinja2->torch->bitsandbytes==0.43.0) (2.1.5)\n",
      "Requirement already satisfied: mpmath>=0.19 in /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages (from sympy->torch->bitsandbytes==0.43.0) (1.3.0)\n",
      "\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n",
      "\u001b[0m\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n",
      "\u001b[0m\u001b[33mWARNING: Ignoring invalid distribution -ransformers (/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n",
      "\u001b[0mInstallation completed.\n"
     ]
    }
   ],
   "source": [
    "import sys\n",
    "import site\n",
    "from pathlib import Path\n",
    "\n",
    "!echo \"Installation in progress, please wait...\"\n",
    "!{sys.executable} -m pip cache purge > /dev/null\n",
    "!{sys.executable} -m pip install --pre --upgrade \"bigdl-llm[xpu]==2.5.0b20240318\" -f https://developer.intel.com/ipex-whl-stable-xpu\n",
    "!{sys.executable} -m pip install \"peft==0.5.0\"  #> /dev/null\n",
    "!{sys.executable} -m pip install \"accelerate==0.23.0\" --no-warn-script-location #> /dev/null\n",
    "!{sys.executable} -m pip install \"transformers==4.34.0\" --no-warn-script-location #> /dev/null \n",
    "!{sys.executable} -m pip install \"datasets==2.14.6\" --no-warn-script-location #> /dev/null 2>&1 \n",
    "!{sys.executable} -m pip install \"bitsandbytes==0.43.0\" \"scipy==1.12.0\" #> /dev/null  2>&1\n",
    "!echo \"Installation completed.\"\n",
    "\n",
    "def get_python_version():\n",
    "    return \"python\" + \".\".join(map(str, sys.version_info[:2]))\n",
    "\n",
    "def set_local_bin_path():\n",
    "    local_bin = str(Path.home() / \".local\" / \"bin\") \n",
    "    local_site_packages = str(\n",
    "        Path.home() / \".local\" / \"lib\" / get_python_version() / \"site-packages\"\n",
    "    )\n",
    "    sys.path.append(local_bin)\n",
    "    sys.path.insert(0, site.getusersitepackages())\n",
    "    sys.path.insert(0, sys.path.pop(sys.path.index(local_site_packages)))\n",
    "\n",
    "set_local_bin_path()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "31eb9cf2-abcf-48f8-918b-37a18f85ac7c",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-03-24 01:29:30,660 - root - INFO - intel_extension_for_pytorch auto imported\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/bitsandbytes/libbitsandbytes_cpu.so: undefined symbol: cadam32bit_grad_fp32\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-03-24 01:29:32.212342: I tensorflow/core/util/port.cc:111] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`.\n",
      "2024-03-24 01:29:32.219815: I tensorflow/tsl/cuda/cudart_stub.cc:28] Could not find cuda drivers on your machine, GPU will not be used.\n",
      "2024-03-24 01:29:32.245983: E tensorflow/compiler/xla/stream_executor/cuda/cuda_dnn.cc:9342] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\n",
      "2024-03-24 01:29:32.246003: E tensorflow/compiler/xla/stream_executor/cuda/cuda_fft.cc:609] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered\n",
      "2024-03-24 01:29:32.246022: E tensorflow/compiler/xla/stream_executor/cuda/cuda_blas.cc:1518] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered\n",
      "2024-03-24 01:29:32.251166: I tensorflow/tsl/cuda/cudart_stub.cc:28] Could not find cuda drivers on your machine, GPU will not be used.\n",
      "2024-03-24 01:29:32.251625: I tensorflow/core/platform/cpu_feature_guard.cc:182] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.\n",
      "To enable the following instructions: AVX2 AVX512F AVX512_VNNI AVX512_BF16 AVX_VNNI AMX_TILE AMX_INT8 AMX_BF16 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.\n",
      "2024-03-24 01:29:34.718987: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT\n",
      "2024-03-24 01:29:36.469335: I itex/core/wrapper/itex_cpu_wrapper.cc:60] Intel Extension for Tensorflow* AVX512 CPU backend is loaded.\n",
      "2024-03-24 01:29:36.877562: I itex/core/wrapper/itex_gpu_wrapper.cc:35] Intel Extension for Tensorflow* GPU backend is loaded.\n",
      "2024-03-24 01:29:36.959003: I itex/core/devices/gpu/itex_gpu_runtime.cc:129] Selected platform: Intel(R) Level-Zero\n",
      "2024-03-24 01:29:36.959284: I itex/core/devices/gpu/itex_gpu_runtime.cc:154] number of sub-devices is zero, expose root device.\n"
     ]
    }
   ],
   "source": [
    "import logging\n",
    "import os\n",
    "import warnings\n",
    "import predictionguard as pg\n",
    "\n",
    "warnings.filterwarnings(\n",
    "    \"ignore\", category=UserWarning, module=\"intel_extension_for_pytorch\"\n",
    ")\n",
    "warnings.filterwarnings(\n",
    "    \"ignore\", category=UserWarning, module=\"torchvision.io.image\", lineno=13\n",
    ")\n",
    "warnings.filterwarnings(\n",
    "    \"ignore\",\n",
    "    message=\"The installed version of bitsandbytes was compiled without GPU support.*\",\n",
    "    category=UserWarning,\n",
    "    module='bitsandbytes.cextension'\n",
    ")\n",
    "warnings.filterwarnings(\"ignore\")\n",
    "warnings.filterwarnings(\n",
    "    \"ignore\",\n",
    "    category=FutureWarning,\n",
    "    message=\"This implementation of AdamW is deprecated\",\n",
    ")\n",
    "os.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n",
    "os.environ[\"NUMEXPR_MAX_THREADS\"] = \"28\"\n",
    "os.environ[\"ENABLE_SDP_FUSION\"] = \"true\"\n",
    "os.environ[\"SYCL_PI_LEVEL_ZERO_USE_IMMEDIATE_COMMANDLISTS\"]=\"1\"\n",
    "\n",
    "os.environ[\"PREDICTIONGUARD_TOKEN\"] = \"q1VuOjnffJ3NO2oFN8Q9m8vghYc84ld13jaqdF7E\"\n",
    "\n",
    "logging.getLogger(\"transformers\").setLevel(logging.ERROR)\n",
    "logging.getLogger(\"bigdl\").setLevel(logging.ERROR)\n",
    "\n",
    "\n",
    "import torch\n",
    "import intel_extension_for_pytorch as ipex\n",
    "from datasets import load_dataset\n",
    "from datasets import Dataset\n",
    "from bigdl.llm.transformers import AutoModelForCausalLM\n",
    "from bigdl.llm.transformers.qlora import (\n",
    "    get_peft_model,\n",
    "    prepare_model_for_kbit_training as prepare_model,\n",
    ")\n",
    "from peft import LoraConfig\n",
    "from bigdl.llm.transformers.qlora import PeftModel\n",
    "import transformers\n",
    "from transformers import (\n",
    "    BitsAndBytesConfig,\n",
    "    DataCollatorForSeq2Seq,\n",
    "    LlamaTokenizer,\n",
    "    AutoTokenizer,\n",
    "    Trainer,\n",
    "    TrainingArguments,\n",
    ")\n",
    "\n",
    "transformers.logging.set_verbosity_error()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "02b08285",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "**Note on Model Storage Management**\n",
    "\n",
    "A set of LLM foundation models are supported out-of-the-box as stated below `BASE_MDOELS` dictionary. However, if you're interested in experimenting with additional models, consider the following guidelines:\n",
    "\n",
    "- **Storage Quota:** Be mindful of your free storage quota and space requirements for additional models.\n",
    "- **PEFT Library Support:** For models supported by `peft`, refer to the [PEFT repository](https://github.com/huggingface/peft/blob/main/src/peft/utils/other.py#L434) for predefined LoRA target modules.\n",
    "- **Custom Models:** For non-`peft` models, manually configure LoRA target modules in `LoraConfig`. Example for llama models: `[\"q_proj\", \"k_proj\", \"v_proj\", \"o_proj\"]`.\n",
    "- **Disk Space Management:** Check disk space with the provided Python function. Delete cache to free space, but this requires re-downloading models later.\n",
    "- **Reset Model Cache Path:** Update `MODEL_CACHE_PATH = \"~/\"` in the **Model Configuration** cell.\n",
    "\n",
    "---\n",
    "\n",
    "**Python Function to Check Disk Space**\n",
    "\n",
    "```python\n",
    "# Function to check available disk space in the Hugging Face cache directory\n",
    "import os\n",
    "import shutil\n",
    "\n",
    "def check_disk_space(path=\"~/.cache/huggingface/\"):\n",
    "    abs_path = os.path.expanduser(path)\n",
    "    total, used, free = shutil.disk_usage(abs_path)\n",
    "    print(f\"Total: {total // (2**30)} GiB\")\n",
    "    print(f\"Used: {used // (2**30)} GiB\")\n",
    "    print(f\"Free: {free // (2**30)} GiB\")\n",
    "\n",
    "# Example usage\n",
    "check_disk_space()\n",
    "```\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "131864cb-ce5d-405b-8886-5d0f1f487c30",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "**Tailoring Your Model Configuration**\n",
    "\n",
    "Dive into the customization core of LLM fine-tuning, equipped with a diverse range of base models to suit unique goals.\n",
    "\n",
    "- **Model Choices in `BASE_MODELS`**: \n",
    "  - From the `open_llama_3b_v2` to the broader `Llama-2-13b-hf`.\n",
    "  - Specialized options like `CodeLlama-7b-hf`.\n",
    "  - Experiment to find the best fit for your objectives.\n",
    "\n",
    "- **Dataset**:\n",
    "  - Using `b-mc2/sql-create-context` from Huggingface datasets, a set of 78,577 examples (natural language queries, SQL statements).\n",
    "  - Ideal for text-to-SQL models. Dataset details [here](https://huggingface.co/datasets/b-mc2/sql-create-context).\n",
    "\n",
    "- **Your Model Options**: Within the `BASE_MODELS`, you’ll find options ranging from the nimble\n",
    "  `open_llama_7b_v2` to the more expansive `Llama-2-13b-hf`, and specialized variants like `CodeLlama-7b-hf`.\n",
    "  Feel free to switch between these models to discover which one aligns best with your objectives.\n",
    "\n",
    "- **LoRA Parameters - Your Knobs to Turn**:\n",
    "  - `r` (Rank): This is a key factor in how finely your model can adapt. A higher rank can grasp more\n",
    "    complex nuances, while a lower rank ensures a leaner memory footprint.\n",
    "  - `lora_alpha` (Scaling Factor): Adjusts LoRA adapters' impact.\n",
    "    the integrity of the pre-trained weights.\n",
    "  - `target_modules`: You decide which parts of the transformer model to enhance with LoRA adapters,\n",
    "    directly impacting how your model interprets and generates language.\n",
    "  - `lora_dropout`: Controls overfitting; experiment for optimal generalization.\n",
    "  - `bias`: Modify to observe learning dynamic changes.\n",
    "\n",
    "This notebook is set to start with `CodeLlama-7b-hf` as the default model, as our task is to generate code. To use models like Llama 2, you will have to accept the usage policy as stipulated [here](https://ai.meta.com/llama/use-policy/)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "88077cc2-8fcf-4128-ac44-9fb2bb327398",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================================================================\n",
      "Using Device: xpu\n",
      "Final model will be saved to: ./final_model\n",
      "LoRA adapters will be saved to: ./lora_adapters\n",
      "Finetuning Model: NousResearch/CodeLlama-7b-hf\n",
      "Using dataset from: b-mc2/sql-create-context\n",
      "Model cache: /home/common/data/Big_Data/GenAI/llm_models\n",
      "================================================================================\n"
     ]
    }
   ],
   "source": [
    "BASE_MODELS = {\n",
    "    \"0\": \"NousResearch/Nous-Hermes-Llama-2-7b\",  # https://huggingface.co/NousResearch/Nous-Hermes-llama-2-7b\n",
    "    \"1\": \"NousResearch/Llama-2-7b-chat-hf\",  # https://huggingface.co/NousResearch/Llama-2-7b-chat-hf\n",
    "    \"2\": \"NousResearch/Llama-2-13b-hf\",  # https://huggingface.co/NousResearch/Llama-2-13b-hf\n",
    "    \"3\": \"NousResearch/CodeLlama-7b-hf\",  # https://huggingface.co/NousResearch/CodeLlama-7b-hf\n",
    "    \"4\": \"Phind/Phind-CodeLlama-34B-v2\",  # https://huggingface.co/Phind/Phind-CodeLlama-34B-v2\n",
    "    \"5\": \"openlm-research/open_llama_3b_v2\",  # https://huggingface.co/openlm-research/open_llama_3b_v2\n",
    "    \"6\": \"openlm-research/open_llama_13b\",  # https://huggingface.co/openlm-research/open_llama_13b\n",
    "    \"7\": \"HuggingFaceH4/zephyr-7b-beta\", # https://huggingface.co/HuggingFaceH4/zephyr-7b-beta\n",
    "}\n",
    "BASE_MODEL = BASE_MODELS[\"3\"]\n",
    "DATA_PATH = \"b-mc2/sql-create-context\"\n",
    "MODEL_PATH = \"./final_model\"\n",
    "ADAPTER_PATH = \"./lora_adapters\"\n",
    "DEVICE = torch.device(\"xpu\" if torch.xpu.is_available() else \"cpu\")\n",
    "LORA_CONFIG = LoraConfig(\n",
    "    r=16,  # rank\n",
    "    lora_alpha=32,  # scaling factor\n",
    "    target_modules=[\"q_proj\", \"k_proj\", \"v_proj\"], \n",
    "    lora_dropout=0.05,\n",
    "    bias=\"none\",\n",
    "    task_type=\"CAUSAL_LM\",\n",
    ")\n",
    "MODEL_CACHE_PATH = \"/home/common/data/Big_Data/GenAI/llm_models\"\n",
    "\n",
    "print(\"=\" * 80)\n",
    "print(f\"Using Device: {DEVICE}\")\n",
    "print(f\"Final model will be saved to: {MODEL_PATH}\")\n",
    "print(f\"LoRA adapters will be saved to: {ADAPTER_PATH}\")\n",
    "print(f\"Finetuning Model: {BASE_MODEL}\")\n",
    "print(f\"Using dataset from: {DATA_PATH}\")\n",
    "print(f\"Model cache: {MODEL_CACHE_PATH}\")\n",
    "print(\"=\" * 80)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d797b621-fd06-4ae9-a883-d7d15f16d6c4",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "**Prompt Engineering for Text-to-SQL Conversion**\n",
    "\n",
    "In the realm of fine-tuning language models for specialized tasks, the design of the prompt is pivotal. The function `generate_prompt_sql` encapsulates the input question, the relevant database context, and the expected output in a structured and concise manner.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "d8ecd7df-b7ce-48b0-ba9f-04b7ec0c1cf4",
   "metadata": {},
   "outputs": [],
   "source": [
    "def generate_prompt_sql(input_question, context, output=\"\"):\n",
    "    \"\"\"\n",
    "    Generates a prompt for fine-tuning the LLM model for text-to-SQL tasks.\n",
    "\n",
    "    Parameters:\n",
    "        input_question (str): The input text or question to be converted to SQL.\n",
    "        context (str): The schema or context in which the SQL query operates.\n",
    "        output (str, optional): The expected SQL query as the output.\n",
    "\n",
    "    Returns:\n",
    "        str: A formatted string serving as the prompt for the fine-tuning task.\n",
    "    \"\"\"\n",
    "    return f\"\"\"You are a powerful text-to-SQL model. Your job is to answer questions about a database. You are given a question and context regarding one or more tables.\"\"\" \n",
    "\n",
    "### Input:\n",
    "input_question = str(\"How many employees live in california\")\n",
    "\n",
    "### Context:\n",
    "context = str(\"the number of approximate employees worldwide, country, and state they are in a single company\")\n",
    "\n",
    "### Response:\n",
    "response = f\"Knowing {context}, can you answer {input_question}?\"\n",
    "\n",
    "output = \"Select from table employees with california home\" #approximately"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9dd863cc",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "**Model Loading and Configuration**\n",
    "\n",
    "Initializing the `FineTuner`, we load the base model using `base_model_id`. Key to this setup is the ` bnb_4bit_quant_type=\"nf4\"` option, using bitsandbytes library, checkout [BigDL library](https://bigdl.readthedocs.io/en/latest/) for more information on this. This approach significantly cuts down on memory. Additionally, we configure the LoRA adapters for mixed-precision training with `torch.float16`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "aeab82dc",
   "metadata": {},
   "outputs": [],
   "source": [
    "def setup_model_and_tokenizer(base_model_id: str):\n",
    "    \"\"\"Downloads / Loads the pre-trained model and tokenizer based on the given base model ID for training, \n",
    "    with fallbacks for permission errors to use default cache.\"\"\"\n",
    "    local_model_id = base_model_id.replace(\"/\", \"--\")\n",
    "    local_model_path = os.path.join(MODEL_CACHE_PATH, local_model_id)\n",
    "\n",
    "    bnb_config = BitsAndBytesConfig(\n",
    "        load_in_8bit=True,\n",
    "        bnb_4bit_use_double_quant=False,\n",
    "        bnb_4bit_quant_type=\"nf4\",\n",
    "        bnb_4bit_compute_dtype=torch.bfloat16,\n",
    "        accelerator='onnxruntime',\n",
    "    )\n",
    "    try:\n",
    "        print(f\"Attempting to load model and tokenizer from: {local_model_path}\")\n",
    "        model = AutoModelForCausalLM.from_pretrained(\n",
    "            local_model_path,\n",
    "            quantization_config=bnb_config,\n",
    "        )\n",
    "        tokenizer_class = LlamaTokenizer if \"llama\" in base_model_id.lower() else AutoTokenizer\n",
    "        tokenizer = tokenizer_class.from_pretrained(local_model_path)\n",
    "    except (OSError, PermissionError) as e:\n",
    "        print(f\"Failed to load from {local_model_path} due to {e}. Attempting to download...\")\n",
    "        model = AutoModelForCausalLM.from_pretrained(\n",
    "            base_model_id, \n",
    "            quantization_config=bnb_config,\n",
    "        )\n",
    "        tokenizer_class = LlamaTokenizer if \"llama\" in base_model_id.lower() else AutoTokenizer\n",
    "        tokenizer = tokenizer_class.from_pretrained(base_model_id)\n",
    "\n",
    "    tokenizer.pad_token_id = 0\n",
    "    tokenizer.padding_side = \"left\"\n",
    "    return model, tokenizer\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3777656b-74f4-4ebc-b741-a5d50bc6e79a",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "**FineTuner**\n",
    "\n",
    "The `FineTuner` class encapsulates the entire process of fine-tuning llms for tasks such as text-to-SQL conversion.\n",
    "\n",
    "\n",
    "**Tokenization Strategy**\n",
    "\n",
    "The tokenization process is tailored to the type of model being fine-tuned. For instance, if we are working with a Llama model, we utilize a `LlamaTokenizer` to ensure compatibility with the model's expected input format. For other models, a generic `AutoTokenizer` is used. We configure the tokenizer to pad from the left side (`padding_side=\"left\"`) and set the pad token ID to 0.\n",
    "\n",
    "**Data Tokenization and Preparation**\n",
    "\n",
    "The `tokenize_data` method is where the fine-tuner ingests raw text data and converts it into a format suitable for training the model. This method handles the addition of end-of-sequence tokens, truncation to a specified `cutoff_len`, and conditioning on the input for training.\n",
    "\n",
    "**Dataset Handling**\n",
    "\n",
    "`prepare_data` manages the splitting of data into training and validation sets, applying the `tokenize_data` transformation to each entry. This ensures that our datasets are ready for input into the model, with all necessary tokenization applied.\n",
    "\n",
    "**Training Process**\n",
    "\n",
    "Finally, the `train_model` method orchestrates the training process, setting up the `Trainer` with the correct datasets, training arguments, and data collator. The fine-tuning process is encapsulated within the `finetune` method, which strings together all the previous steps into a coherent pipeline, from model setup to training execution.\n",
    "\n",
    "**Using QLoRA for Efficient Fine-Tuning**\n",
    "1. Load a pretrained model (e.g., LLaMA2) in low precision with ` bnb_4bit_quant_type=\"nf4\"` for 4-bit quantized weights.\n",
    "2. Prepare the quantized model with `prepare_model(model)`, handling weight quantization.\n",
    "3. Add LoRA adapters via `get_peft_model(model, config)` for setting adapter parameters.\n",
    "4. Fine-tune with `Trainer`, focusing gradients on adapters while keeping base model weights fixed.\n",
    "\n",
    "**Code Implementation**\n",
    "- Model loading with BigDL's `AutoModelForCausalLM`, initializing in 4-bit using `load_in_low_bit=\"nf4\"`.\n",
    "- `prepare_model()` quantizes the model weights.\n",
    "- `get_peft_model()` adds LoRA adapters.\n",
    "- Trainer handles fine-tuning, optimizing only adapter weights.\n",
    "\n",
    "\n",
    "So in summary, we leverage QLoRA in BigDL to load the base LLM in low precision, inject adapters with `peft`, and efficiently finetune by optimizing just the adapters end-to-end while keeping the base model fixed. This unlocks huge memory savings, allowing us to adapt giant models."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "4d8f4cb8-0da5-4572-bd07-bdae1db897a3",
   "metadata": {},
   "outputs": [],
   "source": [
    "class FineTuner:\n",
    "    \"\"\"A class to handle the fine-tuning of LLM models.\"\"\"\n",
    "\n",
    "    def __init__(self, base_model_id: str, model_path: str, device: torch.device):\n",
    "        \"\"\"\n",
    "        Initialize the FineTuner with base model, model path, and device.\n",
    "\n",
    "        Parameters:\n",
    "            base_model_id (str): Id of pre-trained model to use for fine-tuning.\n",
    "            model_path (str): Path to save the fine-tuned model.\n",
    "            device (torch.device): Device to run the model on.\n",
    "        \"\"\"\n",
    "        self.base_model_id = base_model_id\n",
    "        self.model_path = model_path\n",
    "        self.device = device\n",
    "        self.model, self.tokenizer = setup_model_and_tokenizer(base_model_id)\n",
    "\n",
    "\n",
    "    def tokenize_data(\n",
    "        self, data_points, add_eos_token=True, train_on_inputs=False, cutoff_len=512\n",
    "    ) -> dict:\n",
    "        \"\"\"\n",
    "        Tokenizes dataset of SQL related data points consisting of questions, context, and answers.\n",
    "\n",
    "        Parameters:\n",
    "            data_points (dict): A batch from the dataset containing 'question', 'context', and 'answer'.\n",
    "            add_eos_token (bool): Whether to add an EOS token at the end of each tokenized sequence.\n",
    "            cutoff_len (int): The maximum length for each tokenized sequence.\n",
    "\n",
    "        Returns:\n",
    "            dict: A dictionary containing tokenized 'input_ids', 'attention_mask', and 'labels'.\n",
    "        \"\"\"\n",
    "        try:\n",
    "            question = data_points[\"question\"]\n",
    "            context = data_points[\"context\"]\n",
    "            answer = data_points[\"answer\"]\n",
    "            if train_on_inputs:\n",
    "                user_prompt = generate_prompt_sql(question, context)\n",
    "                tokenized_user_prompt = self.tokenizer(\n",
    "                    user_prompt,\n",
    "                    truncation=True,\n",
    "                    max_length=cutoff_len,\n",
    "                    padding=False,\n",
    "                    return_tensors=None,\n",
    "                )\n",
    "                user_prompt_len = len(tokenized_user_prompt[\"input_ids\"])\n",
    "                if add_eos_token:\n",
    "                    user_prompt_len -= 1\n",
    "\n",
    "            combined_text = generate_prompt_sql(question, context, answer)\n",
    "            tokenized = self.tokenizer(\n",
    "                combined_text,\n",
    "                truncation=True,\n",
    "                max_length=cutoff_len,\n",
    "                padding=False,\n",
    "                return_tensors=None,\n",
    "            )\n",
    "            if (\n",
    "                tokenized[\"input_ids\"][-1] != self.tokenizer.eos_token_id\n",
    "                and add_eos_token\n",
    "                and len(tokenized[\"input_ids\"]) < cutoff_len\n",
    "            ):\n",
    "                tokenized[\"input_ids\"].append(self.tokenizer.eos_token_id)\n",
    "                tokenized[\"attention_mask\"].append(1)\n",
    "            tokenized[\"labels\"] = tokenized[\"input_ids\"].copy()\n",
    "            if train_on_inputs:\n",
    "                tokenized[\"labels\"] = [-100] * user_prompt_len + tokenized[\"labels\"][\n",
    "                    user_prompt_len:\n",
    "                ]\n",
    "            return tokenized\n",
    "        except Exception as e:\n",
    "            logging.error(\n",
    "                f\"Error in batch tokenization: {e}\"\n",
    "            )\n",
    "            raise e\n",
    "\n",
    "    def prepare_data(self, data, val_set_size=100) -> Dataset:\n",
    "        \"\"\"Prepare training and validation datasets.\"\"\"\n",
    "        try:\n",
    "            train_val_split = data[\"train\"].train_test_split(\n",
    "                test_size=val_set_size, shuffle=True, seed=42\n",
    "            )\n",
    "            train_data = train_val_split[\"train\"].shuffle().map(self.tokenize_data)\n",
    "            val_data = train_val_split[\"test\"].shuffle().map(self.tokenize_data)\n",
    "            return train_data, val_data\n",
    "        except Exception as e:\n",
    "            logging.error(\n",
    "                f\"Error in preparing data: {e}\"\n",
    "            )\n",
    "            raise e\n",
    "\n",
    "    def train_model(self, train_data, val_data, training_args):\n",
    "        \"\"\"\n",
    "        Fine-tune the model with the given training and validation data.\n",
    "\n",
    "        Parameters:\n",
    "            train_data (Dataset): Training data.\n",
    "            val_data (Optional[Dataset]): Validation data.\n",
    "            training_args (TrainingArguments): Training configuration.\n",
    "        \"\"\"\n",
    "        try:\n",
    "            self.model = self.model.to(self.device)\n",
    "            self.model.gradient_checkpointing_enable()\n",
    "            self.model = prepare_model(self.model)\n",
    "            self.model = get_peft_model(self.model, LORA_CONFIG)\n",
    "            trainer = Trainer(\n",
    "                model=self.model,\n",
    "                train_dataset=train_data,\n",
    "                eval_dataset=val_data,\n",
    "                args=training_args,\n",
    "                data_collator=DataCollatorForSeq2Seq(\n",
    "                    self.tokenizer,\n",
    "                    pad_to_multiple_of=8,\n",
    "                    return_tensors=\"pt\",\n",
    "                    padding=True,\n",
    "                ),\n",
    "            )\n",
    "            self.model.config.use_cache = False\n",
    "            results = trainer.train()\n",
    "            #print(results)\n",
    "            self.model.save_pretrained(self.model_path)\n",
    "        except Exception as e:\n",
    "            logging.error(f\"Error in model training: {e}\")\n",
    "\n",
    "    def finetune(self, data_path, training_args):\n",
    "        \"\"\"\n",
    "        Execute the fine-tuning pipeline.\n",
    "\n",
    "        Parameters:\n",
    "            data_path (str): Path to the data for fine-tuning.\n",
    "            training_args (TrainingArguments): Training configuration.\n",
    "        \"\"\"\n",
    "        try:\n",
    "            data = load_dataset(data_path)\n",
    "            train_data, val_data = self.prepare_data(data)\n",
    "            self.train_model(train_data, val_data, training_args)\n",
    "        except KeyboardInterrupt:\n",
    "            print(\"Interrupt received, saving model...\")\n",
    "            self.model.save_pretrained(f\"{self.model_path}_interrupted\")\n",
    "            print(f\"Model saved to {self.model_path}_interrupted\")\n",
    "        except Exception as e:\n",
    "            logging.error(f\"Error in fintuning: {e}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "34af4187-d362-49b8-bdbc-e8d2a7ae0ac0",
   "metadata": {},
   "source": [
    "---\n",
    "**Fine-Tuning the Model**\n",
    "\n",
    "The `lets_finetune` function orchestrates the fine-tuning process, offering a customizable interface for training. It enables specification of device, model, batch size, warm-up steps, learning rate, and maximum training steps.\n",
    "\n",
    "\n",
    "**Some of the key Training Parameters:**\n",
    "- `per_device_batch_size`: Number of batches on each XPU.\n",
    "- `gradient_accumulation_steps`: Enables larger effective batch sizes.\n",
    "- `warmup_steps`: Stabilizes training dynamics at the start.\n",
    "- `save_steps`: Determines checkpoint frequency.\n",
    "- `max_steps`: Limits training iterations, start with a high number like 1000 or 2000 (default here is `200`).\n",
    "- `learning_rate`: Balances convergence speed and training stability.\n",
    "- `max_grad_norm`: Clips gradients to avoid excessively large values.\n",
    "\n",
    "**Monitoring and Interruption**\n",
    "- Monitor training/validation loss to identify optimal stopping point.\n",
    "- Interrupt training in Jupyter via `Kernel -> Interrupt Kernel` if performance is satisfactory before `max_steps`.\n",
    "- Latest checkpoint is saved in `./final_model_interrupted`; last saved adapter checkpoint in `./lora_adapters`.\n",
    "\n",
    "This setup allows for efficient and flexible model fine-tuning, adaptable to varying project needs and computational constraints.\n",
    "\n",
    "---\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "67a39122-eafc-483c-ad81-9c55de15e936",
   "metadata": {},
   "outputs": [],
   "source": [
    "ENABLE_WANDB = True\n",
    "\n",
    "def lets_finetune(\n",
    "    device=DEVICE,\n",
    "    model=BASE_MODEL,\n",
    "    per_device_batch_size=4,\n",
    "    warmup_steps=20,\n",
    "    learning_rate=2e-5,\n",
    "    max_steps=200,\n",
    "    gradient_accum_steps=4,\n",
    "):\n",
    "    try:\n",
    "        # Training parameters\n",
    "        save_steps = 20\n",
    "        eval_steps = 20\n",
    "        max_grad_norm = 0.3\n",
    "        save_total_limit = 3\n",
    "        logging_steps = 20\n",
    "\n",
    "        print(\"\\n\" + \"\\033[1;34m\" + \"=\" * 60 + \"\\033[0m\")\n",
    "        print(\"\\033[1;34mTraining Parameters:\\033[0m\")\n",
    "        param_format = \"\\033[1;34m{:<25} {}\\033[0m\"\n",
    "        print(param_format.format(\"Foundation model:\", BASE_MODEL))\n",
    "        print(param_format.format(\"Model save path:\", MODEL_PATH))\n",
    "        print(param_format.format(\"Device used:\", DEVICE))\n",
    "        if DEVICE.type.startswith(\"xpu\"):\n",
    "            print(param_format.format(\"Intel GPU:\", torch.xpu.get_device_name()))\n",
    "        print(param_format.format(\"Batch size per device:\", per_device_batch_size))\n",
    "        print(param_format.format(\"Gradient accum. steps:\", gradient_accum_steps))\n",
    "        print(param_format.format(\"Warmup steps:\", warmup_steps))\n",
    "        print(param_format.format(\"Save steps:\", save_steps))\n",
    "        print(param_format.format(\"Evaluation steps:\", eval_steps))\n",
    "        print(param_format.format(\"Max steps:\", max_steps))\n",
    "        print(param_format.format(\"Learning rate:\", learning_rate))\n",
    "        print(param_format.format(\"Max gradient norm:\", max_grad_norm))\n",
    "        print(param_format.format(\"Save total limit:\", save_total_limit))\n",
    "        print(param_format.format(\"Logging steps:\", logging_steps))\n",
    "        print(\"\\033[1;34m\" + \"=\" * 60 + \"\\033[0m\\n\")\n",
    "\n",
    "        # Initialize the finetuner with the model and device information\n",
    "        finetuner = FineTuner(\n",
    "            base_model_id=model, model_path=MODEL_PATH, device=device\n",
    "        )\n",
    "\n",
    "        training_args = TrainingArguments(\n",
    "            per_device_train_batch_size=per_device_batch_size,\n",
    "            gradient_accumulation_steps=gradient_accum_steps,\n",
    "            warmup_steps=warmup_steps,\n",
    "            save_steps=save_steps,\n",
    "            save_strategy=\"steps\",\n",
    "            eval_steps=eval_steps,\n",
    "            evaluation_strategy=\"steps\",\n",
    "            max_steps=max_steps,\n",
    "            learning_rate=learning_rate,\n",
    "            #max_grad_norm=max_grad_norm,\n",
    "            bf16=True,\n",
    "            use_ipex=True,\n",
    "            #lr_scheduler_type=\"cosine\",\n",
    "            load_best_model_at_end=True,\n",
    "            ddp_find_unused_parameters=False,\n",
    "            group_by_length=True,\n",
    "            save_total_limit=save_total_limit,\n",
    "            logging_steps=logging_steps,\n",
    "            optim=\"adamw_hf\",\n",
    "            output_dir=\"./lora_adapters\",\n",
    "            logging_dir=\"./logs\",\n",
    "            report_to=\"wandb\" if ENABLE_WANDB else [],\n",
    "        )\n",
    "        # Start fine-tuning\n",
    "        finetuner.finetune(DATA_PATH, training_args)\n",
    "    except Exception as e:\n",
    "        logging.error(f\"Error occurred: {e}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5ddc5dee-498b-498a-9ad8-d03f569e9e9a",
   "metadata": {},
   "source": [
    "We can optionally use Weights & Biases to track our training metrics, uncomment the below cell to enable `wandb`. You will need to pass in your API key when prompted. You can ofcourse skip this step if you'd like to.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "f1a31697-8bf5-4ec9-9e13-bb7095218fcd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "installing wandb...\n",
      "installation complete...\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-03-24 01:30:49,246 - wandb.jupyter - ERROR - Failed to detect the name of this notebook, you can set it manually with the WANDB_NOTEBOOK_NAME environment variable to enable code saving.\n",
      "2024-03-24 01:30:54,065 - wandb.sdk.lib.retry - INFO - Retry attempt failed:\n",
      "Traceback (most recent call last):\n",
      "  File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/connectionpool.py\", line 793, in urlopen\n",
      "    response = self._make_request(\n",
      "  File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/connectionpool.py\", line 491, in _make_request\n",
      "    raise new_e\n",
      "  File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/connectionpool.py\", line 467, in _make_request\n",
      "    self._validate_conn(conn)\n",
      "  File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/connectionpool.py\", line 1099, in _validate_conn\n",
      "    conn.connect()\n",
      "  File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/connection.py\", line 653, in connect\n",
      "    sock_and_verified = _ssl_wrap_socket_and_match_hostname(\n",
      "  File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/connection.py\", line 806, in _ssl_wrap_socket_and_match_hostname\n",
      "    ssl_sock = ssl_wrap_socket(\n",
      "  File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/util/ssl_.py\", line 465, in ssl_wrap_socket\n",
      "    ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls, server_hostname)\n",
      "  File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/util/ssl_.py\", line 509, in _ssl_wrap_socket_impl\n",
      "    return ssl_context.wrap_socket(sock, server_hostname=server_hostname)\n",
      "  File \"/opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/ssl.py\", line 501, in wrap_socket\n",
      "    return self.sslsocket_class._create(\n",
      "  File \"/opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/ssl.py\", line 1074, in _create\n",
      "    self.do_handshake()\n",
      "  File \"/opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/ssl.py\", line 1343, in do_handshake\n",
      "    self._sslobj.do_handshake()\n",
      "ConnectionResetError: [Errno 104] Connection reset by peer\n",
      "\n",
      "During handling of the above exception, another exception occurred:\n",
      "\n",
      "Traceback (most recent call last):\n",
      "  File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/requests/adapters.py\", line 486, in send\n",
      "    resp = conn.urlopen(\n",
      "  File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/connectionpool.py\", line 847, in urlopen\n",
      "    retries = retries.increment(\n",
      "  File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/util/retry.py\", line 470, in increment\n",
      "    raise reraise(type(error), error, _stacktrace)\n",
      "  File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/util/util.py\", line 38, in reraise\n",
      "    raise value.with_traceback(tb)\n",
      "  File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/connectionpool.py\", line 793, in urlopen\n",
      "    response = self._make_request(\n",
      "  File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/connectionpool.py\", line 491, in _make_request\n",
      "    raise new_e\n",
      "  File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/connectionpool.py\", line 467, in _make_request\n",
      "    self._validate_conn(conn)\n",
      "  File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/connectionpool.py\", line 1099, in _validate_conn\n",
      "    conn.connect()\n",
      "  File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/connection.py\", line 653, in connect\n",
      "    sock_and_verified = _ssl_wrap_socket_and_match_hostname(\n",
      "  File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/connection.py\", line 806, in _ssl_wrap_socket_and_match_hostname\n",
      "    ssl_sock = ssl_wrap_socket(\n",
      "  File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/util/ssl_.py\", line 465, in ssl_wrap_socket\n",
      "    ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls, server_hostname)\n",
      "  File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/urllib3/util/ssl_.py\", line 509, in _ssl_wrap_socket_impl\n",
      "    return ssl_context.wrap_socket(sock, server_hostname=server_hostname)\n",
      "  File \"/opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/ssl.py\", line 501, in wrap_socket\n",
      "    return self.sslsocket_class._create(\n",
      "  File \"/opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/ssl.py\", line 1074, in _create\n",
      "    self.do_handshake()\n",
      "  File \"/opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/ssl.py\", line 1343, in do_handshake\n",
      "    self._sslobj.do_handshake()\n",
      "urllib3.exceptions.ProtocolError: ('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))\n",
      "\n",
      "During handling of the above exception, another exception occurred:\n",
      "\n",
      "Traceback (most recent call last):\n",
      "  File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/wandb/sdk/lib/retry.py\", line 131, in __call__\n",
      "    result = self._call_fn(*args, **kwargs)\n",
      "  File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/wandb/sdk/internal/internal_api.py\", line 366, in execute\n",
      "    return self.client.execute(*args, **kwargs)  # type: ignore\n",
      "  File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/wandb/vendor/gql-0.2.0/wandb_gql/client.py\", line 52, in execute\n",
      "    result = self._get_result(document, *args, **kwargs)\n",
      "  File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/wandb/vendor/gql-0.2.0/wandb_gql/client.py\", line 60, in _get_result\n",
      "    return self.transport.execute(document, *args, **kwargs)\n",
      "  File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/wandb/sdk/lib/gql_request.py\", line 58, in execute\n",
      "    request = self.session.post(self.url, **post_args)\n",
      "  File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/requests/sessions.py\", line 637, in post\n",
      "    return self.request(\"POST\", url, data=data, json=json, **kwargs)\n",
      "  File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/requests/sessions.py\", line 589, in request\n",
      "    resp = self.send(prep, **send_kwargs)\n",
      "  File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/requests/sessions.py\", line 703, in send\n",
      "    r = adapter.send(request, **kwargs)\n",
      "  File \"/home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/requests/adapters.py\", line 501, in send\n",
      "    raise ConnectionError(err, request=request)\n",
      "requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))\n",
      "\u001b[34m\u001b[1mwandb\u001b[0m: Network error (ConnectionError), entering retry loop.\n",
      "\u001b[34m\u001b[1mwandb\u001b[0m: W&B API key is configured. Use \u001b[1m`wandb login --relogin`\u001b[0m to force relogin\n"
     ]
    }
   ],
   "source": [
    "if ENABLE_WANDB:\n",
    "    print(\"installing wandb...\")\n",
    "    !{sys.executable} -m pip install -U --force \"wandb==0.15.12\" > /dev/null 2>&1\n",
    "    print(\"installation complete...\")\n",
    "\n",
    "    import wandb\n",
    "    os.environ[\"WANDB_PROJECT\"] = f\"text-to-sql-finetune-model-name_{BASE_MODEL.replace('/', '_')}\"\n",
    "    os.environ[\"WANDB_LOG_MODEL\"] = \"checkpoint\"\n",
    "    wandb.login()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c497cbaf-994b-474b-92f1-fb33fca6b81f",
   "metadata": {},
   "source": [
    "\n",
    "---\n",
    "\n",
    "**Let's Finetune!**\n",
    "\n",
    "Now it's time to actually fine-tune the model. The `lets_finetune` function below takes care of this. It initializes a FineTuner object with the configurations you've set or left as default."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "1fa45c6d-fac1-4331-8dd5-3ebf9cceed6d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\u001b[1;34m============================================================\u001b[0m\n",
      "\u001b[1;34mTraining Parameters:\u001b[0m\n",
      "\u001b[1;34mFoundation model:         NousResearch/CodeLlama-7b-hf\u001b[0m\n",
      "\u001b[1;34mModel save path:          ./final_model\u001b[0m\n",
      "\u001b[1;34mDevice used:              xpu\u001b[0m\n",
      "\u001b[1;34mIntel GPU:                Intel(R) Data Center GPU Max 1100\u001b[0m\n",
      "\u001b[1;34mBatch size per device:    4\u001b[0m\n",
      "\u001b[1;34mGradient accum. steps:    4\u001b[0m\n",
      "\u001b[1;34mWarmup steps:             20\u001b[0m\n",
      "\u001b[1;34mSave steps:               20\u001b[0m\n",
      "\u001b[1;34mEvaluation steps:         20\u001b[0m\n",
      "\u001b[1;34mMax steps:                200\u001b[0m\n",
      "\u001b[1;34mLearning rate:            2e-05\u001b[0m\n",
      "\u001b[1;34mMax gradient norm:        0.3\u001b[0m\n",
      "\u001b[1;34mSave total limit:         3\u001b[0m\n",
      "\u001b[1;34mLogging steps:            20\u001b[0m\n",
      "\u001b[1;34m============================================================\u001b[0m\n",
      "\n",
      "Attempting to load model and tokenizer from: /home/common/data/Big_Data/GenAI/llm_models/NousResearch--CodeLlama-7b-hf\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "118e0ed053b744399bd7b4509b2269c4",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Loading checkpoint shards:   0%|          | 0/3 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "7205d215ca1d4a24a0060e1b728fb7c2",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Map:   0%|          | 0/78477 [00:00<?, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "b1ffa52982cf4e14bb4e6e415ac8452a",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Map:   0%|          | 0/100 [00:00<?, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "99e3ee573e8142ffb08379f52023da19",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "VBox(children=(Label(value='Waiting for wandb.init()...\\r'), FloatProgress(value=0.011112394375312659, max=1.0…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "wandb: Network error (ConnectTimeout), entering retry loop.\n",
      "2024-03-24 01:34:18,614 - root - ERROR - Error in model training: Run initialization has timed out after 90.0 sec. \n",
      "Please refer to the documentation for additional information: https://docs.wandb.ai/guides/track/tracking-faq#initstarterror-error-communicating-with-wandb-process-\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Problem at: /home/uafcb7f73a7c1b7b8895a40af90eab07/.local/lib/python3.9/site-packages/transformers/integrations/integration_utils.py 740 setup\n"
     ]
    }
   ],
   "source": [
    "lets_finetune()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "1b20eb38-aa96-4b44-8d72-03f0a89dfee6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "91dee373103542d7b4224662b7f46dd9",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "VBox(children=(HTML(value='<center> <img\\nsrc=https://huggingface.co/front/assets/huggingface_logo-noborder.sv…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "5d94af4c93b5473294d0a7868591cea1",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading config.json: 0.00B [00:00, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "ename": "OSError",
     "evalue": "It looks like the config file at '/home/uafcb7f73a7c1b7b8895a40af90eab07/.cache/huggingface/hub/models--Fredswqa1--DysfunctEcosenseLLM/snapshots/c8a9df5a77a07883e4ee3e59c9ca2683c4189c6b/config.json' is not a valid JSON file.",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mJSONDecodeError\u001b[0m                           Traceback (most recent call last)",
      "File \u001b[0;32m~/.local/lib/python3.9/site-packages/transformers/configuration_utils.py:705\u001b[0m, in \u001b[0;36mPretrainedConfig._get_config_dict\u001b[0;34m(cls, pretrained_model_name_or_path, **kwargs)\u001b[0m\n\u001b[1;32m    703\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[1;32m    704\u001b[0m     \u001b[38;5;66;03m# Load config dict\u001b[39;00m\n\u001b[0;32m--> 705\u001b[0m     config_dict \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mcls\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_dict_from_json_file\u001b[49m\u001b[43m(\u001b[49m\u001b[43mresolved_config_file\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m    706\u001b[0m     config_dict[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m_commit_hash\u001b[39m\u001b[38;5;124m\"\u001b[39m] \u001b[38;5;241m=\u001b[39m commit_hash\n",
      "File \u001b[0;32m~/.local/lib/python3.9/site-packages/transformers/configuration_utils.py:801\u001b[0m, in \u001b[0;36mPretrainedConfig._dict_from_json_file\u001b[0;34m(cls, json_file)\u001b[0m\n\u001b[1;32m    800\u001b[0m     text \u001b[38;5;241m=\u001b[39m reader\u001b[38;5;241m.\u001b[39mread()\n\u001b[0;32m--> 801\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mjson\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mloads\u001b[49m\u001b[43m(\u001b[49m\u001b[43mtext\u001b[49m\u001b[43m)\u001b[49m\n",
      "File \u001b[0;32m/opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/json/__init__.py:346\u001b[0m, in \u001b[0;36mloads\u001b[0;34m(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)\u001b[0m\n\u001b[1;32m    343\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m (\u001b[38;5;28mcls\u001b[39m \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m object_hook \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m\n\u001b[1;32m    344\u001b[0m         parse_int \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m parse_float \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m\n\u001b[1;32m    345\u001b[0m         parse_constant \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m object_pairs_hook \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m kw):\n\u001b[0;32m--> 346\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43m_default_decoder\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mdecode\u001b[49m\u001b[43m(\u001b[49m\u001b[43ms\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m    347\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mcls\u001b[39m \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n",
      "File \u001b[0;32m/opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/json/decoder.py:337\u001b[0m, in \u001b[0;36mJSONDecoder.decode\u001b[0;34m(self, s, _w)\u001b[0m\n\u001b[1;32m    333\u001b[0m \u001b[38;5;250m\u001b[39m\u001b[38;5;124;03m\"\"\"Return the Python representation of ``s`` (a ``str`` instance\u001b[39;00m\n\u001b[1;32m    334\u001b[0m \u001b[38;5;124;03mcontaining a JSON document).\u001b[39;00m\n\u001b[1;32m    335\u001b[0m \n\u001b[1;32m    336\u001b[0m \u001b[38;5;124;03m\"\"\"\u001b[39;00m\n\u001b[0;32m--> 337\u001b[0m obj, end \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mraw_decode\u001b[49m\u001b[43m(\u001b[49m\u001b[43ms\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43midx\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43m_w\u001b[49m\u001b[43m(\u001b[49m\u001b[43ms\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m0\u001b[39;49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mend\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m    338\u001b[0m end \u001b[38;5;241m=\u001b[39m _w(s, end)\u001b[38;5;241m.\u001b[39mend()\n",
      "File \u001b[0;32m/opt/intel/oneapi/intelpython/envs/pytorch-gpu/lib/python3.9/json/decoder.py:355\u001b[0m, in \u001b[0;36mJSONDecoder.raw_decode\u001b[0;34m(self, s, idx)\u001b[0m\n\u001b[1;32m    354\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mStopIteration\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m err:\n\u001b[0;32m--> 355\u001b[0m     \u001b[38;5;28;01mraise\u001b[39;00m JSONDecodeError(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mExpecting value\u001b[39m\u001b[38;5;124m\"\u001b[39m, s, err\u001b[38;5;241m.\u001b[39mvalue) \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m\n\u001b[1;32m    356\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m obj, end\n",
      "\u001b[0;31mJSONDecodeError\u001b[0m: Expecting value: line 1 column 1 (char 0)",
      "\nDuring handling of the above exception, another exception occurred:\n",
      "\u001b[0;31mOSError\u001b[0m                                   Traceback (most recent call last)",
      "Cell \u001b[0;32mIn[11], line 14\u001b[0m\n\u001b[1;32m     11\u001b[0m checkpoint_path \u001b[38;5;241m=\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mFredswqa1/DysfunctEcosenseLLM\u001b[39m\u001b[38;5;124m\"\u001b[39m  \u001b[38;5;66;03m# Replace with your checkpoint folder\u001b[39;00m\n\u001b[1;32m     13\u001b[0m \u001b[38;5;66;03m# Load the model\u001b[39;00m\n\u001b[0;32m---> 14\u001b[0m model \u001b[38;5;241m=\u001b[39m \u001b[43mAutoModelForSequenceClassification\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mfrom_pretrained\u001b[49m\u001b[43m(\u001b[49m\u001b[43mcheckpoint_path\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m     16\u001b[0m \u001b[38;5;66;03m# Load the tokenizer\u001b[39;00m\n\u001b[1;32m     17\u001b[0m tokenizer \u001b[38;5;241m=\u001b[39m AutoTokenizer\u001b[38;5;241m.\u001b[39mfrom_pretrained(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mLlamaTokenizer\u001b[39m\u001b[38;5;124m\"\u001b[39m) \u001b[38;5;66;03m#add name of your model's tokenizer on Hugging Face OR custom tokenizer\u001b[39;00m\n",
      "File \u001b[0;32m~/.local/lib/python3.9/site-packages/transformers/models/auto/auto_factory.py:525\u001b[0m, in \u001b[0;36m_BaseAutoModelClass.from_pretrained\u001b[0;34m(cls, pretrained_model_name_or_path, *model_args, **kwargs)\u001b[0m\n\u001b[1;32m    522\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m kwargs\u001b[38;5;241m.\u001b[39mget(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mquantization_config\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;28;01mNone\u001b[39;00m) \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[1;32m    523\u001b[0m     _ \u001b[38;5;241m=\u001b[39m kwargs\u001b[38;5;241m.\u001b[39mpop(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mquantization_config\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m--> 525\u001b[0m config, kwargs \u001b[38;5;241m=\u001b[39m \u001b[43mAutoConfig\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mfrom_pretrained\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m    526\u001b[0m \u001b[43m    \u001b[49m\u001b[43mpretrained_model_name_or_path\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m    527\u001b[0m \u001b[43m    \u001b[49m\u001b[43mreturn_unused_kwargs\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;28;43;01mTrue\u001b[39;49;00m\u001b[43m,\u001b[49m\n\u001b[1;32m    528\u001b[0m \u001b[43m    \u001b[49m\u001b[43mtrust_remote_code\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mtrust_remote_code\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m    529\u001b[0m \u001b[43m    \u001b[49m\u001b[43mcode_revision\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mcode_revision\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m    530\u001b[0m \u001b[43m    \u001b[49m\u001b[43m_commit_hash\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mcommit_hash\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m    531\u001b[0m \u001b[43m    \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mhub_kwargs\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m    532\u001b[0m \u001b[43m    \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m    533\u001b[0m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m    535\u001b[0m \u001b[38;5;66;03m# if torch_dtype=auto was passed here, ensure to pass it on\u001b[39;00m\n\u001b[1;32m    536\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m kwargs_orig\u001b[38;5;241m.\u001b[39mget(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mtorch_dtype\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;28;01mNone\u001b[39;00m) \u001b[38;5;241m==\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mauto\u001b[39m\u001b[38;5;124m\"\u001b[39m:\n",
      "File \u001b[0;32m~/.local/lib/python3.9/site-packages/transformers/models/auto/configuration_auto.py:1034\u001b[0m, in \u001b[0;36mAutoConfig.from_pretrained\u001b[0;34m(cls, pretrained_model_name_or_path, **kwargs)\u001b[0m\n\u001b[1;32m   1031\u001b[0m trust_remote_code \u001b[38;5;241m=\u001b[39m kwargs\u001b[38;5;241m.\u001b[39mpop(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mtrust_remote_code\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;28;01mNone\u001b[39;00m)\n\u001b[1;32m   1032\u001b[0m code_revision \u001b[38;5;241m=\u001b[39m kwargs\u001b[38;5;241m.\u001b[39mpop(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mcode_revision\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;28;01mNone\u001b[39;00m)\n\u001b[0;32m-> 1034\u001b[0m config_dict, unused_kwargs \u001b[38;5;241m=\u001b[39m \u001b[43mPretrainedConfig\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mget_config_dict\u001b[49m\u001b[43m(\u001b[49m\u001b[43mpretrained_model_name_or_path\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m   1035\u001b[0m has_remote_code \u001b[38;5;241m=\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mauto_map\u001b[39m\u001b[38;5;124m\"\u001b[39m \u001b[38;5;129;01min\u001b[39;00m config_dict \u001b[38;5;129;01mand\u001b[39;00m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mAutoConfig\u001b[39m\u001b[38;5;124m\"\u001b[39m \u001b[38;5;129;01min\u001b[39;00m config_dict[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mauto_map\u001b[39m\u001b[38;5;124m\"\u001b[39m]\n\u001b[1;32m   1036\u001b[0m has_local_code \u001b[38;5;241m=\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mmodel_type\u001b[39m\u001b[38;5;124m\"\u001b[39m \u001b[38;5;129;01min\u001b[39;00m config_dict \u001b[38;5;129;01mand\u001b[39;00m config_dict[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mmodel_type\u001b[39m\u001b[38;5;124m\"\u001b[39m] \u001b[38;5;129;01min\u001b[39;00m CONFIG_MAPPING\n",
      "File \u001b[0;32m~/.local/lib/python3.9/site-packages/transformers/configuration_utils.py:620\u001b[0m, in \u001b[0;36mPretrainedConfig.get_config_dict\u001b[0;34m(cls, pretrained_model_name_or_path, **kwargs)\u001b[0m\n\u001b[1;32m    618\u001b[0m original_kwargs \u001b[38;5;241m=\u001b[39m copy\u001b[38;5;241m.\u001b[39mdeepcopy(kwargs)\n\u001b[1;32m    619\u001b[0m \u001b[38;5;66;03m# Get config dict associated with the base config file\u001b[39;00m\n\u001b[0;32m--> 620\u001b[0m config_dict, kwargs \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mcls\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_get_config_dict\u001b[49m\u001b[43m(\u001b[49m\u001b[43mpretrained_model_name_or_path\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m    621\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m_commit_hash\u001b[39m\u001b[38;5;124m\"\u001b[39m \u001b[38;5;129;01min\u001b[39;00m config_dict:\n\u001b[1;32m    622\u001b[0m     original_kwargs[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m_commit_hash\u001b[39m\u001b[38;5;124m\"\u001b[39m] \u001b[38;5;241m=\u001b[39m config_dict[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m_commit_hash\u001b[39m\u001b[38;5;124m\"\u001b[39m]\n",
      "File \u001b[0;32m~/.local/lib/python3.9/site-packages/transformers/configuration_utils.py:708\u001b[0m, in \u001b[0;36mPretrainedConfig._get_config_dict\u001b[0;34m(cls, pretrained_model_name_or_path, **kwargs)\u001b[0m\n\u001b[1;32m    706\u001b[0m     config_dict[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m_commit_hash\u001b[39m\u001b[38;5;124m\"\u001b[39m] \u001b[38;5;241m=\u001b[39m commit_hash\n\u001b[1;32m    707\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m (json\u001b[38;5;241m.\u001b[39mJSONDecodeError, \u001b[38;5;167;01mUnicodeDecodeError\u001b[39;00m):\n\u001b[0;32m--> 708\u001b[0m     \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mEnvironmentError\u001b[39;00m(\n\u001b[1;32m    709\u001b[0m         \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mIt looks like the config file at \u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mresolved_config_file\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124m is not a valid JSON file.\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m    710\u001b[0m     )\n\u001b[1;32m    712\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m is_local:\n\u001b[1;32m    713\u001b[0m     logger\u001b[38;5;241m.\u001b[39minfo(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mloading configuration file \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mresolved_config_file\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n",
      "\u001b[0;31mOSError\u001b[0m: It looks like the config file at '/home/uafcb7f73a7c1b7b8895a40af90eab07/.cache/huggingface/hub/models--Fredswqa1--DysfunctEcosenseLLM/snapshots/c8a9df5a77a07883e4ee3e59c9ca2683c4189c6b/config.json' is not a valid JSON file."
     ]
    }
   ],
   "source": [
    "# Logging in to Hugging Face\n",
    "from huggingface_hub import notebook_login, Repository\n",
    "\n",
    "# Login to Hugging Face\n",
    "notebook_login()\n",
    "\n",
    "# Model and Tokenize Loading\n",
    "from transformers import AutoModelForSequenceClassification, AutoTokenizer\n",
    "\n",
    "# Define the path to the checkpoint\n",
    "checkpoint_path = \"Fredswqa1/DysfunctEcosenseLLM\"  # Replace with your checkpoint folder\n",
    "\n",
    "# Load the model\n",
    "model = AutoModelForSequenceClassification.from_pretrained(checkpoint_path)\n",
    "\n",
    "# Load the tokenizer\n",
    "tokenizer = AutoTokenizer.from_pretrained(\"LlamaTokenizer\") #add name of your model's tokenizer on Hugging Face OR custom tokenizer\n",
    "\n",
    "# Save the model and tokenizer\n",
    "model_name_on_hub = \"EcoSense-LLMChat\"\n",
    "model.save_pretrained(model_name_on_hub)\n",
    "tokenizer.save_pretrained(model_name_on_hub)\n",
    "\n",
    "# Push to the hub\n",
    "model.push_to_hub(model_name_on_hub)\n",
    "tokenizer.push_to_hub(model_name_on_hub)\n",
    "\n",
    "# Congratulations! Your fine-tuned model is now uploaded to the Hugging Face Model Hub. \n",
    "# You can view and share your model using its URL: https://huggingface.co/<your-username>/<your-model-name>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "39613af7-3408-4412-8ded-aa6116759f06",
   "metadata": {},
   "source": [
    "\n",
    "**Testing our Fine-Tuned LLM**\n",
    "\n",
    "Congratulations on successfully fine-tuning your Language Model for Text-to-SQL tasks! It's now time to put the model to the test.\n",
    "\n",
    "___"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "00cb638e-1464-4596-8809-186834b3f277",
   "metadata": {},
   "source": [
    "**TextToSQLGenerator: Generating SQL Queries from Text Prompts**\n",
    "\n",
    "**Important Note**: Remember to re-import necessary packages and re-define `BASE_MODELS` by rerunning relevant cells if the Jupyter kernel is restarted.\n",
    "\n",
    "**Overview of `TextToSQLGenerator`**\n",
    "- Designed for generating SQL queries from natural language prompts.\n",
    "- Allows model selection at initialization.\n",
    "\n",
    "**Initialization and Configuration:**\n",
    "- Set `use_adapter` to `True` for using the fine-tuned LoRA model; defaults to the base model otherwise.\n",
    "- Automatic tokenizer selection based on the model ID, with special handling for 'llama' models.\n",
    "- Optimized loading for CPU / XPUs (`low_cpu_mem_usage`, `load_in_4bit`).\n",
    "- For LoRA models, loads fine-tuned checkpoints for inference.\n",
    "\n",
    "**Generating SQL Queries:**\n",
    "\n",
    "The `generate` method is where the actual translation occurs. Given a text prompt, the method encodes the prompt using the tokenizer, ensuring that it fits within the model's maximum length constraints. It then performs inference to generate the SQL query.\n",
    "\n",
    "The method parameters like `temperature` and `repetition_penalty` which we can tweak to control the creativity and quality of the generated queries!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "10a0e504-46b7-4c6e-8d80-b28798607ed6",
   "metadata": {},
   "outputs": [],
   "source": [
    "os.environ[\"WANDB_DISABLED\"] = \"true\"\n",
    "INFERENCE_DEVICE = torch.device(\"xpu\")  # change this to `xpu` to use Intel GPU for inference  \n",
    "\n",
    "def generate_prompt_sql(input_question, context, output=\"\"):\n",
    "    \"\"\"\n",
    "    Generates a prompt for fine-tuning the LLM model for text-to-SQL tasks.\n",
    "\n",
    "    Parameters:\n",
    "        input_question (str): The input text or question to be converted to SQL.\n",
    "        context (str): The schema or context in which the SQL query operates.\n",
    "        output (str, optional): The expected SQL query as the output.\n",
    "\n",
    "    Returns:\n",
    "        str: A formatted string serving as the prompt for the fine-tuning task.\n",
    "    \"\"\"\n",
    "    return f\"\"\"You are a powerful text-to-SQL model. Your job is to answer questions about a database. You are given a question and context regarding one or more tables. \n",
    "\n",
    "You must output the SQL query that answers the question.\n",
    "\n",
    "### Input:\n",
    "{input_question}\n",
    "\n",
    "### Context:\n",
    "{context}\n",
    "\n",
    "### Response:\n",
    "{output}\"\"\"\n",
    "\n",
    "\n",
    "def setup_model_and_tokenizer(base_model_id: str):\n",
    "    \"\"\"Downloads / Loads the pre-trained model and tokenizer in nf4 based on the given base model ID for training, \n",
    "    with fallbacks for permission errors to use default cache.\"\"\"\n",
    "    local_model_id = base_model_id.replace(\"/\", \"--\")\n",
    "    local_model_path = os.path.join(MODEL_CACHE_PATH, local_model_id)\n",
    "\n",
    "    bnb_config = BitsAndBytesConfig(\n",
    "        load_in_4bit=True,\n",
    "        bnb_4bit_use_double_quant=False,\n",
    "        bnb_4bit_quant_type=\"nf4\",\n",
    "        bnb_4bit_compute_dtype=torch.bfloat16\n",
    "    )\n",
    "    try:\n",
    "        print(f\"Attempting to load model and tokenizer from: {local_model_path}\")\n",
    "        model = AutoModelForCausalLM.from_pretrained(\n",
    "            local_model_path,\n",
    "            quantization_config=bnb_config\n",
    "            )\n",
    "        tokenizer_class = LlamaTokenizer if \"llama\" in base_model_id.lower() else AutoTokenizer\n",
    "        tokenizer = tokenizer_class.from_pretrained(local_model_path)\n",
    "    except (OSError, PermissionError) as e:\n",
    "        print(f\"Failed to load from {local_model_path} due to {e}. Attempting to download...\")\n",
    "        model = AutoModelForCausalLM.from_pretrained(\n",
    "            base_model_id, \n",
    "            quantization_config=bnb_config\n",
    "            )\n",
    "        tokenizer_class = LlamaTokenizer if \"llama\" in base_model_id.lower() else AutoTokenizer\n",
    "        tokenizer = tokenizer_class.from_pretrained(base_model_id)\n",
    "\n",
    "    tokenizer.pad_token_id = 0\n",
    "    tokenizer.padding_side = \"left\"\n",
    "    return model.to(INFERENCE_DEVICE), tokenizer\n",
    "\n",
    "class TextToSQLGenerator:\n",
    "    \"\"\"Handles SQL query generation for a given text prompt.\"\"\"\n",
    "\n",
    "    def __init__(\n",
    "        self, base_model_id=BASE_MODEL, use_adapter=False, lora_checkpoint=None, loaded_base_model=None\n",
    "    ):\n",
    "        \"\"\"\n",
    "        Initialize the InferenceModel class.\n",
    "        Parameters:\n",
    "            use_adapter (bool, optional): Whether to use LoRA model. Defaults to False.\n",
    "        \"\"\"\n",
    "        try:\n",
    "            if loaded_base_model:\n",
    "                self.model = loaded_base_model.model\n",
    "                self.tokenizer = loaded_base_model.tokenizer\n",
    "            else:\n",
    "                self.model, self.tokenizer = setup_model_and_tokenizer(base_model_id)\n",
    "            if use_adapter:\n",
    "                self.model = PeftModel.from_pretrained(self.model, lora_checkpoint)\n",
    "        except Exception as e:\n",
    "            logging.error(f\"Exception occurred during model initialization: {e}\")\n",
    "            raise\n",
    "\n",
    "        self.model.to(INFERENCE_DEVICE)\n",
    "        self.max_length = 512\n",
    "\n",
    "\n",
    "    def generate(self, prompt, **kwargs):\n",
    "        \"\"\"Generates an SQL query based on the given prompt.\n",
    "        Parameters:\n",
    "            prompt (str): The SQL prompt.\n",
    "        Returns:\n",
    "            str: The generated SQL query.\n",
    "        \"\"\"\n",
    "        try:\n",
    "            encoded_prompt = self.tokenizer(\n",
    "                prompt,\n",
    "                truncation=True,\n",
    "                max_length=self.max_length,\n",
    "                padding=False,\n",
    "                return_tensors=\"pt\",\n",
    "            ).input_ids.to(INFERENCE_DEVICE)\n",
    "            with torch.no_grad():\n",
    "                with torch.xpu.amp.autocast():\n",
    "                    outputs = self.model.generate(\n",
    "                        input_ids=encoded_prompt,\n",
    "                        do_sample=True,\n",
    "                        max_length=self.max_length,\n",
    "                        temperature=0.3,\n",
    "                        repetition_penalty=1.2,\n",
    "                    )\n",
    "            generated = self.tokenizer.decode(outputs[0], skip_special_tokens=True)\n",
    "            return generated\n",
    "        except Exception as e:\n",
    "            logging.error(f\"Exception occurred during query generation: {e}\")\n",
    "            raise"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dfb1c247-f6e2-4ccd-bdc6-26f41ea63c55",
   "metadata": {},
   "source": [
    "---\n",
    "**Generate SQL from Natural Language!** 🚀 \n",
    "\n",
    "**With `TextToSQLGenerator`:**\n",
    "- Compare base model 🆚 LoRA model.\n",
    "- Instantiate with different `use_adapter` settings for side-by-side comparison.\n",
    "\n",
    "**Things to try out:**\n",
    "\n",
    "1. **Select a Natural Language Question** 🗣️: Use a prompt or sample data (see samples dict below) for SQL translation.\n",
    "2. **Base Model SQL Generation** 🏗️: Generate SQL from the prompt using the base model.\n",
    "3. **Fine-Tuned Model SQL Generation** ✨: Generate SQL with the fine-tuned model; note improvements.\n",
    "4. **Compare Outputs** 🔍: Evaluate both SQL queries for accuracy to compare both models.\n",
    "5. **Iterate and Refine** 🔁: Adjust training parameters or dataset and finetune again if required.\n",
    "6. **Integrate with 🗂️ LlamaIndex 🦙**: Use frameworks like [LlamaIndex](https://github.com/run-llama/llama_index) to integrated your finetuned model for querying a database using natural language.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "94c63bc1-9e86-4760-ac9b-c915969ee5fb",
   "metadata": {},
   "source": [
    "**Now let's see how our model performance, Let's generate some SQL queries:**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dd2c6f25-5c45-4061-9b62-91233149b7a2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# lets load base model for a baseline comparison\n",
    "base_model = TextToSQLGenerator(\n",
    "    use_adapter=False,\n",
    "    lora_checkpoint=\"\",\n",
    ")  # setting use_adapter=False to use the base model\n",
    "finetuned_model = None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b8417146-0c28-4996-81a4-c4b0857d81e7",
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "\n",
    "from IPython.display import display, HTML\n",
    "\n",
    "\n",
    "# let's use some fake sample data\n",
    "samples = \"\"\"\n",
    "[\n",
    "  {\n",
    "    \"question\": \"What is the capacity of the stadium where the team 'Mountain Eagles' plays?\",\n",
    "    \"context\": \"CREATE TABLE stadium_info (team_name VARCHAR, stadium_name VARCHAR, capacity INT)\"\n",
    "  },\n",
    "  {\n",
    "    \"question\": \"How many goals did player John Smith score last season?\",\n",
    "    \"context\": \"CREATE TABLE player_stats (player_name VARCHAR, goals_scored INT, season VARCHAR)\"\n",
    "  },\n",
    "  {\n",
    "    \"question\": \"What are the operating hours for the Central Library on weekends?\",\n",
    "    \"context\": \"CREATE TABLE library_hours (library_name VARCHAR, day_of_week VARCHAR, open_time TIME, close_time TIME)\"\n",
    "  }\n",
    "]\n",
    "\"\"\"\n",
    "\n",
    "def _extract_sections(output):\n",
    "    input_section = output.split(\"### Input:\")[1].split(\"### Context:\")[0]\n",
    "    context_section = output.split(\"### Context:\")[1].split(\"### Response:\")[0]\n",
    "    response_section = output.split(\"### Response:\")[1]\n",
    "    return input_section, context_section, response_section\n",
    "\n",
    "def run_inference(sample_data, model, finetuned=False):\n",
    "    if INFERENCE_DEVICE.type.startswith(\"xpu\"):\n",
    "        torch.xpu.empty_cache()\n",
    "    \n",
    "    color = \"#4CAF52\" if finetuned else \"#2196F4\"\n",
    "    model_type = \"finetuned\" if finetuned else \"base\"\n",
    "    display(HTML(f\"<div style='color:{color};'>Processing queries on {INFERENCE_DEVICE} please wait...</div>\"))\n",
    "    \n",
    "    for index, row in enumerate(sample_data):\n",
    "        try:\n",
    "            prompt = generate_prompt_sql(row[\"question\"], context=row[\"context\"])\n",
    "            output = model.generate(prompt)            \n",
    "            input_section, context_section, response_section = _extract_sections(output)\n",
    "            \n",
    "            tabbed_output = f\"\"\"\n",
    "            <details>\n",
    "                <summary style='color: {color};'><b>{model_type} model - Sample {index+1}</b> (Click to expand)</summary>\n",
    "                <div style='padding-left: 20px;'>\n",
    "                    <p><b>Expected input 📝:</b><br>{input_section}</p>\n",
    "                    <p><b>Expected context 📚:</b><br>{context_section}</p>\n",
    "                    <p><b>Generated response 💡:</b><br>{response_section}</p>\n",
    "                </div>\n",
    "            </details>\n",
    "            <hr style='border-top: 1px solid #bbb;'>\"\"\"  # Subtle separator\n",
    "            display(HTML(tabbed_output))\n",
    "        except Exception as e:\n",
    "            logging.error(f\"Exception occurred during sample processing: {e}\")\n",
    "\n",
    "# checkpoints are saved to `./lora_adapters`.\n",
    "# Update the USING_CHECKPOINT to the one you want to use.\n",
    "USING_CHECKPOINT=200\n",
    "# if the kernel is interrupted the latest adapter (LORA_CHECKPOINT) is `./final_model_interrupted/`\n",
    "# or else, the final model LORA_CHECKPOINT is `./final_model`\n",
    "LORA_CHECKPOINT = f\"./lora_adapters/checkpoint-{USING_CHECKPOINT}/\"\n",
    "\n",
    "if os.path.exists(LORA_CHECKPOINT):\n",
    "    sample_data = json.loads(samples)\n",
    "    run_inference(sample_data, model=base_model)\n",
    "    if not finetuned_model:\n",
    "        finetuned_model = TextToSQLGenerator(\n",
    "            use_adapter=True,\n",
    "            lora_checkpoint=LORA_CHECKPOINT,\n",
    "            loaded_base_model=base_model\n",
    "        )\n",
    "    run_inference(sample_data, model=finetuned_model, finetuned=True)\n",
    "\n",
    "    # To conserve memory we can delete the model\n",
    "    #del finetuned_model\n",
    "    #del base_model"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "11c2506c",
   "metadata": {},
   "source": [
    "---\n",
    "**Conclusion** 👏\n",
    "\n",
    "We've successfully navigated the process of selecting and fine-tuning a foundational LLM model on Intel GPUs, showcasing its SQL generation capabilities. I hope that I have been able to highlight the potential of customizing language models for specific tasks and on how to efficiently finetune LLMs on Intel XPUs. As a suggestion for your continued journey, consider experimenting with different models, adjusting inference settings, and exploring various LoRA configurations to refine your results. Keep exploring!\n",
    "\n",
    "---\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c458cac4",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true
   },
   "source": [
    "\n",
    "**Disclaimer for Using Large Language Models**\n",
    "\n",
    "Please be aware that while Large Language Models are powerful tools for text generation, they may sometimes produce results that are unexpected, biased, or inconsistent with the given prompt. It's advisable to carefully review the generated text and consider the context and application in which you are using these models.\n",
    "\n",
    "For detailed information on each model's capabilities, licensing, and attribution, please refer to the respective model cards:\n",
    "\n",
    "1. **Open LLaMA 3B v2**\n",
    "   - Model Card: [openlm-research/open_llama_3b_v2](https://huggingface.co/openlm-research/open_llama_3b_v2)\n",
    "\n",
    "2. **Open LLaMA 13B**\n",
    "   - Model Card: [openlm-research/open_llama_13b](https://huggingface.co/openlm-research/open_llama_13b)\n",
    "\n",
    "3. **Nous-Hermes LLaMA 2-7B**\n",
    "   - Model Card: [NousResearch/Nous-Hermes-llama-2-7b](https://huggingface.co/NousResearch/Nous-Hermes-llama-2-7b)\n",
    "\n",
    "4. **LLaMA 2-7B Chat HF**\n",
    "   - Model Card: [NousResearch/Llama-2-7b-chat-hf](https://huggingface.co/NousResearch/Llama-2-7b-chat-hf)\n",
    "\n",
    "5. **LLaMA 2-13B HF**\n",
    "   - Model Card: [NousResearch/Llama-2-13b-hf](https://huggingface.co/NousResearch/Llama-2-13b-hf)\n",
    "\n",
    "6. **CodeLlama 7B HF**\n",
    "   - Model Card: [NousResearch/CodeLlama-7b-hf](https://huggingface.co/NousResearch/CodeLlama-7b-hf)\n",
    "\n",
    "7. **Phind-CodeLlama 34B v2**\n",
    "   - Model Card: [Phind/Phind-CodeLlama-34B-v2](https://huggingface.co/Phind/Phind-CodeLlama-34B-v2)\n",
    "\n",
    "8. **Zephyr-7b-beta**\n",
    "   - Model Card:  [HuggingFaceH4/zephyr-7b-beta](https://huggingface.co/HuggingFaceH4/zephyr-7b-beta)\n",
    "\n",
    "\n",
    "Usage of these models must also adhere to the licensing agreements and be in accordance with ethical guidelines and best practices for AI. If you have any concerns or encounter issues with the models, please refer to the respective model cards and documentation provided in the links above.\n",
    "To the extent that any public or non-Intel datasets or models are referenced by or accessed using these materials those datasets or models are provided by the third party indicated as the content source. Intel does not create the content and does not warrant its accuracy or quality. By accessing the public content, or using materials trained on or with such content, you agree to the terms associated with that content and that your use complies with the applicable license.\n",
    "\n",
    " \n",
    "Intel expressly disclaims the accuracy, adequacy, or completeness of any such public content, and is not liable for any errors, omissions, or defects in the content, or for any reliance on the content. Intel is not liable for any liability or damages relating to your use of public content.\n",
    "\n",
    "Intel’s provision of these resources does not expand or otherwise alter Intel’s applicable published warranties or warranty disclaimers for Intel products or solutions, and no additional obligations, indemnifications, or liabilities arise from Intel providing such resources. Intel reserves the right, without notice, to make corrections, enhancements, improvements, and other changes to its materials.\n",
    "\n",
    "---\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "pytorch-gpu",
   "language": "python",
   "name": "pytorch-gpu"
  },
  "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.9.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}